:type graph: VariantGraph
970241
def merge(self, graph, witness_sigil, witness_tokens, alignments={}):
        
        # NOTE: token_to_vertex only contains newly generated vertices
        token_to_vertex = {}
        last = graph.start
        for token in witness_tokens:
            vertex = alignments.get(token, None)
            if not vertex:
                vertex = graph.add_vertex(token, witness_sigil)
                token_to_vertex[token] = vertex
            else:
                vertex.add_token(witness_sigil, token)
                # graph.add_token_to_vertex(vertex, token, witness_sigil)
            graph.connect(last, vertex, witness_sigil)
            last = vertex
        graph.connect(last, graph.end, witness_sigil)
        return token_to_vertex
1298250
def _build_gene_disease_model(
            self,
            gene_id,
            relation_id,
            disease_id,
            variant_label,
            consequence_predicate=None,
            consequence_id=None,
            allelic_requirement=None,
            pmids=None):
        
        model = Model(self.graph)
        geno = Genotype(self.graph)

        pmids = [] if pmids is None else pmids

        is_variant = False
        variant_or_gene = gene_id

        variant_id_string = variant_label
        variant_bnode = self.make_id(variant_id_string, "_")

        if consequence_predicate is not None \
                and consequence_id is not None:
            is_variant = True
            model.addTriple(variant_bnode,
                            consequence_predicate,
                            consequence_id)
            # Hack to add labels to terms that
            # don't exist in an ontology
            if consequence_id.startswith(':'):
                model.addLabel(consequence_id,
                               consequence_id.strip(':').replace('_', ' '))

        if is_variant:
            variant_or_gene = variant_bnode
            # Typically we would type the variant using the
            # molecular consequence, but these are not specific
            # enough for us to make mappings (see translation table)
            model.addIndividualToGraph(variant_bnode,
                                       variant_label,
                                       self.globaltt['variant_locus'])
            geno.addAffectedLocus(variant_bnode, gene_id)
            model.addBlankNodeAnnotation(variant_bnode)

        assoc = G2PAssoc(
            self.graph, self.name, variant_or_gene, disease_id, relation_id)
        assoc.source = pmids
        assoc.add_association_to_graph()

        if allelic_requirement is not None and is_variant is False:
            model.addTriple(
                assoc.assoc_id, self.globaltt['has_allelic_requirement'],
                allelic_requirement)
            if allelic_requirement.startswith(':'):
                model.addLabel(
                    allelic_requirement,
                    allelic_requirement.strip(':').replace('_', ' '))
183791
public String getVariant(String variantType) {
		String variant = null;
		if (bundleVariants != null) {
			variant = (String) bundleVariants.get(variantType);
		}
		return variant;
	}
521266
def graph_repr(self):
        """"""

        # Replace any floating point numbers in the expression
        # with their scientific notation
        final = re.sub(r"[-+]?\d*\.\d+",
                       lambda x: format(float(x.group(0)), '.2E'),
                       self._expr)
        # Graphviz interprets `\l` as "divide label into lines, left-justified"
        return "Expression:\\l  {}\\l".format(
            final,
        )
516753
void graphToRDF(String graphName, Map<String, Object> graph) {
        // 4.2)
        final List<Quad> triples = new ArrayList<Quad>();
        // 4.3)
        final List<String> subjects = new ArrayList<String>(graph.keySet());
        // Collections.sort(subjects);
        for (final String id : subjects) {
            if (JsonLdUtils.isRelativeIri(id)) {
                continue;
            }
            final Map<String, Object> node = (Map<String, Object>) graph.get(id);
            final List<String> properties = new ArrayList<String>(node.keySet());
            Collections.sort(properties);
            for (String property : properties) {
                final List<Object> values;
                // 4.3.2.1)
                if ("@type".equals(property)) {
                    values = (List<Object>) node.get("@type");
                    property = RDF_TYPE;
                }
                // 4.3.2.2)
                else if (isKeyword(property)) {
                    continue;
                }
                // 4.3.2.3)
                else if (property.startsWith("_:") && !api.opts.getProduceGeneralizedRdf()) {
                    continue;
                }
                // 4.3.2.4)
                else if (JsonLdUtils.isRelativeIri(property)) {
                    continue;
                } else {
                    values = (List<Object>) node.get(property);
                }

                Node subject;
                if (id.indexOf("_:") == 0) {
                    // NOTE: don't rename, just set it as a blank node
                    subject = new BlankNode(id);
                } else {
                    subject = new IRI(id);
                }

                // RDF predicates
                Node predicate;
                if (property.startsWith("_:")) {
                    predicate = new BlankNode(property);
                } else {
                    predicate = new IRI(property);
                }

                for (final Object item : values) {
                    // convert @list to triples
                    if (isList(item)) {
                        final List<Object> list = (List<Object>) ((Map<String, Object>) item)
                                .get("@list");
                        Node last = null;
                        Node firstBNode = nil;
                        if (!list.isEmpty()) {
                            last = objectToRDF(list.get(list.size() - 1));
                            firstBNode = new BlankNode(api.generateBlankNodeIdentifier());
                        }
                        triples.add(new Quad(subject, predicate, firstBNode, graphName));
                        for (int i = 0; i < list.size() - 1; i++) {
                            final Node object = objectToRDF(list.get(i));
                            triples.add(new Quad(firstBNode, first, object, graphName));
                            final Node restBNode = new BlankNode(api.generateBlankNodeIdentifier());
                            triples.add(new Quad(firstBNode, rest, restBNode, graphName));
                            firstBNode = restBNode;
                        }
                        if (last != null) {
                            triples.add(new Quad(firstBNode, first, last, graphName));
                            triples.add(new Quad(firstBNode, rest, nil, graphName));
                        }
                    }
                    // convert value or node object to triple
                    else {
                        final Node object = objectToRDF(item);
                        if (object != null) {
                            triples.add(new Quad(subject, predicate, object, graphName));
                        }
                    }
                }
            }
        }
        put(graphName, triples);
    }
966963
public void findStronglyConnectedComponents(GraphType g, GraphToolkit<GraphType, EdgeType, VertexType> toolkit) {

        // Perform the initial depth first search
        DepthFirstSearch<GraphType, EdgeType, VertexType> initialDFS = new DepthFirstSearch<>(g);
        if (m_vertexChooser != null) {
            initialDFS.setVertexChooser(m_vertexChooser);
        }
        initialDFS.search();

        // Create a transposed graph
        Transpose<GraphType, EdgeType, VertexType> t = new Transpose<>();
        GraphType transpose = t.transpose(g, toolkit);

        // Create a set of vertices in the transposed graph,
        // in descending order of finish time in the initial
        // depth first search.
        VisitationTimeComparator<VertexType> comparator = new VisitationTimeComparator<>(
                initialDFS.getFinishTimeList(), VisitationTimeComparator.DESCENDING);
        Set<VertexType> descendingByFinishTimeSet = new TreeSet<>(comparator);
        Iterator<VertexType> i = transpose.vertexIterator();
        while (i.hasNext()) {
            descendingByFinishTimeSet.add(i.next());
        }

        // Create a SearchTreeBuilder for transposed DFS
        SearchTreeBuilder<VertexType> searchTreeBuilder = new SearchTreeBuilder<>();

        // Now perform a DFS on the transpose, choosing the vertices
        // to visit in the main loop by descending finish time
        final Iterator<VertexType> vertexIter = descendingByFinishTimeSet.iterator();
        DepthFirstSearch<GraphType, EdgeType, VertexType> transposeDFS = new DepthFirstSearch<GraphType, EdgeType, VertexType>(
                transpose) {
            @Override
            protected VertexType getNextSearchTreeRoot() {
                while (vertexIter.hasNext()) {
                    VertexType vertex = vertexIter.next();
                    if (visitMe(vertex)) {
                        return vertex;
                    }
                }
                return null;
            }
        };
        if (m_vertexChooser != null) {
            transposeDFS.setVertexChooser(m_vertexChooser);
        }
        transposeDFS.setSearchTreeCallback(searchTreeBuilder);
        transposeDFS.search();

        // The search tree roots of the second DFS represent the
        // strongly connected components. Note that we call copySearchTree()
        // to make the returned search trees relative to the original
        // graph, not the transposed graph (which would be very confusing).
        Iterator<SearchTree<VertexType>> j = searchTreeBuilder.searchTreeIterator();
        while (j.hasNext()) {
            m_stronglyConnectedSearchTreeList.add(copySearchTree(j.next(), t));
        }
    }
307314
def inline_xref_graph(self):
        
        xg = self.xref_graph
        for n in self.nodes():
            if n in xg:
                self._add_meta_element(n, 'xrefs', [{'val':x} for x in xg.neighbors(n)])
829524
function factoryGraph(ParentClass) {
  
  if (!ParentClass) {
    var ParentClass = class {}
  }
  
  /**
   * Class to inherit. Class with methods for control links in graph.
   * Must be completed for adaptation to a particular database.
   * 
   * @class
   * @description `import { Graph } from 'ancient-graph';`
   */
  class Graph extends ParentClass {
    
    /**
     * Construct new graph and checks for required adaptation methods.
     * @throws {Error} if the adapter methods is not complete
     * 
     * @param {} collection - A pointer to the collection dannymineobhodimye daapteru to work with the graph. This may be a connection to the SQL database and table name, for example, or a collection of Mongo. 
     * @param {Object.<string, string>} fields - Comparison of the data in the collection of data in the graph. It is necessary for the adapter.
     * @param {Object} [config] - Additional config.
     * @param {Object} [config.aliases]
     * @param {String} [config.aliases.$]
     */
    constructor(collection, fields, config) {
      super(...arguments);
      this.collection = collection;
      this.fields = fields;
      if (typeof(config) != 'object') var config = {};
      this.config = config;
      if (typeof(config.aliases) != 'object') config.aliases = {};
      for (var f in fields) {
        if (!config.aliases[f]) config.aliases[f] = f;
      }
      this.config._aliases = {};
      for (var a in this.config.aliases) {
        this.config._aliases[this.config.aliases[a]] = a;
      }
      if (this.insert == Graph.prototype.insert) {
        throw new Error('Method `insert` is not adapted.');
      }
      if (this.update == Graph.prototype.update) {
        throw new Error('Method `update` is not adapted.');
      }
      if (this.remove == Graph.prototype.remove) {
        throw new Error('Method `remove` is not adapted.');
      }
      if (this.query == Graph.prototype.query) {
        throw new Error('Method `query` is not adapted.');
      }
      if (this.options == Graph.prototype.options) {
        throw new Error('Method `options` is not adapted.');
      }
      if (this.fetch == Graph.prototype.fetch) {
        throw new Error('Method `fetch` is not adapted.');
      }
      if (this.get == Graph.prototype.get) {
        throw new Error('Method `get` is not adapted.');
      }
      if (this.each == Graph.prototype.each) {
        throw new Error('Method `each` is not adapted.');
      }
      if (this.map == Graph.prototype.map) {
        throw new Error('Method `map` is not adapted.');
      }
      if (this.count == Graph.prototype.count) {
        throw new Error('Method `count` is not adapted.');
      }
      if (this.on == Graph.prototype.on) {
        throw new Error('Method `on` is not adapted.');
      }
    }
    
    /**
     * Should insert new link into graph.
     * If the database allows, it is recommended to return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {Link} link
     * @param {Graph~insertCallback} [callback]
     * @param {Object} [context]
     * @return {string} [id]
     */
    insert(link, callback, context) {}
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the unique id of inserted link as the second.
     *
     * @callback Graph~insertCallback
     * @param {Error} [error]
     * @param {string} [id]
     */
    
    /**
     * Should update to new state of modifier object link by unique id or by link query object.
     * If the database allows, it is recommended to return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {string|LinkSelector} selector
     * @param {LinkModifier} modifier
     * @param {Graph~updateCallback} [callback]
     * @param {Object} [context]
     * @return {number} [count]
     */
    update(selector, modifier, callback, context) {}
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.
     *
     * @callback Graph~updateCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should remove link by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @param {Graph~removeCallback} [callback]
     * @param {Object} [context]
     */
    remove(selector, callback, context) {}
    
    /**
     * Optional callback. If present, called with an error object as the first argument.
     *
     * @callback Graph~removeCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should generate adapter for database query for links search by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @return {*} query
     */
    query(selector) {}
    
    /**
     * Should generate adapter for database options. 
     * 
     * @param {Object} [options]
     * @return {*} options - a options suitable for the database
     */
    options(options) {}
    
    /**
     * Find and all matching links as an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~fetchCallback} [callback]
     * @return {Link[]} links - result links objects in array
     */
    fetch(selector, options, callback) {}
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the result links objects in array.
     *
     * @callback Graph~fetchCallback
     * @param {Error} [error]
     * @param {Link[]} [links]
     */
    
    /**
     * Get one first matching link.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~getCallback} [callback]
     * @return {Link} link - result link object
     */
    get(selector, options, callback) {}
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the result link object.
     *
     * @callback Graph~getCallback
     * @param {Error} [error]
     * @param {Link} [link]
     */
    
    /**
     * Should call callback once for each matching document, sequentially and synchronously.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~eachCallback} [callback]
     */
    each(selector, options, callback) {}
    
    /**
     * @callback Graph~eachCallback
     * @param {Link} [link]
     */
    
    /**
     * Should map callback over all matching documents. Returns an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~mapCallback} [callback]
     * @return {Array} results
     */
    map(selector, options, callback) {}
    
    /**
     * @callback Graph~mapCallback
     * @param {Link} [link]
     * @return {*} result
     */
    
    /**
     * Should count all matching documents.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~countCallback} [callback]
     * @return {number} [count]
     */
    count(selector, options, callback) {}
    
    /**
     * @callback Graph~countCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should subscribe to the events: link, unlink, insert, update, remove.
     * 
     * @param {string} event - One event name
     * @param {Graph~onCallback} callback
     * @returns {Function} Stops event subscription.
     * @example
     * var counter = 0;
     * var stop = graph.on('update', (oldData, newData) => {
     *   if (oldData.id == '1') console.log(oldData.id, 'is changed');
     *   counter++;
     *   if (counter == 3) stop();
     * });
     */
    on(event, callback) {}
    
    /**
     * @callback Graph~onCallback
     * @param {Link} [oldLink] - can be undefined on link and insert events
     * @param {Link} [newLink] - can be undefined on unlink and remove events
     * @param {Object} [context] - additional app information, such as context.userId
     */
  };
  
  return Graph;
}
841709
function factoryObjectGraph(ParentClassGraph){/**
   * Inherited class. Class with methods for control links in graph.
   * Adapted for array collection.
   * 
   * @class
   * @description `import { ObjectGraph as Graph } from 'ancient-graph';`
   */var ObjectGraph=function(_ParentClassGraph){_inherits(ObjectGraph,_ParentClassGraph);/**
     * Construct new graph and checks for required adaptation methods.
     * @param {Array[]} collection
     * @param {Object.<string, string>} fields - matching of fields in the link with fields in document
     * @param {Object} [config] - Additional config.
     * @param {Object} [config.aliases]
     * @param {String} [config.aliases.$]
     * @throws {Error} if the adapter methods is not complete
     */function ObjectGraph(collection,fields,config){_classCallCheck(this,ObjectGraph);var _this=_possibleConstructorReturn(this,(ObjectGraph.__proto__||Object.getPrototypeOf(ObjectGraph)).apply(this,arguments));_this.emitter=new _fbemitter.EventEmitter;return _this}/**
     * Specifies the id field on insert
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */_createClass(ObjectGraph,[{key:'_idGenerator',value:function _idGenerator(index,link){return''+index}},{key:'_insertModifier',/**
     * Generate insert modifier.
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */value:function _insertModifier(link){var _modifier={};for(var f in link){if(this.fields[f]){_modifier[this.fields[f]]=link[this.config.aliases[f]]}}return _modifier}},{key:'insert',/**
     * Should insert new link into graph.
     * Return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {Link} link
     * @param {Graph~insertCallback} [callback]
     * @param {Object} [context]
     * @return {number|string} [id]
     */value:function insert(link,callback,context){this.callback;var _modifier=this._insertModifier(link);var index,error,id;try{index=this.collection.push(_modifier)-1;if(!this.collection[index].hasOwnProperty(this.fields[this.config.aliases['id']])){id=this.collection[index][this.fields[this.config.aliases['id']]]=this._idGenerator(index,this.collection[index])}this.emitter.emit('insert',this.collection[index])}catch(_error){error=_error}if(callback){callback(error,id)}return id}/**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the unique id of inserted link as the second.
     *
     * @callback Graph~insertCallback
     * @param {Error} [error]
     * @param {number|string} [id]
     *//**
     * Push into link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */},{key:'_updateModifierPush',value:function _updateModifierPush(data,item){data.push(item)}/**
     * Push into link value some item/items if not already exists.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */},{key:'_updateModifierAdd',value:function _updateModifierAdd(data,item){if(_lodash2.default.isArray(item)){for(var i in item){this._updateModifierAdd(data,item[i])}}else{var index=_lodash2.default.indexOf(data,item);if(index<0){this._updateModifierPush(data,item)}}}/**
     * Remove from link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */},{key:'_updateModifierRemove',value:function _updateModifierRemove(data,item){if(_lodash2.default.isArray(item)){for(var i in item){this._updateModifierRemove(data,item[i])}}else{_lodash2.default.remove(data,function(value){return value==item})}}/**
     * Generate update modifier.
     * 
     * @param {LinkModifier} modifier 
     * @param {Object} result
     * @return {number|string} id;
     */},{key:'_updateModifier',value:function _updateModifier(modifier,result){for(var m in modifier){if(this.fields[m]){if(typeof modifier[m]=='undefined'){delete result[this.fields[m]]}else{if(_typeof(modifier[m])=='object'){if(_lodash2.default.isArray(modifier[m])){result[this.fields[m]]=modifier[m]}else{if(!_lodash2.default.isArray(result[this.fields[m]])){result[this.fields[m]]=result[this.fields[m]]?[result[this.fields[m]]]:[]}for(var key in modifier[m]){if(key=='add'){this._updateModifierAdd(result[this.fields[m]],modifier[m][key])}if(key=='push'){this._updateModifierPush(result[this.fields[m]],modifier[m][key])}if(key=='remove'){this._updateModifierRemove(result[this.fields[m]],modifier[m][key])}}}}else{result[this.fields[m]]=modifier[m]}}}}}},{key:'update',/**
     * Should update to new state of modifier object link by unique id or by link query object.
     * If the database allows, it is recommended to return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {string|LinkSelector} selector
     * @param {LinkModifier} modifier
     * @param {Graph~updateCallback} [callback]
     * @param {Object} [context]
     * @return {number} [count]
     */value:function update(selector,modifier,callback,context){var results=this._fetch(selector);for(var r in results){var oldResult=_lodash2.default.cloneDeep(results[r]);this._updateModifier(modifier,results[r]);this.emitter.emit('update',results[r],oldResult)}if(callback)callback(undefined,results.length);return results.length}/**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.
     *
     * @callback Graph~updateCallback
     * @param {Error} [error]
     * @param {number} [count]
     *//**
     * Should remove link by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @param {Graph~removeCallback} [callback]
     * @param {Object} [context]
     */},{key:'remove',value:function remove(selector,callback,context){var _this2=this;var oldLength=this.collection.length;var removed=[];_lodash2.default.remove(this.collection,function(result){var _query=_this2.query(selector)(result);if(_query)removed.push(result);return _query});for(var r in removed){this.emitter.emit('remove',removed[r])}var newLength=this.collection.length;if(callback)callback(undefined,oldLength-newLength)}/**
     * Optional callback. If present, called with an error object as the first argument.
     *
     * @callback Graph~removeCallback
     * @param {Error} [error]
     * @param {number} [count]
     *//**
     * Generate adapter for database query for links search by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @return {*} query
     */},{key:'query',value:function query(selector){var _this3=this;var type=typeof selector==='undefined'?'undefined':_typeof(selector);if(type=='string'||type=='number'){return function(doc){return doc[_this3.fields[_this3.config.aliases['id']]]==selector}}else if(type=='object'){return function(doc){if((typeof doc==='undefined'?'undefined':_typeof(doc))!='object')return false;for(var m in selector){if(_this3.fields[m]){if(typeof selector[m]=='undefined'){if(doc.hasOwnProperty(_this3.fields[m]))return false}else{if(_lodash2.default.isArray(doc[_this3.fields[m]])){if(_lodash2.default.isArray(selector[m])){for(var s in selector[m]){if(!_lodash2.default.includes(doc[_this3.fields[m]],selector[m][s])){return false}}}else{if(!_lodash2.default.includes(doc[_this3.fields[m]],selector[m])){return false}}}else{if(doc[_this3.fields[m]]!=selector[m])return false}}}}return true}}}/**
     * Generate adapted for database options object.
     * 
     * @param {Object} [options]
     * @return {*} options - a options suitable for the database
     */},{key:'options',value:function options(_options2){var _options={};if(_options2){if(_options2.sort){_options.sort={keys:[],orders:[]};for(var s in _options2.sort){if(this.fields[s]){_options.sort.keys.push(this.fields[s]);_options.sort.orders.push(_options2.sort[s]?'asc':'desc')}}}if(typeof _options2.skip=='number'){_options.skip=_options2.skip}if(typeof _options2.limit=='number'){_options.limit=_options2.limit}}return _options}/**
     * Generate Link from document by fields.
     * 
     * @param {Object} document
     * @return {Link} link
     */},{key:'_generateLink',value:function _generateLink(document){var link={};for(var f in this.fields){if(document.hasOwnProperty(this.fields[f])){link[f]=document[this.fields[f]]}}return link}/**
     * Get one first matching link.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~getCallback} [callback]
     * @return {Link} link - result link object
     */},{key:'get',value:function get(selector,options,callback){var results=this.fetch(selector,options,function(error,results){if(callback)callback(error,results?results[0]:undefined)});if(results)return results[0]}/**
     * Fetch native database documents.
     * 
     * @param {string|linkSelector} selector
     * @param {SelectOptions} [options]
     * @return {Object[]} documents - result documents
     */},{key:'_fetch',value:function _fetch(selector,options){var query=this.query(selector);var documents=_lodash2.default.filter(this.collection,query);var _options=this.options(options);if(_options.sort)documents=_lodash2.default.orderBy(documents,_options.sort.keys,_options.orders);var skip=_options.skip?_options.skip:0;var limit=_options.limit?skip+_options.limit:_options.limit;documents=documents.slice(skip,limit);return documents}/**
     * Find and all matching links as an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~fetchCallback} [callback]
     * @return {Link[]} links - result links objects in array
     */},{key:'fetch',value:function fetch(selector,options,callback){var documents=this._fetch(selector,options);var links=[];for(var d in documents){links.push(this._generateLink(documents[d]))}if(callback)callback(undefined,links);return links}/**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the result links objects in array.
     *
     * @callback Graph~fetchCallback
     * @param {Error} [error]
     * @param {Link[]} [links]
     *//**
     * Should call callback once for each matching document, sequentially and synchronously.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~eachCallback} [callback]
     */},{key:'each',value:function each(selector,options,callback){var links=this.fetch(selector,options);for(var l in links){callback(links[l])}}/**
     * @callback Graph~eachCallback
     * @param {Link} [link]
     *//**
     * Map callback over all matching documents. Returns an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~mapCallback} [callback]
     * @return {Array} results
     */},{key:'map',value:function map(selector,options,callback){var links=this.fetch(selector,options);return links.map(callback)}/**
     * @callback Graph~mapCallback
     * @param {Link} [link]
     * @return {*} result
     *//**
     * Count all matching documents.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~countCallback} [callback]
     * @return {number} [count]
     */},{key:'count',value:function count(selector,options,callback){var links=this.fetch(selector,options);if(callback)callback(undefined,links.length);return links.length}/**
     * @callback Graph~countCallback
     * @param {Error} [error]
     * @param {number} [count]
     *//**
     * Should subscribe to the events: link, unlink, insert, update, remove.
     * 
     * @param {string} event - One event name
     * @param {Graph~onCallback} callback
     * @returns {Function} Stops event subscription.
     * @example
     * var counter = 0;
     * var stop = graph.on('update', (oldData, newData) => {
     *   if (oldData.id == '1') console.log(oldData.id, 'is changed');
     *   counter++;
     *   if (counter == 3) stop();
     * });
     */},{key:'on',value:function on(event,callback){var _this4=this;var subscriptions=[];if(event=='insert'){subscriptions.push(this.emitter.addListener('insert',function(document){callback(undefined,_this4._generateLink(document))}))}if(event=='update'){subscriptions.push(this.emitter.addListener('update',function(newDocument,oldDocument){callback(_this4._generateLink(oldDocument),_this4._generateLink(newDocument))}))}if(event=='remove'){subscriptions.push(this.emitter.addListener('remove',function(document){callback(_this4._generateLink(document),undefined)}))}if(event=='link'){subscriptions.push(this.emitter.addListener('insert',function(document){callback(undefined,_this4._generateLink(document))}));subscriptions.push(this.emitter.addListener('update',function(newDocument,oldDocument){callback(_this4._generateLink(oldDocument),_this4._generateLink(newDocument))}))}if(event=='unlink'){subscriptions.push(this.emitter.addListener('update',function(newDocument,oldDocument){callback(_this4._generateLink(oldDocument),_this4._generateLink(newDocument))}));subscriptions.push(this.emitter.addListener('remove',function(document){callback(_this4._generateLink(document),undefined)}))}return function(){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=subscriptions[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var subscription=_step.value;subscription.remove()}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}}/**
     * @callback Graph~onCallback
     * @param {Link} [oldLink] - can be undefined on link and insert events
     * @param {Link} [newLink] - can be undefined on unlink and remove events
     * @param {Object} [context] - additional app information, such as context.userId
     */}]);return ObjectGraph}(ParentClassGraph);return ObjectGraph}
452541
function(graph, opt) {

        opt = opt || {};

        var glGraphType = joint.util.pick(opt, 'directed', 'compound', 'multigraph');
        var glGraph = new graphlib.Graph(glGraphType);
        var setNodeLabel = opt.setNodeLabel || joint.util.noop;
        var setEdgeLabel = opt.setEdgeLabel || joint.util.noop;
        var setEdgeName = opt.setEdgeName || joint.util.noop;
        var collection = graph.get('cells');

        for (var i = 0, n = collection.length; i < n; i++) {

            var cell = collection.at(i);
            if (cell.isLink()) {

                var source = cell.get('source');
                var target = cell.get('target');

                // Links that end at a point are ignored.
                if (!source.id || !target.id) break;

                // Note that if we are creating a multigraph we can name the edges. If
                // we try to name edges on a non-multigraph an exception is thrown.
                glGraph.setEdge(source.id, target.id, setEdgeLabel(cell), setEdgeName(cell));

            } else {

                glGraph.setNode(cell.id, setNodeLabel(cell));

                // For the compound graphs we have to take embeds into account.
                if (glGraph.isCompound() && cell.has('parent')) {
                    var parentId = cell.get('parent');
                    if (collection.has(parentId)) {
                        // Make sure the parent cell is included in the graph (this can
                        // happen when the layout is run on part of the graph only).
                        glGraph.setParent(cell.id, parentId);
                    }
                }
            }
        }

        return glGraph;
    }
435127
static void constructAvgHitsGraph(Map.Entry<String, LrProjectScenarioResults> scenarioResults,
                                      JSONObject scenarioGraphData) {
        Map<Integer, WholeRunResult> avgHitsPerSec = scenarioResults.getValue().getAverageHitsPerSecondResults();
        JSONObject avgHitsPerSecGraphSet = extractWholeRunSlaResult(avgHitsPerSec, "Hits/Sec");
        if (!avgHitsPerSecGraphSet.getJSONArray(LABELS).isEmpty()) {
            avgHitsPerSecGraphSet.put(TITLE, "Average Hits per Second");
            avgHitsPerSecGraphSet.put(X_AXIS_TITLE, "Build number");
            avgHitsPerSecGraphSet.put(Y_AXIS_TITLE, "Hits");
            avgHitsPerSecGraphSet.put(DESCRIPTION,
                    "Displays the number of hits made on the Web server by Vusers " +
                            "during each second of the load test. This graph helps you evaluate the amount of load " +
                            "Vusers" +
                            " " +
                            "generate, in terms of the number of hits.");
            scenarioGraphData.put("avgHitsPerSec", avgHitsPerSecGraphSet);
        }
    }
427823
def clone_subgraphs(self, g):
        if not isinstance(g, CGRContainer):
            raise InvalidData('only CGRContainer acceptable')

        r_group = []
        x_group = {}
        r_group_clones = []
        newcomponents = []

        ''' 
        '''
        components, lost_bonds, term_atoms = self.__split_graph(g)
        lost_map = {x: y for x, y in lost_bonds}
        ''' extract subgraphs and sort by group type (R or X)
        '''
        x_terminals = set(lost_map.values())
        r_terminals = set(lost_map)

        for i in components:
            x_terminal_atom = x_terminals.intersection(i)
            if x_terminal_atom:
                x_group[x_terminal_atom.pop()] = i
                continue

            r_terminal_atom = r_terminals.intersection(i)
            if r_terminal_atom:
                r_group.append([r_terminal_atom, i])
                continue

            newcomponents.append(i)
        ''' search similar R groups and patch.
        '''
        tmp = g
        for i in newcomponents:
            for k, j in r_group:
                gm = GraphMatcher(j, i, node_match=self.__node_match_products,
                                  edge_match=self.__edge_match_products)
                ''' search for similar R-groups started from bond breaks.
                '''
                mapping = next((x for x in gm.subgraph_isomorphisms_iter() if k.issubset(x) and
                                all(x[y] in term_atoms for y in k)), None)
                if mapping:
                    r_group_clones.append([k, mapping])
                    tmp = compose(tmp, self.__remap_group(j, tmp, mapping)[0])
                    break

        ''' add lose X groups to R groups
        '''
        for i, j in r_group_clones:
            for k in i:
                remappedgroup, mapping = self.__remap_group(x_group[lost_map[k]], tmp, {})
                tmp = CGRcore.union(tmp, remappedgroup)
                tmp.add_edge(j[k], mapping[lost_map[k]], s_bond=1, sp_bond=(1, None))

        if r_group_clones:
            tmp.meta.update(g.meta)
            return tmp

        return tmp.copy()
81512
def as_graph(self) -> Graph:  # pragma: no cover
        """"""
        if Graph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Graph()
        nodes_left = {}  # type: Dict[TLeft, str]
        nodes_right = {}  # type: Dict[TRight, str]
        node_id = 0
        for (left, right), value in self._edges.items():
            if left not in nodes_left:
                name = 'node{:d}'.format(node_id)
                nodes_left[left] = name
                graph.node(name, label=str(left))
                node_id += 1
            if right not in nodes_right:
                name = 'node{:d}'.format(node_id)
                nodes_right[right] = name
                graph.node(name, label=str(right))
                node_id += 1
            edge_label = value is not True and str(value) or ''
            graph.edge(nodes_left[left], nodes_right[right], edge_label)
        return graph
132642
def iter_variants(self):
        """"""
        for v in self.get_vcf():
            yield Variant(v.ID, v.CHROM, v.POS, {v.REF} | set(v.ALT))
320971
def kruskal_mst(graph):
    
    edges_accepted = 0
    ds = DisjointSet()
    pq = PriorityQueue()
    accepted_edges = []
    label_lookup = {}

    nodes = graph.get_all_node_ids()
    num_vertices = len(nodes)
    for n in nodes:
        label = ds.add_set()
        label_lookup[n] = label

    edges = graph.get_all_edge_objects()
    for e in edges:
        pq.put(e['id'], e['cost'])

    while edges_accepted < (num_vertices - 1):
        edge_id = pq.get()

        edge = graph.get_edge(edge_id)
        node_a, node_b = edge['vertices']
        label_a = label_lookup[node_a]
        label_b = label_lookup[node_b]

        a_set = ds.find(label_a)
        b_set = ds.find(label_b)

        if a_set != b_set:
            edges_accepted += 1
            accepted_edges.append(edge_id)
            ds.union(a_set, b_set)

    return accepted_edges
273540
public static List<Map<String, String>> getAllVariants(Map<String, ? extends Collection<String>> variantSets) {

		List<Map<String, String>> variants = new ArrayList<>();
		if (variantSets != null) {
			for (Entry<String, Collection<String>> variantEntry : new TreeMap<>(variantSets).entrySet()) {
				String variantType = variantEntry.getKey();
				Collection<String> variantList = variantEntry.getValue();
				if (variants.isEmpty()) {
					variants = getVariants(null, variantType, variantList);
				} else {

					List<Map<String, String>> tmpResult = new ArrayList<>();
					for (Map<String, String> curVariant : variants) {
						tmpResult.addAll(getVariants(curVariant, variantType, variantList));
					}
					variants = tmpResult;
				}
			}
		}

		return variants;
	}
407198
public static <V> void swapVertices(DirectedGraph<V, DefaultEdge> graph, Map<V, Set<V>> alternates) {
        Objects.requireNonNull(graph,"graph");
        Objects.requireNonNull(alternates, "alternates");
        // add all of the new vertices to prep for linking
        addAllVertices(graph, alternates.keySet());

        for (Entry<V, Set<V>> entry : alternates.entrySet()) {
            V alternateVertex = entry.getKey();
            Set<V> dependencies = entry.getValue();
            // make sure we can satisfy all dependencies before continuing
            // TODO: this should probably done outside so it can be handled better.
            if (!graph.vertexSet().containsAll(dependencies)) {
                continue;
            }

            // figure out which vertices depend on the incumbent vertex
            Set<V> dependents = Collections.emptySet();
            if (graph.containsVertex(alternateVertex)) {
                dependents = getIncomingVertices(graph, alternateVertex);
                graph.removeVertex(alternateVertex);
            }
            // (re)insert the vertex and re-link the dependents
            graph.addVertex(alternateVertex);
            addIncomingEdges(graph, alternateVertex, dependents);

            // create the dependencies
            addOutgoingEdges(graph, alternateVertex, dependencies);
        }
    }