code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public void setTrackTheme(String value) { // data-track-theme is not available for flipswitch, so we have to hack it trackTheme = value != null ? value.trim() : value; refreshTrackTheme(); }
Sets the theme for the track button
public static <S extends HasAttachHandlers> void fire(S source, PanelState panelState) { if (TYPE != null) { JQMPanelEvent event = new JQMPanelEvent(panelState); source.fireEvent(event); } }
Fires an {@link JQMPanelEvent} on all registered handlers in the handler source. @param <S> The handler source type @param source - the source of the handlers
static void changePage(String url, TransitionIntf<?> t, boolean reverse, boolean changeHash, boolean dialog) { changingPage = true; try { changePage(url, t.getJqmValue(), reverse, changeHash, dialog ? DATA_ROLE_DIALOG : null); } finally { changingPage = false; } }
Invokes the $.mobile.changePage method
private void created() { String t = getTheme(); if (t != null && !t.isEmpty()) setTheme(t); }
Unfortunately it's not called in case of manual JQMContext.render(), though widget is getting created and enhanced.
public static void fire(HasHandlers source, String jqmEventName, JavaScriptObject jQueryEvent) { JQMEvent<?> event = JQMEventFactory.createEvent(jqmEventName, jQueryEvent); source.fireEvent(event); }
Fires a {@link JQMEvent} on all registered handlers in the handler manager. If no such handlers exist, this method will do nothing. @param source - the source of the handlers
@Override public void onModuleLoad() { ScriptUtils.waitJqmLoaded(new Callback<Void, Throwable>() { @Override public void onSuccess(Void result) { runExamples(); } @Override public void onFailure(Throwable reason) { Window.alert(reason.getMessage()); } }); }
This is the entry point method.
public void setDefaultContentType(DefaultContentType value) { defaultContentType = value; if (defaultContentType != null) { setData(""); searchable = false; orderable = false; } }
Set default, static, content for a column - predefined widgets, defaultContent will be used for innerHtml if defined.
public String calcDefaultContent() { if (defaultContentType == null) return defaultContent; String s; switch (defaultContentType) { case BUTTON: s = "<button data-role='none'>"; if (!Empty.is(defaultContent)) s += defaultContent; return s + "</button>"; case CHECKBOX: case CHECKBOX_ROWSELECT: s = "<input type='checkbox' data-role='none'"; if (DefaultContentType.CHECKBOX_ROWSELECT.equals(defaultContentType)) { s += " class='" + JsDataTable.CHECKBOX_ROWSEL + "'"; } if (!Empty.is(defaultContent)) { s += ">" + defaultContent + "</input>"; } else { s += "></input>"; } return s; case ROW_DETAILS: return ""; default: return defaultContent; } }
Combines both defaultContentType and defaultContent and generates proper content.
@Override public void setText(String text) { if (text == null) { if (header != null) flow.remove(header); } else { if (header == null) { header = new Heading(1); flow.add(header); } header.setText(text); } }
Sets the value of the header(Hn) element
@Override public void setHTML(String html) { if (html == null) { if (header != null) flow.remove(header); } else { if (header == null) { header = new Heading(1); flow.add(header); } header.getElement().setInnerHTML(html); } }
Sets the value of the header(Hn) element
private SearchResult transform(Query query, IndexSearcher searcher, boolean highlight, TopDocs topDocs) throws CorruptIndexException, IOException { final SearchResult response = new SearchResult(); final List<BioPAXElement> hits = new ArrayList<BioPAXElement>(); response.setMaxHitsPerPage(maxHitsPerPage); response.setHits(hits); for(ScoreDoc scoreDoc : topDocs.scoreDocs) { Document doc = searcher.doc(scoreDoc.doc); String uri = doc.get(FIELD_URI); BioPAXElement bpe = model.getByID(uri); LOG.debug("transform: doc:" + scoreDoc.doc + ", uri:" + uri); // use the highlighter (get matching fragments) // for this to work, all keywords were stored in the index field if (highlight && doc.get(FIELD_KEYWORD) != null) { // use a Highlighter (store.YES must be enabled for 'keyword' field) QueryScorer scorer = new QueryScorer(query, FIELD_KEYWORD); //this fixes scoring/highlighting for all-field wildcard queries like q=insulin* //but not for term/prefix queries, i.e, q=name:insulin*, q=pathway:brca2. TODO scorer.setExpandMultiTermQuery(true); //TODO try PostingsHighlighter once it's stable... // (see http://lucene.apache.org/core/4_10_0/highlighter/org/apache/lucene/search/postingshighlight/PostingsHighlighter.html) SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span class='hitHL'>", "</span>"); Highlighter highlighter = new Highlighter(formatter, scorer); highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer, 80)); final String text = StringUtils.join(doc.getValues(FIELD_KEYWORD), " "); try { TokenStream tokenStream = analyzer.tokenStream("", new StringReader(text)); String res = highlighter.getBestFragments(tokenStream, text, 7, "..."); if(res != null && !res.isEmpty()) { bpe.getAnnotations().put(HitAnnotation.HIT_EXCERPT.name(), res); } } catch (Exception e) {throw new RuntimeException(e);} } else if(highlight) { LOG.warn("Highlighter skipped, because KEYWORD field was null; hit: " + uri + ", " + bpe.getModelInterface().getSimpleName()); } // extract organisms (URI only) if not done before if(doc.get(FIELD_ORGANISM) != null && !bpe.getAnnotations().containsKey(HitAnnotation.HIT_ORGANISM.name())) { Set<String> uniqueVals = new TreeSet<String>(); for(String o : doc.getValues(FIELD_ORGANISM)) { //note: only URIS are stored in the index uniqueVals.add(o); } bpe.getAnnotations().put(HitAnnotation.HIT_ORGANISM.name(), uniqueVals); } // extract values form the index if not previously done if(doc.get(FIELD_DATASOURCE) != null && !bpe.getAnnotations().containsKey(HitAnnotation.HIT_DATASOURCE.name())) { Set<String> uniqueVals = new TreeSet<String>(); for(String d : doc.getValues(FIELD_DATASOURCE)) { //note: only URIS are stored in the index uniqueVals.add(d); } bpe.getAnnotations().put(HitAnnotation.HIT_DATASOURCE.name(), uniqueVals); } // extract only pathway URIs if not previously done //(because names and IDs used to be stored in the index field as well) if(doc.get(FIELD_PATHWAY) != null && !bpe.getAnnotations().containsKey(HitAnnotation.HIT_PATHWAY.name())) { Set<String> uniqueVals = new TreeSet<String>(); for(String d : doc.getValues(FIELD_PATHWAY)) { //only URIs were stored (though all names/ids were indexed/analyzed) if(!d.equals(uri)) //exclude itself uniqueVals.add(d); } bpe.getAnnotations().put(HitAnnotation.HIT_PATHWAY.name(), uniqueVals); } //store the no. processes in the sub-network if not previously done if(doc.get(FIELD_N_PARTICIPANTS)!=null && !bpe.getAnnotations().containsKey(HitAnnotation.HIT_PARTICIPANTS.name())) bpe.getAnnotations().put(HitAnnotation.HIT_PARTICIPANTS.name(), Integer.valueOf(doc.get(FIELD_N_PARTICIPANTS))); if(doc.get(FIELD_N_PROCESSES)!=null && !bpe.getAnnotations().containsKey(HitAnnotation.HIT_PROCESSES.name())) bpe.getAnnotations().put(HitAnnotation.HIT_PROCESSES.name(), Integer.valueOf(doc.get(FIELD_N_PROCESSES))); //store the Lucene's score and explanation. String excerpt = (String) bpe.getAnnotations().get(HitAnnotation.HIT_EXCERPT.name()); if(excerpt == null) excerpt = ""; excerpt += " -SCORE- " + scoreDoc.score + " -EXPLANATION- " + searcher.explain(query, scoreDoc.doc); bpe.getAnnotations().put(HitAnnotation.HIT_EXCERPT.name(), excerpt); hits.add(bpe); } //set total no. hits response.setTotalHits(topDocs.totalHits); return response; }
Returns a SearchResult that contains a List<BioPAXElement>, some parameters, totals, etc.
void index(BioPAXElement bpe, IndexWriter indexWriter) { // create a new document final Document doc = new Document(); // save URI (not indexed field) Field field = new StoredField(FIELD_URI, bpe.getUri()); doc.add(field); // index and store but not analyze/tokenize the biopax class name: field = new StringField(FIELD_TYPE, bpe.getModelInterface().getSimpleName().toLowerCase(), Field.Store.YES); doc.add(field); // make index fields from the annotations map (of pre-calculated/inferred values) if(!bpe.getAnnotations().isEmpty()) { if(bpe.getAnnotations().containsKey(FIELD_PATHWAY)) { addPathways((Set<Pathway>)bpe.getAnnotations().get(FIELD_PATHWAY), doc); } if(bpe.getAnnotations().containsKey(FIELD_ORGANISM)) { addOrganisms((Set<BioSource>)bpe.getAnnotations().get(FIELD_ORGANISM), doc); } if(bpe.getAnnotations().containsKey(FIELD_DATASOURCE)) { addDatasources((Set<Provenance>)bpe.getAnnotations().get(FIELD_DATASOURCE), doc); } if(bpe.getAnnotations().containsKey(FIELD_KEYWORD)) { addKeywords((Set<String>)bpe.getAnnotations().get(FIELD_KEYWORD), doc); } if(bpe.getAnnotations().containsKey(FIELD_N_PARTICIPANTS)) { field = new StoredField(FIELD_N_PARTICIPANTS, Integer.parseInt((String)bpe.getAnnotations().get(FIELD_N_PARTICIPANTS))); doc.add(field); } if(bpe.getAnnotations().containsKey(FIELD_N_PROCESSES)) { field = new IntField(FIELD_N, Integer.parseInt((String)bpe.getAnnotations().get(FIELD_N_PROCESSES)), Field.Store.NO); doc.add(field); field = new StoredField(FIELD_N_PROCESSES, Integer.parseInt((String)bpe.getAnnotations().get(FIELD_N_PROCESSES))); doc.add(field); } if(bpe.getAnnotations().containsKey(FIELD_XREFID)) { //index biological IDs as keywords addKeywords((Set<String>)bpe.getAnnotations().get(FIELD_XREFID), doc); //index all IDs using "xrefid" fields for (String id : (Set<String>)bpe.getAnnotations().get(FIELD_XREFID)) { Field f = new StringField(FIELD_XREFID, id.toLowerCase(), Field.Store.NO); doc.add(f); } } } bpe.getAnnotations().remove(FIELD_KEYWORD); bpe.getAnnotations().remove(FIELD_DATASOURCE); bpe.getAnnotations().remove(FIELD_ORGANISM); bpe.getAnnotations().remove(FIELD_PATHWAY); bpe.getAnnotations().remove(FIELD_N_PARTICIPANTS); bpe.getAnnotations().remove(FIELD_N_PROCESSES); bpe.getAnnotations().remove(FIELD_XREFID); // name if(bpe instanceof Named) { Named named = (Named) bpe; if(named.getStandardName() != null) { field = new TextField(FIELD_NAME, named.getStandardName(), Field.Store.NO); field.setBoost(3.5f); doc.add(field); } if(named.getDisplayName() != null && !named.getDisplayName().equalsIgnoreCase(named.getStandardName())) { field = new TextField(FIELD_NAME, named.getDisplayName(), Field.Store.NO); field.setBoost(3.0f); doc.add(field); } for(String name : named.getName()) { if(name.equalsIgnoreCase(named.getDisplayName()) || name.equalsIgnoreCase(named.getStandardName())) continue; field = new TextField(FIELD_NAME, name.toLowerCase(), Field.Store.NO); field.setBoost(2.5f); doc.add(field); } } // write try { indexWriter.addDocument(doc); } catch (IOException e) { throw new RuntimeException("Failed to index; " + bpe.getUri(), e); } }
Creates a new Lucene Document that corresponds to a BioPAX object. It does not check whether the document exists (should not be there, because the {@link #index()} method cleans up the index) Some fields also include biopax data type property values not only from the biopax object but also from its child elements, up to some depth (using key-value pairs in the pre-computed bpe.annotations map): 'uri' - biopax object's absolute URI, analyze=no, store=yes; 'name' - names, analyze=yes, store=yes; boosted; 'keyword' - infer from this bpe and its child objects' data properties, such as Score.value, structureData, structureFormat, chemicalFormula, availability, term, comment, patoData, author, source, title, url, published, up to given depth/level; and also all 'pathway' field values are included here; analyze=yes, store=yes; 'datasource', 'organism' and 'pathway' - infer from this bpe and its child objects up to given depth/level, analyze=no, store=yes; 'size' - number of child processes, an integer as string; analyze=no, store=yes @param bpe BioPAX object @param indexWriter index writer
public <D extends BioPAXElement> void traverse(D element, Model model) { Set<PropertyEditor> editors = editorMap.getEditorsOf(element); if (editors == null) { log.warn("No editors for : " + element.getModelInterface()); return; } for (PropertyEditor<? super D,?> editor : editors) { if (filter(editor)) { Set<?> valueSet = editor.getValueFromBean(element); if (!valueSet.isEmpty()) traverseElements(element, model, editor, valueSet); } } }
Traverse and visit {@link Visitor} all properties of the element. This method does not traverse iteratively to the values. @param element BioPAX element to be traversed @param model to be traversed, but not necessarily (depends on the Visitor implementation). @param <D> actual BioPAX type which properties and inherited properties will be used
@Override public boolean satisfies(Match match, int... ind) { assertIndLength(ind); // Collect values of the element group Set values = new HashSet(); for (BioPAXElement gen : con1.generate(match, ind)) { values.addAll(pa1.getValueFromBean(gen)); } // If emptiness is desired, check that if (value == EMPTY) return values.isEmpty(); // If cannot be empty, check it if (oper == Operation.NOT_EMPTY_AND_NOT_INTERSECT && values.isEmpty()) return false; // If the second element is desired value, check that else if (value == USE_SECOND_ARG) { BioPAXElement q = match.get(ind[1]); return oper == Operation.INTERSECT ? values.contains(q) : !values.contains(q); } // If element group is compared to preset value, but the value is actually a collection, // then iterate the collection, see if any of them matches else if (value instanceof Collection) { Collection query = (Collection) value; values.retainAll(query); if (oper == Operation.INTERSECT) return !values.isEmpty(); else return values.isEmpty(); } // If two set of elements should share a field value, check that else if (pa2 != null) { // Collect values of the second group Set others = new HashSet(); for (BioPAXElement gen : con2.generate(match, ind)) { others.addAll(pa2.getValueFromBean(gen)); } switch (oper) { case INTERSECT: others.retainAll(values); return !others.isEmpty(); case NOT_INTERSECT: others.retainAll(values); return others.isEmpty(); case NOT_EMPTY_AND_NOT_INTERSECT: if (others.isEmpty()) return false; others.retainAll(values); return others.isEmpty(); default: throw new RuntimeException("Unhandled operation: " + oper); } } // Check if the element field values contain the parameter value else if (oper == Operation.INTERSECT) return values.contains(value); else return !values.contains(value); }
Checks if the generated elements from the first mapped element has either the desired value, or has some value in common with the elements generated from second mapped element. @param match current pattern match @param ind mapped indices @return true if a value match is found
public void initUpstream() { for (Interaction inter : pe.getParticipantOf()) { AbstractNode wrapper = (AbstractNode) graph.getGraphObject(inter); if (wrapper == null) continue; Edge edge = new EdgeL3(wrapper, this, graph); wrapper.getDownstreamNoInit().add(edge); this.getUpstreamNoInit().add(edge); } }
Binds to upstream interactions.
protected void initUpperEquivalent() { this.upperEquivalent = new HashSet<Node>(); for (PhysicalEntity eq : pe.getMemberPhysicalEntityOf()) { Node node = (Node) graph.getGraphObject(eq); if (node != null) this.upperEquivalent.add(node); } upperEquivalentInited = true; }
Finds homology parent.
protected void initLowerEquivalent() { this.lowerEquivalent = new HashSet<Node>(); for (PhysicalEntity eq : pe.getMemberPhysicalEntity()) { Node node = (Node) graph.getGraphObject(eq); if (node != null) this.lowerEquivalent.add(node); } lowerEquivalentInited = true; }
Finds member nodes if this is a homology node
protected boolean semanticallyEquivalent(BioPAXElement element) { final interaction that = (conversion) element; return LEFT.equals(that.getPARTICIPANTS()); }
todo
public AdjacencyMatrix searchSIFGetMatrix(Model model) { Set<SIFInteraction> sifInts = searchSIF(model); return new AdjacencyMatrix( SIFInteraction.convertToAdjacencyMatrix(sifInts), SIFInteraction.getSortedGeneNames(sifInts)); }
Searches the given model with the contained miners. @param model model to search @return sif interactions
public Set<SIFInteraction> searchSIF(final Model model) { if (miners == null) initMiners(); final Map<SIFInteraction, SIFInteraction> map = new ConcurrentHashMap<SIFInteraction, SIFInteraction>(); for (final SIFMiner miner : miners) { if (miner instanceof MinerAdapter) ((MinerAdapter) miner).setIdMap(new HashMap<BioPAXElement, Set<String>>()); Map<BioPAXElement,List<Match>> matches = Searcher.search(model, miner.getPattern()); for (final List<Match> matchList : matches.values()) { for (Match m : matchList) { Set<SIFInteraction> sifs = miner.createSIFInteraction(m, idFetcher); for (SIFInteraction sif : sifs) { if ( sif != null && sif.hasIDs() && !sif.sourceID.equals(sif.targetID) && (types == null || types.contains(sif.type)) ) { SIFInteraction existing = map.get(sif); if(existing != null) existing.mergeWith(sif); else map.put(sif, sif); } } } } } return new HashSet<SIFInteraction>(map.values()); }
Searches the given model with the contained miners. @param model model to search @return sif interactions
public boolean searchSIF(Model model, OutputStream out) { return searchSIF(model, out, new SIFToText() { @Override public String convert(SIFInteraction inter) { return inter.toString(); } }); }
Searches the given model with the contained miners. Writes the textual result to the given output stream. Closes the stream at the end. Produces the simplest version of SIF format. @param model model to search @param out stream to write @return true if any output produced successfully
public boolean searchSIF(Model model, OutputStream out, SIFToText stt) { Set<SIFInteraction> inters = searchSIF(model); if (!inters.isEmpty()) { List<SIFInteraction> interList = new ArrayList<SIFInteraction>(inters); Collections.sort(interList); try { boolean first = true; OutputStreamWriter writer = new OutputStreamWriter(out); for (SIFInteraction inter : interList) { if (first) first = false; else writer.write("\n"); writer.write(stt.convert(inter)); } writer.close(); return true; } catch (IOException e) { e.printStackTrace(); } } return false; }
Searches the given model with the contained miners. Writes the textual result to the given output stream. Closes the stream at the end. @param model model to search @param out stream to write @param stt sif to text converter @return true if any output produced successfully
public <T extends BioPAXElement> T copy(Model model, T source, String newID) { T copy = copy(source, newID); model.add(copy); return copy; }
Creates a copy of the BioPAX object with all its properties are the same, and also adds it to a model. @param <T> BioPAX type/class of the source and copy elements @param model target biopax model @param source a biopax object to copy @param newID new (copy) biopax object's URI @return copy of the source biopax element
public <T extends BioPAXElement> T copy(T source, String newID) { T copy = (T) level.getDefaultFactory().create( (Class<T>) source.getModelInterface(), newID); this.copy = copy; // to avoid unnecessary checks/warnings when existing valid element is being cloned //(e.g., copying BPS.stepProcess values, if there is a Conversion, which was set via stepConversion). AbstractPropertyEditor.checkRestrictions.set(false); traverser.traverse(source, null); AbstractPropertyEditor.checkRestrictions.set(true);//back to default return copy; }
Returns a copy of the BioPAX element (with all the property values are same) @param <T> biopax type @param source biopax element to copy @param newID copy biopax element's absolute URI @return a copy of the source biopax element
public void visit(BioPAXElement domain, Object range, Model model, PropertyEditor editor) { editor.setValueToBean(range, copy); }
{@inheritDoc}
protected boolean semanticallyEquivalent(BioPAXElement element) { final physicalEntityParticipant that = (physicalEntityParticipant) element; return isInEquivalentState(that) && isInEquivalentContext(that); }
--------------------- Interface BioPAXElement ---------------------
@Override public void setEntityReference(EntityReference entityReference) { if(entityReference instanceof DnaRegionReference || entityReference == null) super.setEntityReference(entityReference); else throw new IllegalBioPAXArgumentException("setEntityReference failed: " + entityReference.getUri() + " is not a DnaRegionReference."); }
------------------------ INTERFACE METHODS ------------------------
@Override public boolean satisfies(Match match, int... ind) { return generate(match, ind).contains(match.get(ind[ind.length - 1])); }
Use this method only if constraint canGenerate, and satisfaction criteria is that simple. @param match current pattern match @param ind mapped indices @return true if the match satisfies this constraint
protected ConversionDirectionType getDirection(Conversion conv, Control cont) { return getDirection(conv, null, cont); }
Gets the direction of the Control chain the the Interaction. @param conv controlled conversion @param cont top control @return the direction of the conversion related to the catalysis
protected ConversionDirectionType getDirection(Conversion conv, Pathway pathway, Control cont) { for (Control ctrl : getControlChain(cont, conv)) { ConversionDirectionType dir = getCatalysisDirection(ctrl); if (dir != null) return dir; } Set<StepDirection> dirs = new HashSet<StepDirection>(); Set<PathwayStep> convSteps = conv.getStepProcessOf(); // maybe the direction is embedded in a pathway step for (PathwayStep step : cont.getStepProcessOf()) { if (pathway != null && !step.getPathwayOrderOf().equals(pathway)) continue; if (step instanceof BiochemicalPathwayStep && convSteps.contains(step)) { StepDirection dir = ((BiochemicalPathwayStep) step).getStepDirection(); if (dir != null) dirs.add(dir); } } if (dirs.size() > 1) return ConversionDirectionType.REVERSIBLE; else if (!dirs.isEmpty()) return convertStepDirection(dirs.iterator().next()); return getDirection(conv); }
Gets the direction of the Control chain the the Interaction. @param conv controlled conversion @param pathway the container pathway @param cont top control @return the direction of the conversion related to the catalysis
protected ConversionDirectionType getDirection(Conversion conv, Pathway pathway) { Set<StepDirection> dirs = new HashSet<StepDirection>(); // find the direction in the pathway step for (PathwayStep step : conv.getStepProcessOf()) { if (step.getPathwayOrderOf().equals(pathway) && step instanceof BiochemicalPathwayStep) { StepDirection dir = ((BiochemicalPathwayStep) step).getStepDirection(); if (dir != null) dirs.add(dir); } } if (dirs.size() > 1) return ConversionDirectionType.REVERSIBLE; else if (!dirs.isEmpty()) return convertStepDirection(dirs.iterator().next()); return getDirection(conv); }
Gets the direction of the Control chain the the Interaction. @param conv controlled conversion @param pathway the container pathway @return the direction of the conversion related to the catalysis
protected ConversionDirectionType getCatalysisDirection(Control cont) { if (cont instanceof Catalysis) { CatalysisDirectionType catDir = ((Catalysis) cont).getCatalysisDirection(); if (catDir == CatalysisDirectionType.LEFT_TO_RIGHT) { return ConversionDirectionType.LEFT_TO_RIGHT; } else if (catDir == CatalysisDirectionType.RIGHT_TO_LEFT) { return ConversionDirectionType.RIGHT_TO_LEFT; } } return null; }
Gets the direction of the Control, if exists. @param cont Control to get its direction @return the direction of the Control
protected List<Control> getControlChain(Control control, Interaction inter) { LinkedList<Control> list = new LinkedList<Control>(); list.add(control); boolean found = search(list, inter); if (!found) throw new RuntimeException("No link from Control to Conversion."); return list; }
Gets the chain of Control, staring from the given Control, leading to the given Interaction. Use this method only if you are sure that there is a link from the control to conversion. Otherwise a RuntimeException is thrown. This assumes that there is only one control chain towards the interaction. It not, then one of the chains will be returned. @param control top level Control @param inter target Interaction @return Control chain controlling the Interaction
private boolean search(LinkedList<Control> list, Interaction inter) { if (list.getLast().getControlled().contains(inter)) return true; for (Process process : list.getLast().getControlled()) { if (process instanceof Control) { // prevent searching in cycles if (list.contains(process)) continue; list.add((Control) process); if (search(list, inter)) return true; else list.removeLast(); } } return false; }
Checks if the control chain is actually controlling the Interaction. @param list the Control chain @param inter target Interaction @return true if the chain controls the Interaction
protected Set<PhysicalEntity> getConvParticipants(Conversion conv, RelType type) { ConversionDirectionType dir = getDirection(conv); if (dir == ConversionDirectionType.REVERSIBLE) { HashSet<PhysicalEntity> set = new HashSet<PhysicalEntity>(conv.getLeft()); set.addAll(conv.getRight()); return set; } else if (dir == ConversionDirectionType.RIGHT_TO_LEFT) { return type == RelType.INPUT ? conv.getRight() : conv.getLeft(); } else return type == RelType.OUTPUT ? conv.getRight() : conv.getLeft(); }
Gets input ot output participants of the Conversion. @param conv Conversion to get participants @param type input or output @return related participants
protected ConversionDirectionType findDirectionInPathways(Conversion conv) { Set<StepDirection> dirs = new HashSet<StepDirection>(); for (PathwayStep step : conv.getStepProcessOf()) { if (step instanceof BiochemicalPathwayStep) { StepDirection dir = ((BiochemicalPathwayStep) step).getStepDirection(); if (dir != null) dirs.add(dir); } } if (dirs.size() > 1) return ConversionDirectionType.REVERSIBLE; else if (!dirs.isEmpty()) { return dirs.iterator().next() == StepDirection.LEFT_TO_RIGHT ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT; } else return null; }
Searches pathways that contains this conversion for the possible directions. If both directions exist, then the result is reversible. @param conv the conversion @return direction inferred from pathway membership
protected ConversionDirectionType findDirectionInCatalysis(Conversion conv) { Set<ConversionDirectionType> dirs = new HashSet<ConversionDirectionType>(); for (Control control : conv.getControlledOf()) { ConversionDirectionType dir = getCatalysisDirection(control); if (dir != null) dirs.add(dir); } if (dirs.size() > 1) return ConversionDirectionType.REVERSIBLE; else if (!dirs.isEmpty()) return dirs.iterator().next(); else return null; }
Searches the controlling catalysis for possible direction of the conversion. @param conv the conversion @return direction inferred from catalysis objects
@Override public Pattern constructPattern() { Pattern p = new Pattern(SmallMoleculeReference.class, "SMR"); p.add(new Size( new PathConstraint("SmallMoleculeReference/entityReferenceOf/participantOf:Conversion"), 50, Size.Type.GREATER_OR_EQUAL), "SMR"); return p; }
Constructs the pattern. @return pattern
@Override public String getValue(Match m, int col) { assert col == 0; return getRelatedIDs((SmallMoleculeReference) m.get("SMR", getPattern())); }
Gets the ids of the small molecule reference and its physical entities. @param m current match @param col current column @return ubique IDs
private String getRelatedIDs(SmallMoleculeReference smr) { String ids = smr.getUri(); for (Object o : new PathAccessor( "SmallMoleculeReference/entityReferenceOf").getValueFromBean(smr)) { SimplePhysicalEntity spe = (SimplePhysicalEntity) o; ids += "\n" + spe.getUri(); } return ids; }
Gets IDs of the small molecule reference and its physical entities. @param smr small molecule reference @return related IDs
public static Set<ModificationFeature>[] getChangedModifications(PhysicalEntity before, PhysicalEntity after) { Set<Modification> set1 = collectFeatures(before); Set<Modification> set2 = collectFeatures(after); Set<Modification> temp = new HashSet<Modification>(set1); set1.removeAll(set2); set2.removeAll(temp); // Remove common features that can be deemed semantically equivalent Set<Modification> furtherRemove = new HashSet<Modification>(); for (Modification m1 : set1) { for (Modification m2 : set2) { if (furtherRemove.contains(m2)) continue; if (m1.getKey().equals(m2.getKey())) { furtherRemove.add(m1); furtherRemove.add(m2); break; } } } set1.removeAll(furtherRemove); set2.removeAll(furtherRemove); return new Set[]{collectFeatures(set2), collectFeatures(set1)}; }
Gets the differential features. @param before first entity @param after second entity @return array of differential features. index 0: gained features, index 1: lost features
@Override public Pattern constructPattern() { Pattern p = new Pattern(SequenceEntityReference.class, "controller ER"); p.add(isHuman(), "controller ER"); p.add(linkedER(true), "controller ER", "controller generic ER"); p.add(erToPE(), "controller generic ER", "controller simple PE"); p.add(linkToComplex(), "controller simple PE", "controller PE"); p.add(peToControl(), "controller PE", "Control"); p.add(controlToInter(), "Control", "Interaction"); p.add(new NOT(participantER()), "Interaction", "controller ER"); p.add(participant(), "Interaction", "affected PE"); p.add(linkToSpecific(), "affected PE", "affected simple PE"); p.add(new Type(SequenceEntity.class), "affected simple PE"); p.add(peToER(), "affected simple PE", "affected generic ER"); p.add(peToER(), "affected generic ER", "affected ER"); return p; }
Constructs the pattern. @return pattern
@Override public void writeResult(Map<BioPAXElement, List<Match>> matches, OutputStream out) throws IOException { writeResultAsSIF(matches, out, true, getSourceLabel(), getTargetLabel()); }
Writes the result as "A B", where A and B are gene symbols, and whitespace is tab. @param matches pattern search result @param out output stream
public static Constraint nameEquals(String... name) { return new Field("Named/name", Field.Operation.INTERSECT, new HashSet<String>(Arrays.asList(name))); }
Filters Named to contain a name from the input set. @param name name to require @return constraint
public static Constraint differentialActivity(boolean activating) { if (activating) return new AND(new MappedConst(new ActivityConstraint(true), 1), new MappedConst(new ActivityConstraint(false), 0)); else return new AND(new MappedConst(new ActivityConstraint(true), 0), new MappedConst(new ActivityConstraint(false), 1)); }
Gets a constraint to ensure that ensures only one of the two PhysicalEntities has an activity. Size of this constraint is 2. @param activating true/false (TODO explain) @return constraint to make sure only one of the PhysicalEntity has an activity
public static Constraint isHuman() { return new OR( new MappedConst(new Field("SequenceEntityReference/organism/displayName", Field.Operation.INTERSECT, "Homo sapiens"), 0), new MappedConst(new Field("PhysicalEntity/entityReference/organism/displayName", Field.Operation.INTERSECT, "Homo sapiens"), 0)); }
Makes sure the EntityReference or the PhysicalEntity belongs to human. Please note that this check depends on the display name of the related BioSource object to be "Homo sapiens". If that is not the case, the constraint won't work. @return constraint to make sure the EntityReference or the PhysicalEntity belongs to human
public static Constraint modificationConstraint(String modifTerm) { return new FieldOfMultiple(new MappedConst(new LinkedPE(LinkedPE.Type.TO_SPECIFIC), 0), "PhysicalEntity/feature:ModificationFeature/modificationType/term", Field.Operation.INTERSECT, modifTerm); }
Makes sure that the PhysicalEntity or any linked PE contains the modification term. Size = 1. @param modifTerm term to check @return constraint to filter out PhysicalEntity not associated to a modification term
public static Constraint inSamePathway() { String s1 = "Interaction/stepProcessOf/pathwayOrderOf"; String s2 = "Interaction/pathwayComponentOf"; return new OR(new MappedConst(new Field(s1, s1, Field.Operation.INTERSECT), 0, 1), new MappedConst(new Field(s2, s2, Field.Operation.INTERSECT), 0, 1)); }
Makes sure that the two interactions are members of the same pathway. @return non-generative constraint
public static Constraint moreControllerThanParticipant() { return new ConstraintAdapter(1) { PathAccessor partConv = new PathAccessor("PhysicalEntity/participantOf:Conversion"); PathAccessor partCompAss = new PathAccessor("PhysicalEntity/participantOf:ComplexAssembly"); PathAccessor effects = new PathAccessor("PhysicalEntity/controllerOf/controlled*:Conversion"); @Override public boolean satisfies(Match match, int... ind) { PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); int partCnvCnt = partConv.getValueFromBean(pe).size(); int partCACnt = partCompAss.getValueFromBean(pe).size(); int effCnt = effects.getValueFromBean(pe).size(); return (partCnvCnt - partCACnt) <= effCnt; } }; }
Makes sure that the PhysicalEntity is controlling more reactions than it participates (excluding complex assembly). @return non-generative constraint
public static Constraint hasDifferentCompartments() { String acStr = "PhysicalEntity/cellularLocation/term"; return new Field(acStr, acStr, Field.Operation.NOT_EMPTY_AND_NOT_INTERSECT); }
Checks if two physical entities have non-empty and different compartments. @return the constraint
public Map<GraphObject, Integer> run() { initMaps(); // Add all source nodes to the queue if traversal is needed if (limit > 0) { queue.addAll(sourceSet); } // Initialize dist and color of source set for (Node source : sourceSet) { setLabel(source, 0); setColor(source, GRAY); labelEquivRecursive(source, UPWARD, 0, true, false); labelEquivRecursive(source, DOWNWARD, 0, true, false); } // Process the queue while (!queue.isEmpty()) { Node current = queue.remove(0); processNode(current); // Current node is processed setColor(current, BLACK); } return dist; }
Executes the algorithm. @return BFS tree
protected void initMaps() { // Initialize label, maps and queue dist = new HashMap<GraphObject, Integer>(); colors = new HashMap<GraphObject, Integer>(); queue = new LinkedList<Node>(); }
Initializes maps used during query.
protected void processNode(Node current) { // Do not process the node if it is ubique if (current.isUbique()) { setColor(current, BLACK); return; } // System.out.println("processing = " + current); // Process edges towards the direction for (Edge edge : direction == Direction.DOWNSTREAM ? current.getDownstream() : current.getUpstream()) { assert edge != null; // Label the edge considering direction of traversal and type of current node if (direction == Direction.DOWNSTREAM || !current.isBreadthNode()) { setLabel(edge, getLabel(current)); } else { setLabel(edge, getLabel(current) + 1); } // Get the other end of the edge Node neigh = direction == Direction.DOWNSTREAM ? edge.getTargetNode() : edge.getSourceNode(); assert neigh != null; // Decide neighbor label according to the search direction and node type int dist = getLabel(edge); if (neigh.isBreadthNode() && direction == Direction.DOWNSTREAM) dist++; // Check if we need to stop traversing the neighbor, enqueue otherwise boolean further = (stopSet == null || !isEquivalentInTheSet(neigh, stopSet)) && (!neigh.isBreadthNode() || dist < limit) && !neigh.isUbique(); // Process the neighbor if not processed or not in queue if (getColor(neigh) == WHITE) { // Label the neighbor setLabel(neigh, dist); if (further) { 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); } } else { // If we do not want to traverse this neighbor, we paint it black setColor(neigh, BLACK); } } labelEquivRecursive(neigh, UPWARD, getLabel(neigh), further, !neigh.isBreadthNode()); labelEquivRecursive(neigh, DOWNWARD, getLabel(neigh), further, !neigh.isBreadthNode()); } }
Processes a node. @param current The current node
protected void labelEquivRecursive(Node node, boolean up, int dist, boolean enqueue, boolean head) { if(node == null) { LOG.error("labelEquivRecursive: null (Node)"); return; } for (Node equiv : up ? node.getUpperEquivalent() : node.getLowerEquivalent()) { if (getColor(equiv) == WHITE) { setLabel(equiv, dist); if (enqueue) { setColor(equiv, GRAY); if (head) queue.addFirst(equiv); else queue.add(equiv); } else { setColor(equiv, BLACK); } } labelEquivRecursive(equiv, up, dist, enqueue, head); } }
Labels equivalent nodes recursively. @param node Node to label equivalents @param up Traversing direction. Up means towards parents, if false then towards children @param dist The label @param enqueue Whether to enqueue equivalents @param head Where to enqueue. Head or tail.
protected boolean isEquivalentInTheSet(Node node, Set<Node> set) { return set.contains(node) || isEquivalentInTheSet(node, UPWARD, set) || isEquivalentInTheSet(node, DOWNWARD, set); }
Checks if an equivalent of the given node is in the set. @param node Node to check equivalents @param set Node set @return true if an equivalent is in the set
protected boolean isEquivalentInTheSet(Node node, boolean direction, Set<Node> set) { for (Node eq : direction == UPWARD ? node.getUpperEquivalent() : node.getLowerEquivalent()) { if (set.contains(eq)) return true; boolean isIn = isEquivalentInTheSet(eq, direction, set); if (isIn) return true; } return false; }
Checks if an equivalent of the given node is in the set. @param node Node to check equivalents @param direction Direction to go to get equivalents @param set Node set @return true if an equivalent is in the set
protected int getColor(Node node) { if (!colors.containsKey(node)) { // Absence of color is interpreted as white return WHITE; } else { return colors.get(node); } }
Gets color tag of the node @param node Node to get color tag @return color tag
public int getLabel(GraphObject go) { if (!dist.containsKey(go)) { // Absence of label is interpreted as infinite return Integer.MAX_VALUE-(limit*2); } else { return dist.get(go); } }
Gets the distance label of the object. @param go object to get the distance @return the distance label
@Override public boolean satisfies(Match match, int... ind) { Control ctrl = (Control) match.get(ind[0]); for (Process process : ctrl.getControlled()) { if (process instanceof Interaction) { Interaction inter = (Interaction) process; Set<Entity> participant = inter.getParticipant(); for (Controller controller : ctrl.getController()) { if (participant.contains(controller)) return false; } } } return true; }
Checks if the controlled Interaction contains a controller as a participant. This constraint filters out such cases. @param match current pattern match @param ind mapped indices @return true if participants of teh controlled Interactions not also a controller of the Control.
public void setBindsTo(BindingFeature bindsTo) { //Check if we need to update if (this.bindsTo != bindsTo) { //ok go ahead - first get a pointer to the old binds to as we will swap this soon. BindingFeature old = this.bindsTo; //swap it this.bindsTo = bindsTo; //make sure old feature no longer points to this if (old != null && old.getBindsTo() == this) { old.setBindsTo(null); } //make sure new feature points to this if (!(this.bindsTo == null || this.bindsTo.getBindsTo() == this)) { this.bindsTo.setBindsTo(this); } } }
This method will set the paired binding feature that binds to this feature. This method will preserve the symmetric bidirectional semantics. If not-null old feature's bindsTo will be set to null and if not null new feature's binds to will set to this @param bindsTo paired binding feature.
public <T extends LocalizableResource> T create(Class<T> cls, String locale) { Locale l = null; if (locale != null) { String[] parts = locale.split("_", 3); l = new Locale( parts[0], parts.length > 1 ? parts[1] : "", parts.length > 2 ? parts[2] : "" ); } return LocaleProxy.create(cls, l); }
Create the resource using the Locale provided. If the locale is null, the locale is retrieved from the LocaleProvider in LocaleProxy. @param cls localization interface class @param <T> localization interface class @param locale locale string @return object implementing specified class
public boolean atEquivalentLocation(EntityFeature that) { return getEntityFeatureOf() != null && getEntityFeatureOf().isEquivalent(that.getEntityFeatureOf()) && getFeatureLocation() != null && getFeatureLocation().isEquivalent(that.getFeatureLocation()); }
This method returns true if and only if two entity features are on the same known location on a known ER. Unknown location or ER on any one of the features results in a false.
public static List<Match> search(Match m, Pattern pattern) { assert pattern.getStartingClass().isAssignableFrom(m.get(0).getModelInterface()); return searchRecursive(m, pattern.getConstraints(), 0); }
Searches the pattern starting from the given match. The first element of the match should be assigned. Others are optional. @param m match to start from @param pattern pattern to search @return result matches
public static List<Match> search(BioPAXElement ele, Pattern pattern) { assert pattern.getStartingClass().isAssignableFrom(ele.getModelInterface()); Match m = new Match(pattern.size()); m.set(ele, 0); return search(m, pattern); }
Searches the pattern starting from the given element. @param ele element to start from @param pattern pattern to search @return matching results
public static List<Match> searchRecursive(Match match, List<MappedConst> mc, int index) { List<Match> result = new ArrayList<Match>(); Constraint con = mc.get(index).getConstr(); int[] ind = mc.get(index).getInds(); int lastInd = ind[ind.length-1]; if (con.canGenerate() && match.get(lastInd) == null) { Collection<BioPAXElement> elements = con.generate(match, ind); for (BioPAXElement ele : elements) { match.set(ele, lastInd); if (mc.size() == index + 1) { result.add((Match) match.clone()); } else { result.addAll(searchRecursive(match, mc, index + 1)); } match.set(null, lastInd); } } else { if (con.satisfies(match, ind)) { if (mc.size() == index + 1) { result.add((Match) match.clone()); } else { result.addAll(searchRecursive(match, mc, index + 1)); } } } return result; }
Continues searching with the mapped constraint at the given index. @param match match to start from @param mc mapped constraints of the pattern @param index index of the current mapped constraint @return matching results
public static List<Match> searchPlain(Model model, Pattern pattern) { List<Match> list = new LinkedList<Match>(); Map<BioPAXElement, List<Match>> map = search(model, pattern); for (List<Match> matches : map.values()) { list.addAll(matches); } return list; }
Searches the pattern in a given model, but instead of a match map, returns all matches in a list. @param model model to search in @param pattern pattern to search for @return matching results
public static List<Match> searchPlain(Collection<? extends BioPAXElement> eles, Pattern pattern) { List<Match> list = new LinkedList<Match>(); Map<BioPAXElement, List<Match>> map = search(eles, pattern); for (List<Match> matches : map.values()) { list.addAll(matches); } return list; }
Searches the pattern starting from given elements, but instead of a match map, returns all matches in a list. @param eles elements to start from @param pattern pattern to search for @return matching results
public static Map<BioPAXElement, List<Match>> search(Model model, Pattern pattern) { return search(model, pattern, null); }
Searches the given pattern in the given model. @param model model to search in @param pattern pattern to search for @return map from starting elements to the list matching results
public static Map<BioPAXElement, List<Match>> search(final Model model, final Pattern pattern, final ProgressWatcher prg) { final Map<BioPAXElement, List<Match>> map = new ConcurrentHashMap<BioPAXElement, List<Match>>(); final ExecutorService exec = Executors.newFixedThreadPool(20); Set<? extends BioPAXElement> eles = model.getObjects(pattern.getStartingClass()); if (prg != null) prg.setTotalTicks(eles.size()); for (final BioPAXElement ele : eles) { exec.execute(new Runnable() { @Override public void run() { List<Match> matches = search(ele, pattern); if (!matches.isEmpty()) { map.put(ele, matches); } if (prg != null) prg.tick(1); } }); } exec.shutdown(); try { exec.awaitTermination(10, TimeUnit.MINUTES); } catch (InterruptedException e) { throw new RuntimeException("search, failed due to exec timed out.", e); } return Collections.unmodifiableMap(map); }
Searches the given pattern in the given model. @param model model to search in @param pattern pattern to search for @param prg progress watcher to keep track of the progress @return map from starting elements to the list matching results
public static Map<BioPAXElement, List<Match>> search(final Collection<? extends BioPAXElement> eles, final Pattern pattern) { final Map<BioPAXElement, List<Match>> map = new ConcurrentHashMap<BioPAXElement, List<Match>>(); final ExecutorService exec = Executors.newFixedThreadPool(10); for (final BioPAXElement ele : eles) { if (!pattern.getStartingClass().isAssignableFrom(ele.getModelInterface())) continue; exec.execute(new Runnable() { @Override public void run() { List<Match> matches = search(ele, pattern); if (!matches.isEmpty()) { map.put(ele, matches); } } }); } exec.shutdown(); try { exec.awaitTermination(10, TimeUnit.MINUTES); } catch (InterruptedException e) { throw new RuntimeException("search, failed due to exec timed out.", e); } return Collections.unmodifiableMap(new HashMap<BioPAXElement, List<Match>>(map)); }
Searches the given pattern starting from the given elements. @param eles elements to start from @param pattern pattern to search for @return map from starting element to the matching results
public static <T extends BioPAXElement> Set<T> searchAndCollect( Model model, Pattern pattern, int index, Class<T> c) { return searchAndCollect(model.getObjects(pattern.getStartingClass()), pattern, index, c); }
Searches a model for the given pattern, then collects the specified elements of the matches and returns. @param <T> BioPAX type @param model model to search in @param pattern pattern to search for @param index index of the element in the match to collect @param c type of the element to collect @return set of the elements at the specified index of the matching results
public static <T extends BioPAXElement> Set<T> searchAndCollect( Collection<? extends BioPAXElement> eles, Pattern pattern, int index, Class<T> c) { Set<T> set = new HashSet<T>(); for (Match match : searchPlain(eles, pattern)) { set.add((T) match.get(index)); } return set; }
Searches the given pattern starting from the given elements, then collects the specified elements of the matches and returns. @param <T> BioPAX type @param eles elements to start from @param pattern pattern to search for @param index index of the element in the match to collect @param c type of the element to collect @return set of the elements at the specified index of the matching results
public static <T extends BioPAXElement> Set<T> searchAndCollect( BioPAXElement ele, Pattern pattern, int index, Class<T> c) { Set<T> set = new HashSet<T>(); for (Match match : search(ele, pattern)) { set.add((T) match.get(index)); } return set; }
Searches the given pattern starting from the given element, then collects the specified elements of the matches and returns. @param <T> BioPAX type @param ele element to start from @param pattern pattern to search for @param index index of the element in the match to collect @param c type of the element to collect @return set of the elements at the specified index of the matching results
public boolean hasSolution(Pattern p, BioPAXElement ... ele) { Match m = new Match(p.size()); for (int i = 0; i < ele.length; i++) { m.set(ele[i], i); } return !search(m, p).isEmpty(); }
Checks if there is any match for the given pattern if search starts from the given element. @param p pattern to search for @param ele element to start from @return true if there is a match
public static void searchInFile(Pattern p, String inFile, String outFile) throws FileNotFoundException { searchInFile(p, inFile, outFile, Integer.MAX_VALUE, Integer.MAX_VALUE); }
Searches a pattern reading the model from the given file, and creates another model that is excised using the matching patterns. @param p pattern to search for @param inFile filename for the model to search in @param outFile filename for the result model @throws FileNotFoundException when no file exists
public static void searchInFile(Pattern p, String inFile, String outFile, int seedLimit, int graphPerSeed) throws FileNotFoundException { SimpleIOHandler h = new SimpleIOHandler(); Model model = h.convertFromOWL(new FileInputStream(inFile)); Map<BioPAXElement,List<Match>> matchMap = Searcher.search(model, p); System.out.println("matching groups size = " + matchMap.size()); List<Set<Interaction>> inters = new LinkedList<Set<Interaction>>(); Set<Integer> encountered = new HashSet<Integer>(); Set<BioPAXElement> toExise = new HashSet<BioPAXElement>(); int seedCounter = 0; for (BioPAXElement ele : matchMap.keySet()) { if (seedCounter >= seedLimit) break; int matchCounter = 0; List<Match> matches = matchMap.get(ele); if (!matches.isEmpty()) seedCounter++; for (Match match : matches) { matchCounter++; if (matchCounter > graphPerSeed) break; Set<Interaction> ints = getInter(match); toExise.addAll(Arrays.asList(match.getVariables())); toExise.addAll(ints); Integer hash = hashSum(ints); if (!encountered.contains(hash)) { encountered.add(hash); inters.add(ints); } } } System.out.println("created pathways = " + inters.size()); Model clonedModel = excise(toExise); int i = 0; for (Set<Interaction> ints : inters) { Pathway pathway = clonedModel.addNew(Pathway.class, System.currentTimeMillis() + "PaxtoolsPatternGeneratedMatch" + (++i)); pathway.setDisplayName("Match " + getLeadingZeros(i, inters.size()) + i); for (Interaction anInt : ints) { pathway.addPathwayComponent((Process) clonedModel.getByID(anInt.getUri())); } } handler.convertToOWL(clonedModel, new FileOutputStream(outFile)); }
Searches a pattern reading the model from the given file, and creates another model that is excised using the matching patterns. Users can limit the max number of starting element, and max number of matches for any starting element. These parameters is good for limiting the size of the result graph. @param p pattern to search for @param inFile filename for the model to search in @param outFile filename for the result model @param seedLimit max number of starting elements @param graphPerSeed max number of matches for a starting element @throws FileNotFoundException when no file exists
private static String getLeadingZeros(int i, int size) { assert i <= size; int w1 = (int) Math.floor(Math.log10(size)); int w2 = (int) Math.floor(Math.log10(i)); String s = ""; for (int j = w2; j < w1; j++) { s += "0"; } return s; }
Prepares an int for printing with leading zeros for the given size. @param i the int to prepare @param size max value for i @return printable string for i with leading zeros
private static Model excise(Set<BioPAXElement> result) { Completer c = new Completer(EM); result = c.complete(result); Cloner cln = new Cloner(EM, BioPAXLevel.L3.getDefaultFactory()); return cln.clone(result); }
Excises a model to the given elements. @param result elements to excise to @return excised model
private static Set<Interaction> getInter(Match match) { Set<Interaction> set = new HashSet<Interaction>(); for (BioPAXElement ele : match.getVariables()) { if (ele instanceof Interaction) { set.add((Interaction) ele); addControlsRecursive((Interaction) ele, set); } } return set; }
Gets all interactions in a match. @param match match to search @return all interaction in the match
private static void addControlsRecursive(Interaction inter, Set<Interaction> set) { for (Control ctrl : inter.getControlledOf()) { set.add(ctrl); addControlsRecursive(ctrl, set); } }
Adds controls of the given interactions recursively to the given set. @param inter interaction to add its controls @param set set to add to
private static Integer hashSum(Set<Interaction> set) { int x = 0; for (Interaction inter : set) { x += inter.hashCode(); } return x; }
Creates a hash code for a set of interactions. @param set interactions @return sum of hashes
@Override public boolean satisfies(Match match, int... ind) { assertIndLength(ind); return con.generate(match, ind).isEmpty(); }
Checks if the wrapped Constraint can generate any elements. This satisfies if it cannot. @param match current pattern match @param ind mapped indices @return true if the wrapped Constraint generates nothing
protected void addToUpstream(BioPAXElement ele, Graph graph) { AbstractNode node = (AbstractNode) graph.getGraphObject(ele); if (node == null) return; Edge edge = new EdgeL3(node, this, graph); if (isTranscription()) { if (node instanceof ControlWrapper) { ((ControlWrapper) node).setTranscription(true); } } node.getDownstreamNoInit().add(edge); this.getUpstreamNoInit().add(edge); }
Bind the wrapper of the given element to the upstream. @param ele Element to bind @param graph Owner graph.
private boolean passesFilters(Level3Element ele) { if (filters == null) return true; for (Filter filter : filters) { if (!filter.okToTraverse(ele)) return false; } return true; }
There must be no filter opposing to traverse this object to traverse it. @param ele element to check @return true if ok to traverse
@Override public Node wrap(Object obj) { // Check if the object is level3 if (!(obj instanceof Level3Element)) throw new IllegalArgumentException( "An object other than a Level3Element is trying to be wrapped: " + obj); // Check if the object passes the filter if (!passesFilters((Level3Element) obj)) return null; // Wrap if traversible if (obj instanceof PhysicalEntity) { return new PhysicalEntityWrapper((PhysicalEntity) obj, this); } else if (obj instanceof Control) { return new ControlWrapper((Control) obj, this); } else if (obj instanceof Interaction) { return new InteractionWrapper((Interaction) obj, this); } else { if (log.isWarnEnabled()) { log.warn("Invalid BioPAX object to wrap as node. Ignoring: " + obj); } return null; } }
This method creates a wrapper for every wrappable L3 element. @param obj Object to wrap @return The wrapper
@Override public String getKey(Object wrapped) { if (wrapped instanceof BioPAXElement) { return ((BioPAXElement) wrapped).getUri(); } throw new IllegalArgumentException("Object cannot be wrapped: " + wrapped); }
RDF IDs of elements is used as key in the object map. @param wrapped Object to wrap @return Key
public Set<Node> getWrapperSet(Set<?> objects) { Set<Node> wrapped = new HashSet<Node>(); for (Object object : objects) { Node node = (Node) getGraphObject(object); if (node != null) { wrapped.add(node); } } return wrapped; }
Gets wrappers of given elements @param objects Wrapped objects @return wrappers
public Map<Object, Node> getWrapperMap(Set<?> objects) { Map<Object, Node> map = new HashMap<Object, Node>(); for (Object object : objects) { Node node = (Node) getGraphObject(object); if (node != null) { map.put(object, node); } } return map; }
Gets an element-to-wrapper map for the given elements. @param objects Wrapped objects @return object-to-wrapper map
public Set<Object> getWrappedSet(Set<? extends GraphObject> wrappers) { Set<Object> objects = new HashSet<Object>(); for (GraphObject wrapper : wrappers) { if (wrapper instanceof PhysicalEntityWrapper) { objects.add(((PhysicalEntityWrapper) wrapper).getPhysicalEntity()); } else if (wrapper instanceof ControlWrapper) { objects.add(((ControlWrapper) wrapper).getControl()); } else if (wrapper instanceof InteractionWrapper) { objects.add(((InteractionWrapper) wrapper).getInteraction()); } } return objects; }
Gets the wrapped objects of the given wrappers. @param wrappers Wrappers @return Wrapped objects
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { Collection<BioPAXElement> gen = new HashSet<BioPAXElement> ( con[0].generate(match, ind)); for (int i = 1; i < con.length; i++) { if (gen.isEmpty()) break; gen.retainAll(con[i].generate(match, ind)); } return gen; }
Gets intersection of the generated elements by the member constraints. @param match match to process @param ind mapped indices @return satisfying elements
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); Set<BioPAXElement> set = getLinkedElements(pe); return set; }
Gets to the linked PhysicalEntity. @param match current pattern match @param ind mapped indices @return linked PhysicalEntity
protected void enrichWithGenerics(Set<BioPAXElement> seed, Set<BioPAXElement> all) { Set addition; if (type == Type.TO_GENERAL) addition = access(upperGenAcc, seed, all); else addition = access(lowerGenAcc, seed, all); all.addAll(addition); seed.addAll(addition); enrichWithCM(seed, all); }
Gets the linked homologies and then switches to complex-relationship mode. These two enrich methods call each other recursively. @param seed to get the linked elements from @param all already found links
protected void enrichWithCM(Set<BioPAXElement> seed, Set<BioPAXElement> all) { Set addition = access(type == Type.TO_GENERAL ? complexAcc : memberAcc, seed, all); if (blacklist != null) addition = blacklist.getNonUbiqueObjects(addition); if (!addition.isEmpty()) { all.addAll(addition); enrichWithGenerics(addition, all); } }
Gets parent complexes or complex members recursively according to the type of the linkage. @param seed elements to link @param all already found links
protected Set access(PathAccessor pa, Set<BioPAXElement> seed, Set<BioPAXElement> all) { Set set = pa.getValueFromBeans(seed); set.removeAll(all); // remove blacklisted if (blacklist == null) return set; else return blacklist.getNonUbiqueObjects(set); }
Uses the given PathAccessor to access fields of the seed and return only new elements that is not in the given element set (all). @param pa accessor to the filed @param seed entities to get their fields @param all already found values @return new values
public static <D extends BioPAXElement, R> PropertyEditor<D, R> createPropertyEditor(Class<D> domain, String property) { PropertyEditor editor = null; try { Method getMethod = detectGetMethod(domain, property); boolean multipleCardinality = isMultipleCardinality(getMethod); Class<R> range = detectRange(getMethod); if (range.isPrimitive() || range.equals(Boolean.class)) { editor = new PrimitivePropertyEditor<D, R>(property, getMethod, domain, range, multipleCardinality); } else if (range.isEnum()) { editor = new EnumeratedPropertyEditor(property, getMethod, domain, range, multipleCardinality); } else if (range.equals(String.class)) { editor = new StringPropertyEditor(property, getMethod, domain, multipleCardinality); } else { editor = new ObjectPropertyEditor(property, getMethod, domain, range, multipleCardinality); } } catch (NoSuchMethodException e) { if (log.isWarnEnabled()) log.warn("Failed creating the controller for " + property + " on " + domain); } return editor; }
This method creates a property reflecting on the domain and property. Proper subclass is chosen based on the range of the property. @param domain paxtools level2 interface that maps to the corresponding owl level2. @param property to be managed by the constructed controller. @param <D> domain @param <R> range @return a property controller to manipulate the beans for the given property.
private static String getJavaName(String owlName) { // Since java does not allow '-' replace them all with '_' String s = owlName.replaceAll("-", "_"); s = s.substring(0, 1).toUpperCase() + s.substring(1); return s; }
Given the name of a property's name as indicated in the OWL file, this method converts the name to a Java compatible name. @param owlName the property name as a string @return the Java compatible name of the property
protected static Class detectRange(Method getMethod) { Class range = getMethod.getReturnType(); //if the return type is a collection then we have multiple cardinality if (Collection.class.isAssignableFrom(range)) { //it is a collection, by default assume non parameterized. range = Object.class; //If the collection is parameterized, get it. Type genericReturnType = getMethod.getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { try { range = (Class) ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } //Now this is required as autoboxing will not work with reflection if (range == Double.class) { range = double.class; } if (range == Float.class) { range = float.class; } if (range == Integer.class) { range = int.class; } } if (log.isTraceEnabled()) log.trace(range.getCanonicalName()); } return range; }
Given the multiple cardinality feature, the range of the get method is returned. @param getMethod default method @return the range as a class
private void detectMethods() throws NoSuchMethodException { String javaName = getJavaName(property); if (multipleCardinality) { this.addMethod = domain.getMethod("add" + javaName, range); this.removeMethod = domain.getMethod("remove" + javaName, range); } else { this.setMethod = domain.getMethod("set" + javaName, range); } }
Detects and sets the default methods for the property to which editor is associated. If property has multiple cardinality, {@link #setMethod}, {@link #addMethod}, and {@link #removeMethod} are set, otherwise only the {@link #setMethod}. @exception NoSuchMethodException if a method for the property does not exist
@Override public void addMaxCardinalityRestriction(Class<? extends D> domain, int max) { if (multipleCardinality) { this.maxCardinalities.put(domain, max); } else { if (max == 1) { if (log.isInfoEnabled()) { log.info("unnecessary use of cardinality restriction. " + "Maybe you want to use functional instead?"); } } else if (max == 0) { this.maxCardinalities.put(domain, max); } else { assert false; } } }
-------------------------- OTHER METHODS --------------------------
protected boolean isInstanceOfAtLeastOne(Set<Class<? extends BioPAXElement>> classes, Object value) { boolean check = false; for (Class aClass : classes) { if (aClass.isInstance(value)) { check = true; break; } } return check; }
Checks if <em>value</em> is an instance of one of the classes given in a set. This method becomes useful, when the restrictions have to be checked for a set of objects. e.g. check if the value is in the range of the editor. @param classes a set of classes to be checked @param value value whose class will be checked @return true if value belongs to one of the classes in the set