Draw an RDF graph as an image
353512
def draw_graph( g, fmt='svg', prg='dot', options={} ):
    
    # Convert RDF to Graphviz
    buf = StringIO()
    rdf2dot( g, buf, options )

    gv_options = options.get('graphviz',[])
    if fmt == 'png':
        gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
        metadata = { "width": 5500, "height": 2200, "unconfined" : True }

    #import codecs
    #with codecs.open('/tmp/sparqlkernel-img.dot','w',encoding='utf-8') as f:
    #    f.write( buf.getvalue() )
    
    # Now use Graphviz to generate the graph
    image = run_dot( buf.getvalue(), fmt=fmt, options=gv_options, prg=prg )

    #with open('/tmp/sparqlkernel-img.'+fmt,'w') as f:
    #    f.write( image )

    # Return it
    if fmt == 'png':
        return { 'image/png' : base64.b64encode(image).decode('ascii') }, \
               { "image/png" : metadata }
    elif fmt == 'svg':
        return { 'image/svg+xml' : image.decode('utf-8').replace('<svg','<svg class="unconfined"',1) }, \
               { "unconfined" : True }
803711
def draw(self, img, pixmapper, bounds):
        ''''''
        if self._img is None:
            self._img = self.draw_legend()

        w = self._img.shape[1]
        h = self._img.shape[0]
        px = 5
        py = 5
        img[py:py+h,px:px+w] = self._img
1147108
def ontology2df(self):
        ''''''

        if isinstance(self.path, str) or isinstance(self.path, p):
            self.path = str(self.path)
            filetype = p(self.path).suffix
            if filetype == '.json':
                self.g = None
                try:
                    records = open_json(self.path)
                    return pd.DataFrame(records)
                except:
                    exit('Json file is not in records format.')
            if filetype == '.pickle':
                self.g = None
                return pickle.load(open(self.path, 'rb'))
            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()')
1139266
def graph_draw(dir: '/tmp', format: 'svg'.freeze)
      graph_save do |dotfile|
        base = File.basename(dotfile.path)
        dest = File.join(dir, "#{base}.#{format}")
        system("dot -T#{format} #{dotfile.path} -o #{dest}")
        dest
      end
    end
548212
def _draw_trees(trees, nrow=1, ncol=1, rmargin=.3, iopts=None, outdir=".",
    shfile=None, **kwargs):
    
    from jcvi.graphics.tree import draw_tree

    if shfile:
        SHs = DictFile(shfile, delimiter="\t")

    ntrees = len(trees)
    n = nrow * ncol
    for x in xrange(int(ceil(float(ntrees)/n))):
        fig = plt.figure(1, (iopts.w, iopts.h)) if iopts \
              else plt.figure(1, (5, 5))
        root = fig.add_axes([0, 0, 1, 1])

        xiv = 1. / ncol
        yiv = 1. / nrow
        xstart = list(np.arange(0, 1, xiv)) * nrow
        ystart = list(chain(*zip(*[list(np.arange(0, 1, yiv))[::-1]] * ncol)))
        for i in xrange(n*x, n*(x+1)):
            if i == ntrees:
                break
            ax = fig.add_axes([xstart[i%n], ystart[i%n], xiv, yiv])
            f = trees.keys()[i]
            tree = trees[f]
            try:
                SH = SHs[f]
            except:
                SH = None
            draw_tree(ax, tree, rmargin=rmargin, reroot=False, \
                supportcolor="r", SH=SH, **kwargs)

        root.set_xlim(0, 1)
        root.set_ylim(0, 1)
        root.set_axis_off()

        format = iopts.format if iopts else "pdf"
        dpi = iopts.dpi if iopts else 300
        if n == 1:
            image_name = f.rsplit(".", 1)[0] + "." + format
        else:
            image_name = "trees{0}.{1}".format(x, format)
        image_name = op.join(outdir, image_name)
        savefig(image_name, dpi=dpi, iopts=iopts)
        plt.clf()
1251960
def arcsIn(G: Graph, n: Node) -> RDFGraph:
    
    return RDFGraph(G.triples((None, None, n)))
545345
def arcsOut(G: Graph, n: Node) -> RDFGraph:
    
    return RDFGraph(G.triples((n, None, None)))
565926
def dcdict2rdfpy(dc_dict):
    """"""
    ark_prefix = 'ark: ark:'
    uri = URIRef('')
    # Create the RDF Python object.
    rdf_py = ConjunctiveGraph()
    # Set DC namespace definition.
    DC = Namespace('http://purl.org/dc/elements/1.1/')
    # Get the ark for the subject URI from the ark identifier.
    for element_value in dc_dict['identifier']:
        if element_value['content'].startswith(ark_prefix):
            uri = URIRef(
                element_value['content'].replace(
                    ark_prefix, 'info:ark'
                )
            )
    # Bind the prefix/namespace pair.
    rdf_py.bind('dc', DC)
    # Get the values for each element in the ordered DC elements.
    for element_name in DC_ORDER:
        element_value_list = dc_dict.get(element_name, [])
        # Add the values to the RDF object.
        for element_value in element_value_list:
            # Handle URL values differently.
            if ('http' in element_value['content'] and ' ' not in element_value['content']):
                rdf_py.add((
                    uri,
                    DC[element_name],
                    URIRef(element_value['content'])
                ))
            else:
                rdf_py.add((
                    uri,
                    DC[element_name],
                    Literal(element_value['content'])
                ))
    return rdf_py
291174
def draw(self):
        """"""
        str_wires = [["-"]*7 * self.depth]
        str_wires[0][0] = "0"
        str_wires[0][1] = " o"
        str_spaces = []

        for i in range(1, self.dimension):
            str_wires.append(["-"]*7 * self.depth)
            str_spaces.append([" "]*7 * self.depth)
            str_wires[i][0] = str(i)
            str_wires[i][1] = " o"
        
        for index, level in enumerate(self):
            for wire1, wire2 in level:
                str_wires[wire1][(index+1)*6] = "x"
                str_wires[wire2][(index+1)*6] = "x"
                for i in range(wire1, wire2):
                    str_spaces[i][(index+1)*6+1] = "|"
                for i in range(wire1+1, wire2):
                    str_wires[i][(index+1)*6] = "|"
        
        network_draw = "".join(str_wires[0])
        for line, space in zip(str_wires[1:], str_spaces):
            network_draw += "\n"
            network_draw += "".join(space)
            network_draw += "\n"
            network_draw += "".join(line)
        return network_draw
761141
def _rdf2dot_simple(g, stream):
    """"""
    from itertools import chain

    import re

    path_re = re.compile(
        r'file:///(?P<type>[a-zA-Z]+)/'
        r'(?P<commit>\w+)'
        r'(?P<path>.+)?'
    )

    inputs = g.query(
        """
        SELECT ?input ?role ?activity ?comment
        WHERE {
            ?activity (prov:qualifiedUsage/prov:entity) ?input .
            ?activity prov:qualifiedUsage ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:entity ?input .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun .
            ?activity rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )
    outputs = g.query(
        """
        SELECT ?activity ?role ?output ?comment
        WHERE {
            ?output (prov:qualifiedGeneration/prov:activity) ?activity .
            ?output prov:qualifiedGeneration ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:activity ?activity .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun ;
                      rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )

    activity_nodes = {}
    artifact_nodes = {}
    for source, role, target, comment, in chain(inputs, outputs):
        # extract the pieces of the process URI
        src_path = path_re.match(source).groupdict()
        tgt_path = path_re.match(target).groupdict()

        # write the edge
        stream.write(
            '\t"{src_commit}:{src_path}" -> '
            '"{tgt_commit}:{tgt_path}" '
            '[label={role}] \n'.format(
                src_commit=src_path['commit'][:5],
                src_path=src_path.get('path') or '',
                tgt_commit=tgt_path['commit'][:5],
                tgt_path=tgt_path.get('path') or '',
                role=role
            )
        )
        if src_path.get('type') == 'commit':
            activity_nodes.setdefault(source, {'comment': comment})
            artifact_nodes.setdefault(target, {})
        if tgt_path.get('type') == 'commit':
            activity_nodes.setdefault(target, {'comment': comment})
            artifact_nodes.setdefault(source, {})

    # customize the nodes
    for node, content in activity_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[shape=box label="#{commit}:{path}:{comment}"] \n'.format(
                comment=content['comment'],
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    for node, content in artifact_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[label="#{commit}:{path}"] \n'.format(
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    stream.write('}\n')
1162739
def rdf_source(self, format="turtle"):
        
        s = self.rdflib_graph.serialize(format=format)
        if isinstance(s, bytes):
            s = s.decode('utf-8')
        return s
1268027
def html_output_graph(self, node):
    
    graph = node['graph']
    parts = node['parts']

    graph_hash = get_graph_hash(node)
    name = "inheritance%s" % graph_hash
    path = '_images'
    dest_path = os.path.join(setup.app.builder.outdir, path)
    if not os.path.exists(dest_path):
        os.makedirs(dest_path)
    png_path = os.path.join(dest_path, name + ".png")
    path = setup.app.builder.imgpath

    # Create a mapping from fully-qualified class names to URLs.
    urls = {}
    for child in node:
        if child.get('refuri') is not None:
            urls[child['reftitle']] = child.get('refuri')
        elif child.get('refid') is not None:
            urls[child['reftitle']] = '#' + child.get('refid')

    # These arguments to dot will save a PNG file to disk and write
    # an HTML image map to stdout.
    image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'],
                              name, parts, urls)
    return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' %
            (path, name, name, image_map))
948673
def _graph_of_triples_from_construct_or_describe(construct_query)
      ntriples_str = Tripod::SparqlClient::Query.query(construct_query, Tripod.ntriples_header_str)
      _rdf_graph_from_ntriples_string(ntriples_str, graph=nil)
    end
748887
def load_rdf(self,
                 uri_or_path=None,
                 data=None,
                 file_obj=None,
                 rdf_format="",
                 verbose=False,
                 hide_base_schemas=True,
                 hide_implicit_types=True,
                 hide_implicit_preds=True):
        """"""
        loader = RDFLoader(verbose=verbose)
        loader.load(uri_or_path, data, file_obj, rdf_format)
        self.rdflib_graph = loader.rdflib_graph
        self.sources = loader.sources_valid
        self.sparqlHelper = SparqlHelper(self.rdflib_graph)
        self.namespaces = sorted(self.rdflib_graph.namespaces())
1314803
def load_graph_from_rdf(fname):
    
    print("reading RDF from " + fname + "....")
    store = Graph()
    store.parse(fname, format="n3")
    print("Loaded " + str(len(store)) + " tuples")
    return store
973433
def _parse_graph(self):

		'''
		
		'''

		# if resource exists, parse self.rdf.data
		if self.exists:
			self.rdf.graph = self.repo.api.parse_rdf_payload(self.rdf.data, self.headers)

		# else, create empty graph
		else:
			self.rdf.graph = rdflib.Graph()

		# bind any additional namespaces from repo instance, but do not override
		self.rdf.namespace_manager = rdflib.namespace.NamespaceManager(self.rdf.graph)
		for ns_prefix, ns_uri in self.rdf.prefixes.__dict__.items():
			self.rdf.namespace_manager.bind(ns_prefix, ns_uri, override=False)

		# conversely, add namespaces from parsed graph to self.rdf.prefixes
		for ns_prefix, ns_uri in self.rdf.graph.namespaces():
			setattr(self.rdf.prefixes, ns_prefix, rdflib.Namespace(ns_uri))
			setattr(self.rdf.uris, rdflib.Namespace(ns_uri), ns_prefix)

		# pin old graph to resource, create copy graph for modifications
		self.rdf._orig_graph = copy.deepcopy(self.rdf.graph)

		# parse triples for object-like access
		self.parse_object_like_triples()
816279
def _graphify(self, *args, graph=None): #  defined
        
        if graph is None:
            graph = self.out_graph

        ################## LABELS ARE DEFINED HERE ##################
        gl = self.genLabel
        ll = self.localLabel
        ol = self.origLabel
        graph.add((self.id_, ilxtr.genLabel, rdflib.Literal(gl)))
        if ll != gl:
            graph.add((self.id_, ilxtr.localLabel, rdflib.Literal(ll)))

        if ol and ol != gl:
            graph.add((self.id_, ilxtr.origLabel, rdflib.Literal(ol)))

        members = [self.expand(self.owlClass)]
        for pe in self.pes:
            target = pe._graphify(graph=graph)
            if isinstance(pe, NegPhenotype):  # isinstance will match NegPhenotype -> Phenotype
                #self.Class.disjointWith = [target]  # FIXME for defined neurons this is what we need and I think it is strong than the complementOf version
                djc = infixowl.Class(graph=graph)  # TODO for generic neurons this is what we need
                djc.complementOf = target
                members.append(djc)
            else:
                members.append(target)  # FIXME negative logical phenotypes :/
        intersection = infixowl.BooleanClass(members=members, graph=graph)  # FIXME dupes
        #existing = list(self.Class.equivalentClass)
        #if existing or str(pe.pLabel) == 'Htr3a':
            #embed()
        ec = [intersection]
        self.Class.equivalentClass = ec
        return self.Class