code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
private void createLNode(VNode vNode, VNode parent) { LNode lNode = layout.newNode(vNode); lNode.type = vNode.glyph.getClazz(); lNode.label = vNode.glyph.getId(); LGraph rootLGraph = layout.getGraphManager().getRoot(); //Add corresponding nodes to corresponding maps viewToLayout.put(vNode, lNode); layoutToView.put(lNode.label,vNode); // if the vNode has a parent, add the lNode as a child of the parent l-node. // otherwise, add the node to the root graph. if (parent != null) { LNode parentLNode = viewToLayout.get(parent); parentLNode.getChild().add(lNode); } else { rootLGraph.add(lNode); } lNode.setLocation(vNode.glyph.getBbox().getX(), vNode.glyph.getBbox().getY()); if (vNode instanceof VCompound) { VCompound vCompound = (VCompound) vNode; // add new LGraph to the graph manager for the compound node layout.getGraphManager().add(layout.newGraph(null), lNode); // for each VNode in the node set create an LNode for (VNode vChildNode: vCompound.getChildren()) { createLNode(vChildNode, vCompound); } } else { lNode.setWidth(vNode.glyph.getBbox().getW()); lNode.setHeight(vNode.glyph.getBbox().getH()); } }
Helper function for creating LNode objects from VNode objects and adds them to the given layout. @param vNode VNode object from which a corresponding LNode object will be created. @param parent parent of vNode, if not null vNode will be added to layout as child node.
private void setCompartmentRefForComplexMembers(final Glyph glyph, final Glyph compartment, final Set<Glyph> visited) { if(!visited.add(glyph)) return; glyph.setCompartmentRef(compartment); if(glyph.getGlyph().size() > 0) { for(Glyph g: glyph.getGlyph() ) { setCompartmentRefForComplexMembers(g, compartment, visited); } } }
Recursively sets compartmentRef fields of members of a complex glyph to the same value as complex's compartment. @param glyph target glyph where compartmentRef(compartment parameter) will be set. @param compartment compartmentRef value that will be set. @param visited (initially an empty set of) previously processed glyphs, to escape infinite loops
private void removePortsFromArcs(List<Arc> arcs) { for(Arc arc: arcs ) { // If source is port, first clear port indicators else retrieve it from hashmaps if (arc.getSource() instanceof Port ) { Glyph source = portIDToOwnerGlyph.get(((Port)arc.getSource()).getId()); arc.setSource(source); } // If target is port, first clear port indicators else retrieve it from hashmaps if (arc.getTarget() instanceof Port) { Glyph target = portIDToOwnerGlyph.get(((Port)arc.getTarget()).getId()); arc.setTarget(target); } } }
This method replaces ports of arc objects with their owners. @param arcs Arc list of SBGN model
private void initPortIdToGlyphMap(List<Glyph> glyphs) { for(Glyph glyph: glyphs) { for(Port p: glyph.getPort()) { portIDToOwnerGlyph.put(p.getId(), glyph ); } if(glyph.getGlyph().size() > 0) initPortIdToGlyphMap(glyph.getGlyph()); } }
This method initializes map for glyphs and their respective ports. @param glyphs Glyph list of SBGN model
private boolean isChildless(Glyph targetGlyph) { boolean checker = true; for(Glyph glyph: targetGlyph.getGlyph() ) { if ( !glyphClazzOneOf(glyph, GlyphClazz.STATE_VARIABLE, GlyphClazz.UNIT_OF_INFORMATION) ) { checker = false; break; } } return checker; }
Returns true if a glyph includes child glyphs (state and info glyphs are out of count!) @param targetGlyph target glyph that will be queried. @return true/false
public void merge(Model target, Model... sources) { for (Model source : sources) if (source != null) merge(target, source.getObjects()); }
Merges the <em>source</em> models into <em>target</em> model, one after another (in the order they are listed). If the target model is self-integral (complete) or empty, then the result of the merge will be also a complete model (contain unique objects with unique URIs, all objects referenced from any other object in the model). Source models do not necessarily have to be complete and may even indirectly contain different objects of the same type with the same URI. Though, in most cases, one probably wants target model be complete or empty for the best possible results. So, if your target is incomplete, or you are not quite sure, then do simply merge it as the first source to a new empty model or itself (or call {@link Model#repair()} first). @param target model into which merging process will be done @param sources models to be merged/updated to <em>target</em>; order can be important
public void merge(Model target, Collection<? extends BioPAXElement> elements) { @SuppressWarnings("unchecked") final Fetcher fetcher = new Fetcher(map); // Auto-complete source 'elements' by discovering all the implicit elements there // copy all elements, as the collection can be immutable or unsafe to add elements to final Set<BioPAXElement> sources = new HashSet<BioPAXElement>(elements); for(BioPAXElement se : elements) { sources.addAll(fetcher.fetch(se)); } // Next, we only copy elements having new URIs - for (BioPAXElement bpe : sources) { /* if there exists target element with the same id, * do not copy this one! (this 'source' element will * be soon replaced with the target's, same id, one * in all parent objects) */ final String uri = bpe.getUri(); if (!target.containsID(uri)) { /* * Warning: other than the default (ModelImpl) target Model * implementations may add child elements recursively (e.g., * using jpa cascades/recursion); it might also override target's * properties with the corresponding ones from the source, even * though SimpleMerger is not supposed to do this; also, is such cases, * the number of times this loop body is called can be less that * the number of elements in sourceElements set that weren't * originally present in the target model, or - even equals to * one) */ target.add(bpe); } else if(bpe.getModelInterface() != target.getByID(uri).getModelInterface()) { // source object/model(s) have to be fixed (URI conflicts resolved) before merging by URI throw new RuntimeException(String.format( "URI:%s of %s (to merge) is also URI of %s in target model (different class)", uri, bpe.getModelInterface().getSimpleName(), target.getByID(uri).getModelInterface().getSimpleName())); } } // Finally, update object references for (BioPAXElement bpe : sources) { updateObjectFields(bpe, target); } }
Merges the <em>elements</em> and all their child biopax objects into the <em>target</em> model. @see #merge(Model, Model...) for details about the target model. @param target model into which merging will be done @param elements elements that are going to be merged/updated to <em>target</em>
public void merge(Model target, BioPAXElement source) { merge(target, Collections.singleton(source)); }
Merges the <em>source</em> element (and its "downstream" dependents) into <em>target</em> model. @see #merge(Model, Collection) @param target the BioPAX model to merge into @param source object to add or merge
private void updateObjectFields(BioPAXElement source, Model target) { //Skip if target model had a different object with the same URI as the source's, //and no Filter was set (mergePropOf is null); i.e., when //we simply want the source to be replaced with the object //having the same type and URI and that's already present in the target model. BioPAXElement keep = target.getByID(source.getUri()); if(keep != source && mergePropOf ==null) { return; //nothing to do } Set<PropertyEditor> editors = map.getEditorsOf(source); for (PropertyEditor editor : editors) { if (editor instanceof ObjectPropertyEditor) { //copy prop. values (to avoid concurrent modification exception) Set<BioPAXElement> values = new HashSet<BioPAXElement>((Set<BioPAXElement>) editor.getValueFromBean(source)); if(keep == source) //i.e., it has been just added to the target, - simply update properties { for (BioPAXElement value : values) { migrateToTarget(source, target, editor, value); } } else //source is normally to be entirely replaced, but if it passes the filter, if(mergePropOf !=null && mergePropOf.filter(source) && editor.isMultipleCardinality()) // and the prop. is multi-cardinality, { // - then we want to copy some values for (BioPAXElement value : values) { mergeToTarget(keep, target, editor, value); } } } else // - primitive, enum, or string property editor (e.g., comment, name), and - if (mergePropOf != null && mergePropOf.filter(source) && editor.isMultipleCardinality()) { Set<Object> values = new HashSet<Object>((Set<Object>) editor.getValueFromBean(source)); for (Object value : values) { mergeToTarget(keep, target, editor, value); } } } }
Updates each value of <em>existing</em> element, using the value(s) of <em>update</em>. @param source BioPAX element of which values are used for update @param target the BioPAX model
public void breakCycles() { for (GraphObject go : new ArrayList<GraphObject>(result)) { if (go instanceof Node) { Node node = (Node) go; for (Edge edge : node.getDownstream()) { if (result.contains(edge) && !isSafe(node, edge)) { result.remove(edge); } } } } }
Run the algorithm.
public boolean isSafe(Node node, Edge edge) { initMaps(); setColor(node, BLACK); setLabel(node, 0); setLabel(edge, 0); labelEquivRecursive(node, UPWARD, 0, false, false); labelEquivRecursive(node, DOWNWARD, 0, false, false); // Initialize dist and color of source set Node neigh = edge.getTargetNode(); if (getColor(neigh) != WHITE) return false; setColor(neigh, GRAY); setLabel(neigh, 0); queue.add(neigh); labelEquivRecursive(neigh, UPWARD, 0, true, false); labelEquivRecursive(neigh, DOWNWARD, 0, true, false); // Process the queue while (!queue.isEmpty()) { Node current = queue.remove(0); if (ST.contains(current)) return true; boolean safe = processNode2(current); if (safe) return true; // Current node is processed setColor(current, BLACK); } return false; }
Checks whether an edge is on an unwanted cycle. @param node Node that the edge is bound @param edge The edge to check @return True if no cycle is detected, false otherwise
protected boolean processNode2(Node current) { return processEdges(current, current.getDownstream()) || processEdges(current, current.getUpstream()); }
Continue the search from the node. 2 is added because a name clash in the parent class. @param current The node to traverse @return False if a cycle is detected
private boolean processEdges(Node current, Collection<Edge> edges) { for (Edge edge : edges) { if (!result.contains(edge)) continue; // Label the edge considering direction of traversal and type of current node setLabel(edge, getLabel(current)); // Get the other end of the edge Node neigh = edge.getSourceNode() == current ? edge.getTargetNode() : edge.getSourceNode(); // Process the neighbor if not processed or not in queue if (getColor(neigh) == WHITE) { // Label the neighbor according to the search direction and node type if (neigh.isBreadthNode()) { setLabel(neigh, getLabel(current) + 1); } else { setLabel(neigh, getLabel(edge)); } // Check if we need to stop traversing the neighbor, enqueue otherwise if (getLabel(neigh) == limit || isEquivalentInTheSet(neigh, ST)) { return true; } setColor(neigh, GRAY); // Enqueue the node according to its type if (neigh.isBreadthNode()) { queue.addLast(neigh); } else { // Non-breadth nodes are added in front of the queue queue.addFirst(neigh); } labelEquivRecursive(neigh, UPWARD, getLabel(neigh), true, !neigh.isBreadthNode()); labelEquivRecursive(neigh, DOWNWARD, getLabel(neigh), true, !neigh.isBreadthNode()); } } return false; }
Continue evaluating the next edge. @param current Current node @param edges The edge to evaluate @return False if a cycle is detected
protected final void resetLevel(BioPAXLevel level, BioPAXFactory factory) { this.level = (level != null) ? level : BioPAXLevel.L3; this.factory = (factory != null) ? factory : this.level.getDefaultFactory(); // default flags if (this.level == BioPAXLevel.L2) { this.fixReusedPEPs = true; } bp = this.level.getNameSpace(); resetEditorMap(); //implemented by concrete subclasses }
Updates the level and factory for this I/O (final - because used in the constructor) @param level BioPAX Level @param factory concrete BioPAX factory impl.
public Model convertFromOWL(InputStream in) { init(in); //cache the namespaces. namespaces = this.readNameSpaces(); autodetectBiopaxLevel(); // this may update level, editorMap and factory! Model model = factory.createModel(); model.getNameSpacePrefixMap().putAll(namespaces); model.setXmlBase(base); boolean fixingPEPS = model.getLevel() == BioPAXLevel.L2 && this.isFixReusedPEPs(); if (fixingPEPS) { reusedPEPHelper = new ReusedPEPHelper(model); } createAndBind(model); if (fixingPEPS) { this.getReusedPEPHelper().copyPEPFields(); } reset(in); return model; }
Reads a BioPAX model from an OWL file input stream (<em>in</em>) and converts it to a model. @param in inputStream from which the model will be read @return an empty model in case of invalid input.
protected void createAndAdd(Model model, String id, String localName) { BioPAXElement bpe = this.getFactory().create(localName, id); if (log.isTraceEnabled()) { log.trace("id:" + id + " " + localName + " : " + bpe); } /* null might occur here, * so the following is to prevent the NullPointerException * and to continue the model assembling. */ if (bpe != null) { model.add(bpe); } else { log.warn("null object created during reading. It might not be an official BioPAX class.ID: " + id + " Class " + "name " + localName); } }
This method is called by the reader for each OWL instance in the OWL model. It creates a POJO instance, with the given id and inserts it into the model. The inserted object is "clean" in the sense that its properties are not set yet. Implementers of this abstract class can override this method to inject code during object creation. @param model to be inserted @param id of the new object. The model should not contain another object with the same ID. @param localName of the class to be instantiated.
protected Object resourceFixes(BioPAXElement bpe, Object value) { if (this.isFixReusedPEPs() && value instanceof physicalEntityParticipant) { value = this.getReusedPEPHelper().fixReusedPEP((physicalEntityParticipant) value, bpe); } return value; }
This method currently only fixes reusedPEPs if the option is set. As L2 is becoming obsolete this method will be slated for deprecation. @param bpe to be bound @param value to be assigned. @return a "fixed" value.
protected void bindValue(String valueString, PropertyEditor editor, BioPAXElement bpe, Model model) { if (log.isDebugEnabled()) { log.debug("Binding: " + bpe + '(' + bpe.getModelInterface() + " has " + editor + ' ' + valueString); } Object value = (valueString==null)?null:valueString.trim(); if (editor instanceof ObjectPropertyEditor) { value = model.getByID(valueString); value = resourceFixes(bpe, value); if (value == null) { throw new IllegalBioPAXArgumentException( "Illegal or Dangling Value/Reference: " + valueString + " (element: " + bpe.getUri() + " property: " + editor.getProperty() + ")"); } } if (editor == null) { log.error("Editor is null. This probably means an invalid BioPAX property. Failed to set " + valueString); } else //is either EnumeratedPropertyEditor or DataPropertyEditor { editor.setValueToBean(value, bpe); } }
This method binds the value to the bpe. Actual assignment is handled by the editor - but this method performs most of the workarounds and also error handling due to invalid parameters. @param valueString to be assigned @param editor that maps to the property @param bpe to be bound @param model to be populated.
protected StringPropertyEditor getRDFCommentEditor(BioPAXElement bpe) { StringPropertyEditor editor; Class<? extends BioPAXElement> inter = bpe.getModelInterface(); if (this.getLevel().equals(BioPAXLevel.L3)) { editor = (StringPropertyEditor) this.getEditorMap().getEditorForProperty("comment", inter); } else { editor = (StringPropertyEditor) this.getEditorMap().getEditorForProperty("COMMENT", inter); } return editor; }
Paxtools maps BioPAX:comment (L3) and BioPAX:COMMENT (L2) to rdf:comment. This method handles that. @param bpe to be bound. @return a property editor responsible for editing comments.
public void convertToOWL(Model model, OutputStream outputStream, String... ids) { if (ids.length == 0) { convertToOWL(model, outputStream); } else { Model m = model.getLevel().getDefaultFactory().createModel(); m.setXmlBase(model.getXmlBase()); Fetcher fetcher = new Fetcher(SimpleEditorMap.get(model.getLevel())); //no Filters anymore for (String uri : ids) { BioPAXElement bpe = model.getByID(uri); if (bpe != null) { fetcher.fetch(bpe, m); } } convertToOWL(m, outputStream); } }
Similar to {@link BioPAXIOHandler#convertToOWL(org.biopax.paxtools.model.Model, java.io.OutputStream)} (org.biopax.paxtools.model.Model, Object)}, but extracts a sub-model, converts it into BioPAX (OWL) format, and writes it into the outputStream. Saved data can be then read via {@link BioPAXIOHandler} interface (e.g., {@link SimpleIOHandler}). @param model model to be converted into OWL format @param outputStream output stream into which the output will be written @param ids optional list of "root" element absolute URIs; direct/indirect child objects are auto-exported as well.
private boolean containsNull(PhysicalEntity[] pes) { for (PhysicalEntity pe : pes) { if (pe == null) return true; } return false; }
Checks if any element in the chain is null. @param pes element array @return true if null found
protected PhysicalEntity[] fillArray(PhysicalEntity parent, PhysicalEntity target, int depth, int dir) { if (parent == target) { PhysicalEntity[] pes = new PhysicalEntity[depth]; pes[0] = target; return pes; } if (parent instanceof Complex) { for (PhysicalEntity mem : ((Complex) parent).getComponent()) { PhysicalEntity[] pes = fillArray(mem, target, depth + 1, 0); if (pes != null) { pes[pes.length - depth] = parent; return pes; } } } if (dir <= 0) for (PhysicalEntity mem : parent.getMemberPhysicalEntity()) { PhysicalEntity[] pes = fillArray(mem, target, depth + 1, -1); if (pes != null) { pes[pes.length - depth] = parent; return pes; } } if (dir >= 0) for (PhysicalEntity grand : parent.getMemberPhysicalEntityOf()) { PhysicalEntity[] pes = fillArray(grand, target, depth + 1, 1); if (pes != null) { pes[pes.length - depth] = parent; return pes; } } return null; }
Creates the chain that links the given endpoints. @param parent current element @param target target at the member end @param depth current depth @param dir current direction to traverse homologies @return array of entities
public Set<String> getCellularLocations() { Set<String> locs = new HashSet<String>(); for (PhysicalEntity pe : pes) { CellularLocationVocabulary voc = pe.getCellularLocation(); if (voc != null) { for (String term : voc.getTerm()) { if (term != null && term.length() > 0) locs.add(term); } } } return locs; }
Retrieves the cellular location of the PhysicalEntity. @return cellular location of the PhysicalEntity
public boolean intersects(PhysicalEntityChain rpeh, boolean ignoreEndPoints) { for (PhysicalEntity pe1 : pes) { for (PhysicalEntity pe2 : rpeh.pes) { if (pe1 == pe2) { if (ignoreEndPoints) { if ((pes[0] == pe1 || pes[pes.length-1] == pe1) && (rpeh.pes[0] == pe2 || rpeh.pes[rpeh.pes.length-1] == pe2)) { continue; } } return true; } } } return false; }
Checks if two chains intersect. @param rpeh second chain @param ignoreEndPoints flag to ignore intersections at the endpoints of the chains @return true if they intersect
public Activity checkActivityLabel() { boolean active = false; boolean inactive = false; for (PhysicalEntity pe : pes) { for (Object o : PE2TERM.getValueFromBean(pe)) { String s = (String) o; if (s.contains("inactiv")) inactive = true; else if (s.contains("activ")) active = true; } for (String s : pe.getName()) { if (s.contains("inactiv")) inactive = true; else if (s.contains("activ")) active = true; } } if (active) if (inactive) return Activity.BOTH; else return Activity.ACTIVE; else if (inactive) return Activity.INACTIVE; else return Activity.NONE; }
Checks if the chain has a member with an activity label. @return the activity status found
public Set<ModificationFeature> getModifications() { Set<ModificationFeature> set = new HashSet<ModificationFeature>(); for (PhysicalEntity pe : pes) { set.addAll(PE2FEAT.getValueFromBean(pe)); } return set; }
Collects modifications from the elements of the chain. @return modifications
@Override public boolean satisfies(Match match, int... ind) { Collection<BioPAXElement> set = con.generate(match, ind); switch (type) { case EQUAL: return set.size() == size; case GREATER: return set.size() > size; case GREATER_OR_EQUAL: return set.size() >= size; case LESS: return set.size() < size; case LESS_OR_EQUAL: return set.size() <= size; default: throw new RuntimeException( "Should not reach here. Did somebody modify Type enum?"); } }
Checks if generated element size is in limits. @param match current pattern match @param ind mapped indices @return true if generated element size is in limits
public void writeResult(Map<BioPAXElement, List<Match>> matches, OutputStream out) throws IOException { writeResultDetailed(matches, out, 5); }
Writes the result as "A modifications-of-A B gains-of-B loss-of-B", where A and B are gene symbols, and whitespace is tab. Modifications are comma separated. @param matches pattern search result @param out output stream
@Override public String getValue(Match m, int col) { switch(col) { case 0: { return getGeneSymbol(m, "controller ER"); } case 1: { return concat(getModifications(m, "controller simple PE", "controller PE"), " "); } case 2: { return getGeneSymbol(m, "changed ER"); } case 3: { return concat(getDeltaModifications(m, "input simple PE", "input PE", "output simple PE", "output PE")[0], " "); } case 4: { return concat(getDeltaModifications(m, "input simple PE", "input PE", "output simple PE", "output PE")[1], " "); } default: throw new RuntimeException("Invalid col number: " + col); } }
Creates values for the result file columns. @param m current match @param col current column @return value of the given match at the given column
public static <T extends LocalizableResource> T get(Class<T> cls) { return get(cls, null); }
Get localization object for <em>current</em> locale. <p> On server side <em>current</em> locale is determined dynamically by {@link net.lightoze.gwt.i18n.server.LocaleProvider} and can change in runtime for the same object. @param cls localization interface class @param <T> localization interface class @return object implementing specified class
public static <T extends Messages> T getEncoder(Class<T> cls) { return get(cls, ENCODER); }
Get <em>encoding</em> localization object, which will encode all requests so that they can be decoded later by {@link net.lightoze.gwt.i18n.server.LocaleProxy#decode}. <p> The purpose is to separate complex (e.g. template-based) text generation and its localization for particular locale into two separate phases. <p> <strong>Supported only on server side.</strong> @param cls localization interface class @param <T> localization interface class @return object implementing specified class
@SuppressWarnings({"unchecked"}) public static <T extends LocalizableResource> T get(Class<T> cls, String locale) { Map<String, LocalizableResource> localeCache = getLocaleCache(cls); T m = (T) localeCache.get(locale); if (m != null) { return m; } synchronized (cache) { m = (T) localeCache.get(locale); if (m != null) { return m; } m = provider.create(cls, locale); put(cls, locale, m); return m; } }
Get localization object for the specified locale. @param cls localization interface class @param locale locale string @param <T> localization interface class @return object implementing specified class
public static <T extends LocalizableResource> void put(Class<T> cls, T m) { put(cls, null, m); }
Populate localization object cache for <em>current</em> locale. @param cls localization interface class @param m localization object @param <T> localization interface class
public static <T extends LocalizableResource> void put(Class<T> cls, String locale, T m) { Map<String, LocalizableResource> localeCache = getLocaleCache(cls); synchronized (cache) { localeCache.put(locale, m); } }
Populate localization object cache for the specified locale. @param cls localization interface class @param locale locale string @param m localization object @param <T> localization interface class
public Glyph.State createStateVar(EntityFeature ef, ObjectFactory factory) { if (ef instanceof FragmentFeature) { FragmentFeature ff = (FragmentFeature) ef; SequenceLocation loc = ff.getFeatureLocation(); if (loc instanceof SequenceInterval) { SequenceInterval si = (SequenceInterval) loc; SequenceSite begin = si.getSequenceIntervalBegin(); SequenceSite end = si.getSequenceIntervalEnd(); if (begin != null && end != null) { Glyph.State state = factory.createGlyphState(); state.setValue("x[" + begin.getSequencePosition() + " - " + end.getSequencePosition() + "]"); return state; } } } else if (ef instanceof ModificationFeature) { ModificationFeature mf = (ModificationFeature) ef; SequenceModificationVocabulary modType = mf.getModificationType(); if (modType != null) { Set<String> terms = modType.getTerm(); if (terms != null && !terms.isEmpty()) { String orig = terms.iterator().next(); String term = orig.toLowerCase(); String s = symbolMapping.containsKey(term) ? symbolMapping.get(term) : orig; Glyph.State state = factory.createGlyphState(); state.setValue(s); SequenceLocation loc = mf.getFeatureLocation(); if (locMapping.containsKey(term)) { state.setVariable(locMapping.get(term)); } if (loc instanceof SequenceSite) { SequenceSite ss = (SequenceSite) loc; if (ss.getSequencePosition() > 0) { state.setVariable( (state.getVariable() != null ? state.getVariable() : "") + ss.getSequencePosition()); } } return state; } } } // Binding features are ignored return null; }
Creates State to represent the entity feature. @param ef feature to represent @param factory factory that can create the State class @return State representing the feature
protected int[] translate(int[] outer) { int[] t = new int[inds.length]; for (int i = 0; i < t.length; i++) { t[i] = outer[inds[i]]; } return t; }
This methods translates the indexes of outer constraint, to this inner constraint. @param outer mapped indices for the outer constraints @return translated indices
@Override public Collection<BioPAXElement> generate(Match match, int... outer) { return constr.generate(match, translate(outer)); }
Calls generate method of the constraint with index translation. @param match current pattern match @param outer untranslated indices @return generated satisfying elements
protected boolean semanticallyEquivalent(BioPAXElement element) { final deltaGprimeO that = (deltaGprimeO) element; return (Float.compare(that.getDELTA_G_PRIME_O(), DELTA_G_PRIME_O) == 0) && (Float.compare(that.getIONIC_STRENGTH(), IONIC_STRENGTH) == 0) && (Float.compare(that.getPH(), PH) == 0) && (Float.compare(that.getPMG(), PMG) == 0) && (Float.compare(that.getTEMPERATURE(), TEMPERATURE) == 0); }
--------------------- Interface BioPAXElement ---------------------
public String normalize(String biopaxOwlData) { if(biopaxOwlData == null || biopaxOwlData.length() == 0) throw new IllegalArgumentException("no data. " + description); // quick-fix for older BioPAX L3 version (v0.9x) property 'taxonXref' (range: BioSource) biopaxOwlData = biopaxOwlData.replaceAll("taxonXref","xref"); // build the model Model model = null; try { model = biopaxReader.convertFromOWL( new ByteArrayInputStream(biopaxOwlData.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Failed! " + description, e); } if(model == null) { throw new IllegalArgumentException("Failed to create Model! " + description); } // auto-convert to Level3 model if (model.getLevel() != BioPAXLevel.L3) { log.info("Converting model to BioPAX Level3..."); model = (new LevelUpgrader()).filter(model); } normalize(model); // L3 only! // return as BioPAX OWL return convertToOWL(model); }
Normalizes BioPAX OWL data and returns the result as BioPAX OWL (string). This public method is actually intended to use outside the BioPAX Validator framework, with not too large models. @param biopaxOwlData RDF/XML BioPAX content string @return normalized BioPAX RDF/XML @deprecated this method will fail if the data exceeds ~1Gb (max UTF8 java String length)
private void normalizeXrefs(Model model) { final NormalizerMap map = new NormalizerMap(model); final String xmlBase = getXmlBase(model); //current base, the default or model's one, if set. // use a copy of the xrefs set (to avoid concurrent modif. exception) Set<? extends Xref> xrefs = new HashSet<Xref>(model.getObjects(Xref.class)); for(Xref ref : xrefs) { //skip not well-defined ones (incl. PublicationXrefs w/o db/id - won't normalize) if(ref.getDb() == null || ref.getId() == null) continue; ref.setDb(ref.getDb().toLowerCase()); //set lowercase String idPart = ref.getId(); if(ref instanceof RelationshipXref) { // only normalize (replace URI of) RXs that could potentially clash with other RX, CVs, ERs; // skip, won't bother, for all other RXs... if(!ref.getUri().startsWith("http://identifiers.org/")) continue; //RXs might have the same db, id but different rel. type. RelationshipTypeVocabulary cv = ((RelationshipXref) ref).getRelationshipType(); if(ref.getIdVersion()!=null) { idPart += "_" + ref.getIdVersion(); } if(cv != null && !cv.getTerm().isEmpty()) { idPart += "_" + StringUtils.join(cv.getTerm(), '_').toLowerCase(); } } else if(ref instanceof UnificationXref) { // first, try to normalize the db name (using MIRIAM EBI registry) try { ref.setDb(MiriamLink.getName(ref.getDb()).toLowerCase()); } catch (IllegalArgumentException e) { // - unknown/unmatched db name (normalize using defaults) if(ref.getIdVersion()!=null) { idPart += "_" + ref.getIdVersion(); } map.put(ref, Normalizer.uri(xmlBase, ref.getDb(), idPart, ref.getModelInterface())); continue; //shortcut (non-standard db name) } // a hack for uniprot/isoform xrefs if (ref.getDb().startsWith("uniprot")) { //auto-fix (guess) for possibly incorrect db/id (can be 'uniprot isoform' with/no idVersion, etc..) if (isValidDbId("uniprot isoform", ref.getId()) && ref.getId().contains("-")) //the second condition is important { //then it's certainly an isoform id; so - fix the db name ref.setDb("uniprot isoform"); //fix the db } else { //id does not end with "-\\d+", i.e., not a isoform id //(idVersion is a different thing, but id db was "uniprot isoform" they probably misused idVersion) if(ref.getDb().equals("uniprot isoform")) { if(ref.getIdVersion() != null && ref.getIdVersion().matches("^\\d+$")) idPart = ref.getId()+"-"+ref.getIdVersion(); //guess, by idVersion, they actually meant isoform if(isValidDbId(ref.getDb(), idPart)) { ref.setId(idPart); //moved the isoform # to the ID ref.setIdVersion(null); } else if(!isValidDbId(ref.getDb(), ref.getId())) { //certainly not isoform (might not even uniprot, but try...) ref.setDb("uniprot knowledgebase"); //guess, fix } idPart = ref.getId(); } } } } // shelve it for URI replace map.put(ref, Normalizer.uri(xmlBase, ref.getDb(), idPart, ref.getModelInterface())); } // execute replace xrefs map.doSubs(); }
Normalizes all xrefs (not unification xrefs only) to help normalizing/merging other objects, and also because some of the original xref URIs ("normalized") are in fact to be used for other biopax types (e.g., CV or ProteinReference); therefore this method will replace URI also for "bad" xrefs, i.e., those with empty/illegal 'db' or 'id' values. @param model biopax model to update
public static String uri(final String xmlBase, String dbName, String idPart, Class<? extends BioPAXElement> type) { if(type == null || (dbName == null && idPart == null)) throw new IllegalArgumentException("'Either type' is null, or both dbName and idPart are nulls."); if (idPart != null) idPart = idPart.trim(); if (dbName != null) dbName = dbName.trim(); // try to find a standard URI, if exists, for a publication xref, or at least a standard name: if (dbName != null) { try { // try to get the preferred/standard name // for any type, for consistency dbName = MiriamLink.getName(dbName); // a shortcut: a standard and resolvable URI exists for some BioPAX types if ((type.equals(PublicationXref.class) && "pubmed".equalsIgnoreCase(dbName)) || type.equals(RelationshipTypeVocabulary.class) || ProteinReference.class.isAssignableFrom(type) || SmallMoleculeReference.class.isAssignableFrom(type) || (type.equals(BioSource.class) && "taxonomy".equalsIgnoreCase(dbName) && idPart!=null && idPart.matches("^\\d+$")) ) { //get the standard URI and quit (success), or fail and continue making a new URI below... return MiriamLink.getIdentifiersOrgURI(dbName, idPart); } } catch (IllegalArgumentException e) { log.info(String.format("uri(for a %s): db:%s, id:%s are not standard; %s)", type.getSimpleName(), dbName, idPart, e.getMessage())); } } // If not returned above this point - no standard URI (Identifiers.org) was found - // then let's consistently build a new URI from args, anyway, the other way around: StringBuilder sb = new StringBuilder(); if (dbName != null) //lowercase for consistency sb.append(dbName.toLowerCase()); if (idPart != null) { if (dbName != null) sb.append("_"); sb.append(idPart); } String localPart = sb.toString(); String strategy = System.getProperty(PROPERTY_NORMALIZER_URI_STRATEGY, VALUE_NORMALIZER_URI_STRATEGY_MD5); if(VALUE_NORMALIZER_URI_STRATEGY_SIMPLE.equals(strategy) || Xref.class.isAssignableFrom(type)) //i.e., for xrefs, always use the simple URI strategy (makes them human-readable) { //simply replace "unsafe" symbols with underscore (some uri clashes might be possible but rare...) localPart = localPart.replaceAll("[^-\\w]", "_"); } else { //replace the local part with its md5 sum string (32-byte) localPart = ModelUtils.md5hex(localPart); } // create URI using the xml:base and digest of other values: return ((xmlBase != null) ? xmlBase : "") + type.getSimpleName() + "_" + localPart; }
Consistently generates a new BioPAX element URI using given URI namespace (xml:base), BioPAX class, and two different identifiers (at least one is required). Miriam registry is used to get the standard db name and identifiers.org URI, if possible, only for relationship type vocabulary, publication xref, and entity reference types. @param xmlBase xml:base (common URI prefix for a BioPAX model), case-sensitive @param dbName a bio data collection name or synonym, case-insensitive @param idPart optional (can be null), e.g., xref.id, case-sensitive @param type BioPAX class @return URI @throws IllegalArgumentException if either type is null or both 'dbName' and 'idPart' are all nulls.
private UnificationXref findPreferredUnificationXref(XReferrable bpe) { UnificationXref toReturn = null; Collection<UnificationXref> orderedUrefs = getUnificationXrefsSorted(bpe); //use preferred db prefix for different type of ER if(bpe instanceof ProteinReference) { // prefer xref having db starts with "uniprot" (preferred) or "refseq"; toReturn = findSingleUnificationXref(orderedUrefs, "uniprot"); // if null, next try refseq. if(toReturn==null) toReturn = findSingleUnificationXref(orderedUrefs, "refseq"); } else if(bpe instanceof SmallMoleculeReference) { // - "chebi", then "pubchem"; toReturn = findSingleUnificationXref(orderedUrefs, "chebi"); if(toReturn==null) toReturn = findSingleUnificationXref(orderedUrefs, "pubchem"); } else if(bpe instanceof NucleicAcidReference) { //that includes NucleicAcidRegionReference, etc. sub-classes; toReturn = findSingleUnificationXref(orderedUrefs, "ncbi gene"); if(toReturn==null) toReturn = findSingleUnificationXref(orderedUrefs, "entrez"); } else { //for other XReferrable types (BioSource or ControlledVocabulary) //use if there's only one xref (return null if many) if(orderedUrefs.size()==1) toReturn = orderedUrefs.iterator().next(); } return toReturn; }
Finds one preferred unification xref, if possible. Preferred db values are: "ncbi gene" - for NucleicAcidReference and the sub-classes; "uniprot" or "refseq" for ProteinReference; "chebi" - for SmallMoleculeReference; @param bpe BioPAX object that can have xrefs @return the "best" first unification xref
public void normalize(Model model) { if(model.getLevel() != BioPAXLevel.L3) throw new IllegalArgumentException("Not Level3 model. " + "Consider converting it first (e.g., with the PaxTools)."); //if set, update the xml:base if(xmlBase != null && !xmlBase.isEmpty()) model.setXmlBase(xmlBase); // Normalize/merge xrefs, first, and then CVs // (also because some of original xrefs might have "normalized" URIs // that, in fact, must be used for other biopax types, such as CV or ProteinReference) log.info("Normalizing xrefs..." + description); normalizeXrefs(model); // fix displayName where possible if(fixDisplayName) { log.info("Normalizing display names..." + description); fixDisplayName(model); } log.info("Normalizing CVs..." + description); normalizeCVs(model); //normalize BioSource objects (better, as it is here, go after Xrefs and CVs) log.info("Normalizing organisms..." + description); normalizeBioSources(model); // auto-generate missing entity references: for(SimplePhysicalEntity spe : new HashSet<SimplePhysicalEntity>(model.getObjects(SimplePhysicalEntity.class))) { //it skips if spe has entityReference or memberPE already ModelUtils.addMissingEntityReference(model, spe); } log.info("Normalizing entity references..." + description); normalizeERs(model); // find/add lost (in replace) children log.info("Repairing..." + description); model.repair(); // it does not remove dangling utility class objects (can be done separately, later, if needed) log.info("Optional tasks (reasoning)..." + description); }
BioPAX normalization (modifies the original Model) @param model BioPAX model to normalize @throws NullPointerException if model is null @throws IllegalArgumentException if model is not Level3 BioPAX
public static void autoName(Provenance pro) { if(!(pro.getUri().startsWith("urn:miriam:") || pro.getUri().startsWith("http://identifiers.org/")) && pro.getName().isEmpty()) { log.info("Skipping: cannot normalize Provenance: " + pro.getUri()); } else { // i.e., 'name' is not empty or ID is the URN final SortedSet<String> names = new TreeSet<String>(); String key = null; if(pro.getUri().startsWith("urn:miriam:") || pro.getUri().startsWith("http://identifiers.org/")) { key = pro.getUri(); } else if (pro.getStandardName() != null) { key = pro.getStandardName(); } else { key = pro.getDisplayName(); // can be null } if (key != null) { try { names.addAll(Arrays.asList(MiriamLink.getNames(key))); pro.setStandardName(MiriamLink.getName(key)); // get the datasource description String description = MiriamLink.getDataTypeDef(pro.getStandardName()); pro.addComment(description); } catch (IllegalArgumentException e) { // ignore (then, names is still empty...) } } // when the above failed (no match in Miriam), or key was null - if(names.isEmpty()) { // finally, trying to find all valid names for each existing one for (String name : pro.getName()) { try { names.addAll(Arrays.asList(MiriamLink.getNames(name))); } catch (IllegalArgumentException e) { // ignore } } // pick up the first name, get the standard name if(!names.isEmpty()) pro.setStandardName(MiriamLink .getName(names.iterator().next())); } // and add all the synonyms if any for(String name : names) pro.addName(name); //set display name if not set (standard name is set already) if(pro.getDisplayName() == null) pro.setDisplayName(pro.getStandardName()); } }
Auto-generates standard and other names for the datasource from either its ID (if URN) or one of its existing names (preferably - standard name) @param pro data source (BioPAX Provenance)
public static String convertToLevel3(final String biopaxData) { String toReturn = ""; try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = new ByteArrayInputStream(biopaxData.getBytes()); SimpleIOHandler io = new SimpleIOHandler(); io.mergeDuplicates(true); Model model = io.convertFromOWL(is); if (model.getLevel() != BioPAXLevel.L3) { log.info("Converting to BioPAX Level3... " + model.getXmlBase()); model = (new LevelUpgrader()).filter(model); if (model != null) { io.setFactory(model.getLevel().getDefaultFactory()); io.convertToOWL(model, os); toReturn = os.toString(); } } else { toReturn = biopaxData; } } catch(Exception e) { throw new RuntimeException( "Cannot convert to BioPAX Level3", e); } return toReturn; }
Converts BioPAX L1 or L2 RDF/XML string data to BioPAX L3 string. WARN: this is not for huge (larger than 1GB) BioPAX RDF/XML data due to use of (UTF-8) String and Byte Array internally. This can be and is used by online web apps, such as the BioPAX Validator. @param biopaxData String @return BioPAX Level3 RDF/XML string
@Override public boolean satisfies(Match match, int... ind) { BioPAXElement ele0 = match.get(ind[0]); BioPAXElement ele1 = match.get(ind[1]); if (ele1 == null) return false; Set vals = pa.getValueFromBean(ele0); return vals.contains(ele1); }
Checks if the PathAccessor is generating the second mapped element. @param match current pattern match @param ind mapped indices @return true if second element is generated by PathAccessor
@Override public Collection<BioPAXElement> generate(Match match, int ... ind) { BioPAXElement ele0 = match.get(ind[0]); if (ele0 == null) throw new RuntimeException("Constraint cannot generate based on null value"); Set vals = pa.getValueFromBean(ele0); List<BioPAXElement> list = new ArrayList<BioPAXElement>(vals.size()); for (Object o : vals) { assert o instanceof BioPAXElement; list.add((BioPAXElement) o); } return list; }
Uses the encapsulated PAthAccessor to generate satisfying elements. @param match current pattern match @param ind mapped indices @return generated elements
@Override public boolean satisfies(Match match, int... ind) { assert ind.length == 2; return (match.get(ind[0]) == match.get(ind[1])) == equals; }
Checks if the two elements are identical or not identical as desired. @param match current pattern match @param ind mapped indices @return true if identity checks equals the desired value
public void writeToGSEA(final Model model, OutputStream out) throws IOException { Collection<GMTEntry> entries = convert(model); if (entries.size() > 0) { Writer writer = new OutputStreamWriter(out); for (GMTEntry entry : entries) { if ((minNumOfGenesPerEntry <= 1 && !entry.identifiers().isEmpty()) || entry.identifiers().size() >= minNumOfGenesPerEntry) { writer.write(entry.toString() + "\n"); } } writer.flush(); } }
Converts model to GSEA (GMT) and writes to out. See class declaration for more information. @param model Model @param out output stream to write the result to @throws IOException when there's an output stream error
public Collection<GMTEntry> convert(final Model model) { final Collection<GMTEntry> toReturn = new TreeSet<GMTEntry>(new Comparator<GMTEntry>() { @Override public int compare(GMTEntry o1, GMTEntry o2) { return o1.toString().compareTo(o2.toString()); } }); Model l3Model; // convert to level 3 in necessary if (model.getLevel() == BioPAXLevel.L2) l3Model = (new LevelUpgrader()).filter(model); else l3Model = model; //a modifiable copy of the set of all PRs in the model - //after all, it has all the PRs that do not belong to any pathway final Set<SequenceEntityReference> sequenceEntityReferences = new HashSet<SequenceEntityReference>(l3Model.getObjects(SequenceEntityReference.class)); final Set<Pathway> pathways = l3Model.getObjects(Pathway.class); for (Pathway pathway : pathways) { String name = (pathway.getDisplayName() == null) ? pathway.getStandardName() : pathway.getDisplayName(); if(name == null || name.isEmpty()) name = pathway.getUri(); final Pathway currentPathway = pathway; final String currentPathwayName = name; final boolean ignoreSubPathways = (!skipSubPathwaysOf.isEmpty() && shareSomeObjects(currentPathway.getDataSource(), skipSubPathwaysOf)) || skipSubPathways; LOG.debug("Begin converting " + currentPathwayName + " pathway, uri=" + currentPathway.getUri()); // collect sequence entity references from current pathway //TODO: add Fetcher.evidenceFilter? Fetcher fetcher = new Fetcher(SimpleEditorMap.L3, Fetcher.nextStepFilter); fetcher.setSkipSubPathways(ignoreSubPathways); Set<SequenceEntityReference> pathwaySers = fetcher.fetch(currentPathway, SequenceEntityReference.class); if(!pathwaySers.isEmpty()) { LOG.debug("For pathway: " + currentPathwayName + " (" + currentPathway.getUri() + "), got " + pathwaySers.size() + " sERs; now - grouping by organism..."); Map<String,Set<SequenceEntityReference>> orgToPrsMap = organismToProteinRefsMap(pathwaySers); // create GSEA/GMT entries - one entry per organism (null organism also makes one) String dataSource = getDataSource(currentPathway.getDataSource()); Collection<GMTEntry> entries = createGseaEntries(currentPathway.getUri(), currentPathwayName, dataSource, orgToPrsMap); if(!entries.isEmpty()) toReturn.addAll(entries); sequenceEntityReferences.removeAll(pathwaySers);//keep not processed PRs (a PR can be processed multiple times) LOG.debug("- collected " + entries.size() + "entries."); } } //when there're no pathways, only empty pathays, pathways w/o PRs, then use all/rest of PRs - //organize PRs by species (GSEA s/w can handle only same species identifiers in a data row) if(!sequenceEntityReferences.isEmpty() && !skipOutsidePathways) { LOG.info("Creating entries for the rest of PRs (outside any pathway)..."); Map<String,Set<SequenceEntityReference>> orgToPrsMap = organismToProteinRefsMap(sequenceEntityReferences); if(!orgToPrsMap.isEmpty()) { // create GSEA/GMT entries - one entry per organism (null organism also makes one) if(model.getUri()==null) { toReturn.addAll(createGseaEntries( "other", "other", getDataSource(l3Model.getObjects(Provenance.class)), orgToPrsMap)); } else { toReturn.addAll(createGseaEntries(model.getUri() , model.getName(), getDataSource(l3Model.getObjects(Provenance.class)), orgToPrsMap)); } } } return toReturn; }
Creates GSEA entries from the pathways contained in the model. @param model Model @return a set of GSEA entries
private Map<String, Set<SequenceEntityReference>> organismToProteinRefsMap(Set<SequenceEntityReference> seqErs) { Map<String,Set<SequenceEntityReference>> map = new HashMap<String, Set<SequenceEntityReference>>(); if(seqErs.isEmpty()) throw new IllegalArgumentException("Empty set"); if (crossSpeciesCheckEnabled) { for (SequenceEntityReference r : seqErs) { String key = getOrganismKey(r.getOrganism()); // null org. is ok (key == "") //collect PRs only from allowed organisms if(allowedOrganisms==null || allowedOrganisms.isEmpty() || allowedOrganisms.contains(key)) { Set<SequenceEntityReference> sers = map.get(key); if (sers == null) { sers = new HashSet<SequenceEntityReference>(); map.put(key, sers); } sers.add(r); } } } else { final Set<SequenceEntityReference> sers = new HashSet<SequenceEntityReference>(); for (SequenceEntityReference r : seqErs) { String key = getOrganismKey(r.getOrganism()); //collect PRs only from allowed organisms if(allowedOrganisms==null || allowedOrganisms.isEmpty() || allowedOrganisms.contains(key)) { sers.add(r); } } map.put("", sers); } return map; }
warn: there can be many equivalent BioSource objects (same taxonomy id, different URIs)
private String getDataSource(Set<Provenance> provenances) { if(provenances.isEmpty()) return "N/A"; Set<String> dsNames = new TreeSet<String>(); for (Provenance provenance : provenances) { String name = provenance.getDisplayName(); if(name == null) name = provenance.getStandardName(); if(name == null && !provenance.getName().isEmpty()) name = provenance.getName().iterator().next(); if (name != null && name.length() > 0) dsNames.add(name.toLowerCase()); } return StringUtils.join(dsNames, ";"); }
/* Gets datasource names, if any, in a consistent way/order, excl. duplicates
@Override public Set<R> getValueFromBean(D bean) throws IllegalBioPAXArgumentException { Object value = null; try { if (this.getDomain().isInstance(bean)) value = this.getMethod.invoke(bean); } catch (IllegalAccessException e) { throw new IllegalBioPAXArgumentException( "Could not invoke get method " + getMethod.getName() + " for " + bean, e); } catch (IllegalArgumentException e) { throw new IllegalBioPAXArgumentException( "Could not invoke get method " + getMethod.getName() + " for " + bean, e); } catch (InvocationTargetException e) { throw new IllegalBioPAXArgumentException( "Could not invoke get method " + getMethod.getName() + " for " + bean, e); } if (value == null) return Collections.emptySet(); else if (this.isMultipleCardinality()) { return (Collections.unmodifiableSet(((Set<R>) value))); } else { return Collections.singleton(((R) value)); } }
Returns the value of the <em>bean</em> using the default {@link #getMethod}. If the value is unknown returns null or an empty set depending on the cardinality. @param bean the object whose property is requested @return an object as the value
public boolean isUnknown(Object value) { return value == null || (value instanceof Set ? ((Set) value).isEmpty() : false); }
Checks if the <em>value</em> is unkown. In this context a <em>value</em> is regarded to be unknown if it is null (unset). @param value the value to be checked @return true if the value is unknown
public Collection<GMTEntry> convert(final Model model) { final Collection<GMTEntry> toReturn = new TreeSet<GMTEntry>(new Comparator<GMTEntry>() { @Override public int compare(GMTEntry o1, GMTEntry o2) { return o1.toString().compareTo(o2.toString()); } }); Model l3Model; // convert to level 3 in necessary if (model.getLevel() == BioPAXLevel.L2) l3Model = (new LevelUpgrader()).filter(model); else l3Model = model; //a modifiable copy of the set of all PRs in the model - //after all, it has all the ERs that do not belong to any pathway final Set<EntityReference> entityReferences = new HashSet<EntityReference>(l3Model.getObjects(EntityReference.class)); final Set<Pathway> pathways = l3Model.getObjects(Pathway.class); for (Pathway pathway : pathways) { String name = (pathway.getDisplayName() == null) ? pathway.getStandardName() : pathway.getDisplayName(); if(name == null || name.isEmpty()) name = pathway.getUri(); final Pathway currentPathway = pathway; final String currentPathwayName = name; LOG.debug("Begin converting " + currentPathwayName + " pathway, uri=" + currentPathway.getUri()); final Set<EntityReference> ers = new HashSet<EntityReference>(); final Traverser traverser = new AbstractTraverser(SimpleEditorMap.L3, Fetcher.nextStepFilter, Fetcher.objectPropertiesOnlyFilter) { @Override protected void visit(Object range, BioPAXElement domain, Model model, PropertyEditor editor) { BioPAXElement bpe = (BioPAXElement) range; //cast is safe (due to objectPropertiesOnlyFilter) if(bpe instanceof EntityReference) { ers.add((EntityReference) bpe); } if(bpe instanceof Pathway) { if(skipSubPathways) { //do not traverse into the sub-pathway; log LOG.debug("Skipping sub-pathway: " + bpe.getUri()); } else { traverse(bpe, model); } } else { traverse(bpe, model); } } }; //run it - collect all PRs from the pathway traverser.traverse(currentPathway, null); if(!ers.isEmpty()) { LOG.debug("For pathway: " + currentPathwayName + " (" + currentPathway.getUri() + "), got " + ers.size() + " ERs"); // create GMT entries Collection<GMTEntry> entries = createGseaEntries(currentPathway.getUri(), currentPathwayName, getDataSource(currentPathway.getDataSource()), ers); if(!entries.isEmpty()) toReturn.addAll(entries); entityReferences.removeAll(ers);//keep not processed PRs (a PR can be processed multiple times) LOG.debug("- collected " + entries.size() + "entries."); } } //when there're no pathways, only empty pathays, pathways w/o PRs, then use all/rest of PRs - //organize PRs by species (GSEA s/w can handle only same species identifiers in a data row) if(!entityReferences.isEmpty() && !skipOutsidePathways) { LOG.info("Creating entries for the rest of PRs (outside any pathway)..."); toReturn.addAll(createGseaEntries("other","other", getDataSource(l3Model.getObjects(Provenance.class)),entityReferences)); } return toReturn; }
Creates GMT entries from the pathways contained in the model. @param model Model @return a set of GMT entries
protected void addAccessor(PathAccessor acc, Class<? extends BioPAXElement> clazz) { accessors.put(acc, clazz); }
Adds the given <code>PathAccessor</code> to the list of accessors to use to get field values of objects and their related objects. @param acc accessor @param clazz the type of element that the accessor is applied
protected void addValidValue(String value) { if(value!=null && !value.isEmpty()) validValues.add(value.toLowerCase()); }
Adds the given valid value to the set of valid values. @param value a valid value
@Override public boolean okToTraverse(Level3Element ele) { if(validValues.isEmpty()) return true; boolean empty = true; boolean objectRelevant = false; for (PathAccessor acc : accessors.keySet()) { Class clazz = accessors.get(acc); if (!clazz.isAssignableFrom(ele.getClass())) continue; objectRelevant = true; Set values = acc.getValueFromBean(ele); if (empty) empty = values.isEmpty(); for (Object o : values) //ignoring capitalization (case) if (validValues.contains(o.toString().toLowerCase())) return true; } return !objectRelevant || (empty && isEmptyOK()); }
Checks if the related values of the object are among valid values. Returns true if none of the accessors is applicable to the given object. @param ele level 3 element to check @return true if ok to traverse
public int equivalenceCode() { int result = 29 + SEQUENCE_POSITION; result = 29 * result + (POSITION_STATUS != null ? POSITION_STATUS.hashCode() : 0); return result; }
------------------------ CANONICAL METHODS ------------------------
protected boolean semanticallyEquivalent(BioPAXElement element) { if (!(element instanceof sequenceSite)) { return false; } final sequenceSite that = (sequenceSite) element; return (SEQUENCE_POSITION == that.getSEQUENCE_POSITION()) && (POSITION_STATUS != null ? POSITION_STATUS.equals(that.getPOSITION_STATUS()) : that.getPOSITION_STATUS() == null); }
--------------------- Interface BioPAXElement ---------------------
public String getName(SmallMoleculeReference smr) { if (map.containsKey(smr)) return map.get(smr).getDisplayName(); else return smr.getDisplayName(); }
Gets the standard name of the small molecule. @param smr the molecule to check standard name @return standard name
public int equivalenceCode() { int result = 29 + (SEQUENCE_INTERVAL_BEGIN != null ? SEQUENCE_INTERVAL_BEGIN.hashCode() : 0); result = 29 * result + (SEQUENCE_INTERVAL_END != null ? SEQUENCE_INTERVAL_END.hashCode() : 0); return result; }
------------------------ CANONICAL METHODS ------------------------
protected boolean semanticallyEquivalent(BioPAXElement element) { if (!(element instanceof sequenceInterval)) { return false; } final sequenceInterval that = (sequenceInterval) element; return (SEQUENCE_INTERVAL_BEGIN != null ? SEQUENCE_INTERVAL_BEGIN.isEquivalent( that.getSEQUENCE_INTERVAL_BEGIN()) : that.getSEQUENCE_INTERVAL_BEGIN() == null) && (SEQUENCE_INTERVAL_END != null ? SEQUENCE_INTERVAL_END.isEquivalent( that.getSEQUENCE_INTERVAL_END()) : that.getSEQUENCE_INTERVAL_END() != null); }
--------------------- Interface BioPAXElement ---------------------
@Override public boolean satisfies(Match match, int... ind) { BioPAXElement ele1 = match.get(ind[0]); BioPAXElement ele2 = match.get(ind[1]); EntityReference er = ((SimplePhysicalEntity) ele1).getEntityReference(); Set set1 = pa.getValueFromBean(ele1); Set set2 = pa.getValueFromBean(ele2); Set gain = new HashSet(set2); gain.removeAll(set1); Set loss = new HashSet(set1); loss.removeAll(set2); int activatingCnt = 0; int inhibitingCnt = 0; for (Object o : gain) { if (activityFeat.get(er).contains(o)) activatingCnt++; if (inactivityFeat.get(er).contains(o)) inhibitingCnt++; } for (Object o : loss) { if (inactivityFeat.get(er).contains(o)) activatingCnt++; if (activityFeat.get(er).contains(o)) inhibitingCnt++; } // Match without considering the locations Set<String> gainTypes = null; Set<String> lossTypes = null; if (activatingCnt + inhibitingCnt == 0) { gainTypes = extractModifNames(gain); lossTypes = extractModifNames(loss); for (String s : gainTypes) { if (activityStr.get(er).contains(s)) activatingCnt++; if (inactivityStr.get(er).contains(s)) inhibitingCnt++; } for (String s : lossTypes) { if (inactivityStr.get(er).contains(s)) activatingCnt++; if (activityStr.get(er).contains(s)) inhibitingCnt++; } } // Try to match modifications with approximate name matching if (activatingCnt + inhibitingCnt == 0) { for (String genName : general) { boolean foundInActivating = setContainsGeneralTerm(activityStr.get(er), genName); boolean foundInInhibiting = setContainsGeneralTerm(inactivityStr.get(er), genName); if (foundInActivating == foundInInhibiting) continue; boolean foundInGain = setContainsGeneralTerm(gainTypes, genName); boolean foundInLose = setContainsGeneralTerm(lossTypes, genName); if (foundInGain == foundInLose) continue; if (foundInActivating && foundInGain) activatingCnt++; else if (foundInInhibiting && foundInLose) activatingCnt++; else if (foundInActivating && foundInLose) inhibitingCnt++; else /*if (foundInInhibiting && foundInGain)*/ inhibitingCnt++; } } if (activatingCnt > 0 && inhibitingCnt > 0) return false; return activating ? activatingCnt > 0 : inhibitingCnt > 0; }
Checks the gained and and lost features to predict the activity change is the desired change. If exact matching (terms with locations) is not conclusive, then terms without locations are checked. If still not conclusive, then approximate matching is used. @param match current pattern match @param ind mapped indices @return true if the modification gain or loss is mapped to the desired change
protected Map<EntityReference, Set<String>> extractModifNames(Map mfMap) { Map<EntityReference, Set<String>> map = new HashMap<EntityReference, Set<String>>(); for (Object o : mfMap.keySet()) { EntityReference er = (EntityReference) o; map.put(er, extractModifNames((Set) mfMap.get(er))); } return map; }
Extracts the modification terms from the moficiation features. @param mfMap map for the features @return map from EntityReference to the set of the extracted terms
protected Set<String> extractModifNames(Set mfSet) { Set<String> set = new HashSet<String>(); for (Object o : mfSet) { ModificationFeature mf = (ModificationFeature) o; if (mf.getModificationType() != null && !mf.getModificationType().getTerm().isEmpty()) { set.add(mf.getModificationType().getTerm().iterator().next()); } } return set; }
Extracts terms of the modification features. @param mfSet set of modification features @return set of extracted terms
protected boolean setContainsGeneralTerm(Set<String> set, String term) { for (String s : set) { if (s.contains(term)) return true; } return false; }
Checks if any element in the set contains the term. @param set set to check @param term term to search for @return true if any element contains the term
public E get(String uri) { if(map==empty) return null; synchronized (map) { return map.get(uri); } }
Gets a BioPAX element by URI. @param uri absolute URI of a BioPAX individual @return BioPAX object or null
public int equivalenceCode() { int result = 29 + K_PRIME != +0.0f ? Float.floatToIntBits(K_PRIME) : 0; result = 29 * result + TEMPERATURE != +0.0f ? Float.floatToIntBits(TEMPERATURE) : 0; result = 29 * result + IONIC_STRENGTH != +0.0f ? Float.floatToIntBits(IONIC_STRENGTH) : 0; result = 29 * result + PH != +0.0f ? Float.floatToIntBits(PH) : 0; result = 29 * result + PMG != +0.0f ? Float.floatToIntBits(PMG) : 0; return result; }
------------------------ CANONICAL METHODS ------------------------
protected boolean semanticallyEquivalent(BioPAXElement element) { final kPrime aKPrime = (kPrime) element; return (Float.compare(aKPrime.getIONIC_STRENGTH(), IONIC_STRENGTH) == 0) && (Float.compare(aKPrime.getK_PRIME(), K_PRIME) == 0) && (Float.compare(aKPrime.getPH(), PH) == 0) && (Float.compare(aKPrime.getPMG(), PMG) == 0) && (Float.compare(aKPrime.getTEMPERATURE(), TEMPERATURE) == 0); }
--------------------- Interface BioPAXElement ---------------------
@Override public void initUpstream() { for (Controller controller : ctrl.getController()) { if (controller instanceof Pathway) continue; PhysicalEntity pe = (PhysicalEntity) controller; bindUpstream(pe); } for (Control control : ctrl.getControlledOf()) { bindUpstream(control); } }
Binds the controller and other Controls that controls this control.
@Override public void initDownstream() { for (Process prc : ctrl.getControlled()) { if (prc instanceof Conversion || prc instanceof Control || prc instanceof TemplateReaction) { AbstractNode node = (AbstractNode) graph.getGraphObject(prc); if (node != null) { Edge edge = new EdgeL3(this, node, graph); node.getUpstreamNoInit().add(edge); getDownstreamNoInit().add(edge); } } } }
Binds the controlled objects.
public synchronized void replace(final BioPAXElement existing, final BioPAXElement replacement) { ModelUtils.replace(this, Collections.singletonMap(existing, replacement)); remove(existing); if(replacement != null) add(replacement); }
It does not automatically replace or clean up the old element's object properties, therefore, some child elements may become "dangling" if they were used by the replaced element only. Can also clear object properties (- replace with null).
public synchronized void merge(Model source) { SimpleMerger merger = new SimpleMerger( SimpleEditorMap.get(level)); if(source == null) merger.merge(this, this); //repairs itself else merger.merge(this, source); }
This is default implementation that uses the id-based merging ({@link SimpleMerger#merge(Model, Model...)}) NOTE: some applications, such as those dealing with persistence/transactions or advanced BioPAX alignment/comparison algorithms (like the Patch), may have to implement and use a more specific method instead. @see SimpleMerger @see Model#merge(Model)
private void init() { setSize(600, 400); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new BorderLayout()); getContentPane().setBackground(BACKGROUND); JPanel modelPanel = new JPanel(new GridBagLayout()); pcRadio = new JRadioButton("Use Pathway Commons"); pcRadio.addActionListener(this); pcRadio.setBackground(BACKGROUND); GridBagConstraints con = new GridBagConstraints(); con.gridx = 0; con.gridy = 0; con.anchor = GridBagConstraints.LINE_START; modelPanel.add(pcRadio, con); pcCombo = new JComboBox(PC_RES_NAMES); pcCombo.setBackground(BACKGROUND); con = new GridBagConstraints(); con.gridx = 1; con.gridy = 0; con.anchor = GridBagConstraints.CENTER; con.ipadx = 5; modelPanel.add(pcCombo, con); customFileRadio = new JRadioButton("Use custom file"); customFileRadio.addActionListener(this); customFileRadio.setBackground(BACKGROUND); con = new GridBagConstraints(); con.gridx = 0; con.gridy = 1; con.anchor = GridBagConstraints.LINE_START; modelPanel.add(customFileRadio, con); JPanel modelChooserPanel = new JPanel(new FlowLayout()); modelField = new JTextField(15); modelField.addKeyListener(this); modelField.setEnabled(false); modelChooserPanel.add(modelField); loadButton = new JButton("Load"); loadButton.addActionListener(this); loadButton.setEnabled(false); modelChooserPanel.add(loadButton); modelChooserPanel.setBackground(BACKGROUND); con = new GridBagConstraints(); con.gridx = 1; con.gridy = 1; con.anchor = GridBagConstraints.CENTER; modelPanel.add(modelChooserPanel, con); customURLRadio = new JRadioButton("Use the owl at URL"); customURLRadio.addActionListener(this); customURLRadio.setBackground(BACKGROUND); con = new GridBagConstraints(); con.gridx = 0; con.gridy = 2; con.anchor = GridBagConstraints.LINE_START; modelPanel.add(customURLRadio, con); urlField = new JTextField(15); urlField.addKeyListener(this); urlField.setEnabled(false); con = new GridBagConstraints(); con.gridx = 1; con.gridy = 2; con.anchor = GridBagConstraints.LINE_START; modelPanel.add(urlField, con); ButtonGroup group = new ButtonGroup(); group.add(pcRadio); group.add(customFileRadio); group.add(customURLRadio); group.setSelected(pcRadio.getModel(), true); modelPanel.setBorder(BorderFactory.createTitledBorder("Source model")); modelPanel.setBackground(BACKGROUND); getContentPane().add(modelPanel, BorderLayout.NORTH); JPanel minerPanel = new JPanel(new BorderLayout()); minerPanel.setBackground(BACKGROUND); minerPanel.setBorder(BorderFactory.createTitledBorder("Pattern to search")); JPanel comboPanel = new JPanel(new FlowLayout()); comboPanel.setBackground(BACKGROUND); JLabel patternLabel = new JLabel("Pattern: "); patternCombo = new JComboBox(getAvailablePatterns()); patternCombo.addActionListener(this); patternCombo.setBackground(BACKGROUND); comboPanel.add(patternLabel); comboPanel.add(patternCombo); minerPanel.add(comboPanel, BorderLayout.NORTH); descArea = new JTextArea(30, 3); descArea.setEditable(false); descArea.setBorder(BorderFactory.createTitledBorder("Description")); descArea.setText(((Miner) patternCombo.getSelectedItem()).getDescription()); descArea.setLineWrap(true); descArea.setWrapStyleWord(true); minerPanel.add(descArea, BorderLayout.CENTER); JPanel progressPanel = new JPanel(new GridBagLayout()); progressPanel.setBackground(BACKGROUND); prgLabel = new JLabel(" "); prgBar = new JProgressBar(); prgBar.setStringPainted(true); prgBar.setVisible(false); con = new GridBagConstraints(); con.gridx = 0; con.anchor = GridBagConstraints.CENTER; con.ipady = 12; con.ipadx = 10; progressPanel.add(prgLabel, con); con = new GridBagConstraints(); con.gridx = 1; con.anchor = GridBagConstraints.LINE_END; progressPanel.add(prgBar, con); minerPanel.add(progressPanel, BorderLayout.SOUTH); getContentPane().add(minerPanel, BorderLayout.CENTER); JPanel finishPanel = new JPanel(new BorderLayout()); JPanel lowerPanel = new JPanel(new FlowLayout()); lowerPanel.setBackground(BACKGROUND); outputField = new JTextField(20); outputField.setBorder(BorderFactory.createTitledBorder("Output file")); outputField.addActionListener(this); outputField.addKeyListener(this); outputField.setText(((Miner) patternCombo.getSelectedItem()).getName() + ".txt"); finishPanel.add(outputField, BorderLayout.WEST); runButton = new JButton("Run"); runButton.addActionListener(this); finishPanel.add(runButton, BorderLayout.EAST); JPanel bufferPanel = new JPanel(new FlowLayout()); bufferPanel.setMinimumSize(new Dimension(300, 10)); bufferPanel.setBackground(BACKGROUND); bufferPanel.add(new JLabel(" ")); finishPanel.add(bufferPanel, BorderLayout.CENTER); finishPanel.setBackground(BACKGROUND); lowerPanel.add(finishPanel); getContentPane().add(lowerPanel, BorderLayout.SOUTH); }
Initializes GUI elements.
private int getMaxMemory() { int total = 0; for (MemoryPoolMXBean mpBean: ManagementFactory.getMemoryPoolMXBeans()) { if (mpBean.getType() == MemoryType.HEAP) { total += mpBean.getUsage().getMax() >> 20; } } return total; }
Gets the maximum memory heap size for the application. This size can be modified by passing -Xmx option to the virtual machine, like "java -Xmx5G MyClass.java". @return maximum memory heap size in megabytes
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == pcRadio || e.getSource() == customFileRadio || e.getSource() == customURLRadio) { pcCombo.setEnabled(pcRadio.isSelected()); modelField.setEnabled(customFileRadio.isSelected()); loadButton.setEnabled(customFileRadio.isSelected()); urlField.setEnabled(customURLRadio.isSelected()); } else if (e.getSource() == loadButton) { String current = modelField.getText(); String initial = current.trim().length() > 0 ? current : "."; JFileChooser fc = new JFileChooser(initial); fc.setFileFilter(new FileNameExtensionFilter("BioPAX file (*.owl)", "owl")); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); modelField.setText(file.getPath()); } } else if (e.getSource() == patternCombo) { Miner m = (Miner) patternCombo.getSelectedItem(); descArea.setText(m.getDescription()); // Update output file name String text = outputField.getText(); if (text.contains("/")) text = text.substring(0, text.lastIndexOf("/") + 1); else text = ""; text += m.getName() + ".txt"; outputField.setText(text); } else if (e.getSource() == runButton) { run(); } checkRunButton(); }
Performs interactive operations. @param e current event
private void checkRunButton() { runButton.setEnabled((pcRadio.isSelected() || (customFileRadio.isSelected() && !modelField.getText().trim().isEmpty()) || (customURLRadio.isSelected() && !urlField.getText().trim().isEmpty())) && !outputField.getText().trim().isEmpty()); }
Checks if the run button should be enabled.
private Object[] getAvailablePatterns() { List<Miner> minerList = new ArrayList<Miner>(); if (miners != null && miners.length > 0) { minerList.addAll(Arrays.asList(miners)); } else { minerList.add(new DirectedRelationMiner()); minerList.add(new ControlsStateChangeOfMiner()); minerList.add(new CSCOButIsParticipantMiner()); minerList.add(new CSCOBothControllerAndParticipantMiner()); minerList.add(new CSCOThroughControllingSmallMoleculeMiner()); minerList.add(new CSCOThroughBindingSmallMoleculeMiner()); minerList.add(new ControlsStateChangeDetailedMiner()); minerList.add(new ControlsPhosphorylationMiner()); minerList.add(new ControlsTransportMiner()); minerList.add(new ControlsExpressionMiner()); minerList.add(new ControlsExpressionWithConvMiner()); minerList.add(new CSCOThroughDegradationMiner()); minerList.add(new ControlsDegradationIndirectMiner()); minerList.add(new ConsumptionControlledByMiner()); minerList.add(new ControlsProductionOfMiner()); minerList.add(new CatalysisPrecedesMiner()); minerList.add(new ChemicalAffectsThroughBindingMiner()); minerList.add(new ChemicalAffectsThroughControlMiner()); minerList.add(new ControlsTransportOfChemicalMiner()); minerList.add(new InComplexWithMiner()); minerList.add(new InteractsWithMiner()); minerList.add(new NeighborOfMiner()); minerList.add(new ReactsWithMiner()); minerList.add(new UsedToProduceMiner()); minerList.add(new RelatedGenesOfInteractionsMiner()); minerList.add(new UbiquitousIDMiner()); } for (Miner miner : minerList) { if (miner instanceof MinerAdapter) ((MinerAdapter) miner).setBlacklist(blacklist); } return minerList.toArray(new Object[minerList.size()]); }
Gets the available pattern miners. First lists the parameter miners, then adds the known miners in the package. @return pattern miners
private void mine() { Miner miner = (Miner) patternCombo.getSelectedItem(); if (miner instanceof MinerAdapter) ((MinerAdapter) miner).setIDFetcher(new CommonIDFetcher()); // Constructing the pattern before loading any model for a debug friendly code. Otherwise if // loading model takes time and an exception occurs in pattern construction, it is just too // much wait for nothing. ((Miner) patternCombo.getSelectedItem()).getPattern(); // Prepare progress bar ProgressWatcher prg = new ProgressWatcher() { @Override public synchronized void setTotalTicks(int total) { prgBar.setMaximum(total); } @Override public synchronized void tick(int times) { prgBar.setValue(prgBar.getValue() + times); } }; prgBar.setVisible(true); // Get the model file File modFile; if (pcRadio.isSelected()) { if (getMaxMemory() < 4000) { showMessageDialog(this, "Maximum memory not large enough for handling\n" + "Pathway Commons data. But will try anyway.\n" + "Please consider running this application with the\n" + "virtual machine parameter \"-Xmx5G\"."); } modFile = new File(getPCFilename()); if (!modFile.exists()) { prgLabel.setText("Downloading model"); if (!downloadPC(prg)) { eraseProgressBar(); showMessageDialog(this, "Cannot download Pathway Commons data for some reason. Sorry."); return; } assert modFile.exists(); } } else if (customFileRadio.isSelected()) { modFile = new File(modelField.getText()); } else if (customURLRadio.isSelected()) { String url = urlField.getText().trim(); prgLabel.setText("Downloading model"); if (url.endsWith(".gz")) downloadCompressed(prg, url, "temp.owl", true); else if (url.endsWith(".zip")) downloadCompressed(prg, url, "temp.owl", false); else downloadPlain(url, "temp.owl"); modFile = new File("temp.owl"); if (!modFile.exists()) { showMessageDialog(this, "Cannot download the model at the given URL."); eraseProgressBar(); return; } } else { throw new RuntimeException("Code should not be able to reach here!"); } // Get the output file File outFile = new File(outputField.getText()); try { BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); writer.write("x"); writer.close(); outFile.delete(); } catch (IOException e) { e.printStackTrace(); eraseProgressBar(); showMessageDialog(this, "Cannot write to file: " + outFile.getPath()); return; } // Load model prgLabel.setText("Loading the model"); prgBar.setIndeterminate(true); prgBar.setStringPainted(false); SimpleIOHandler io = new SimpleIOHandler(); Model model; try { model = io.convertFromOWL(new FileInputStream(modFile)); prgBar.setIndeterminate(false); prgBar.setStringPainted(true); } catch (FileNotFoundException e) { e.printStackTrace(); eraseProgressBar(); showMessageDialog(this, "File not found: " + modFile.getPath()); return; } // Search Miner min = (Miner) patternCombo.getSelectedItem(); Pattern p = min.getPattern(); prgLabel.setText("Searching the pattern"); prgBar.setValue(0); Map<BioPAXElement,List<Match>> matches = Searcher.search(model, p, prg); if (matches.isEmpty()) { prgLabel.setText("No results found!"); } else { try { prgLabel.setText("Writing result"); prgBar.setValue(0); prgBar.setStringPainted(false); prgBar.setIndeterminate(true); FileOutputStream os = new FileOutputStream(outFile); min.writeResult(matches, os); os.close(); prgBar.setIndeterminate(false); } catch (IOException e) { e.printStackTrace(); eraseProgressBar(); showMessageDialog(this, "Error occurred while writing the results"); return; } prgLabel.setText("Success! "); System.out.println("Success!"); this.dispose(); } }
Executes the pattern search.
public void validate(boolean autofix, String profile, RetFormat retFormat, Behavior filterBy, Integer maxErrs, String biopaxUrl, File[] biopaxFiles, OutputStream out) throws IOException { MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.setCharset(Charset.forName("UTF-8")); if(autofix) meb.addTextBody("autofix", "true"); //TODO add extra options (normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource, normalizer.xmlBase)? if(profile != null && !profile.isEmpty()) meb.addTextBody("profile", profile); if(retFormat != null) meb.addTextBody("retDesired", retFormat.toString().toLowerCase()); if(filterBy != null) meb.addTextBody("filter", filterBy.toString()); if(maxErrs != null && maxErrs > 0) meb.addTextBody("maxErrors", maxErrs.toString()); if(biopaxFiles != null && biopaxFiles.length > 0) for (File f : biopaxFiles) //important: use MULTIPART_FORM_DATA content-type meb.addBinaryBody("file", f, ContentType.MULTIPART_FORM_DATA, f.getName()); else if(biopaxUrl != null) { meb.addTextBody("url", biopaxUrl); } else { log.error("Nothing to do (no BioPAX data specified)!"); return; } //execute the query and get results as string HttpEntity httpEntity = meb.build(); // httpEntity.writeTo(System.err); String content = Executor.newInstance()//Executor.newInstance(httpClient) .execute(Request.Post(url).body(httpEntity)) .returnContent().asString(); //save: append to the output stream (file) BufferedReader res = new BufferedReader(new StringReader(content)); String line; PrintWriter writer = new PrintWriter(out); while((line = res.readLine()) != null) { writer.println(line); } writer.flush(); res.close(); }
Checks a BioPAX OWL file(s) or resource using the online BioPAX Validator and prints the results to the output stream. @param autofix true/false (experimental) @param profile validation profile name @param retFormat xml, html, or owl (no errors, just modified owl, if autofix=true) @param filterBy filter validation issues by the error/warning level @param maxErrs errors threshold - max no. critical errors to collect before quitting (warnings not counted; null/0/negative value means unlimited) @param biopaxUrl check the BioPAX at the URL @param biopaxFiles an array of BioPAX files to validate @param out validation report data output stream @throws IOException when there is an I/O error
public static ValidatorResponse unmarshal(String xml) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance("org.biopax.validator.jaxb"); Unmarshaller un = jaxbContext.createUnmarshaller(); Source src = new StreamSource(new StringReader(xml)); ValidatorResponse resp = un.unmarshal(src, ValidatorResponse.class).getValue(); return resp; }
Converts a biopax-validator XML response to the java object. @param xml input XML data - validation report - to import @return validation report object @throws JAXBException when there is an JAXB unmarshalling error
public static Set<? extends BioPAXElement> getObjectBiopaxPropertyValues(BioPAXElement bpe, String property) { Set<BioPAXElement> values = new HashSet<BioPAXElement>(); // get the BioPAX L3 property editors map EditorMap em = SimpleEditorMap.L3; // get the 'organism' biopax property editor, // if exists for this type of bpe @SuppressWarnings("unchecked") PropertyEditor<BioPAXElement, BioPAXElement> editor = (PropertyEditor<BioPAXElement, BioPAXElement>) em .getEditorForProperty(property, bpe.getModelInterface()); // if the biopax object does have such property, get values if (editor != null) { return editor.getValueFromBean(bpe); } else return values; }
Example 1. How to get values from an object biopax property if the type of the biopax object is not known at runtime, and you do not want to always remember the domain and range of the property nor write many if-else statements to find out. @param bpe BioPAX object @param property BioPAX property @return the BioPAX object property values or empty set
public static Set getBiopaxPropertyValues(BioPAXElement bpe, String property) { // get the BioPAX L3 property editors map EditorMap em = SimpleEditorMap.L3; // get the 'organism' biopax property editor, // if exists for this type of bpe @SuppressWarnings("unchecked") PropertyEditor<BioPAXElement, Object> editor = (PropertyEditor<BioPAXElement, Object>) em .getEditorForProperty(property, bpe.getModelInterface()); // if the biopax object does have such property, get values if (editor != null) { return editor.getValueFromBean(bpe); } else return null; }
Example 2. How to get values from a biopax property if the type of the biopax object is not known at runtime, and you do not want to always remember the domain and range of the property nor write many if-else statements to find out. @param bpe BioPAX object @param property BioPAX property @return the BioPAX property values or null
public void processRequest(RequestContext context) throws Exception { if (processorIterator.hasNext()){ RequestSecurityProcessor processor = processorIterator.next(); logger.debug("Executing processor {}", processor); processor.processRequest(context, this); } }
Calls the next {@link RequestSecurityProcessor} of the iterator. @param context the request context @throws Exception
@Override public void to(final NodeDescriptor descriptor, final OutputStream output) throws DescriptorExportException, IllegalArgumentException { // Precondition checks if (descriptor == null) { throw new IllegalArgumentException("descriptor must be specified"); } if (output == null) { throw new IllegalArgumentException("stream must be specified"); } // Get the root node final Node root = descriptor.getRootNode(); // Delegate this.to(root, output); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorExporter#to(org.jboss.shrinkwrap.descriptor.api.Descriptor, java.io.OutputStream)
@Override public T fromFile(final File file) throws IllegalArgumentException, DescriptorImportException { // Precondition checks if (file == null) { throw new IllegalArgumentException("File not specified"); } // Delegate try { return this.fromStream(new FileInputStream(file)); } catch (final FileNotFoundException e) { throw new IllegalArgumentException("Specified file does not exist or is a directory: " + file.getAbsolutePath()); } }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromFile(java.io.File)
@Override @Deprecated public T from(final String string) throws IllegalArgumentException, DescriptorImportException { return fromString(string); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#from(java.lang.String)
@Override public T fromString(final String string) throws IllegalArgumentException, DescriptorImportException { // Precondition check if (string == null) { throw new IllegalArgumentException("Input must be specified"); } // Check if empty String if (string.trim().length() == 0) { return endUserViewImplType.cast(ApiExposition.createFromImplModelType(endUserViewImplType, descriptorName)); } // Return return this.fromStream(new ByteArrayInputStream(string.getBytes())); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#from(java.lang.String)
@Override public T fromStream(final InputStream in) throws IllegalArgumentException, DescriptorImportException { return fromStream(in, true); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromStream(java.io.InputStream)
@Override public T fromFile(final String file) throws IllegalArgumentException, DescriptorImportException { return this.from(new File(file)); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#fromFile(java.lang.String)
@Override public T from(final InputStream in, boolean close) throws IllegalArgumentException, DescriptorImportException { return this.fromStream(in, close); }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.DescriptorImporter#from(java.io.InputStream, boolean)
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception { HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); HttpServletRequest wrappedSavedRequest = requestCache.getMatchingRequest(request, response); if (wrappedSavedRequest != null) { logger.debug("A previously saved request was found, and has been merged with the current request"); context.setRequest(wrappedSavedRequest); } processorChain.processRequest(context); }
Checks if there's a request in the request cache (which means that a previous request was cached). If there's one, the request cache creates a new request by merging the saved request with the current request. The new request is used through the rest of the processor chain. @param context the context which holds the current request and response @param processorChain the processor chain, used to call the next processor
@Override // TODO Accept final values // TODO put explicit IllegalArgumentException in throws clause (just to be clear) public FilterMutableType description(final String... values) throws IllegalArgumentException { // TODO Added precondition checks per the docs for (final String name : values) { if (name == null || name.length() == 0) { throw new IllegalArgumentException("no value for description may be null or blank"); } this.getRootNode().createChild("description").text(name); } return this; }
TODO Add @Override
@Override public FilterMutableType removeDescription(final String value) throws IllegalArgumentException { // Precondition checks if (value == null || value.length() == 0) { throw new IllegalArgumentException("value must be specified"); } // Get all "description" elements final List<Node> descriptions = this.getRootNode().get("description"); if (descriptions != null) { // For each description for (final Node description : descriptions) { // If matches if (description.getText().equals(value)) { // Remove description.getParent().removeChild(description); System.out.println(description); } } } // Return return this; }
{@inheritDoc} @see org.jboss.shrinkwrap.descriptor.api.webcommon30.FilterMutableTypeBase#removeDescription(java.lang.String)
public static void simpleTransform(final String sourcePath, final String xsltPath, final String resultDir, final Map<String, String> parameters) throws TransformerException { final TransformerFactory tFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null); final Transformer transformer = tFactory.newTransformer(new StreamSource(new File(xsltPath))); applyParameters(transformer, parameters); transformer.transform(new StreamSource(new File(sourcePath)), new StreamResult(new File(resultDir))); }
Simple transformation method. @param sourcePath - Absolute path to source xml file. @param xsltPath - Absolute path to xslt file. @param resultDir - Directory where you want to put resulting files. @param parameters - Map defining global XSLT parameters based via tranformer to the XSLT file. @throws TransformerException
public static void simpleTransform(final String contextFile, final InputStream xsltSource, final File result, final Map<String, String> parameters) throws TransformerException { final TransformerFactory tFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null); final Transformer transformer = tFactory.newTransformer(new StreamSource(xsltSource)); applyParameters(transformer, parameters); transformer.transform(new StreamSource(new File(contextFile)), new StreamResult(result)); }
Simple transformation method. @param contextFile - Absolute path to source xml file. @param StreamSource - the xslt file. @param resultDir - Directory where you want to put resulting files. @param parameters - Map defining global XSLT parameters based via transformer to the XSLT file. @throws TransformerException
private static void applyParameters(final Transformer transformer, final Map<String, String> parameters) { final Set<String> keys = parameters.keySet(); for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) { final String key = iterator.next(); transformer.setParameter(key, parameters.get(key)); } }
Applies all key/value pairs as defined by the given <code>Map</code> to the given <code>Transformer</code> instance. @param transformer @param parameters
@Override public void handle(RequestContext context) throws SecurityProviderException, IOException { RedirectUtils.redirect(context.getRequest(), context.getResponse(), getTargetUrl()); }
Redirects to the target URL. @param context the request context
public void addEnumValue(final String enumName, final String enumValue) { for (MetadataEnum instance : enumList) { if (instance.getName().equals(enumName) && instance.getNamespace().equals(getCurrentNamespace())) { instance.addValue(enumValue); return; } } final MetadataEnum newEnum = new MetadataEnum(enumName); newEnum.addValue(enumValue); newEnum.setNamespace(getCurrentNamespace()); newEnum.setSchemaName(getCurrentSchmema()); newEnum.setPackageApi(getCurrentPackageApi()); enumList.add(newEnum); }
Adds a enumeration value to the specified enumeration name. If no enumeration class is found, then a new enumeration class will be created. @param enumName the enumeration class name. @param enumValue the new enumeration value.