Import model GraphDef into the current graph.
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)
478224
def export_compact(model_path):
    
    pred_config = PredictConfig(
        session_init=get_model_loader(model_path),
        model=Model(),
        input_names=['input_img'],
        output_names=['prediction_img'])
    ModelExporter(pred_config).export_compact('/tmp/compact_graph.pb')
576785
def insert_into_graph(self, graph):
        
        u = self.source.as_bel()
        v = self.target.as_bel()

        if self.evidence:
            return graph.add_qualified_edge(u, v, **json.loads(self.data))
        else:
            return graph.add_unqualified_edge(u, v, self.relation)
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)
34240
def _to_graph(self, contexts):
        """"""
        prev = None

        for context in contexts:
            if prev is None:
                prev = context
                continue

            yield prev[0], context[1], context[0]
            prev = context
1288689
def add_model(refwcs, newcoeffs):
    
    # Update refwcs with distortion model
    for kw in model_attrs:
        if newcoeffs.__dict__[key] is not None:
            refwcs.__dict__[key] = newcoeffs.__dict__[key]
310049
def write(self)->None:
        ""
        self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
346468
def _store_graph_parts(self, graph: BELGraph, use_tqdm: bool = False) -> Tuple[List[Node], List[Edge]]:
        
        log.debug('inserting %s into edge store', graph)
        log.debug('building node models')
        node_model_build_start = time.time()

        nodes = list(graph)
        if use_tqdm:
            nodes = tqdm(nodes, total=graph.number_of_nodes(), desc='nodes')

        node_model = {}
        for node in nodes:
            namespace = node.get(NAMESPACE)

            if graph.skip_storing_namespace(namespace):
                continue  # already know this node won't be cached

            node_object = self.get_or_create_node(graph, node)

            if node_object is None:
                log.warning('can not add node %s', node)
                continue

            node_model[node] = node_object

        node_models = list(node_model.values())
        log.debug('built %d node models in %.2f seconds', len(node_models), time.time() - node_model_build_start)

        node_model_commit_start = time.time()
        self.session.add_all(node_models)
        self.session.commit()
        log.debug('stored %d node models in %.2f seconds', len(node_models), time.time() - node_model_commit_start)

        log.debug('building edge models')
        edge_model_build_start = time.time()

        edges = graph.edges(keys=True, data=True)
        if use_tqdm:
            edges = tqdm(edges, total=graph.number_of_edges(), desc='edges')

        edge_models = list(self._get_edge_models(graph, node_model, edges))

        log.debug('built %d edge models in %.2f seconds', len(edge_models), time.time() - edge_model_build_start)

        edge_model_commit_start = time.time()
        self.session.add_all(edge_models)
        self.session.commit()
        log.debug('stored %d edge models in %.2f seconds', len(edge_models), time.time() - edge_model_commit_start)

        return node_models, edge_models
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))
932705
def build_class_graph(modules, klass=None, graph=None):
        
        if klass is None:
            class_graph = nx.DiGraph()
            for name, classmember in inspect.getmembers(modules, inspect.isclass):
                if issubclass(classmember, Referent) and classmember is not Referent:
                    TaxonomyCell.build_class_graph(modules, classmember, class_graph)
            return class_graph
        else:
            parents = getattr(klass, '__bases__')
            for parent in parents:
                if parent != Referent:
                    graph.add_edge(parent.__name__, klass.__name__)
                    # store pointer to classes in property 'class'
                    graph.node[parent.__name__]['class'] = parent
                    graph.node[klass.__name__]['class'] = klass 
                    if issubclass(parent, Referent):
                        TaxonomyCell.build_class_graph(modules, parent, graph)
231094
function modelsToTypes(models) {
  let typeMap = models.filter(model => {
    if (_typeMap[model.modelName]) return false;
    return true;
  }).reduce((map, model) => {
    return (0, _assign2.default)(map, { [model.modelName]: toType(model) });
  }, {});
  _typeMap = (0, _assign2.default)(_typeMap, typeMap);

  // Deal with ref after all types are defined
  (0, _entries2.default)(typeMap).forEach(_ref => {
    var _ref2 = (0, _slicedToArray3.default)(_ref, 2);

    let modelName = _ref2[0];
    let type = _ref2[1];

    const originFileds = type._typeConfig.fields();
    const newTypeFileds = (0, _entries2.default)(originFileds).map(_ref3 => {
      var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);

      let path = _ref4[0];
      let pathValue = _ref4[1];

      let newPathValue = (0, _assign2.default)({}, pathValue);
      if (newPathValue.ref) {
        const ref = newPathValue.ref;
        if (!_typeMap[ref]) throw TypeError(`${ref} is not a model`);
        const model = models.find(m => m.modelName === ref);
        const refModelType = _typeMap[ref];
        if (newPathValue.type instanceof _graphql.GraphQLList) {
          newPathValue = (0, _assign2.default)({}, newPathValue, {
            type: new _graphql.GraphQLList(refModelType),
            resolve: (() => {
              var _ref5 = (0, _asyncToGenerator3.default)(function* (instance) {
                // TODO: args filter
                return yield model.find({ _id: { $in: instance[path] } });
              });

              return function resolve(_x) {
                return _ref5.apply(this, arguments);
              };
            })()
          });
        } else {
          newPathValue = (0, _assign2.default)({}, newPathValue, {
            type: refModelType,
            resolve: (() => {
              var _ref6 = (0, _asyncToGenerator3.default)(function* (instance) {
                return yield model.findById(instance[path]);
              });

              return function resolve(_x2) {
                return _ref6.apply(this, arguments);
              };
            })()
          });
        }
      }
      return { [path]: newPathValue };
    }).reduce((typeField, path) => (0, _assign2.default)(typeField, path), {});

    typeMap[modelName]._typeConfig.fields = () => newTypeFileds;
  });

  _typeMap = (0, _assign2.default)(_typeMap, typeMap);
  return _typeMap;
}
598274
def add_graph_copy(self, graph, tags=None):
    """"""
    with graph.as_default():
      # Remove default attrs so that Modules created by a tensorflow version
      # with ops that have new attrs that are left to their default values can
      # still be loaded by older versions unware of those attributes.
      meta_graph = tf_v1.train.export_meta_graph(strip_default_attrs=True)
      _export_tags(meta_graph, tags)
      _export_signatures(meta_graph)
      _export_module_attachments(meta_graph)
    self._proto.meta_graphs.extend([meta_graph])
567697
def process_input_graph(func):
    """"""
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        input_graph = args[0]
        if isinstance(input_graph, nx.DiGraph):
            return func(*args, **kwargs)
        else:
            nx_graph = dict_to_nx(args[0], oriented=True)
            args = [nx_graph] + list(args[1:])
            return func(*args, **kwargs)
    return wrapped_func
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
354664
private void addModuleToGraph(final DbModule module, final AbstractGraph graph, final int depth) {
        if (graph.isTreated(graph.getId(module))) {
            return;
        }

        final String moduleElementId = graph.getId(module);
        graph.addElement(moduleElementId, module.getVersion(), depth == 0);

        if (filters.getDepthHandler().shouldGoDeeper(depth)) {
            for (final DbDependency dep : DataUtils.getAllDbDependencies(module)) {
                if(filters.shouldBeInReport(dep)){
                    addDependencyToGraph(dep, graph, depth + 1, moduleElementId);
                }
            }
        }
    }
1195356
def import_model(self, source):
        """"""
        source = self._resolve_source(source)
        self._context = FilePathContext(source)
        with self._context.open() as f:
            self._reader = self._open_reader(f)

        return self._reader.create_model()
260112
def build_modelgraph(docs_path, package_name="yacms"):
    
    to_path = os.path.join(docs_path, "img", "graph.png")
    build_path = os.path.join(docs_path, "build", "_images")
    resized_path = os.path.join(os.path.dirname(to_path), "graph-small.png")
    settings = import_dotted_path(package_name +
                                  ".project_template.project_name.settings")
    apps = [a.rsplit(".")[1] for a in settings.INSTALLED_APPS
            if a.startswith("yacms.") or a.startswith(package_name + ".")]
    try:
        from django_extensions.management.commands import graph_models
    except ImportError:
        warn("Couldn't build model_graph, django_extensions not installed")
    else:
        options = {"inheritance": True, "outputfile": "graph.png",
                   "layout": "dot"}
        try:
            graph_models.Command().execute(*apps, **options)
        except Exception as e:
            warn("Couldn't build model_graph, graph_models failed on: %s" % e)
        else:
            try:
                move("graph.png", to_path)
            except OSError as e:
                warn("Couldn't build model_graph, move failed on: %s" % e)
    # docs/img/graph.png should exist in the repo - move it to the build path.
    try:
        if not os.path.exists(build_path):
            os.makedirs(build_path)
        copyfile(to_path, os.path.join(build_path, "graph.png"))
    except OSError as e:
        warn("Couldn't build model_graph, copy to build failed on: %s" % e)
    try:
        from PIL import Image
        image = Image.open(to_path)
        image.width = 800
        image.height = image.size[1] * 800 // image.size[0]
        image.save(resized_path, "PNG", quality=100)
    except Exception as e:
        warn("Couldn't build model_graph, resize failed on: %s" % e)
        return
    # Copy the dashboard screenshot to the build dir too. This doesn't
    # really belong anywhere, so we do it here since this is the only
    # spot we deal with doc images.
    d = "dashboard.png"
    copyfile(os.path.join(docs_path, "img", d), os.path.join(build_path, d))