Return the metagraph definition, if there is one.

    Raises:
      ValueError: If there is no metagraph for this run.

    Returns:
      The `meta_graph_def` proto.
13870
def MetaGraph(self):
    
    if self._meta_graph is None:
      raise ValueError('There is no metagraph in this EventAccumulator')
    meta_graph = meta_graph_pb2.MetaGraphDef()
    meta_graph.ParseFromString(self._meta_graph)
    return meta_graph
1118851
def _ProcessEvent(self, event):
    """"""
    if self._first_event_timestamp is None:
      self._first_event_timestamp = event.wall_time

    if event.HasField('file_version'):
      new_file_version = _ParseFileVersion(event.file_version)
      if self.file_version and self.file_version != new_file_version:
        ## This should not happen.
        logger.warn(('Found new file_version for event.proto. This will '
                         'affect purging logic for TensorFlow restarts. '
                         'Old: {0} New: {1}').format(self.file_version,
                                                     new_file_version))
      self.file_version = new_file_version

    self._MaybePurgeOrphanedData(event)

    ## Process the event.
    # GraphDef and MetaGraphDef are handled in a special way:
    # If no graph_def Event is available, but a meta_graph_def is, and it
    # contains a graph_def, then use the meta_graph_def.graph_def as our graph.
    # If a graph_def Event is available, always prefer it to the graph_def
    # inside the meta_graph_def.
    if event.HasField('graph_def'):
      if self._graph is not None:
        logger.warn(
            ('Found more than one graph event per run, or there was '
             'a metagraph containing a graph_def, as well as one or '
             'more graph events.  Overwriting the graph with the '
             'newest event.'))
      self._graph = event.graph_def
      self._graph_from_metagraph = False
    elif event.HasField('meta_graph_def'):
      if self._meta_graph is not None:
        logger.warn(('Found more than one metagraph event per run. '
                         'Overwriting the metagraph with the newest event.'))
      self._meta_graph = event.meta_graph_def
      if self._graph is None or self._graph_from_metagraph:
        # We may have a graph_def in the metagraph.  If so, and no
        # graph_def is directly available, use this one instead.
        meta_graph = meta_graph_pb2.MetaGraphDef()
        meta_graph.ParseFromString(self._meta_graph)
        if meta_graph.graph_def:
          if self._graph is not None:
            logger.warn(
                ('Found multiple metagraphs containing graph_defs,'
                 'but did not find any graph events.  Overwriting the '
                 'graph with the newest metagraph version.'))
          self._graph_from_metagraph = True
          self._graph = meta_graph.graph_def.SerializeToString()
    elif event.HasField('tagged_run_metadata'):
      tag = event.tagged_run_metadata.tag
      if tag in self._tagged_metadata:
        logger.warn('Found more than one "run metadata" event with tag ' +
                        tag + '. Overwriting it with the newest event.')
      self._tagged_metadata[tag] = event.tagged_run_metadata.run_metadata
    elif event.HasField('summary'):
      for value in event.summary.value:
        value = data_compat.migrate_value(value)

        if value.HasField('metadata'):
          tag = value.tag
          # We only store the first instance of the metadata. This check
          # is important: the `FileWriter` does strip metadata from all
          # values except the first one per each tag, but a new
          # `FileWriter` is created every time a training job stops and
          # restarts. Hence, we must also ignore non-initial metadata in
          # this logic.
          if tag not in self.summary_metadata:
            self.summary_metadata[tag] = value.metadata
            plugin_data = value.metadata.plugin_data
            if plugin_data.plugin_name:
              with self._plugin_tag_locks[plugin_data.plugin_name]:
                self._plugin_to_tag_to_content[plugin_data.plugin_name][tag] = (
                    plugin_data.content)
            else:
              logger.warn(
                  ('This summary with tag %r is oddly not associated with a '
                   'plugin.'), tag)

        for summary_type, summary_func in SUMMARY_TYPES.items():
          if value.HasField(summary_type):
            datum = getattr(value, summary_type)
            tag = value.tag
            if summary_type == 'tensor' and not tag:
              # This tensor summary was created using the old method that used
              # plugin assets. We must still continue to support it.
              tag = value.node_name
            getattr(self, summary_func)(tag, event.wall_time, event.step, datum)
950488
def get_id(self):
        
        _id = self._meta.get("id", None)
        if _id is None:
            _id = self.save()
        return _id
607660
def new_multidigraph(self, name, data=None, **attr):
        
        self._init_graph(name, 'MultiDiGraph')
        mdg = MultiDiGraph(self, name, data, **attr)
        self._graph_objs[name] = mdg
        return mdg
851934
def load_graphdef(model_url, reset_device=True):
  """"""
  graph_def = load(model_url)

  if reset_device:
    for n in graph_def.node:
      n.device = ""

  return graph_def
262107
def _GetNestedDict(self, value):
    """"""
    row = {}
    for type_info in value.__class__.type_infos:
      # We only expect the metadata proto to be included as ProtoEmbedded.
      if type_info.__class__.__name__ == "ProtoEmbedded":
        row[type_info.name] = self._GetNestedDict(value.Get(type_info.name))
      else:
        row[type_info.name] = utils.SmartStr(value.Get(type_info.name))

    return row
243622
def _MetaPythonBase():
    
    
    class MagicGetItem(type):
        def __new__(mcs, name, bases, dict):
            klass = type.__new__(mcs, name, bases, dict)
            mcs.__getitem__ = lambda _, k: klass()[k]
            return klass
            
    return MagicGetItem
953395
def graph_impl(self, run, tag, is_conceptual, limit_attr_size=None, large_attrs_key=None):
    """"""
    if is_conceptual:
      tensor_events = self._multiplexer.Tensors(run, tag)
      # Take the first event if there are multiple events written from different
      # steps.
      keras_model_config = json.loads(tensor_events[0].tensor_proto.string_val[0])
      graph = keras_util.keras_model_to_graph_def(keras_model_config)
    elif tag:
      tensor_events = self._multiplexer.Tensors(run, tag)
      # Take the first event if there are multiple events written from different
      # steps.
      run_metadata = config_pb2.RunMetadata.FromString(
          tensor_events[0].tensor_proto.string_val[0])
      graph = graph_pb2.GraphDef()

      for func_graph in run_metadata.function_graphs:
        graph_util.combine_graph_defs(graph, func_graph.pre_optimization_graph)
    else:
      graph = self._multiplexer.Graph(run)

    # This next line might raise a ValueError if the limit parameters
    # are invalid (size is negative, size present but key absent, etc.).
    process_graph.prepare_graph_for_ui(graph, limit_attr_size, large_attrs_key)
    return (str(graph), 'text/x-protobuf')
1017646
def protocols(self):
        
        if self.__protocols is None:
            self.__protocols = self.proto_tree_model.protocols
        return self.__protocols
1043388
def generate(self):
        
        t = (self.context.identifier, RDF.type, META.Provenance)
        if t not in self.context.graph:
            self.context.graph.add(t)
        for name, value in self.data.items():
            pat = (self.context.identifier, META[name], None)
            if pat in self.context.graph:
                self.context.graph.remove(pat)
            self.context.graph.add((pat[0], META[name], Literal(value)))
604487
def fetch(self):
        
        self.retrieveVals()
        for parent_name in self._graphNames:
            graph = self._graphDict[parent_name]
            if self.isMultigraph:
                print "multigraph %s" % self._getMultigraphID(parent_name)
            print self._formatVals(graph.getVals())
            print
        if (self.isMultigraph and self._nestedGraphs 
            and self._subgraphDict and self._subgraphNames):
            for (parent_name, subgraph_names) in self._subgraphNames.iteritems():
                for graph_name in subgraph_names:
                    graph = self._subgraphDict[parent_name][graph_name]
                    print "multigraph %s" % self.getMultigraphID(parent_name, 
                                                                 graph_name)
                    print self._formatVals(graph.getVals())
                    print
        return True
115410
def _load(self):
        
        graph = self.context.parent.graph.get_context(self.context.identifier)
        data = {}
        for (_, p, o) in graph.triples((self.context.identifier, None, None)):
            if not p.startswith(META):
                continue
            name = p[len(META):]
            data[name] = o.toPython()
        return data
296290
def get_type(self):
        
        mtype = None
        if "type" not in self.meta_data:
            return mtype

        mtype = self.meta_data["type"]
        if isinstance(mtype, dict):
            mtype = self.meta_data.get("type", {}).get("name", "").upper()
        elif isinstance(mtype, str):
            mtype = mtype

        return mtype
227882
def get_meta(meta, name):
    """"""
    assert name in meta
    data = meta[name]

    if data['t'] in ['MetaString', 'MetaBool']:
        return data['c']
    elif data['t'] == 'MetaInlines':
        # Handle bug in pandoc 2.2.3 and 2.2.3.1: Return boolean value rather
        # than strings, as appropriate.
        if len(data['c']) == 1 and data['c'][0]['t'] == 'Str':
            if data['c'][0]['c'] in ['true', 'True', 'TRUE']:
                return True
            elif data['c'][0]['c'] in ['false', 'False', 'FALSE']:
                return False
        return stringify(data['c'])
    elif data['t'] == 'MetaList':
        return [stringify(v['c']) for v in data['c']]
    else:
        raise RuntimeError("Could not understand metadata variable '%s'." %
                           name)
640341
def get_meta_graph_copy(self, tags=None):
    """"""
    meta_graph = self.get_meta_graph(tags)
    copy = tf_v1.MetaGraphDef()
    copy.CopyFrom(meta_graph)
    return copy
487386
def Graph2Pandas_converter(self):
        ''''''

        if isinstance(self.path, str) or isinstance(self.path, p):
            self.path = str(self.path)
            filetype = p(self.path).suffix
            if filetype == '.pickle':
                self.g = pickle.load(open(self.path, 'rb'))
                if isinstance(self.g, rdflib.graph.Graph):
                    return self.get_sparql_dataframe()
                else:
                    print('WARNING:: function df() wont work unless an ontology source is loaded')
                    return self.g
            elif filetype == '.ttl' or filetype == '.rdf':
                self.g = rdflib.Graph()
                self.g.parse(self.path, format='turtle')
                return self.get_sparql_dataframe()
            elif filetype == '.nt':
                self.g = rdflib.Graph()
                self.g.parse(self.path, format='nt')
                return self.get_sparql_dataframe()
            elif filetype == '.owl' or filetype == '.xrdf':
                self.g = rdflib.Graph()
                try:
                    self.g.parse(self.path, format='xml')
                except:
                    # some owl formats are more rdf than owl
                    self.g.parse(self.path, format='turtle')
                return self.get_sparql_dataframe()
            else:
                exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')
            try:
                return self.get_sparql_dataframe()
                self.path = None
            except:
                exit('Format options: owl, ttl, df_pickle, rdflib.Graph()')

        elif isinstance(self.g, rdflib.graph.Graph):
            self.path = None
            return self.get_sparql_dataframe()

        else:
            exit('Obj given is not str, pathlib obj, or an rdflib.Graph()')
814
def Tags(self):
    
    return {
        TENSORS: list(self.tensors_by_tag.keys()),
        # Use a heuristic: if the metagraph is available, but
        # graph is not, then we assume the metagraph contains the graph.
        GRAPH: self._graph is not None,
        META_GRAPH: self._meta_graph is not None,
        RUN_METADATA: list(self._tagged_metadata.keys())
    }