Ontospy allows to extract and visualise ontology information included in RDF data. Use one of the commands listed below to find out more, or visit http://lambdamusic.github.io/ontospy
971415
def main_cli(ctx, verbose=False):
    
    sTime = time.time()
    if ctx.obj is None:  # Fix for bug (as of 3.0)
        # https://github.com/pallets/click/issues/888
        ctx.obj = {}
    ctx.obj['VERBOSE'] = verbose
    ctx.obj['STIME'] = sTime

    click.secho("Ontospy " + VERSION, fg='white')
    # click.secho("------------", fg='white')
    if not verbose and ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
1120861
def describe_uris(uris)
      graph = RDF::Graph.new

      if uris.length > 0
        uris_sparql_str = uris.map{ |u| "<#{u.to_s}>" }.join(" ")

        # Do a big describe statement, and read the results into an in-memory repo
        ntriples_string = Tripod::SparqlClient::Query.query("CONSTRUCT { ?s ?p ?o } WHERE { VALUES ?s { #{uris_sparql_str} }.  ?s ?p ?o . }", Tripod.ntriples_header_str)
        graph = _rdf_graph_from_ntriples_string(ntriples_string, graph)
      end

      graph
    end
12952
def _as_rdf_xml(self, ns):
        
        self.rdf_identity = self._get_identity(ns)
        elements = []
        elements.append(ET.Element(NS('sbol', 'persistentIdentity'),
                                   attrib={NS('rdf', 'resource'):
                                           self._get_persistent_identitity(ns)}))
        if self.name is not None:
            name = ET.Element(NS('dcterms', 'title'))
            name.text = self.name
            elements.append(name)
        if self.display_id is not None:
            display_id = ET.Element(NS('sbol', 'displayId'))
            display_id.text = self.display_id
            elements.append(display_id)
        if self.version is not None:
            version = ET.Element(NS('sbol', 'version'))
            version.text = self.version
            elements.append(version)
        if self.was_derived_from is not None:
            elements.append(ET.Element(NS('prov', 'wasDerivedFrom'),
                                       attrib={NS('rdf', 'resource'): self.was_derived_from}))
        if self.description is not None:
            description = ET.Element(NS('dcterms', 'description'))
            description.text = self.description
            elements.append(description)
        for a in self.annotations:
            elements.append(a._as_rdf_xml(ns))
        return elements
121096
def rdfgraph_to_ontol(rg):
    
    digraph = networkx.MultiDiGraph()
    from rdflib.namespace import RDF
    label_map = {}
    for c in rg.subjects(RDF.type, OWL.Class):
        cid = contract_uri_wrap(c)
        logging.info("C={}".format(cid))
        for lit in rg.objects(c, RDFS.label):
            label_map[cid] = lit.value
            digraph.add_node(cid, label=lit.value)
        for s in rg.objects(c, RDFS.subClassOf):
            # todo - blank nodes
            sid = contract_uri_wrap(s)
            digraph.add_edge(sid, cid, pred='subClassOf')

    logging.info("G={}".format(digraph))
    payload = {
        'graph': digraph,
        #'xref_graph': xref_graph,
        #'graphdoc': obographdoc,
        #'logical_definitions': logical_definitions
    }
            
    ont = Ontology(handle='wd', payload=payload)
    return ont
1161274
def map_ontologies():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    stmts_json = body.get('statements')
    stmts = stmts_from_json(stmts_json)
    om = OntologyMapper(stmts, wm_ontomap, scored=True, symmetric=False)
    om.map_statements()
    return _return_stmts(stmts)
824961
def ontologyConceptTree(self):
        
        treedict = {}
        if self.all_skos_concepts:
            treedict[0] = self.toplayer_skos
            for element in self.all_skos_concepts:
                if element.children():
                    treedict[element] = element.children()
            return treedict
        return treedict
760742
def update_ontology(ont_url, rdf_path):
    """"""
    yaml_root = load_yaml_from_url(ont_url)
    G = rdf_graph_from_yaml(yaml_root)
    save_hierarchy(G, rdf_path)
312572
def get_ontology(self, id=None, uri=None, match=None):
        

        if not id and not uri and not match:
            return None

        if type(id) == type("string"):
            uri = id
            id = None
            if not is_http(uri):
                match = uri
                uri = None
        if match:
            if type(match) != type("string"):
                return []
            res = []
            for x in self.all_ontologies:
                if match.lower() in x.uri.lower():
                    res += [x]
            return res
        else:
            for x in self.all_ontologies:
                if id and x.id == id:
                    return x
                if uri and x.uri.lower() == uri.lower():
                    return x
            return None
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')
664774
def add_semantic_data(self, path_as_list, value, key):
        
        assert isinstance(key, string_types)
        target_dict = self.get_semantic_data(path_as_list)
        target_dict[key] = value
        return path_as_list + [key]
284043
def process_rdfgraph(self, rg, ont=None):
        
        # TODO: ontology metadata
        if ont is None:
            ont = Ontology()
            subjs = list(rg.subjects(RDF.type, SKOS.ConceptScheme))
            if len(subjs) == 0:
                logging.warning("No ConceptScheme")
            else:
                ont.id = self._uri2id(subjs[0])
            
        subset_map = {}
        for concept in rg.subjects(RDF.type, SKOS.Concept):
            for s in self._get_schemes(rg, concept):
                subset_map[self._uri2id(s)] = s
                
        for concept in sorted(list(rg.subjects(RDF.type, SKOS.Concept))):
            concept_uri = str(concept)
            id=self._uri2id(concept)
            logging.info("ADDING: {}".format(id))
            ont.add_node(id, self._get_label(rg,concept))
                    
            for defn in rg.objects(concept, SKOS.definition):
                if (defn.language == self.lang):
                    td = TextDefinition(id, escape_value(defn.value))
                    ont.add_text_definition(td)
                    
            for s in rg.objects(concept, SKOS.broader):
                ont.add_parent(id, self._uri2id(s))
                
            for s in rg.objects(concept, SKOS.related):
                ont.add_parent(id, self._uri2id(s), self._uri2id(SKOS.related))
                
            for m in rg.objects(concept, SKOS.exactMatch):
                ont.add_xref(id, self._uri2id(m))
                
            for m in rg.objects(concept, SKOS.altLabel):
                syn = Synonym(id, val=self._uri2id(m))
                ont.add_synonym(syn)
                
            for s in self._get_schemes(rg,concept):
                ont.add_to_subset(id, self._uri2id(s))
                
        return ont
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
55059
function getDetails(addonPath) {
  return readManifest(addonPath).then(function(doc) {
    var em = getNamespaceId(doc, 'http://www.mozilla.org/2004/em-rdf#');
    var rdf = getNamespaceId(
        doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');

    var description = doc[rdf + 'RDF'][rdf + 'Description'][0];
    var details = {
      id: getNodeText(description, em + 'id'),
      name: getNodeText(description, em + 'name'),
      version: getNodeText(description, em + 'version'),
      unpack: getNodeText(description, em + 'unpack') || false
    };

    if (typeof details.unpack === 'string') {
      details.unpack = details.unpack.toLowerCase() === 'true';
    }

    if (!details.id) {
      throw new AddonFormatError('Could not find add-on ID for ' + addonPath);
    }

    return details;
  });

  function getNodeText(node, name) {
    return node[name] && node[name][0] || '';
  }

  function getNamespaceId(doc, url) {
    var keys = Object.keys(doc);
    if (keys.length !== 1) {
      throw new AddonFormatError('Malformed manifest for add-on ' + addonPath);
    }

    var namespaces = doc[keys[0]].$;
    var id = '';
    Object.keys(namespaces).some(function(ns) {
      if (namespaces[ns] !== url) {
        return false;
      }

      if (ns.indexOf(':') != -1) {
        id = ns.split(':')[1] + ':';
      }
      return true;
    });
    return id;
  }
}
641054
def ontologyPropTree(self):
        
        treedict = {}
        if self.all_properties:
            treedict[0] = self.toplayer_properties
            for element in self.all_properties:
                if element.children():
                    treedict[element] = element.children()
            return treedict
        return treedict
5552
def _select_ontology(self, line):
        
        try:
            var = int(line)  # it's a string
            if var in range(1, len(self.all_ontologies)+1):
                self._load_ontology(self.all_ontologies[var-1])
        except ValueError:
            out = []
            for each in self.all_ontologies:
                if line in each:
                    out += [each]
            choice = self._selectFromList(out, line, "ontology")
            if choice:
                self._load_ontology(choice)
789666
def user_to_rdf(user, graph=None):
    '''
    
    '''
    graph = graph or Graph(namespace_manager=namespace_manager)
    if user.id:
        user_url = url_for('users.show_redirect',
                           user=user.id,
                           _external=True)
        id = URIRef(user_url)
    else:
        id = BNode()
    o = graph.resource(id)
    o.set(RDF.type, FOAF.Person)
    o.set(FOAF.name, Literal(user.fullname))
    o.set(RDFS.label, Literal(user.fullname))
    if user.website:
        o.set(FOAF.homepage, URIRef(user.website))
    return o
450824
def dataset_to_rdf(dataset, graph=None):
    '''
    
    '''
    # Use the unlocalized permalink to the dataset as URI when available
    # unless there is already an upstream URI
    if 'uri' in dataset.extras:
        id = URIRef(dataset.extras['uri'])
    elif dataset.id:
        id = URIRef(url_for('datasets.show_redirect',
                            dataset=dataset.id,
                            _external=True))
    else:
        id = BNode()
    # Expose upstream identifier if present
    if 'dct:identifier' in dataset.extras:
        identifier = dataset.extras['dct:identifier']
    else:
        identifier = dataset.id
    graph = graph or Graph(namespace_manager=namespace_manager)

    d = graph.resource(id)
    d.set(RDF.type, DCAT.Dataset)
    d.set(DCT.identifier, Literal(identifier))
    d.set(DCT.title, Literal(dataset.title))
    d.set(DCT.description, Literal(dataset.description))
    d.set(DCT.issued, Literal(dataset.created_at))
    d.set(DCT.modified, Literal(dataset.last_modified))

    if dataset.acronym:
        d.set(SKOS.altLabel, Literal(dataset.acronym))

    for tag in dataset.tags:
        d.add(DCAT.keyword, Literal(tag))

    for resource in dataset.resources:
        d.add(DCAT.distribution, resource_to_rdf(resource, dataset, graph))

    if dataset.owner:
        d.add(DCT.publisher, user_to_rdf(dataset.owner, graph))
    elif dataset.organization:
        d.add(DCT.publisher, organization_to_rdf(dataset.organization, graph))

    if dataset.temporal_coverage:
        d.set(DCT.temporal, temporal_to_rdf(dataset.temporal_coverage, graph))

    frequency = frequency_to_rdf(dataset.frequency)
    if frequency:
        d.set(DCT.accrualPeriodicity, frequency)

    return d