code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
private void normalize(Model model) { /* If a pE participates via pEP, no problem. * Otherwise, - there is a special case. * * physicalEntity PARTICIPANT takes part in interactions * either directly or via physicalEntityParticipant (pEP). * With pEP, the corresponding L3 PE and ER have been * already created (above). However, although (if no pEPs used) * we got Complex and basic PhysicalEntity objects created in L3, * and others (protein, dna, etc.) became ER, we still have to * create another PEs for all of them and set their ER property (where exists). */ for (interaction itr : model.getObjects(interaction.class)) { if(itr instanceof conversion || itr instanceof control) continue; // cannot have pE participants anyway (only pEPs) for (InteractionParticipant ip : itr.getPARTICIPANTS()) { if (ip instanceof physicalEntity) { physicalEntity pe = (physicalEntity) ip; // create a new pEP String newId = itr.getUri() + "_" + getLocalId(pe); physicalEntityParticipant pep = model.addNew(physicalEntityParticipant.class, newId); pep.setPHYSICAL_ENTITY(pe); // no other properties though // reset participant itr.removePARTICIPANTS(pe); itr.addPARTICIPANTS(pep); } } } // ...adding step processes to the pathway components (L3) is NOT always required // TODO remove cloned UtilityClass elements // set 'name' for simple physical entities (because pEPs didn't have names) for(EntityReference er : model.getObjects(EntityReference.class)) { for(SimplePhysicalEntity spe : er.getEntityReferenceOf()) { // after the conversion, it's always empty.., but let's double-check if(spe.getName().isEmpty()) { spe.getName().addAll(er.getName()); } if(spe.getDisplayName() == null || spe.getDisplayName().trim().length() == 0) { spe.setDisplayName(er.getDisplayName()); } } } }
/* Fixes several problems in the BioPAX model
private Level3Element mapClass(BioPAXElement bpe) { Level3Element newElement = null; if(bpe instanceof physicalEntityParticipant) { String id = pep2PE.get(bpe.getUri()); if(id == null) { log.warn("No mapping possible for " + bpe.getUri()); return null; } else if (id.equals(bpe.getUri())) { // create a new simplePhysicalEntity //(excluding Complex and basic PhysicalEntity that map directly and have no ERs) newElement = createSimplePhysicalEntity((physicalEntityParticipant)bpe); } } else if(!(bpe instanceof openControlledVocabulary)) // skip oCVs { // using classesmap.properties to map other types String type = bpe.getModelInterface().getSimpleName(); String newType = classesmap.getProperty(type).trim(); if (newType != null && factory.canInstantiate(factory.getLevel().getInterfaceForName(newType))) { newElement = (Level3Element) factory.create(newType, bpe.getUri()); } else { if(log.isDebugEnabled()) log.debug("No mapping found for " + type); return null; } } return newElement; }
creates L3 classes and sets IDs
private SimplePhysicalEntity createSimplePhysicalEntity(physicalEntityParticipant pep) { physicalEntity pe2 = pep.getPHYSICAL_ENTITY(); return createSimplePhysicalEntity(pe2, pep.getUri()); }
/* Create L3 simple PE type using the L2 pEP. When pEP's PHYSICAL_ENTITY is either complex or basic physicalEntity, null will be the result.
private ControlledVocabulary convertAndAddVocabulary(openControlledVocabulary value, Level2Element parent, Model newModel, PropertyEditor newEditor) { String id = ((BioPAXElement) value).getUri(); if (!newModel.containsID(id)) { if (newEditor != null) { newModel.addNew(newEditor.getRange(), id); // copy properties traverse(value, newModel); } else { log.warn("Cannot Convert CV: " + value + " (for prop.: " + newEditor + ")"); } } return (ControlledVocabulary) newModel.getByID(id); }
/* Creates a specific ControlledVocabulary subclass and adds to the new model
protected void visit(Object value, BioPAXElement parent, Model newModel, PropertyEditor editor) { if(editor != null && editor.isUnknown(value)) { return; } String parentType = parent.getModelInterface().getSimpleName(); BioPAXElement newParent = null; Object newValue = value; String newProp = propsmap.getProperty(editor.getProperty()); // special case (PATHWAY-COMPONENTS maps to pathwayComponent or pathwayOrder) if(parent instanceof pathway && value instanceof pathwayStep && editor.getProperty().equals("PATHWAY-COMPONENTS")) { newProp = "pathwayOrder"; } // for pEPs, getting the corresponding simple PE or Complex is different if(parent instanceof physicalEntityParticipant) { newParent = getMappedPE((physicalEntityParticipant) parent, newModel); } else { newParent = newModel.getByID(parent.getUri()); } // bug check! if(newParent == null) { throw new IllegalAccessError("Of " + value + ", parent " + parentType + " : " + parent + " is not yet in the new model: "); } PropertyEditor newEditor = SimpleEditorMap.L3.getEditorForProperty(newProp, newParent.getModelInterface()); if(value instanceof Level2Element) // not a String, Enum, or primitive type { // when pEP, create/add stoichiometry! if(value instanceof physicalEntityParticipant) { physicalEntityParticipant pep = (physicalEntityParticipant) value; newValue = getMappedPE(pep, newModel); float coeff = (float) pep.getSTOICHIOMETRIC_COEFFICIENT(); if (coeff > 1 ) { //!= BioPAXElement.UNKNOWN_DOUBLE) { if(parent instanceof conversion || parent instanceof complex) { PhysicalEntity pe3 = (PhysicalEntity) newValue; Stoichiometry stoichiometry = factory .create(Stoichiometry.class, pe3.getUri() + "-stoichiometry" + Math.random()); stoichiometry.setStoichiometricCoefficient(coeff); stoichiometry.setPhysicalEntity(pe3); //System.out.println("parent=" + parent + "; phy.ent.=" + pep + "; coeff=" + coeff); if (parent instanceof conversion) { // (pep) value participates in the conversion interaction Conversion conv = (Conversion) newModel .getByID(parent.getUri()); conv.addParticipantStoichiometry(stoichiometry); } else { // this (pep) value is component of the complex Complex cplx = (Complex) newModel.getByID(parent.getUri()); cplx.addComponentStoichiometry(stoichiometry); } newModel.add(stoichiometry); } else { if (log.isDebugEnabled()) log.debug(pep + " STOICHIOMETRIC_COEFFICIENT is " + coeff + ", but the pEP's parent is not a conversion or complex - " + parent); } } traverse(pep, newModel); } else if(value instanceof openControlledVocabulary) { // create the proper type ControlledVocabulary instance newValue = convertAndAddVocabulary((openControlledVocabulary)value, (Level2Element)parent, newModel, newEditor); } else { String id = ((Level2Element) value).getUri(); newValue = newModel.getByID(id); } } else if (value.getClass().isEnum()) { newValue = getMatchingEnum(value); } else { // relationshipXref.RELATIONSHIP-TYPE range changed (String -> RelationshipTypeVocabulaty) if(parent instanceof relationshipXref && editor.getProperty().equals("RELATIONSHIP-TYPE")) { String id = URLEncoder.encode(value.toString()); if(!newModel.containsID(id)) { RelationshipTypeVocabulary cv = (RelationshipTypeVocabulary) newModel.addNew(newEditor.getRange(), id); cv.addTerm(value.toString().toLowerCase()); newValue = cv; } else { newValue = newModel.getByID(id); } } } if(newValue == null) { log.debug("Skipped for " + parent + "." + editor.getProperty() + "=" + value + " ==> " + newParent.getUri() + "." + newProp + " = NULL"); return; } if (newProp != null) { if (newEditor != null){ setNewProperty(newParent, newValue, newEditor); } else if(parent instanceof physicalEntity) { // Special mapping for 'AVAILABILITY' and 'DATA-SOURCE' // find parent pEP(s) Set<physicalEntityParticipant> ppeps = ((physicalEntity)parent).isPHYSICAL_ENTITYof(); // if several pEPs use the same phy.entity, we get this property/value cloned... for(physicalEntityParticipant pep: ppeps) { //find proper L3 physical entity newParent = getMappedPE(pep, newModel); if(newParent != null) { newEditor = SimpleEditorMap.L3.getEditorForProperty(newProp, newParent.getModelInterface()); setNewProperty(newParent, newValue, newEditor); } else { // bug! log.error("Cannot find converted PE to map the property " + editor.getProperty() + " of physicalEntity " + parent + " (" + parentType + ")"); } } } else { log.debug("Skipped property " + editor.getProperty() + " in " + parentType + " to " + newParent.getModelInterface().getSimpleName() + " conversion (" + parent + ")"); } } else { log.warn("No mapping defined for property: " + parentType + "." + editor.getProperty()); } }
parent class's abstract method implementation
private PhysicalEntity getMappedPE(physicalEntityParticipant pep, Model newModel) { String id = pep2PE.get(pep.getUri()); physicalEntity pe2er = pep.getPHYSICAL_ENTITY(); if(id == null || pe2er == null) throw new IllegalAccessError("Illegal pEP (cannot convert): " + pep.getUri()); BioPAXElement pe = newModel.getByID(id); String inf = "pEP " + pep + " that contains " + pe2er.getModelInterface().getSimpleName(); if(!isSimplePhysicalEntity(pe2er)) { if(pe == null) { if(log.isDebugEnabled()) log.debug(inf + " gets new ID: " + pe2er.getUri()); pe = newModel.getByID(pe2er.getUri()); } else { // error: complex and basic p.entity's pEP throw new IllegalAccessError("Illegal conversion of pEP: " + inf); } } else if(pe == null){ // for a pEP having a simple PE, a new PE should be created throw new IllegalAccessError("No PE for: " + inf + " found in the new Model"); } return (PhysicalEntity) pe; }
/* pEP->PE; pE->ER class mapping was done for "simple" entities; for complex and the "basic" pE, it is pE->PE mapping (although pEPs were skipped, their properties are to save anyway)
static public String getLocalId(BioPAXElement bpe) { String id = bpe.getUri(); return (id != null) ? id.replaceFirst("^.+[#/]", "") : null; //greedy pattern matches everything up to the last '/' or '#' }
Gets the local part of the BioPAX element ID. @param bpe BioPAX object @return id - local part of the URI
@Override public boolean satisfies(Match match, int... ind) { PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); return pe.getControllerOf().isEmpty() == active; }
Checks if the PhysicalEntity controls anything. @param match current match to validate @param ind mapped index @return true if it controls anything
@Override public void setEntityReference(EntityReference entityReference) { if(entityReference instanceof DnaReference || entityReference == null) super.setEntityReference(entityReference); else throw new IllegalBioPAXArgumentException("setEntityReference failed: " + entityReference.getUri() + " is not a DnaReference."); }
------------------------ INTERFACE METHODS ------------------------
@Override public void setEntityReference(EntityReference entityReference) { if(entityReference instanceof ProteinReference || entityReference == null) super.setEntityReference(entityReference); else throw new IllegalBioPAXArgumentException("setEntityReference failed: " + entityReference.getUri() + " is not a ProteinReference."); }
------------------------ INTERFACE METHODS ------------------------
public void visit(BioPAXElement domain, Object range, Model model, PropertyEditor editor) { if (range instanceof BioPAXElement) { BioPAXElement bpe = (BioPAXElement) range; // do nothing if you already inserted this if (!model.contains(bpe)) { //if there is an identical if (model.getByID(bpe.getUri()) != null) { if (editor.isMultipleCardinality()) { editor.removeValueFromBean(bpe, domain); } editor.setValueToBean(getIdentical(bpe), domain); } } } }
Checks whether <em>model</em> contains <em>bpe</em> element, and if it does, then it updates the value of the equivalent element for <em>bpe</em> by using the specific <em>editor</em>. @param domain owner @param range property value @param model model containing the equivalent element's equivalent @param editor biopax property editor specific for the value type to be updated
public void merge (Model target, Model... sources) { // Empty merged and added elements sets mergedElements.clear(); addedElements.clear(); // Fill equivalence map with objects from target model Set<BioPAXElement> targetElements = target.getObjects(); for (BioPAXElement t_bpe : targetElements) { this.addIntoEquivalanceMap(t_bpe); } // Try to insert every biopax element in every source one by one for (Model source : sources) { Set<BioPAXElement> sourceElements = source.getObjects(); for (BioPAXElement bpe : sourceElements) { insert(target, bpe); } } }
Merges the <em>source</em> models into <em>target</em> model. @param target model into which merging process will be done @param sources model(s) that are going to be merged with <em>target</em>
private void insert(Model target, BioPAXElement bpe) { // do nothing if you already inserted this if (!target.contains(bpe)) { //if there is an identical (in fact, "equal") object BioPAXElement ibpe = target.getByID(bpe.getUri()); if (ibpe != null && ibpe.equals(bpe)) /* - ibpe.equals(bpe) can be 'false' here, because, * even though the above !target.contains(bpe) is true, * it probably compared objects using '==' operator * (see the ModelImpl for details) */ { updateObjectFields(bpe, ibpe, target); // We have a merged element, add it into the tracker mergedElements.add(ibpe); } else { target.add(bpe); this.addIntoEquivalanceMap(bpe); traverser.traverse(bpe, target); // We have a new element, add it into the tracker addedElements.add(bpe); } } }
Inserts a BioPAX element into the <em>target</em> model if it does not contain an equivalent; but if does, than it updates the equivalent using this element's values. @param target model into which bpe will be inserted @param bpe BioPAX element to be inserted into target
private BioPAXElement getIdentical(BioPAXElement bpe) { int key = bpe.hashCode(); List<BioPAXElement> list = equivalenceMap.get(key); if (list != null) { for (BioPAXElement other : list) { if (other.equals(bpe)) { return other; } } } return null; }
Searches the target model for an identical of given BioPAX element, and returns this element if it finds it. @param bpe BioPAX element for which equivalent will be searched in target. @return the BioPAX element that is found in target model, if there is none it returns null
private void updateObjectFields(BioPAXElement update, BioPAXElement existing, Model target) { Set<PropertyEditor> editors = map.getEditorsOf(update); for (PropertyEditor editor : editors) { updateObjectFieldsForEditor(editor, update, existing, target); } // if (!update.getUri().equals(existing.getUri())) // { //TODO addNew a unification xref // if(existing instanceof XReferrable) // { // ((XReferrable) existing).addXref(fa); // } // } }
Updates each value of <em>existing</em> element, using the value(s) of <em>update</em>. @param update BioPAX element of which values are used for update @param existing BioPAX element to be updated @param target
private void updateObjectFieldsForEditor(PropertyEditor editor, BioPAXElement update, BioPAXElement existing, Model target) { if (editor.isMultipleCardinality()) { for (Object updateValue : editor.getValueFromBean(update)) { updateField(editor, updateValue, existing, target); } } else { Set existingValue = editor.getValueFromBean(existing); Set updateValue = editor.getValueFromBean(update); if (editor.isUnknown(existingValue)) { if (!editor.isUnknown(updateValue)) { updateField(editor, updateValue.iterator().next(), existing, target); } } else { if (!existingValue.equals(updateValue)) log.info("Keep existing single cardinality property value: " + existingValue + " (ignore: " + updateValue + ")" ); } } }
Updates the value of <em>existing</em> element, using the value of <em>update</em>. Editor is used for the modification. @param editor editor for the specific value to be updated @param update BioPAX element of which value is used for the update @param existing BioPAX element to be updated @param target
private void updateField(PropertyEditor editor, Object updateValue, BioPAXElement existing, Model target) { if (updateValue instanceof BioPAXElement) { BioPAXElement bpe = (BioPAXElement) updateValue; //Now there are two possibilities BioPAXElement ibpe = target.getByID(bpe.getUri()); //1. has an identical in the target if (ibpe != null) { updateValue = ibpe; } //2. it has no identical in the target //I do not have to do anything as it will eventually //be moved. } editor.setValueToBean(updateValue, existing); }
Updates <em>existing</em>, using the <em>updateValue</em> by the editor. @param editor editor for the specific value to be updated @param updateValue the value for the update @param existing BioPAX element to be updated @param target
private void addIntoEquivalanceMap(BioPAXElement bpe) { int key = bpe.hashCode(); List<BioPAXElement> list = equivalenceMap.get(key); if (list == null) { list = new ArrayList<BioPAXElement>(); equivalenceMap.put(key, list); } list.add(bpe); }
Adds a BioPAX element into the equivalence map. @param bpe BioPAX element to be added into the map.
public static Set<BioPAXElement> runNeighborhood( Set<BioPAXElement> sourceSet, Model model, int limit, Direction direction, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { if (direction == Direction.UNDIRECTED) { graph = new GraphL3Undirected(model, filters); direction = Direction.BOTHSTREAM; } else { graph = new GraphL3(model, filters); } } else return Collections.emptySet(); Set<Node> source = prepareSingleNodeSet(sourceSet, graph); if (sourceSet.isEmpty()) return Collections.emptySet(); NeighborhoodQuery query = new NeighborhoodQuery(source, direction, limit); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, true); }
Gets neighborhood of the source set. @param sourceSet seed to the query @param model BioPAX model @param limit neigborhood distance to get @param direction UPSTREAM, DOWNSTREAM or BOTHSTREAM @param filters for filtering graph elements @return BioPAX elements in the result set
public static Set<BioPAXElement> runPathsBetween(Set<BioPAXElement> sourceSet, Model model, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Collection<Set<Node>> sourceWrappers = prepareNodeSets(sourceSet, graph); if (sourceWrappers.size() < 2) return Collections.emptySet(); PathsBetweenQuery query = new PathsBetweenQuery(sourceWrappers, limit); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, true); }
Gets the graph constructed by the paths between the given seed nodes. Does not get paths between physical entities that belong the same entity reference. @param sourceSet Seed to the query @param model BioPAX model @param limit Length limit for the paths to be found @param filters optional filters - for filtering graph elements @return BioPAX elements in the result
public static Set<BioPAXElement> runGOI( Set<BioPAXElement> sourceSet, Model model, int limit, Filter... filters) { return runPathsFromTo(sourceSet, sourceSet, model, LimitType.NORMAL, limit, filters); }
Gets paths between the seed nodes. @param sourceSet Seed to the query @param model BioPAX model @param limit Length limit for the paths to be found @param filters for filtering graph elements @return BioPAX elements in the result @deprecated Use runPathsBetween instead
public static Set<BioPAXElement> runPathsFromTo( Set<BioPAXElement> sourceSet, Set<BioPAXElement> targetSet, Model model, LimitType limitType, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Set<Node> source = prepareSingleNodeSet(sourceSet, graph); Set<Node> target = prepareSingleNodeSet(targetSet, graph); PathsFromToQuery query = new PathsFromToQuery(source, target, limitType, limit, true); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, true); }
Gets paths the graph composed of the paths from a source node, and ends at a target node. @param sourceSet Seeds for start points of paths @param targetSet Seeds for end points of paths @param model BioPAX model @param limitType either NORMAL or SHORTEST_PLUS_K @param limit Length limit fothe paths to be found @param filters for filtering graph elements @return BioPAX elements in the result
public static Set<BioPAXElement> runPathsFromToMultiSet( Set<Set<BioPAXElement>> sourceSets, Set<Set<BioPAXElement>> targetSets, Model model, LimitType limitType, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Set<Node> source = prepareSingleNodeSetFromSets(sourceSets, graph); Set<Node> target = prepareSingleNodeSetFromSets(targetSets, graph); PathsFromToQuery query = new PathsFromToQuery(source, target, limitType, limit, true); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, true); }
Gets paths the graph composed of the paths from a source node, and ends at a target node. @param sourceSets Seeds for start points of paths @param targetSets Seeds for end points of paths @param model BioPAX model @param limitType either NORMAL or SHORTEST_PLUS_K @param limit Length limit fothe paths to be found @param filters for filtering graph elements @return BioPAX elements in the result
public static Set<BioPAXElement> runCommonStream( Set<BioPAXElement> sourceSet, Model model, Direction direction, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Collection<Set<Node>> source = prepareNodeSets(sourceSet, graph); if (sourceSet.size() < 2) return Collections.emptySet(); CommonStreamQuery query = new CommonStreamQuery(source, direction, limit); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, false); }
Gets the elements in the common upstream or downstream of the seed @param sourceSet Seed to the query @param model BioPAX model @param direction UPSTREAM or DOWNSTREAM @param limit Length limit for the search @param filters for filtering graph elements @return BioPAX elements in the result
public static Set<BioPAXElement> runCommonStreamWithPOI( Set<BioPAXElement> sourceSet, Model model, Direction direction, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Collection<Set<Node>> sourceSets = prepareNodeSets(sourceSet, graph); if (sourceSet.size() < 2) return Collections.emptySet(); return runCommonStreamWithPOIContinued(sourceSets, direction, limit, graph); }
First finds the common stream, then completes it with the paths between seed and common stream. @param sourceSet Seed to the query @param model BioPAX model @param direction UPSTREAM or DOWNSTREAM @param limit Length limit for the search @param filters for filtering graph elements @return BioPAX elements in the result
public static Set<BioPAXElement> runCommonStreamWithPOIMultiSet( Set<Set<BioPAXElement>> sourceSets, Model model, Direction direction, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Collection<Set<Node>> nodes = prepareNodeSetsFromSets(sourceSets, graph); if (nodes.size() < 2) return Collections.emptySet(); return runCommonStreamWithPOIContinued(nodes, direction, limit, graph); }
First finds the common stream, then completes it with the paths between seed and common stream. @param sourceSets Seed to the query @param model BioPAX model @param direction UPSTREAM or DOWNSTREAM @param limit Length limit for the search @param filters for filtering graph elements @return BioPAX elements in the result
private static Set<BioPAXElement> convertQueryResult( Set<GraphObject> resultWrappers, Graph graph, boolean removeDisconnected) { Set<Object> result = graph.getWrappedSet(resultWrappers); Set<BioPAXElement> set = new HashSet<BioPAXElement>(); for (Object o : result) { set.add((BioPAXElement) o); } // remove disconnected simple physical entities if (removeDisconnected) { Set<BioPAXElement> remove = new HashSet<BioPAXElement>(); for (BioPAXElement ele : set) { if (ele instanceof SimplePhysicalEntity && isDisconnected((SimplePhysicalEntity) ele, set)) { remove.add(ele); } } set.removeAll(remove); } return set; }
Converts the query result from wrappers to wrapped BioPAX elements. @param resultWrappers Wrappers of the result set @param graph Queried graph @param removeDisconnected whether to remove disconnected non-complex type physical entities @return Set of elements in the result
public static Set<Node> prepareSingleNodeSet(Set<BioPAXElement> elements, Graph graph) { Map<BioPAXElement, Set<PhysicalEntity>> map = getRelatedPhysicalEntityMap(elements); Set<PhysicalEntity> pes = new HashSet<PhysicalEntity>(); for (Set<PhysicalEntity> valueSet : map.values()) { pes.addAll(valueSet); } Set<Node> nodes = graph.getWrapperSet(pes); // If there are interactions in the seed add them too Set<Node> inters = getSeedInteractions(elements, graph); nodes.addAll(inters); return nodes; }
Gets the related wrappers of the given elements in a set. @param elements Elements to get the related wrappers @param graph Owner graph @return Related wrappers in a set
public static Set<Node> prepareSingleNodeSetFromSets(Set<Set<BioPAXElement>> sets, Graph graph) { Set<BioPAXElement> elements = new HashSet<BioPAXElement>(); for (Set<BioPAXElement> set : sets) { elements.addAll(set); } return prepareSingleNodeSet(elements, graph); }
Gets the related wrappers of the given elements in the sets. @param sets Sets of elements to get the related wrappers @param graph Owner graph @return Related wrappers in a set
private static Collection<Set<Node>> prepareNodeSets(Set<BioPAXElement> elements, Graph graph) { Collection<Set<Node>> sets = new HashSet<Set<Node>>(); Map<BioPAXElement, Set<PhysicalEntity>> map = getRelatedPhysicalEntityMap(elements); for (Set<PhysicalEntity> pes : map.values()) { Set<Node> set = graph.getWrapperSet(pes); if (!set.isEmpty()) sets.add(set); } // Add interactions in the seed as single node set Set<Node> inters = getSeedInteractions(elements, graph); for (Node node : inters) { sets.add(Collections.singleton(node)); } return sets; }
Gets the related wrappers of the given elements in individual sets. An object can be related to more than one wrapper and they will appear in the same set. This method created a set for each parameter element that has a related wrapper. @param elements Elements to get the related wrappers @param graph Owner graph @return Related wrappers in individual sets
private static Collection<Set<Node>> prepareNodeSetsFromSets(Set<Set<BioPAXElement>> sets, Graph graph) { Collection<Set<Node>> result = new HashSet<Set<Node>>(); for (Set<BioPAXElement> set : sets) { Set<Node> nodes = prepareSingleNodeSet(set, graph); if (!nodes.isEmpty()) result.add(nodes); } return result; }
Gets the related wrappers of the given elements in individual sets. An object can be related to more than one wrapper and they will appear in the same set. This method created a set for each parameter element that has a related wrapper. @param sets Sets of elements to get the related wrappers @param graph Owner graph @return Related wrappers in individual sets
public static Map<BioPAXElement, Set<PhysicalEntity>> getRelatedPhysicalEntityMap( Collection<BioPAXElement> elements) { replaceXrefsWithRelatedER(elements); Map<BioPAXElement, Set<PhysicalEntity>> map = new HashMap<BioPAXElement, Set<PhysicalEntity>>(); for (BioPAXElement ele : elements) { Set<PhysicalEntity> ents = getRelatedPhysicalEntities(ele, null); if (!ents.isEmpty()) { map.put(ele, ents); } } return map; }
Maps each BioPAXElement to its related PhysicalEntity objects. @param elements Elements to map @return The mapping
protected static void replaceXrefsWithRelatedER( Collection<BioPAXElement> elements) { Set<EntityReference> ers = new HashSet<EntityReference>(); Set<Xref> xrefs = new HashSet<Xref>(); for (BioPAXElement element : elements) { if (element instanceof Xref) { xrefs.add((Xref) element); for (XReferrable able : ((Xref) element).getXrefOf()) { if (able instanceof EntityReference) { ers.add((EntityReference) able); } } } } elements.removeAll(xrefs); for (EntityReference er : ers) { if (!elements.contains(er)) elements.add(er); } }
Replaces Xref objects with the related EntityReference objects. This is required for the use case when user provides multiple xrefs that point to the same ER. @param elements elements to send to a query as source or target
public static Set<PhysicalEntity> getRelatedPhysicalEntities(BioPAXElement element, Set<PhysicalEntity> pes) { if (pes == null) pes = new HashSet<PhysicalEntity>(); if (element instanceof PhysicalEntity) { PhysicalEntity pe = (PhysicalEntity) element; if (!pes.contains(pe)) { pes.add(pe); for (Complex cmp : pe.getComponentOf()) { getRelatedPhysicalEntities(cmp, pes); } // This is a hack for BioPAX graph. Equivalence relations do not link members and // complexes because members cannot be addressed. Below call makes sure that if the // source node has a generic parents or children and they appear in a complex, we // include the complex in the sources. addEquivalentsComplexes(pe, pes); } } else if (element instanceof Xref) { for (XReferrable xrable : ((Xref) element).getXrefOf()) { getRelatedPhysicalEntities(xrable, pes); } } else if (element instanceof EntityReference) { EntityReference er = (EntityReference) element; for (SimplePhysicalEntity spe : er.getEntityReferenceOf()) { getRelatedPhysicalEntities(spe, pes); } for (EntityReference parentER : er.getMemberEntityReferenceOf()) { getRelatedPhysicalEntities(parentER, pes); } } return pes; }
Gets the related PhysicalEntity objects of the given BioPAXElement, in level 3 models. @param element Element to get related PhysicalEntity objects @param pes Result set. If not supplied, a new set will be initialized. @return Related PhysicalEntity objects
private static void addEquivalentsComplexes(PhysicalEntity pe, Set<PhysicalEntity> pes) { addEquivalentsComplexes(pe, true, pes); // Do not traverse to more specific. This was causing a bug so I commented out. Did not delete it just in case // later we realize that this is needed for another use case. // addEquivalentsComplexes(pe, false, pes); }
Adds equivalents and parent complexes of the given PhysicalEntity to the parameter set. @param pe The PhysicalEntity to add its equivalents and complexes @param pes Set to collect equivalents and complexes
private static void addEquivalentsComplexes(PhysicalEntity pe, boolean outer, Set<PhysicalEntity> pes) { Set<PhysicalEntity> set = outer ? pe.getMemberPhysicalEntityOf() : pe.getMemberPhysicalEntity(); for (PhysicalEntity related : set) { for (Complex cmp : related.getComponentOf()) { getRelatedPhysicalEntities(cmp, pes); } addEquivalentsComplexes(related, outer, pes); } }
Adds equivalents and parent complexes of the given PhysicalEntity to the parameter set. This method traverses homologies only to one direction (either towards parents or to the children). @param pe The PhysicalEntity to add its equivalents and complexes @param outer Give true if towards parents, false if to the children @param pes Set to collect equivalents and complexes
public static Set<Node> getSeedInteractions(Collection<BioPAXElement> elements, Graph graph) { Set<Node> nodes = new HashSet<Node>(); for (BioPAXElement ele : elements) { if (ele instanceof Conversion || ele instanceof TemplateReaction || ele instanceof Control) { GraphObject go = graph.getGraphObject(ele); if (go instanceof Node) { nodes.add((Node) go); } } } return nodes; }
Extracts the querible interactions from the elements. @param elements BioPAX elements to search @param graph graph model @return Querible Interactions (nodes)
public String getColumnValue(SIFInteraction inter) { switch (type) { case MEDIATOR: return concat(inter.getMediatorIDs()); case PATHWAY: return concat(inter.getPathwayNames()); case PATHWAY_URI: return concat(inter.getPathwayUris()); case PUBMED: return concat(inter.getPublicationIDs(true)); case PMC: return concat(inter.getPublicationIDs(false)); case RESOURCE: return concat(inter.getDataSources()); case SOURCE_LOC: return concat(inter.getCellularLocationsOfSource()); case TARGET_LOC: return concat(inter.getCellularLocationsOfTarget()); case COMMENTS: return concat(inter.getMediatorComments()); case CUSTOM: { Set<String> set = new HashSet<String>(); for (PathAccessor acc : accessors) { for (Object o : acc.getValueFromBeans(inter.mediators)) { set.add(o.toString()); } } List<String> list = new ArrayList<String>(set); Collections.sort(list); return concat(list); } default: throw new RuntimeException("Unhandled type: " + type + ". This shouldn't be happening."); } }
Get the string to write in the output file. @param inter the binary interaction @return column value
public int equivalenceCode() { int result = 29 + (DB != null ? DB.hashCode() : 0); result = 29 * result + (DB_VERSION != null ? DB_VERSION.hashCode() : 0); result = 29 * result + (ID_VERSION != null ? ID_VERSION.hashCode() : 0); result = 29 * result + (ID != null ? ID.hashCode() : 0); return result; }
------------------------ CANONICAL METHODS ------------------------
protected boolean semanticallyEquivalent(BioPAXElement other) { final xref anXref = (xref) other; return (DB != null ? DB.equalsIgnoreCase(anXref.getDB()) : anXref.getDB() == null) && (ID != null ? ID.equalsIgnoreCase(anXref.getID()) : anXref.getID() == null) && (DB_VERSION != null ? DB_VERSION.equalsIgnoreCase(anXref.getDB_VERSION()) : anXref.getDB_VERSION() == null) && (ID_VERSION != null ? ID_VERSION.equalsIgnoreCase(anXref.getID_VERSION()) : anXref.getID_VERSION() != null); }
--------------------- Interface BioPAXElement ---------------------
public void writeSBGN(Model model, String file) { // Create the model Sbgn sbgn = createSBGN(model); // Write in file try { SbgnUtil.writeToFile(sbgn, new File(file)); } catch (JAXBException e) { throw new RuntimeException("writeSBGN, SbgnUtil.writeToFile failed", e); } }
Converts the given model to SBGN, and writes in the specified file. @param model model to convert @param file file to write
public void writeSBGN(Model model, OutputStream stream) { Sbgn sbgn = createSBGN(model); try { JAXBContext context = JAXBContext.newInstance("org.sbgn.bindings"); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(sbgn, stream); } catch (JAXBException e) { throw new RuntimeException("writeSBGN: JAXB marshalling failed", e); } }
Converts the given model to SBGN, and writes in the specified output stream. @param model model to convert @param stream output stream to write
public Sbgn createSBGN(Model model) { assert model.getLevel().equals(BioPAXLevel.L3) : "This method only supports L3 graphs"; glyphMap = new HashMap<String, Glyph>(); compartmentMap = new HashMap<String, Glyph>(); arcMap = new HashMap<String, Arc>(); ubiqueSet = new HashSet<Glyph>(); int n = 0; //approximate number of SBGN nodes // Create glyphs for Physical Entities for (Entity entity : model.getObjects(Entity.class)) { if (needsToBeCreatedInitially(entity)) { createGlyph(entity); ++n; } } // Create glyph for conversions and link with arcs for (Interaction interaction : model.getObjects(Interaction.class)) { if(interaction.getParticipant().isEmpty()) continue; // For each conversion we check if we need to create a left-to-right and/or right-to-left process. if(interaction instanceof Conversion) { Conversion conv = (Conversion) interaction; if (conv.getConversionDirection() == null || conv.getConversionDirection().equals(ConversionDirectionType.LEFT_TO_RIGHT) || (conv.getConversionDirection().equals(ConversionDirectionType.REVERSIBLE) && useTwoGlyphsForReversibleConversion)) { createProcessAndConnections(conv, ConversionDirectionType.LEFT_TO_RIGHT); } else if (conv.getConversionDirection() != null && (conv.getConversionDirection().equals(ConversionDirectionType.RIGHT_TO_LEFT) || (conv.getConversionDirection().equals(ConversionDirectionType.REVERSIBLE)) && useTwoGlyphsForReversibleConversion)) { createProcessAndConnections(conv, ConversionDirectionType.RIGHT_TO_LEFT); } else if (conv.getConversionDirection() != null && conv.getConversionDirection().equals(ConversionDirectionType.REVERSIBLE) && !useTwoGlyphsForReversibleConversion) { createProcessAndConnections(conv, ConversionDirectionType.REVERSIBLE); } } else if(interaction instanceof TemplateReaction) { createProcessAndConnections((TemplateReaction) interaction); } else if(interaction instanceof MolecularInteraction) { createBasicProcess(interaction); } else if(interaction instanceof GeneticInteraction) { createGiProcess((GeneticInteraction) interaction); } else if(!(interaction instanceof Control)) { createBasicProcess(interaction); } else { //a Control special case, because these are normally added inside the methods in cases above Control control = (Control) interaction; //Control without any controlled process but with controller and controlledOf if(control.getControlled()==null || control.getControlled().isEmpty()) { Glyph g = createControlStructure(control); processControllers(control.getControlledOf(), g); }//else - do nothing - as it's converted anyway when the controlled interactions are processed } ++n; } // Register created objects into sbgn construct final Sbgn sbgn = factory.createSbgn(); org.sbgn.bindings.Map map = new org.sbgn.bindings.Map(); sbgn.setMap(map); map.setLanguage(Language.PD.toString()); map.getGlyph().addAll(getRootGlyphs(glyphMap.values())); map.getGlyph().addAll(getRootGlyphs(ubiqueSet)); map.getGlyph().addAll(compartmentMap.values()); map.getArc().addAll(arcMap.values()); // //Store some metadata within the standard SBGN-ML extension element: Notes // biopaxMetaDoc.setDocumentURI(model.getUri()); //can be null // SBGNBase.Notes modelNotes = new SBGNBase.Notes(); // sbgn.setNotes(modelNotes); // Element elt = biopaxMetaDoc.createElementNS("","metadata"); // elt.setTextContent(String.format("{name:\"%s\",uri:\"%s\"}", model.getName(), model.getUri()) // .replaceAll("null","")); // modelNotes.getAny().add(elt); final boolean layout = doLayout && n < this.maxNodes && !arcMap.isEmpty(); try { //Must call this, although actual layout might never run; //in some real data tests, skipping createLayout method //led to malformed SBGN model, unfortunately... (new SBGNLayoutManager()).createLayout(sbgn, layout); } catch (Exception e) { throw new RuntimeException("SBGN Layout of " + model.getXmlBase() + ((model.getName()==null) ? "" : model.getName()) + " failed.", e); } if(!layout) log.warn(String.format("No layout, for either " + "it's disabled: %s, or ~ no. nodes > %s: %s, or - no edges: %s", !doLayout, maxNodes, n>maxNodes, arcMap.isEmpty())); return sbgn; //modified sbgn (even when no layout is run) }
Creates an SBGN object from the given BioPAX L3 model. Currently, it converts physical entities (interaction participants) and Conversion, Control, including their sub-classes, TemplateReaction, MolecularInteraction, GeneticInteraction, and base Interaction.class types. I does not convert other BioPAX entities and utility classes, such as: Pathway, Evidence, PathwayStep. @param model model to convert to SBGN @return SBGN representation of the BioPAX model
private void processControllers(Set<Control> controls, Glyph process) { for (Control ctrl : controls) { Glyph g = createControlStructure(ctrl); //if ctrl has upstream controls (modulations), they're processed as well if (g != null) { createArc(g, process, getControlType(ctrl), null); processControllers(ctrl.getControlledOf(), g); } } }
Associate all the controllers of this process;
private boolean needsToBeCreatedInitially(Entity ent) { boolean create = false; if(ent instanceof PhysicalEntity || ent instanceof Gene) { if(ubiqueDet != null && ubiqueDet.isUbique(ent)) create = false; // ubiques will be created where they are actually used. else if (!ent.getParticipantOf().isEmpty()) create = true; else if(ent instanceof Complex && ((Complex) ent).getComponentOf().isEmpty() && ((Complex) ent).getMemberPhysicalEntityOf().isEmpty()) create = true; //do make a root/top complex despite it's dangling } return create; }
/* Initially, we don't want to represent every PhysicalEntity or Gene node. For example, if a Complex is nested under another Complex, and if it is not a participant of any interaction, then we don't want to draw it separately; also skip for dangling entities. @param ent physical entity or gene (it returns false for other entity types) to test @return true if we want to draw this entity in SBGN; false - otherwise, or - to be auto-created later
private Glyph createGlyph(Entity e) { String id = convertID(e.getUri()); if (glyphMap.containsKey(id)) return glyphMap.get(id); // Create its glyph and register Glyph g = createGlyphBasics(e, true); glyphMap.put(g.getId(), g); //TODO: export metadata (e.g., from bpe.getAnnotations() map) using the SBGN Extension feature // SBGNBase.Extension ext = new SBGNBase.Extension(); // g.setExtension(ext); // Element el = biopaxMetaDoc.createElement(e.getModelInterface().getSimpleName()); // el.setAttribute("uri", e.getUri()); // ext.getAny().add(el); if (g.getClone() != null) ubiqueSet.add(g); if(e instanceof PhysicalEntity) { PhysicalEntity pe = (PhysicalEntity) e; assignLocation(pe, g); if("or".equalsIgnoreCase(g.getClazz())) { buildGeneric(pe, g, null); } else if (pe instanceof Complex) { createComplexContent((Complex) pe, g); } } return g; }
/* Creates a glyph representing the given PhysicalEntity. @param e PhysicalEntity or Gene to represent @return the created glyph
private void assignLocation(PhysicalEntity pe, Glyph g) { // Create compartment -- add this inside the compartment Glyph loc = getCompartment(pe); if (loc != null) { g.setCompartmentRef(loc); } }
/* Assigns compartmentRef of the glyph. @param pe Related PhysicalEntity @param g the glyph
private Glyph createGlyphBasics(Entity e, boolean idIsFinal) { Glyph g = factory.createGlyph(); g.setId(convertID(e.getUri())); String s = typeMatchMap.get(e.getModelInterface()); if(( //use 'or' sbgn class for special generic physical entities e instanceof Complex && !((Complex)e).getMemberPhysicalEntity().isEmpty() && ((Complex) e).getComponent().isEmpty()) || (e instanceof SimplePhysicalEntity && ((SimplePhysicalEntity) e).getEntityReference()==null && !((SimplePhysicalEntity) e).getMemberPhysicalEntity().isEmpty())) { s = GlyphClazz.OR.getClazz(); } g.setClazz(s); // Set the label Label label = factory.createLabel(); label.setText(findLabelFor(e)); g.setLabel(label); // Detect if ubique if (ubiqueDet != null && ubiqueDet.isUbique(e)) { g.setClone(factory.createGlyphClone()); } // Put on state variables if (!g.getClazz().equals(GlyphClazz.OR.getClazz())) { g.getGlyph().addAll(getInformation(e)); } // Record the mapping if (idIsFinal) { Set<String> uris = new HashSet<String>(); uris.add(e.getUri()); sbgn2BPMap.put(g.getId(), uris); } return g; }
/* This method creates a glyph for the given PhysicalEntity, sets its title and state variables if applicable. @param e PhysicalEntity or Gene to represent @param idIsFinal if ID is final, then it is recorded for future reference @return the glyph
private Glyph getGlyphToLink(Entity e, String linkID) { if (ubiqueDet == null || !ubiqueDet.isUbique(e)) { return glyphMap.get(convertID(e.getUri())); } else { // Create a new glyph for each use of ubique Glyph g = createGlyphBasics(e, false); g.setId(convertID(e.getUri()) + "_" + ModelUtils.md5hex(linkID)); Set<String> uris = new HashSet<String>(); uris.add(e.getUri()); sbgn2BPMap.put(g.getId(), uris); if(e instanceof PhysicalEntity && ((PhysicalEntity)e).getCellularLocation() != null) { assignLocation((PhysicalEntity) e, g); } ubiqueSet.add(g); return g; } }
/* Gets the representing glyph of the PhysicalEntity or Gene. @param e PhysicalEntity or Gene to get its glyph @param linkID Edge id, used if the Entity is ubique @return Representing glyph
private void createComplexContent(Complex cx, Glyph cg) { if (flattenComplexContent) { for (PhysicalEntity mem : getFlattenedMembers(cx)) { createComplexMember(mem, cg); } } else { for (PhysicalEntity mem : cx.getComponent()) { if (mem instanceof Complex) { addComplexAsMember((Complex) mem, cg); } else { createComplexMember(mem, cg); } } } }
/* Fills in the content of a complex. @param cx Complex to be filled @param cg its glyph
private void addComplexAsMember(Complex cx, Glyph container) { // Create a glyph for the inner complex Glyph inner = createComplexMember(cx, container); for (PhysicalEntity mem : cx.getComponent()) { if (mem instanceof Complex) { // Recursive call for inner complexes addComplexAsMember((Complex) mem, inner); } else { createComplexMember(mem, inner); } } }
/* Recursive method for creating the content of a complex. A complex may contain other complexes (bad practice), but SBGN needs them flattened. If an inner complex is empty, then we represent it using a glyph. Otherwise we represent only the members of this inner complex, merging them with the most outer complex. @param cx inner complex to add as member @param container glyph for most outer complex
private Set<PhysicalEntity> getFlattenedMembers(Complex cx) { Set<PhysicalEntity> set = new HashSet<PhysicalEntity>(); for (PhysicalEntity mem : cx.getComponent()) { if (mem instanceof Complex) { if (!hasNonComplexMember((Complex) mem)) { set.add(mem); } else { set.addAll(getFlattenedMembers((Complex) mem)); } } else set.add(mem); } return set; }
/* Gets the members of the Complex that needs to be displayed in a flattened view. @param cx to get members @return members to display
private boolean hasNonComplexMember(Complex cx) { for (PhysicalEntity mem : cx.getComponent()) { if (!(mem instanceof Complex) || hasNonComplexMember((Complex) mem)) { return true; } } return false; }
/* Checks if a Complex contains any PhysicalEntity member which is not a Complex. @param cx to check @return true if there is a non-complex member
private Glyph createComplexMember(PhysicalEntity pe, Glyph container) { Glyph g = createGlyphBasics(pe, false); container.getGlyph().add(g); // A PhysicalEntity may appear in many complexes -- we identify the member using its complex g.setId(g.getId() + "_" + ModelUtils.md5hex(container.getId())); glyphMap.put(g.getId(), g); Set<String> uris = new HashSet<String>(); uris.add(pe.getUri()); sbgn2BPMap.put(g.getId(), uris); if("or".equalsIgnoreCase(g.getClazz())) { buildGeneric(pe, g, container); } return g; }
/* Creates a glyph for the complex member. @param pe PhysicalEntity to represent as complex member @param container Glyph for the complex shell
private String findLabelFor(Entity pe) { // Use gene symbol of PE for (Xref xref : pe.getXref()) { String sym = extractGeneSymbol(xref); if (sym != null) return sym; } // Use gene symbol of ER EntityReference er = null; if (pe instanceof SimplePhysicalEntity) { er = ((SimplePhysicalEntity) pe).getEntityReference(); } if (er != null) { for (Xref xref : er.getXref()) { String sym = extractGeneSymbol(xref); if (sym != null) return sym; } } // Use display name of entity String name = pe.getDisplayName(); if (name == null || name.trim().isEmpty()) { if (er != null) { name = er.getDisplayName(); } if (name == null || name.trim().isEmpty()) { name = pe.getStandardName(); if (name == null || name.trim().isEmpty()) { if (er != null) { name = er.getStandardName(); } if (name == null || name.trim().isEmpty()) { if (!pe.getName().isEmpty()) { // Use first name of entity name = pe.getName().iterator().next(); } else if (er != null && !er.getName().isEmpty()) { // Use first name of reference name = er.getName().iterator().next(); } } } } } // Search for the shortest name of chemicals if (pe instanceof SmallMolecule) { String shortName = getShortestName((SmallMolecule) pe); if (shortName != null) { if (name == null || (shortName.length() < name.length() && !shortName.isEmpty())) { name = shortName; } } } if (name == null || name.trim().isEmpty()) { // Don't leave it without a name name = "noname"; } return name; }
/* Looks for the display name of this PhysicalEntity. If there is none, then it looks for the display name of its EntityReference. If still no name at hand, it tries the standard name, and then first element in name lists. A good BioPAX file will use a short and specific name (like HGNC symbols) as displayName. @param pe PhysicalEntity or Gene to find a name @return a name for labeling
private String extractGeneSymbol(Xref xref) { if (xref.getDb() != null && ( xref.getDb().equalsIgnoreCase("HGNC Symbol") || xref.getDb().equalsIgnoreCase("Gene Symbol") || xref.getDb().equalsIgnoreCase("HGNC"))) { String ref = xref.getId(); if (ref != null) { ref = ref.trim(); if (ref.contains(":")) ref = ref.substring(ref.indexOf(":") + 1); if (ref.contains("_")) ref = ref.substring(ref.indexOf("_") + 1); // if the reference is an HGNC ID, then convert it to a symbol if (!HGNC.containsSymbol(ref) && Character.isDigit(ref.charAt(0))) { ref = HGNC.getSymbol(ref); } } return ref; } return null; }
Searches for gene symbol in Xref. @param xref Xref to search @return gene symbol
private List<Glyph> getInformation(Entity e) { List<Glyph> list = new ArrayList<Glyph>(); // Add the molecule type before states if this is a nucleic acid or gene if (e instanceof NucleicAcid || e instanceof Gene) { Glyph g = factory.createGlyph(); g.setClazz(GlyphClazz.UNIT_OF_INFORMATION.getClazz()); Label label = factory.createLabel(); String s; if(e instanceof Dna) s = "mt:DNA"; else if(e instanceof DnaRegion) s = "ct:DNA"; else if(e instanceof Rna) s = "mt:RNA"; else if(e instanceof RnaRegion) s = "ct:RNA"; else if(e instanceof Gene) s = "ct:gene"; else s = "mt:NuclAc"; label.setText(s); g.setLabel(label); list.add(g); } // Extract state variables if(e instanceof PhysicalEntity) { PhysicalEntity pe = (PhysicalEntity) e; extractFeatures(pe.getFeature(), true, list); extractFeatures(pe.getNotFeature(), false, list); } return list; }
/* Adds molecule type, and iterates over features of the entity and creates corresponding state variables. Ignores binding features and covalent-binding features. @param e entity or gene to collect features @return list of state variables
private void extractFeatures(Set<EntityFeature> features, boolean normalFeature, List<Glyph> list) { for (EntityFeature feature : features) { if (feature instanceof ModificationFeature || feature instanceof FragmentFeature) { Glyph stvar = factory.createGlyph(); stvar.setClazz(GlyphClazz.STATE_VARIABLE.getClazz()); Glyph.State state = featStrGen.createStateVar(feature, factory); if (state != null) { // Add a "!" in front of NOT features if (!normalFeature) { state.setValue("!" + state.getValue()); } stvar.setState(state); list.add(stvar); } } } }
/* Converts the features in the given feature set. Adds a "!" in front of NOT features. @param features feature set @param normalFeature specifies the type of features -- normal feature = true, NOT feature = false @param list state variables
private Glyph getCompartment(PhysicalEntity pe) { CellularLocationVocabulary cl = pe.getCellularLocation(); if (cl != null && !cl.getTerm().isEmpty()) { String name = null; // get a cv term, // ignoring IDs (should not be there but happens) for(String term : cl.getTerm()) { term = term.toLowerCase(); if(!term.matches("(go|so|mi|bto|cl|pato|mod):")) { name = term; break; } } return getCompartment(name); } else return null; }
/* Gets the compartment of the given PhysicalEntity. @param pe PhysicalEntity to look for its compartment @return name of compartment or null if there is none
private void createProcessAndConnections(Conversion cnv, ConversionDirectionType direction) { assert cnv.getConversionDirection() == null || cnv.getConversionDirection().equals(direction) || cnv.getConversionDirection().equals(ConversionDirectionType.REVERSIBLE); // create the process for the conversion in that direction Glyph process = factory.createGlyph(); process.setClazz(GlyphClazz.PROCESS.getClazz()); process.setId(convertID(cnv.getUri()) + "_" + direction.name().replaceAll("_","")); glyphMap.put(process.getId(), process); // Determine input and output sets Set<PhysicalEntity> input = direction.equals(ConversionDirectionType.RIGHT_TO_LEFT) ? cnv.getRight() : cnv.getLeft(); Set<PhysicalEntity> output = direction.equals(ConversionDirectionType.RIGHT_TO_LEFT) ? cnv.getLeft() : cnv.getRight(); // Create input and outputs ports for the process addPorts(process); Map<PhysicalEntity, Stoichiometry> stoic = getStoichiometry(cnv); // Associate inputs to input port for (PhysicalEntity pe : input) { Glyph g = getGlyphToLink(pe, process.getId()); createArc(g, process.getPort().get(0), direction == ConversionDirectionType.REVERSIBLE ? ArcClazz.PRODUCTION.getClazz() : ArcClazz.CONSUMPTION.getClazz(), stoic.get(pe)); } // Associate outputs to output port for (PhysicalEntity pe : output) { Glyph g = getGlyphToLink(pe, process.getId()); createArc(process.getPort().get(1), g, ArcClazz.PRODUCTION.getClazz(), stoic.get(pe)); } processControllers(cnv.getControlledOf(), process); // Record mapping Set<String> uris = new HashSet<String>(); uris.add(cnv.getUri()); sbgn2BPMap.put(process.getId(), uris); }
/* Creates a representation for Conversion. @param cnv the conversion @param direction direction of the conversion to create
private Map<PhysicalEntity, Stoichiometry> getStoichiometry(Conversion conv) { Map<PhysicalEntity, Stoichiometry> map = new HashMap<PhysicalEntity, Stoichiometry>(); for (Stoichiometry stoc : conv.getParticipantStoichiometry()) map.put(stoc.getPhysicalEntity(), stoc); return map; }
/* Gets the map of stoichiometry coefficients of participants. @param conv the conversion @return map from physical entities to their stoichiometry
private void createProcessAndConnections(TemplateReaction tr) { // create the process for the reaction Glyph process = factory.createGlyph(); process.setClazz(GlyphClazz.PROCESS.getClazz()); process.setId(convertID(tr.getUri())); glyphMap.put(process.getId(), process); final Set<PhysicalEntity> products = tr.getProduct(); final Set<PhysicalEntity> participants = new HashSet<PhysicalEntity>( //new modifiable set new ClassFilterSet<Entity,PhysicalEntity>(tr.getParticipant(), PhysicalEntity.class)); // link products, if any // ('participant' property is there defined sometimes instead of or in addition to 'product' or 'template') for (PhysicalEntity pe : products) { Glyph g = getGlyphToLink(pe, process.getId()); createArc(process, g, ArcClazz.PRODUCTION.getClazz(), null); participants.remove(pe); } // link template, if present PhysicalEntity template = tr.getTemplate(); if(template != null) { Glyph g = getGlyphToLink(template, process.getId()); createArc(g, process, ArcClazz.CONSUMPTION.getClazz(), null); participants.remove(template); } else if(participants.isEmpty()) { //when no template is defined and cannot be inferred, create a source-and-sink as the input Glyph sas = factory.createGlyph(); sas.setClazz(GlyphClazz.SOURCE_AND_SINK.getClazz()); sas.setId("unknown-template_" + ModelUtils.md5hex(process.getId())); glyphMap.put(sas.getId(), sas); createArc(sas, process, ArcClazz.CONSUMPTION.getClazz(), null); } //infer input or output type arc for the rest of participants for (PhysicalEntity pe : participants) { Glyph g = getGlyphToLink(pe, process.getId()); if(template==null) createArc(g, process, ArcClazz.CONSUMPTION.getClazz(), null); else createArc(process, g, ArcClazz.PRODUCTION.getClazz(), null); } // Associate controllers processControllers(tr.getControlledOf(), process); // Record mapping sbgn2BPMap.put(process.getId(), new HashSet<String>(Collections.singleton(tr.getUri()))); }
/* Creates a representation for TemplateReaction. @param tr template reaction
private Glyph createControlStructure(Control ctrl) { Glyph cg; Set<PhysicalEntity> controllers = getControllers(ctrl); // If no representable controller found, skip this control if (controllers.isEmpty()) { cg = null; } else if (controllers.size() == 1 && getControllerSize(ctrl.getControlledOf()) == 0) { // If there is only one controller with no modulator, put an arc for controller cg = getGlyphToLink(controllers.iterator().next(), convertID(ctrl.getUri())); } else { // This list will contain handles for each participant of the AND structure List<Glyph> toConnect = new ArrayList<Glyph>(); // Bundle controllers if necessary Glyph gg = handlePEGroup(controllers, convertID(ctrl.getUri())); if(gg != null) toConnect.add(gg); // Handle co-factors of catalysis if (ctrl instanceof Catalysis) { Set<PhysicalEntity> cofs = ((Catalysis) ctrl).getCofactor(); Glyph g = handlePEGroup(cofs, convertID(ctrl.getUri())); if (g != null) toConnect.add(g); } if (toConnect.isEmpty()) { return null; } else if (toConnect.size() == 1) { cg = toConnect.iterator().next(); } else { cg = connectWithAND(toConnect); } } return cg; }
/* Creates or gets the glyph to connect to the control arc. @param ctrl Control to represent @return glyph representing the controller tree
private Glyph handlePEGroup(Set<PhysicalEntity> pes, String context) { int sz = pes.size(); if (sz > 1) { List<Glyph> gs = getGlyphsOfPEs(pes, context); return connectWithAND(gs); } else if (sz == 1) { PhysicalEntity pe = pes.iterator().next(); if(glyphMap.containsKey(convertID(pe.getUri()))) return getGlyphToLink(pe, context); } //'pes' was empty return null; }
/* Prepares the necessary construct for adding the given PhysicalEntity set to the Control being drawn. @param pes entities to use in control @return the glyph to connect to the appropriate place
private List<Glyph> getGlyphsOfPEs(Set<PhysicalEntity> pes, String context) { List<Glyph> gs = new ArrayList<Glyph>(); for (PhysicalEntity pe : pes) if (glyphMap.containsKey(convertID(pe.getUri()))) gs.add(getGlyphToLink(pe, context)); return gs; }
/* Gets the glyphs of the given set of PhysicalEntity objects. Does not create anything. @param pes entities to get their glyphs @return glyphs of entities
private Glyph connectWithAND(List<Glyph> gs) { // Compose an ID for the AND glyph StringBuilder sb = new StringBuilder(); Iterator<Glyph> iterator = gs.iterator(); if(iterator.hasNext()) sb.append(iterator.next()); while (iterator.hasNext()) sb.append("-AND-").append(iterator.next().getId()); String id = ModelUtils.md5hex(sb.toString()); //shorten a very long id // Create the AND glyph if not exists Glyph and = glyphMap.get(id); if (and == null) { and = factory.createGlyph(); and.setClazz(GlyphClazz.AND.getClazz()); and.setId(id); glyphMap.put(and.getId(), and); } // Connect upstream to the AND glyph for (Glyph g : gs) createArc(g, and, ArcClazz.LOGIC_ARC.getClazz(), null); return and; } /* * Converts the control type of the Control to the SBGN classes. * * @param ctrl Control to get its type * @return SBGN type of the Control */ private String getControlType(Control ctrl) { if (ctrl instanceof Catalysis) { // Catalysis has its own class return ArcClazz.CATALYSIS.getClazz(); } ControlType type = ctrl.getControlType(); if (type == null) { // Use stimulation as the default control type return ArcClazz.STIMULATION.getClazz(); } // Map control type to stimulation or inhibition switch (type) { case ACTIVATION: case ACTIVATION_ALLOSTERIC: case ACTIVATION_NONALLOSTERIC: case ACTIVATION_UNKMECH: return ArcClazz.STIMULATION.getClazz(); case INHIBITION: case INHIBITION_ALLOSTERIC: case INHIBITION_OTHER: case INHIBITION_UNKMECH: case INHIBITION_COMPETITIVE: case INHIBITION_IRREVERSIBLE: case INHIBITION_UNCOMPETITIVE: case INHIBITION_NONCOMPETITIVE: return ArcClazz.INHIBITION.getClazz(); default: throw new RuntimeException("Invalid control type: " + type); } } /* * Gets the size of representable Controller of this set of Controls. * * @param ctrlSet Controls to check their controllers * @return size of representable controllers */ private int getControllerSize(Set<Control> ctrlSet) { int size = 0; for (Control ctrl : ctrlSet) { size += getControllers(ctrl).size(); } return size; } /* * Gets the size of representable Controller of this Control. * * @param ctrl Control to check its controllers * @return size of representable controllers */ private Set<PhysicalEntity> getControllers(Control ctrl) { Set<PhysicalEntity> controllers = new HashSet<PhysicalEntity>(); for (Controller clr : ctrl.getController()) { if (clr instanceof PhysicalEntity && glyphMap.containsKey(convertID(clr.getUri()))) { controllers.add((PhysicalEntity) clr); } } return controllers; } /* * Adds input and output ports to the glyph. * * @param g glyph to add ports */ private void addPorts(Glyph g) { Port inputPort = factory.createPort(); Port outputPort = factory.createPort(); inputPort.setId("INP_" + g.getId()); outputPort.setId("OUT_" + g.getId()); g.getPort().add(inputPort); g.getPort().add(outputPort); } /* * Creates an arc from the source to the target, and sets its class to the specified clazz. * Puts the new arc in the sullied arcMap. * * @param source source of the arc -- either Glyph or Port * @param target target of the arc -- either Glyph or Port * @param clazz class of the arc */ private void createArc(Object source, Object target, String clazz, Stoichiometry stoic) { assert source instanceof Glyph || source instanceof Port : "source = " + source; assert target instanceof Glyph || target instanceof Port : "target = " + target; Arc arc = factory.createArc(); arc.setSource(source); arc.setTarget(target); arc.setClazz(clazz); String sourceID = source instanceof Glyph ? ((Glyph) source).getId() : ((Port) source).getId(); String targetID = target instanceof Glyph ? ((Glyph) target).getId() : ((Port) target).getId(); arc.setId(sourceID + "--TO--" + targetID); if (stoic != null && stoic.getStoichiometricCoefficient() > 1) { Glyph card = factory.createGlyph(); card.setClazz(GlyphClazz.CARDINALITY.getClazz()); Label label = factory.createLabel(); label.setText(new DecimalFormat("0.##").format(stoic.getStoichiometricCoefficient())); card.setLabel(label); arc.getGlyph().add(card); } Arc.Start start = new Arc.Start(); start.setX(0); start.setY(0); arc.setStart(start); Arc.End end = new Arc.End(); end.setX(0); end.setY(0); arc.setEnd(end); arcMap.put(arc.getId(), arc); } /* * Collects root-level glyphs in the given glyph collection. * * @param glyphCol glyph collection to search * @return set of roots */ private Set<Glyph> getRootGlyphs(Collection<Glyph> glyphCol) { Set<Glyph> root = new HashSet<Glyph>(glyphCol); Set<Glyph> children = new HashSet<Glyph>(); for (Glyph glyph : glyphCol) { addChildren(glyph, children); } root.removeAll(children); return root; } /* * Adds children of this glyph to the specified set recursively. * @param glyph to collect children * @param set to add */ private void addChildren(Glyph glyph, Set<Glyph> set) { for (Glyph child : glyph.getGlyph()) { set.add(child); addChildren(child, set); } } /** * Gets the mapping from SBGN IDs to BioPAX IDs. * This mapping is currently many-to-one, but can * potentially become many-to-many in the future. * @return sbgn-to-biopax mapping */ public Map<String, Set<String>> getSbgn2BPMap() { return sbgn2BPMap; } private String convertID(String id) { return id; }
/* Creates an AND glyph downstream of the given glyphs. @param gs upstream glyph list @return AND glyph
public void addRangeRestriction(Class<? extends BioPAXElement> domain, Set<Class<? extends BioPAXElement>> ranges) { this.restrictedRanges.put(domain, ranges); }
This method adds a range restriction to the property editor. e.g. All entityReferences of Proteins should be ProteinReferences. Note: All restrictions specified in the BioPAX specification is automatically created by the {@link EditorMap} during initialization. Use this method if you need to add restrictions that are not specified in the model. @param domain subdomain of the property to be restricted @param ranges valid ranges for this subdomain.
public void setRangeRestriction( Map<Class<? extends BioPAXElement>, Set<Class<? extends BioPAXElement>>> restrictedRanges) { this.restrictedRanges = restrictedRanges; }
This method sets all range restrictions. Note: All restrictions specified in the BioPAX specification is automatically created by the {@link EditorMap} during initialization. Use this method if you need to add restrictions that are not specified in the model. @param restrictedRanges a set of range restrictions specified as a map.
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { Collection<BioPAXElement> gen = new HashSet<BioPAXElement> ( con[0].generate(match, ind)); Set<BioPAXElement> input = new HashSet<BioPAXElement>(); Set<BioPAXElement> output = new HashSet<BioPAXElement>(gen); int[] tempInd = {0, 1}; for (int i = 1; i < con.length; i++) { if (output.isEmpty()) break; input.clear(); input.addAll(output); output.clear(); for (BioPAXElement ele : input) { Match m = new Match(2); m.set(ele, 0); output.addAll(con[i].generate(m, tempInd)); } } return output; }
Chains the member constraints and returns the output of the last constraint. @param match match to process @param ind mapped indices @return satisfying elements
void addXREF(xref XREF_INST) { this.XREF.add(XREF_INST); XREF_INST.isXREFof().add(owner); }
-------------------------- OTHER METHODS --------------------------
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { Control ctrl = (Control) match.get(ind[0]); return new HashSet<BioPAXElement>(getRelatedERs(ctrl)); }
Navigates to the related ERs of the controllers of the given Control. @param match current pattern match @param ind mapped indices @return related ERs
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); Conversion conv = (Conversion) match.get(ind[1]); if (!((peType == RelType.INPUT && getConvParticipants(conv, RelType.INPUT).contains(pe)) || (peType == RelType.OUTPUT && getConvParticipants(conv, RelType.OUTPUT).contains(pe)))) throw new IllegalArgumentException("peType = " + peType + ", and related participant set does not contain this PE. Conv dir = " + getDirection(conv) + " conv.id=" + conv.getUri() + " pe.id=" +pe.getUri()); boolean rightContains = conv.getRight().contains(pe); boolean leftContains = conv.getLeft().contains(pe); assert rightContains || leftContains : "PE is not a participant."; Set<BioPAXElement> result = new HashSet<BioPAXElement>(); ConversionDirectionType avoidDir = (leftContains && rightContains) ? null : peType == RelType.OUTPUT ? (leftContains ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT) : (rightContains ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT); for (Object o : controlledOf.getValueFromBean(conv)) { Control ctrl = (Control) o; ConversionDirectionType dir = getDirection(conv, ctrl); if (avoidDir != null && dir == avoidDir) continue; // don't collect this if the pe is ubique in the context of this control if (blacklist != null && blacklist.isUbique(pe, conv, dir, peType)) continue; result.add(ctrl); } return result; }
According to the relation between PhysicalEntity and the Conversion, checks of the Control is relevant. If relevant it is retrieved. @param match current pattern match @param ind mapped indices @return related controls
@Override public void init() { ControlType type = ctrl.getControlType(); if (type != null && type.toString().startsWith("I")) { sign = NEGATIVE; } else { sign = POSITIVE; } if (ctrl instanceof TemplateReactionRegulation) transcription = true; }
Extracts the sign and the type of the Control.
private void bindUpstream(BioPAXElement element) { AbstractNode node = (AbstractNode) graph.getGraphObject(element); if (node != null) { Edge edge = new EdgeL3(node, this, graph); node.getDownstreamNoInit().add(edge); this.getUpstreamNoInit().add(edge); } }
Puts the wrapper of the parameter element to the upstream of this Control. @param element to put at upstream
@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); } for (Process prc : ctrl.getControlled()) { if (prc instanceof Interaction) { bindUpstream(prc); } } }
Binds the controller and other Controls that controls this control.
@Override public void initDownstream() { for (Controller controller : ctrl.getController()) { if (controller instanceof Pathway) continue; PhysicalEntity pe = (PhysicalEntity) controller; bindDownstream(pe); } for (Control control : ctrl.getControlledOf()) { bindDownstream(control); } for (Process prc : ctrl.getControlled()) { if (prc instanceof Interaction) { bindDownstream(prc); } } }
Binds the controlled objects.
public void visit(BioPAXElement domain, Object range, Model targetModel, PropertyEditor editor) { BioPAXElement targetDomain = targetModel.getByID(domain.getUri()); if (range instanceof BioPAXElement) { BioPAXElement bpe = (BioPAXElement) range; BioPAXElement existing = targetModel.getByID(bpe.getUri()); //set the property value if the value is already present in the target if (existing != null) { editor.setValueToBean(existing, targetDomain); } } else { editor.setValueToBean(range, targetDomain); } }
Implement interface: Visitor
public Set getValueFromModel(Model model) { Set<? extends BioPAXElement> domains = new HashSet<BioPAXElement>(model.getObjects(this.getDomain())); return getValueFromBeans(domains); }
This method runs the path query on all the elements within the model. @param model to be queried @return a merged set of all values that is reachable by the paths starting from all applicable objects in the model. For example running ProteinReference/xref:UnificationXref on the model will get all the unification xrefs of all ProteinReferences.
public void convertToJsonld(InputStream in, OutputStream os) throws IOException { File inputProcessedFile = preProcessFile(in); LOG.info("OWl File processed successfully "); // print current time SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); LOG.info("Conversion RDF to JSONLD started " + sdf.format(Calendar.getInstance().getTime())); // create an empty model Model modelJena = ModelFactory.createDefaultModel(); InputStream internalInputStream = new FileInputStream(inputProcessedFile); // read the RDF/XML file RDFDataMgr.read(modelJena, internalInputStream, Lang.RDFXML); LOG.info("Read into Model finished " + sdf.format(Calendar.getInstance().getTime())); try { //close quietly and delete the temp. input file internalInputStream.close(); inputProcessedFile.delete(); } catch(Exception e) {} RDFDataMgr.write(os, modelJena, Lang.JSONLD); LOG.info("Conversion RDF to JSONLD finished " + sdf.format(Calendar.getInstance().getTime())); LOG.info(" JSONLD file " + " is written successfully."); try { //close, flush quietly os.close(); } catch(Exception e) {} }
/* Convert inputstream in owl/rdf format to outputsream in jsonld format
public void convertFromJsonld(InputStream in, OutputStream out) { Model modelJena = ModelFactory.createDefaultModel(); if (in == null) { throw new IllegalArgumentException("Input File: " + " not found"); } if (out == null) { throw new IllegalArgumentException("Output File: " + " not found"); } // read the JSONLD file modelJena.read(in, null, "JSONLD"); RDFDataMgr.write(out, modelJena, Lang.RDFXML); LOG.info(" RDF file " + " is written successfully."); }
/* Convert inputstream in jsonld format to outputsream if owl/rdf format
public File preProcessFile(InputStream in) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); LOG.info("BIOPAX Conversion started " + sdf.format(Calendar.getInstance().getTime())); if (in == null) { throw new IllegalArgumentException("Input File: " + " is not found"); } SimpleIOHandler simpleIO = new SimpleIOHandler(BioPAXLevel.L3); // create a Paxtools Model from the BioPAX L3 RDF/XML input file (stream) org.biopax.paxtools.model.Model model = simpleIO.convertFromOWL(in); // - and the input stream 'in' gets closed inside the above method call // set for the IO to output full URIs: simpleIO.absoluteUris(true); File fullUriBiopaxInput = File.createTempFile("paxtools", ".owl"); fullUriBiopaxInput.deleteOnExit(); // delete on JVM exits FileOutputStream outputStream = new FileOutputStream(fullUriBiopaxInput); // write to an output stream (back to RDF/XML) simpleIO.convertToOWL((org.biopax.paxtools.model.Model) model, outputStream); // it closes the stream internally LOG.info("BIOPAX Conversion finished " + sdf.format(Calendar.getInstance().getTime())); return fullUriBiopaxInput; }
Converts the BioPAX data (stream) to an equivalent temporary BioPAX RDF/XML file that contains absolute instead of (possibly) relative URIs for all the BioPAX elements out there; and returns that file. @param in biopax input stream @return a temporary file @throws IOException
private void load(String filename) { try { load(new FileInputStream(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } }
Reads data from the given file.
private void load(InputStream is) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { String[] tok = line.split(DELIM); if (tok.length >= 3) { addEntry(tok[0], Integer.parseInt(tok[1]), convertContext(tok[2])); } } reader.close(); } catch (Exception e) { e.printStackTrace(); context = null; score = null; } }
Reads data from the input stream and loads itself.
public void addEntry(String id, int score, RelType context) { this.score.put(id, score); this.context.put(id, context); }
Adds a new blacklisted ID. @param id ID of the blacklisted molecule @param score the ubiquity score @param context context of ubiquity
public void write(String filename) { try { write(new FileOutputStream(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } }
Dumps data to the given file. @param filename output file name
public void write(OutputStream os) { List<String> ids = new ArrayList<String>(score.keySet()); final Map<String, Integer> score = this.score; Collections.sort(ids, new Comparator<String>() { @Override public int compare(String o1, String o2) { return score.get(o2).compareTo(score.get(o1)); } }); try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); boolean notFirst = false; for (String id : ids) { if (notFirst) writer.write("\n"); else notFirst = true; writer.write(id + DELIM + score.get(id) + DELIM + convertContext(context.get(id))); } writer.close(); } catch (IOException e) { e.printStackTrace(); } }
Dumps data to the given output stream. @param os output stream
private RelType convertContext(String type) { if (type.equals("I")) return RelType.INPUT; if (type.equals("O")) return RelType.OUTPUT; if (type.equals("B")) return null; throw new IllegalArgumentException("Unknown context: " + type); }
Converts text context to enum. @param type context @return enum value
private Set<String> getLeastUbique(Collection<String> ids) { Set<String> select = new HashSet<String>(); int s = getLeastScore(ids); for (String id : ids) { if (score.get(id) == s) select.add(id); } return select; }
Gets the subset with the least score.
private int getLeastScore(Collection<String> ids) { int s = Integer.MAX_VALUE; for (String id : ids) { if (score.get(id) < s) s = score.get(id); } return s; }
Gets the least score of the given ids.
private boolean isUbiqueInBothContexts(String id) { return context.containsKey(id) && context.get(id) == null; }
Checks if the given ID is blacklisted in both contexts together.
private boolean isUbique(String id, RelType context) { if (context == null) return this.context.containsKey(id); if (!isUbique(id)) return false; RelType ctx = this.context.get(id); return ctx == null || ctx.equals(context); }
Checks if the given ID is blacklisted in the given context.
public boolean isUbique(PhysicalEntity pe) { String id = getSMRID(pe); return id != null && isUbique(id); }
Checks if the given entity is blacklisted in at least one context. @param pe physical entity BioPAX object @return true/false
public boolean isUbiqueInBothContexts(PhysicalEntity pe) { String id = getSMRID(pe); return id != null && isUbiqueInBothContexts(id); }
Checks if the given entity is blacklisted in both context together. @param pe physical entity BioPAX object @return true/false
public boolean isUbique(PhysicalEntity pe, Conversion conv, ConversionDirectionType dir, RelType context) { String id = getSMRID(pe); if (id == null) return false; if (dir == null) throw new IllegalArgumentException("The conversion direction has to be specified."); if (context == null) throw new IllegalArgumentException("The context has to be only one type."); Set<PhysicalEntity> parts; if (dir == ConversionDirectionType.REVERSIBLE) { if (conv.getLeft().contains(pe)) parts = conv.getLeft(); else if (conv.getRight().contains(pe)) parts = conv.getRight(); else throw new IllegalArgumentException("The PhysicalEntity has to be at least one " + "side of the Conversion"); } else { parts = dir == ConversionDirectionType.LEFT_TO_RIGHT ? context == RelType.INPUT ? conv.getLeft() : conv.getRight() : context == RelType.OUTPUT ? conv.getLeft() : conv.getRight(); } // if the Conversion direction is reversible, then don't mind the current context if (dir == ConversionDirectionType.REVERSIBLE) return getUbiques(parts, null).contains(pe); else return getUbiques(parts, context).contains(pe); }
Checks if the given entity is blacklisted for the given Conversion assuming the Conversion flows towards the given direction, and the entity is in given context. @param pe physical entity BioPAX object @param conv conversion interaction (BioPAX) @param dir conversion direction @param context relationship type - context @return true/false
private String getSMRID(PhysicalEntity pe) { if (pe instanceof SmallMolecule) { EntityReference er = ((SmallMolecule) pe).getEntityReference(); if (er != null) return er.getUri(); } return null; }
Gets the ID of the reference of the given entity if it is a small molecule.
public Collection<SmallMolecule> getUbiques(Set<PhysicalEntity> entities, RelType context) { Map<String, SmallMolecule> ubiques = new HashMap<String, SmallMolecule>(); boolean allUbiques = true; for (PhysicalEntity pe : entities) { if (pe instanceof SmallMolecule) { EntityReference er = ((SmallMolecule) pe).getEntityReference(); if (er != null && isUbique(er.getUri(), context)) { ubiques.put(er.getUri(), (SmallMolecule) pe); } else { allUbiques = false; } } else allUbiques = false; } if (allUbiques && !ubiques.isEmpty()) { Set<String> least = getLeastUbique(ubiques.keySet()); for (String id : least) { ubiques.remove(id); } } return ubiques.values(); }
Gets the ubiquitous small molecules among the given set and in the given context. It is assumed that the given set is either left or right of a Conversion. If there is no non-ubiquitous element in the set, then the least ubique(s) are removed from the result. @param entities left or right of a conversion @param context are these entities input or output @return ubiquitous small molecules in the given context
public Set<PhysicalEntity> getNonUbiques(Set<PhysicalEntity> entities, RelType ctx) { Collection<SmallMolecule> ubiques = getUbiques(entities, ctx); if (ubiques.isEmpty()) return entities; Set<PhysicalEntity> result = new HashSet<PhysicalEntity>(entities); result.removeAll(ubiques); return result; }
Gets the non-ubiquitous physical entities in the given set and in the given context. It is assumed that the given set is either left or right of a Conversion. If there is no non-ubiquitous element in the set, then the least ubique(s) are added to the result. @param entities left or right of a conversion @param ctx are these entities input or output @return non-ubiquitous physical entities in the given context
@Override public void initUpstream() { for (Entity entity : interaction.getParticipant()) { addToUpstream(entity, getGraph()); } for (Control control : interaction.getControlledOf()) { addToUpstream(control, getGraph()); } }
Binds to participants and controllers.
@Override public void initDownstream() { for (Entity entity : interaction.getParticipant()) { addToDownstream(entity, getGraph()); } for (Control control : interaction.getControlledOf()) { addToDownstream(control, getGraph()); } }
Binds to participants and controllers.
protected void addToDownstream(BioPAXElement pe, Graph graph) { AbstractNode node = (AbstractNode) graph.getGraphObject(pe); if (node != null) { EdgeL3 edge = new EdgeL3(this, node, graph); edge.setTranscription(true); node.getUpstreamNoInit().add(edge); this.getDownstreamNoInit().add(edge); } }
Binds the given PhysicalEntity to the downstream. @param pe PhysicalEntity to bind @param graph Owner graph