Generates a sub-ontology based on associations
436179
def subontology(self, minimal=False):
        
        return self.ontology.subontology(self.objects, minimal=minimal)
594900
def index_ontology(self, ont):
        
        self.merged_ontology.merge([ont])
        syns = ont.all_synonyms(include_label=True)
        
        include_id = self._is_meaningful_ids()
        logging.info("Include IDs as synonyms: {}".format(include_id))
        if include_id:
            for n in ont.nodes():
                v = n
                # Get fragment
                if v.startswith('http'):
                    v = re.sub('.*/','',v)
                    v = re.sub('.*#','',v)
                syns.append(Synonym(n, val=v, pred='label'))
        
        logging.info("Indexing {} syns in {}".format(len(syns),ont))
        logging.info("Distinct lexical values: {}".format(len(self.lmap.keys())))
        for syn in syns:
            self.index_synonym(syn, ont)
        for nid in ont.nodes():
            self.id_to_ontology_map[nid].append(ont)
1107155
def predicates(self) -> Dict[str, URIRef]:
        
        rval = dict()
        for parent in self._o.objects(self._subj, RDFS.subClassOf):
            if isinstance(parent, URIRef) and not str(parent).startswith(str(W5)):
                rval.update(**FHIRMetaVocEntry(self._o, parent).predicates())
        for s in self._o.subjects(RDFS.domain, self._subj):
            rval[self._to_str(s)] = s
        return rval
1120739
def convert_association(self, association: Association) -> Entity:
        
        if "header" not in association or association["header"] == False:
            # print(json.dumps(association, indent=4))
            gpi_obj = {
                'id': association["subject"]["id"],
                'label': association["subject"]["label"],  # db_object_symbol,
                'full_name': association["subject"]["fullname"],  # db_object_name,
                'synonyms': association["subject"]["synonyms"],
                'type': association["subject"]["type"], #db_object_type,
                'parents': "", # GAF does not have this field, but it's optional in GPI
                'xrefs': "", # GAF does not have this field, but it's optional in GPI
                'taxon': {
                    'id': association["subject"]["taxon"]["id"]
                }
            }
            return Entity(gpi_obj)

        return None
512692
def generate_schema_mapping(resolver, schema_uri, depth=1):
    
    visitor = SchemaVisitor({'$ref': schema_uri}, resolver)
    return _generate_schema_mapping(visitor, set(), depth)
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()')
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
1236613
def skos_transitive(rdf, narrower=True):
    """"""
    for conc in rdf.subjects(RDF.type, SKOS.Concept):
        for bt in rdf.transitive_objects(conc, SKOS.broader):
            if bt == conc:
                continue
            rdf.add((conc, SKOS.broaderTransitive, bt))
            if narrower:
                rdf.add((bt, SKOS.narrowerTransitive, conc))
859246
def addOntology(self, ontology):
        
        self._ontologyNameMap[ontology.getName()] = ontology
        self._ontologyIdMap[ontology.getId()] = ontology
        self._ontologyIds.append(ontology.getId())
850625
def create_from_tuples(self, tuples, **args):
        
        amap = {}
        subject_label_map = {}
        for a in tuples:
            subj = a[0]
            subject_label_map[subj] = a[1]
            if subj not in amap:
                amap[subj] = []
            amap[subj].append(a[2])

        aset = AssociationSet(subject_label_map=subject_label_map, association_map=amap, **args)
        return aset
1176897
def map_relations
      self.resource_relations = {}
      model.alchemy_resource_relations.each do |name, options|
        name = name.to_s.gsub(/_id$/, '') # ensure that we don't have an id
        association = association_from_relation_name(name)
        foreign_key = association.options[:foreign_key] || "#{association.name}_id".to_sym
        resource_relations[foreign_key] = options.merge(model_association: association, name: name)
      end
    end
685335
def expand_sub_definitions(sub_definitions)
      sub_definitions.each_with_object({}) do |(subkey, value), result|
        result[subkey] = value
        next if value.respond_to? :call
        result[subkey][:attributes] = expand_definition(value[:attributes])
      end
    end
1306396
def create_concept_scheme(rdf, ns, lname=''):
    """"""

    ont = None
    if not ns:
        # see if there's an owl:Ontology and use that to determine namespace
        onts = list(rdf.subjects(RDF.type, OWL.Ontology))
        if len(onts) > 1:
            onts.sort()
            ont = onts[0]
            logging.warning(
                "Multiple owl:Ontology instances found. "
                "Creating concept scheme from %s.", ont)
        elif len(onts) == 1:
            ont = onts[0]
        else:
            ont = None

        if not ont:
            logging.info(
                "No skos:ConceptScheme or owl:Ontology found. "
                "Using namespace auto-detection for creating concept scheme.")
            ns = detect_namespace(rdf)
        elif ont.endswith('/') or ont.endswith('#') or ont.endswith(':'):
            ns = ont
        else:
            ns = ont + '/'

    NS = Namespace(ns)
    cs = NS[lname]

    rdf.add((cs, RDF.type, SKOS.ConceptScheme))

    if ont is not None:
        rdf.remove((ont, RDF.type, OWL.Ontology))
        # remove owl:imports declarations
        for o in rdf.objects(ont, OWL.imports):
            rdf.remove((ont, OWL.imports, o))
        # remove protege specific properties
        for p, o in rdf.predicate_objects(ont):
            prot = URIRef(
                'http://protege.stanford.edu/plugins/owl/protege#')
            if p.startswith(prot):
                rdf.remove((ont, p, o))
        # move remaining properties (dc:title etc.) of the owl:Ontology into
        # the skos:ConceptScheme
        replace_uri(rdf, ont, cs)

    return cs
1146048
function createSubset(keywords, doc) {

    if (!keywords || Object.prototype.toString.call(keywords) !== '[object Array]') {
      return doc;
    }

    var lookup = createLookUp(keywords);

    return traverseThroughObject(lookup, doc);

  }
1006420
def _get_dbid2goids(associations):
        """"""
        id2gos = cx.defaultdict(set)
        for ntd in associations:
            id2gos[ntd.DB_ID].add(ntd.GO_ID)
        return dict(id2gos)
1147532
def ontologyClassTree(self):
        
        treedict = {}
        if self.all_classes:
            treedict[0] = self.toplayer_classes
            for element in self.all_classes:
                if element.children():
                    treedict[element] = element.children()
            return treedict
        return treedict
692747
def schema_map(schema):
    """"""
    mapper = {}
    for name in getFieldNames(schema):
        mapper[name] = name
    return mapper