Read graph and add models to document
175700
def _read_models(self, graph):
        
        for e in self._get_elements(graph, SBOL.Model):
            identity = e[0]
            m = self._get_rdf_identified(graph, identity)
            m['source'] = self._get_triplet_value(graph, identity, SBOL.source)
            m['language'] = self._get_triplet_value(graph, identity, SBOL.language)
            m['framework'] = self._get_triplet_value(graph, identity, SBOL.framework)
            obj = Model(**m)
            self._models[identity.toPython()] = obj
            self._collection_store[identity.toPython()] = obj
698969
def load_graphs():
    ''''''
    mestate.graphs = []
    gfiles = ['mavgraphs.xml']
    if 'HOME' in os.environ:
        for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")):
            for filename in filenames:
                if filename.lower().endswith('.xml'):
                    gfiles.append(os.path.join(dirname, filename))
    elif 'LOCALAPPDATA' in os.environ:
        for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['LOCALAPPDATA'], "MAVProxy")):
            for filename in filenames:
                if filename.lower().endswith('.xml'):
                    gfiles.append(os.path.join(dirname, filename))

    for file in gfiles:
        if not os.path.exists(file):
            continue
        graphs = load_graph_xml(open(file).read(), file)
        if graphs:
            mestate.graphs.extend(graphs)
            mestate.console.writeln("Loaded %s" % file)
    # also load the built in graphs
    try:
        dlist = pkg_resources.resource_listdir("MAVProxy", "tools/graphs")
        for f in dlist:
            raw = pkg_resources.resource_stream("MAVProxy", "tools/graphs/%s" % f).read()
            graphs = load_graph_xml(raw, None)
            if graphs:
                mestate.graphs.extend(graphs)
                mestate.console.writeln("Loaded %s" % f)
    except Exception:
        #we're in a Windows exe, where pkg_resources doesn't work
        import pkgutil
        for f in ["ekf3Graphs.xml", "ekfGraphs.xml", "mavgraphs.xml", "mavgraphs2.xml"]:
            raw = pkgutil.get_data( 'MAVProxy', 'tools//graphs//' + f)
            graphs = load_graph_xml(raw, None)
            if graphs:
                mestate.graphs.extend(graphs)
                mestate.console.writeln("Loaded %s" % f)
    mestate.graphs = sorted(mestate.graphs, key=lambda g: g.name)
1098899
def make_graph(node, inputs):
        
        initializer = []
        tensor_input_info = []
        tensor_output_info = []

        # Adding input tensor info.
        for index in range(len(node.input)):
            tensor_input_info.append(
                helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1]))

            # Creating an initializer for Weight params.
            # Assumes that weight params is named as 'W'.
            # TODO: Handle multiple weight params.
            # TODO: Add for "bias" if needed
            if node.input[index] == 'W':
                dim = inputs[index].shape
                param_tensor = helper.make_tensor(
                    name=node.input[index],
                    data_type=TensorProto.FLOAT,
                    dims=dim,
                    vals=inputs[index].flatten())

                initializer.append(param_tensor)

        # Adding output tensor info.
        for index in range(len(node.output)):
            tensor_output_info.append(
                helper.make_tensor_value_info(str(node.output[index]), TensorProto.FLOAT, [1]))

        # creating graph proto object.
        graph_proto = helper.make_graph(
            [node],
            "test",
            tensor_input_info,
            tensor_output_info,
            initializer=initializer)

        return graph_proto
178250
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):
    """"""
    graph = tf.get_default_graph()
    assert graph.unique_name(scope, False) == scope, (
        'Scope "%s" already exists. Provide explicit scope names when '
        'importing multiple instances of the model.') % scope
    t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)
    tf.import_graph_def(
        self.graph_def, {self.input_name: t_prep_input}, name=scope)
    self.post_import(scope)
246021
def build_graph(self, data_paths, batch_size, graph_mod):
    """"""
    tensors = GraphReferences()
    is_training = graph_mod == GraphMod.TRAIN
    if data_paths:
      _, tensors.examples = _util.read_examples(
          data_paths,
          batch_size,
          shuffle=is_training,
          num_epochs=None if is_training else 2)
    else:
      tensors.examples = tf.placeholder(tf.string, name='input', shape=(None,))

    if graph_mod == GraphMod.PREDICT:
      inception_input, inception_embeddings = self.build_inception_graph()
      # Build the Inception graph. We later add final training layers
      # to this graph. This is currently used only for prediction.
      # For training, we use pre-processed data, so it is not needed.
      embeddings = inception_embeddings
      tensors.input_jpeg = inception_input
    else:
      # For training and evaluation we assume data is preprocessed, so the
      # inputs are tf-examples.
      # Generate placeholders for examples.
      with tf.name_scope('inputs'):
        feature_map = {
            'image_uri':
                tf.FixedLenFeature(
                    shape=[], dtype=tf.string, default_value=['']),
            # Some images may have no labels. For those, we assume a default
            # label. So the number of labels is label_count+1 for the default
            # label.
            'label':
                tf.FixedLenFeature(
                    shape=[1], dtype=tf.int64,
                    default_value=[len(self.labels)]),
            'embedding':
                tf.FixedLenFeature(
                    shape=[BOTTLENECK_TENSOR_SIZE], dtype=tf.float32)
        }
        parsed = tf.parse_example(tensors.examples, features=feature_map)
        labels = tf.squeeze(parsed['label'])
        uris = tf.squeeze(parsed['image_uri'])
        embeddings = parsed['embedding']

    # We assume a default label, so the total number of labels is equal to
    # label_count+1.
    all_labels_count = len(self.labels) + 1
    with tf.name_scope('final_ops'):
      softmax, logits = self.add_final_training_ops(
          embeddings,
          all_labels_count,
          BOTTLENECK_TENSOR_SIZE,
          dropout_keep_prob=self.dropout if is_training else None)

    # Prediction is the index of the label with the highest score. We are
    # interested only in the top score.
    prediction = tf.argmax(softmax, 1)
    tensors.predictions = [prediction, softmax, embeddings]

    if graph_mod == GraphMod.PREDICT:
      return tensors

    with tf.name_scope('evaluate'):
      loss_value = loss(logits, labels)

    # Add to the Graph the Ops that calculate and apply gradients.
    if is_training:
      tensors.train, tensors.global_step = training(loss_value)
    else:
      tensors.global_step = tf.Variable(0, name='global_step', trainable=False)
      tensors.uris = uris

    # Add means across all batches.
    loss_updates, loss_op = _util.loss(loss_value)
    accuracy_updates, accuracy_op = _util.accuracy(logits, labels)

    if not is_training:
      tf.summary.scalar('accuracy', accuracy_op)
      tf.summary.scalar('loss', loss_op)

    tensors.metric_updates = loss_updates + accuracy_updates
    tensors.metric_values = [loss_op, accuracy_op]
    return tensors
1353880
def graph(bare=False, json=False, json_tree=False, reverse=False):
    """"""
    from ..core import do_graph

    do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse)
890714
def _to_graphviz(tree_info, show_info, feature_names, precision=None, **kwargs):
    
    if GRAPHVIZ_INSTALLED:
        from graphviz import Digraph
    else:
        raise ImportError('You must install graphviz to plot tree.')

    def add(root, parent=None, decision=None):
        """Recursively add node or edge."""
        if 'split_index' in root:  # non-leaf
            name = 'split{0}'.format(root['split_index'])
            if feature_names is not None:
                label = 'split_feature_name: {0}'.format(feature_names[root['split_feature']])
            else:
                label = 'split_feature_index: {0}'.format(root['split_feature'])
            label += r'\nthreshold: {0}'.format(_float2str(root['threshold'], precision))
            for info in show_info:
                if info in {'split_gain', 'internal_value'}:
                    label += r'\n{0}: {1}'.format(info, _float2str(root[info], precision))
                elif info == 'internal_count':
                    label += r'\n{0}: {1}'.format(info, root[info])
            graph.node(name, label=label)
            if root['decision_type'] == '<=':
                l_dec, r_dec = '<=', '>'
            elif root['decision_type'] == '==':
                l_dec, r_dec = 'is', "isn't"
            else:
                raise ValueError('Invalid decision type in tree model.')
            add(root['left_child'], name, l_dec)
            add(root['right_child'], name, r_dec)
        else:  # leaf
            name = 'leaf{0}'.format(root['leaf_index'])
            label = 'leaf_index: {0}'.format(root['leaf_index'])
            label += r'\nleaf_value: {0}'.format(_float2str(root['leaf_value'], precision))
            if 'leaf_count' in show_info:
                label += r'\nleaf_count: {0}'.format(root['leaf_count'])
            graph.node(name, label=label)
        if parent is not None:
            graph.edge(parent, name, decision)

    graph = Digraph(**kwargs)
    add(tree_info['tree_structure'])

    return graph
717431
def write(models, base=None, graph=None, rdfsonly=False, prefixes=None, logger=logging):
    '''
    
    '''
    prefixes = prefixes or {}
    g = graph or rdflib.Graph()
    #g.bind('bf', BFNS)
    #g.bind('bfc', BFCNS)
    #g.bind('bfd', BFDNS)
    g.bind('v', VNS)
    for k, v in prefixes.items():
        g.bind(k, v)
    for m in models:
        base_out = m.base
        process(m, g, rdfsonly, base=base_out, logger=logger)
    return g
1070656
def addNodeToGraph(nodeName, graphFileHandle, label, width=0.3, height=0.3, shape="circle", colour="black", fontsize=14):
    
    graphFileHandle.write("node[width=%s,height=%s,shape=%s,colour=%s,fontsize=%s];\n" % (width, height, shape, colour, fontsize))
    graphFileHandle.write("%s [label=\"%s\"];\n" % (nodeName, label))
1202016
def add(model)
      documents = Util.Array(model).map { |m| prepare_full_update(m) }
      add_batch_documents(documents)
    end
779053
@Override
    public void addModelToGraph(URI graphUri, Model data) {
        if (graphUri == null || data == null)
            return;

        // Use HTTP protocol if possible
        if (this.sparqlServiceEndpoint != null) {
            datasetAccessor.add(graphUri.toASCIIString(), data);
        } else {
            this.addModelToGraphSparqlQuery(graphUri, data);
        }
    }
735446
def get_document_models():
    """"""
    mappings = {}
    for i in get_index_names():
        for m in get_index_models(i):
            key = "%s.%s" % (i, m._meta.model_name)
            mappings[key] = m
    return mappings
1106781
def from_model(cls, document):
        
        return cls(meta={'id': document.id}, **cls.serialize(document))
142110
def index_documents(self, fresh_docs, model):
        
        docids = fresh_docs.keys()
        vectors = (model.docs2vecs(fresh_docs[docid] for docid in docids))
        logger.info("adding %i documents to %s" % (len(docids), self))
        self.qindex.add_documents(vectors)
        self.qindex.save()
        self.update_ids(docids)
610258
def addEdgeToGraph(parentNodeName, childNodeName, graphFileHandle, colour="black", length="10", weight="1", dir="none", label="", style=""):
    
    graphFileHandle.write('edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % (colour, length, weight, dir, label, style))
    graphFileHandle.write("%s -- %s;\n" % (parentNodeName, childNodeName))
420645
def _buildGraph(self):
        
        for n in self.namespaces:
            self.rdflib_graph.bind(n[0], rdflib.Namespace(n[1]))
        if self.triples:
            for terzetto in self.triples:
                self.rdflib_graph.add(terzetto)
1203335
function loadPrettyGraphSONSync(graph, filename) {
        var jsonText = fs.readFileSync(filename, { encoding: 'utf8' });
        var jsonObjArray = JSON.parse(jsonText);
        var jsonTextArray = _.map(jsonObjArray, JSON.stringify);
        var uglyText = jsonTextArray.join('\n');
        var StringInputStream = Tinkerpop.autoImport('StringInputStream');
        var stream = StringInputStream.from(uglyText);
        var builder = Tinkerpop.GraphSONReader.build();
        var mapper = _newGraphSONMapperSync();
        builder.mapper(mapper);
        var reader = builder.create();
        reader.readGraph(stream, graph);
        return graph;
    }