def define_shape_properties(definitions): """ Defines the NodeShapes that govern what the values of EntityProperty relationships should look like. The important keys are: - values: defines the set of possible values of this property as an enumeration - units: verifies that the units of the value are one of the given enumeration. - datatype: specifies the expected kind of data type of prop:value - properties: defines other epected properties of the Shape. These properties can have 'datatype' or 'values', in addition to other standard properties like SKOS.definition Some other usage notes: - 'units' and 'datatype' should be used together - 'values' should not be used with units or datatype """ for shape_name, defn in definitions.items(): G.add((shape_name, A, SH.NodeShape)) v = BNode() # prop:value PropertyShape if "values" in defn: ps = BNode() enumeration = BNode() G.add((shape_name, SH.property, ps)) G.add((ps, A, SH.PropertyShape)) G.add((ps, SH.path, BRICK.value)) G.add((ps, SH["in"], enumeration)) G.add((ps, SH.minCount, Literal(1))) Collection(G, enumeration, map(Literal, defn.pop("values"))) if "units" in defn: ps = BNode() enumeration = BNode() G.add((shape_name, SH.property, ps)) G.add((ps, A, SH.PropertyShape)) G.add((ps, SH.path, BRICK.hasUnit)) G.add((ps, SH["in"], enumeration)) G.add((ps, SH.minCount, Literal(1))) Collection(G, enumeration, defn.pop("units")) if "properties" in defn: for prop_name, prop_defn in defn.pop("properties").items(): ps = BNode() G.add((shape_name, SH.property, ps)) G.add((ps, A, SH.PropertyShape)) G.add((ps, SH.path, prop_name)) G.add((ps, SH.minCount, Literal(1))) if "datatype" in prop_defn: G.add((ps, SH.datatype, prop_defn.pop("datatype"))) elif "values" in prop_defn: enumeration = BNode() G.add((ps, SH["in"], enumeration)) G.add((ps, SH.minCount, Literal(1))) Collection(G, enumeration, map(Literal, prop_defn.pop("values"))) add_properties(ps, prop_defn) elif "datatype" in defn: G.add((shape_name, SH.property, v)) G.add((v, A, SH.PropertyShape)) G.add((v, SH.path, BRICK.value)) G.add((v, SH.datatype, defn.pop("datatype"))) G.add((v, SH.minCount, Literal(1)))
def transform(self, graph): """ Transforms a universal restriction on a 'pure' nominal range into a conjunction of value restriction (using set theory and demorgan's laws) """ Individual.factoryGraph = graph for restriction, intermediateCl, nominal, prop, partition in graph.query( self.NOMINAL_QUERY, initNs={ u'owl': OWL_NS, u'rdfs': str(RDFS) }): exceptions = EnumeratedClass() partition = Collection(graph, partition) nominalCollection = Collection(graph, nominal) for i in partition: if i not in nominalCollection: exceptions._rdfList.append(i) #exceptions+=i exists = Class(complementOf=(Property(prop) | some | exceptions)) for s, p, o in graph.triples((None, None, restriction)): graph.add((s, p, exists.identifier)) Individual(restriction).delete() #purge nominalization placeholder iClass = BooleanClass(intermediateCl) iClass.clear() iClass.delete()
def compile_stage2(ir, debug=False, **kw): """ Translate the transitive closure of data, model under inference rules into a simple python dictionary that can be dealt with by Jinja2 """ logging.info("stage2: generating python representation") ir2 = {"circuits": []} model, _, _ = get_one(ir, (None, RDF["type"], RBMO["Model"])) _, _, prefix = get_one(ir, (model, RBMC["prefix"], None)) ir2["prefix"] = prefix.toPython() for _, _, parts in ir.triples((model, RBMC["linear"], None)): circuit = list( map(lambda x: describe_part(ir, x), Collection(ir, parts))) ir2["circuits"].append({"topology": "linear", "parts": circuit}) for _, _, parts in ir.triples((model, RBMC["circular"], None)): circuit = list( map(lambda x: describe_part(ir, x), Collection(ir, parts))) ir2["circuits"].append({"topology": "circular", "parts": circuit}) logging.debug("=" * 80) logging.debug("stage2: output") logging.debug("-" * 80) from pprint import pformat for line in pformat(ir2).split("\n"): logging.debug(line) logging.debug("=" * 80) return ir2
def visit_class(self, cls: ClassDefinition) -> bool: cls_uri = self.class_uri(cls.name) self.graph.add((cls_uri, RDF.type, OWL.Class)) self.graph.add((cls_uri, RDFS.label, Literal(cls.name))) if cls.description: self.graph.add((cls_uri, OBO.IAO_0000115, Literal(cls.description))) # Parent classes if cls.is_a and not cls.defining_slots: self.graph.add((cls_uri, RDFS.subClassOf, self.class_uri(cls.is_a))) if cls.mixin: self.graph.add((cls_uri, RDFS.subClassOf, META.mixin)) for mixin in cls.mixins: self.graph.add((cls_uri, RDFS.subClassOf, self.class_uri(mixin))) # TODO: Add apply_to injections if cls.union_of: union_node = BNode() union_coll = BNode() Collection(self.graph, union_coll, [self.class_uri(union_node) for union_node in cls.union_of]) self.graph.add((union_node, OWL.unionOf, union_coll)) self.graph.add((cls_uri, RDFS.subClassOf, union_node)) # Defining slots give us an equivalent class if cls.defining_slots: equ_node = BNode() self.graph.add((cls_uri, OWL.equivalentClass, equ_node)) self.graph.add((equ_node, RDF.type, OWL.Class)) elts = [] if cls.is_a: elts.append(self.class_uri(cls.is_a)) for slotname in cls.defining_slots: slot = self.schema.slots[slotname] restr_node = BNode() self.graph.add((restr_node, RDF.type, OWL.Restriction)) self.graph.add((restr_node, OWL.onProperty, self.prop_uri(slotname))) self.add_cardinality(restr_node, slot) self.graph.add((restr_node, OWL.someValuesFrom, self.build_range(slot))) elts.append(restr_node) coll_bnode = BNode() Collection(self.graph, coll_bnode, elts) self.graph.add((equ_node, OWL.intersectionOf, coll_bnode)) for slotname in cls.slots: if slotname not in cls.defining_slots: subc_node = BNode() slot = self.schema.slots[slotname] slot_alias = slot.alias if slot.alias else slot.name self.graph.add((subc_node, RDF.type, OWL.Restriction)) self.graph.add((subc_node, OWL.onProperty, self.prop_uri(slot_alias))) self.add_cardinality(subc_node, slot) self.graph.add((subc_node, OWL.someValuesFrom, self.build_range(slot))) self.graph.add((cls_uri, RDFS.subClassOf, subc_node)) return True
def IncomingSIPArcs(sip, predOcc): """docstring for IncomingSIPArcs""" for s, p, o in sip.triples((None, None, predOcc)): if (p, RDF.type, MAGIC.SipArc) in sip: if (s, RDF.type, MAGIC.BoundHeadPredicate) in sip: yield [s], Collection(sip, first(sip.objects(p, MAGIC.bindings))) else: yield Collection(sip, s), Collection( sip, first(sip.objects(p, MAGIC.bindings)))
def parts(): for _, _, pl in g.triples((m, GCC["linear"], None)): ps = Collection(g, pl) for p in ps: _, _, label = get_one(g, (p, GCC["part"], None)) yield str(label) for _, _, pl in g.triples((m, GCC["circular"], None)): ps = Collection(g, pl) for p in ps: _, _, label = get_one(g, (p, GCC["part"], None)) yield str(label)
def check_size(self, g: Graph, g2: Graph, root: URIRef, expected_classes: int, expected_slots: int, expected_types: int, model: str) -> None: for graph in [g, g2]: class_bnode = graph.value(root, BIOENTITY.classes) slot_bnode = graph.value(root, BIOENTITY.slots) type_bnode = graph.value(root, BIOENTITY.types) self.assertEqual(expected_classes, len(list(Collection(graph, class_bnode))), f"Expected {expected_classes} classes in {model}") self.assertEqual(expected_slots, len(list(Collection(graph, slot_bnode))), f"Expected {expected_slots} slots in {model}") self.assertEqual(expected_types, len(list(Collection(graph, type_bnode))), f"Expected {expected_types} types in {model}")
def RenderSIPCollection(sipGraph, dot=None): try: from pydot import Node, Edge, Dot except: import warnings warnings.warn("Missing pydot library", ImportWarning) if not dot: dot = Dot(graph_type='digraph') dot.leftNodesLookup = {} nodes = {} for N, prop, q in sipGraph.query( 'SELECT ?N ?prop ?q { ?prop a magic:SipArc . ?N ?prop ?q . }', initNs={u'magic': MAGIC}): if MAGIC.BoundHeadPredicate in sipGraph.objects(subject=N, predicate=RDF.type): NCol = [N] else: NCol = Collection(sipGraph, N) if q not in nodes: newNode = Node(makeMD5Digest(q), label=normalizeTerm(q, sipGraph), shape='plaintext') nodes[q] = newNode dot.add_node(newNode) bNode = BNode() nodeLabel = ', '.join([normalizeTerm(term, sipGraph) for term in NCol]) edgeLabel = ', '.join([ var.n3() for var in Collection( sipGraph, first(sipGraph.objects(prop, MAGIC.bindings))) ]) markedEdgeLabel = '' if nodeLabel in dot.leftNodesLookup: bNode, leftNode, markedEdgeLabel = dot.leftNodesLookup[nodeLabel] # print("\t", nodeLabel, edgeLabel, # markedEdgeLabel, not edgeLabel == markedEdgeLabel else: leftNode = Node(makeMD5Digest(bNode), label=nodeLabel, shape='plaintext') dot.leftNodesLookup[nodeLabel] = (bNode, leftNode, edgeLabel) nodes[bNode] = leftNode dot.add_node(leftNode) if not edgeLabel == markedEdgeLabel: edge = Edge(leftNode, nodes[q], label=edgeLabel) dot.add_edge(edge) return dot
def collectSip(left, right): if isinstance(left, list): vars = CollectSIPArcVars(left, right, phBoundVars) if not vars and ignoreUnboundDPreds: raise InvalidSIPException("No bound variables for %s" % right) leftList = Collection(sipGraph, None) left = list(set(left)) [leftList.append(i) for i in [GetOp(ii) for ii in left]] left.append(right) # arc = SIPGraphArc(leftList.uri, getOccurrenceId(right, occurLookup), vars, sipGraph) return left else: left.isHead = True vars = CollectSIPArcVars(left, right, phBoundVars) if not vars and ignoreUnboundDPreds: raise InvalidSIPException("No bound variables for %s" % right) ph = GetOp(left) # q = getOccurrenceId(right, occurLookup) if boundHead: # arc = SIPGraphArc(ph, q, vars, sipGraph, headPassing=boundHead) sipGraph.add((ph, RDF.type, MAGIC.BoundHeadPredicate)) rt = [left, right] else: rt = [right] return rt
def pedido_a_envio(graph, pedido, productos): ''' devuelve el pedido transformado en un envio Graph tiene que contener toda la informacion del pedido + toda la informacion de los productos para cada producto del pedido (importe mas que nada) ''' g = Graph() envios_ns = getNamespace('Envios') pedidos_ns = getNamespace('Pedidos') productos_ns = getNamespace('Productos') #Generamos un id aleatorio envio_id = str(random.getrandbits(64)) #Anadimos el ID al envio g.add((envios_ns[envio_id], RDF.type, envios_ns.type)) g.add((envios_ns[envio_id], envios_ns.Id, Literal(envio_id))) #Anadimos el usuario al envio user = graph.value(pedido, pedidos_ns.Hechopor) g.add((envios_ns[envio_id], envios_ns.Hechopor, user)) #Anadimos la referencia al pedido original pedido_uri = pedido g.add((envios_ns[envio_id], envios_ns.Llevaacabo, pedido_uri)) #fecha de realizacion fecha = graph.value(pedido, pedidos_ns.Fecharealizacion) g.add((envios_ns[envio_id], envios_ns.Fecharealizacion, fecha)) #direccion de entrega loc = graph.value(pedido, pedidos_ns.Tienedirecciondeentrega) locGraph = expandirGrafoRec(graph, loc) #sumamos la localizacion al grafo que devolvemos g += locGraph g.add((envios_ns[envio_id], envios_ns.Tienedirecciondeentrega, loc)) #Anadimos el conjunto de productos al grafo de envio. Hay que crear un nodo no anonimo para la lista # o sino la libreria no funciona bien lista = envios_ns[envio_id + '-ListaProductos'] g.add((envios_ns[envio_id], envios_ns.Contiene, lista)) c = Collection(g, lista) #Anadimos las uris de los productos al envio y sumamos el importe total importe = 0 for p in productos: c.append(p) importe += int(graph.value(p, productos_ns.Importe)) #Anadimos el importe total g.add((envios_ns[envio_id], envios_ns.Importetotal, Literal(importe))) #Anadimos la prioridad del envio que es la misma que la prioridad de la entrega prioridad = graph.value(pedido, pedidos_ns.Prioridad) g.add((envios_ns[envio_id], envios_ns.Prioridad, prioridad)) return g
def lote_a_dict(graph, lote): ''' devuelve un diccionario con todos los atributos del lote ''' lotes_ns = getNamespace('Lotes') direcciones_ns = getNamespace('Direcciones') envios_ns = getNamespace('Envios') ret = {} ret['Id'] = graph.value(lote, lotes_ns.Id) ret['Estadodellote'] = str(graph.value(lote, lotes_ns.Estadodellote)) ret['Ciudad'] = graph.value(lote, lotes_ns.Ciudad) ret['Peso'] = graph.value(lote, lotes_ns.Peso) ret['Prioridad'] = graph.value(lote, lotes_ns.Prioridad) #loc = graph.value(lote,lotes_ns.Tienedirecciondeentrega) #ret['direccion'] = graph.value(loc,direcciones_ns.Direccion) #ret['cp'] = graph.value(loc,direcciones_ns.Codigopostal) envs = [] container = graph.value(subject=lote, predicate=lotes_ns.TieneEnvios) c = Collection(graph, container) for item in c: envs += [item] ret['envios'] = envs return ret
def add_restriction(klass, definition): """ Defines OWL.Restrictions linked to Brick classes through OWL.equivalentClass. This populates the property-object pairs (OWL.onProperty, 'property'), (OWL.hasValue, 'value'). The intersection of these properties is made to be equivalent to the given class. Args: klass: the URI of the Brick class to be modeled definition: a list of (property, value) pairs """ if len(definition) == 0: return elements = [] equivalent_class = BNode() list_name = BNode() for idnum, item in enumerate(definition): restriction = BNode() elements.append(restriction) G.add((restriction, A, OWL.Restriction)) G.add((restriction, OWL.onProperty, item[0])) G.add((restriction, OWL.hasValue, item[1])) G.add((klass, OWL.equivalentClass, equivalent_class)) G.add((equivalent_class, OWL.intersectionOf, list_name)) Collection(G, list_name, elements)
def pedido_a_dict(graph, pedido): ''' devuelve un diccionario con todos los atributos de producto ''' pedidos_ns = getNamespace('Pedidos') direcciones_ns = getNamespace('Direcciones') productos_ns = getNamespace('Productos') ret = {} ret['id'] = graph.value(pedido, pedidos_ns.Id) ret['user_id'] = graph.value(pedido, pedidos_ns.Hechopor) ret['date'] = graph.value(pedido, pedidos_ns.Fecharealizacion) ret['prioridad'] = graph.value(pedido, pedidos_ns.Prioridad) ret['responsable'] = graph.value(pedido, pedidos_ns.VendedorResponsable) or False loc = graph.value(pedido, pedidos_ns.Tienedirecciondeentrega) ret['direccion'] = graph.value(loc, direcciones_ns.Direccion) ret['cp'] = graph.value(loc, direcciones_ns.Codigopostal) prods = [] container = graph.value(subject=pedido, predicate=pedidos_ns.Contiene) c = Collection(graph, container) for item in c: dict = {} dict['uri'] = graph.value( subject=item, predicate=productosPedido_ns.AsociadoAlProducto) dict['estado'] = graph.value( subject=item, predicate=productosPedido_ns.EstadoProductoEnPedido) dict['fechaEntrega'] = graph.value( subject=item, predicate=productosPedido_ns.FechaEnvio) prods += [dict] ret['productos'] = prods return ret
def parse_property(self, source, prop, dest): """ Creates property constraints :param source: source rdflib graph :param prop: property IRI :param dest: output SHACL constraints graph :return: property blank node """ node = BNode() dest.add((node, SHACL['path'], prop)) property_range = list([ replace_prefix(x) for x in source.objects(prop, SCHEMA['rangeIncludes']) ]) if len(property_range) > 1: or_node = BNode() or_collection = Collection(dest, or_node) dest.add((node, SHACL['or'], or_node)) for shape in property_range: t = BNode() dest.add((t, SHACL['node'], shape)) or_collection.append(t) else: dest.add((node, SHACL['node'], property_range[0])) return node
def define_constraints(constraints, classname): """ Makes 'classname' a SHACL NodeShape and Class (implicitly targeting all instances of the class) and defines some PropertyShapes based on 'constraints' that apply to the nodeshape. """ for property_name, property_values in constraints.items(): pnode = BNode() onode = BNode() G.add((classname, A, SH.NodeShape)) G.add((classname, SH.property, pnode)) G.add((pnode, SH["path"], property_name)) if isinstance(property_values, URIRef): G.add((pnode, SH["class"], property_values)) elif isinstance(property_values, list): G.add((pnode, SH["or"], onode)) possible_values = [] for pv in property_values: pvnode = BNode() G.add((pvnode, SH["class"], pv)) possible_values.append(pvnode) Collection(G, onode, possible_values) else: raise Exception("Do not know how to handle constraints for %s" % classname)
def process_document(g, fn, subj, cls): g.add((subj, RDF.type, cls)) fn_parts = list(map(rdflib.Literal, fn.replace("\\", "/")[len(base_path)+1:].split("/")))[::-1] c = Collection(g, fqdn(f"doc_{i}_filename"), fn_parts) g.add((subj, fqdn("hasFilename"), c.uri)) def write(s, ct): heading = ct.heading.strip() m = re.search(r"\[([\w\- ]+)\]", heading) if m: mvd = m.group(1) g.add((s, fqdn("hasContext"), rdflib.Literal(mvd))) li = [c for c in heading] li[slice(*m.span())] = [] heading = (mvd, "".join(li).strip()) g.add((s, fqdn("hasCleanHeading"), rdflib.Literal(heading))) g.add((s, fqdn("hasHeading"), rdflib.Literal(ct.heading))) if ct.content.strip(): g.add((s, fqdn("hasText"), rdflib.Literal(ct.content))) for i, ch in enumerate(ct.children): s2 = s + f"_{i}" g.add((s2, fqdn("containedIn"), s)) write(s2, ch) contents = parse_document(fn=fn) if contents: write(subj, contents)
def SIPRepresentation(sipGraph): rt = [] for N, prop, q in sipGraph.query( 'SELECT ?N ?prop ?q { ?prop a magic:SipArc . ?N ?prop ?q . }', initNs={u'magic': MAGIC}): if MAGIC.BoundHeadPredicate in sipGraph.objects(subject=N, predicate=RDF.type): NCol = [N] else: NCol = Collection(sipGraph, N) rt.append("{ %s } -> %s %s" % (', '.join( [normalizeTerm(term, sipGraph) for term in NCol]), ', '.join([ var.n3() for var in Collection( sipGraph, first(sipGraph.objects(prop, MAGIC.bindings))) ]), normalizeTerm(q, sipGraph))) return rt
def define_ontology(G): brick_iri_version = URIRef( f"https://brickschema.org/schema/{BRICK_VERSION}/Brick") G.add((brick_iri_version, RDF.type, OWL.Ontology)) G.add((brick_iri_version, RDFS.isDefinedBy, brick_iri_version)) # add creators from ontology markup above creators = [] creator_list = BNode() for creator in ontology.pop(DCTERMS.creator): creator1 = BNode() creators.append(creator1) for k, v in creator.items(): G.add((creator1, k, v)) # add publisher info publisher = BNode() G.add((brick_iri_version, DCTERMS.publisher, publisher)) for k, v in ontology.pop(DCTERMS.publisher).items(): G.add((publisher, k, v)) Collection(G, creator_list, creators) G.add((brick_iri_version, DCTERMS.creator, creator_list)) # add other simple attributes for k, v in ontology.items(): G.add((brick_iri_version, k, v))
def get_expected_values_str(uri: URIRef, g: Graph, lookups: Graph) -> str: list_value = g.value(uri, SH["in"]) c = Collection(g, list_value) str_value = "" if len(c) > 0: if len(c) == 1: item = c[0] label = _get_label(item, lookups) str_value += f"link:{item}[{label}]" else: for i, item in enumerate(c): uri = None if isinstance(item, URIRef): label = _get_label(item, lookups) uri = str(item) elif isinstance(item, Literal): label = item.n3() if label is None: raise ValueError(f"Could not find label for {item}.") if i + 1 == len(c): if uri: str_value += f"- link:{uri}[{label}]" else: str_value += f"- `{label}`" else: if uri: str_value += f"- link:{uri}[{label}] +\n" else: str_value += f"- `{label}` +\n" return str_value
def add_tags(klass, definition): l = [] equivalent_class = BNode() list_name = BNode() for idnum, item in enumerate(definition): restriction = BNode() l.append(restriction) G.add( (restriction, A, OWL.Restriction) ) G.add( (restriction, OWL.onProperty, BRICK.hasTag) ) G.add( (restriction, OWL.hasValue, item) ) G.add( (item, A, BRICK.Tag) ) # make sure the tag is declared as such G.add( (item, RDFS.label, Literal(item.split('#')[-1])) ) # make sure the tag is declared as such # cardinality #restriction = BNode() #l.append(restriction) #G.add( (restriction, A, OWL.Restriction) ) #G.add( (restriction, OWL.onProperty, BRICK.hasTag) ) #G.add( (restriction, OWL.cardinality, Literal(len(definition))) ) # tag index tagset = tuple(sorted([item.split('#')[-1] for item in definition])) tag_lookup[tagset].add(klass) G.add( (BRICK[klass], OWL.equivalentClass, equivalent_class) ) G.add( (equivalent_class, OWL.intersectionOf, list_name) ) c = Collection(G, list_name, l)
def triples(self, pattern: Optional[Union[QueryTriple, SUBJ]], pred: Optional[PRED]='', obj: Optional[OBJ]='') -> Generator[RDFTriple, None, None]: # Allow a tuple or a list of three items if pattern is None or pred != '' or obj != '': pattern = (pattern, pred, obj) if not self._inside: try: self._inside = True for s, p, o in super().triples(pattern): if o != RDF.nil: if p not in (RDF.first, RDF.rest): if isinstance(o, BNode): if self.value(o, RDF.first, None): for e in Collection(self, o): yield(s, p, e) else: yield (s, p, o) else: yield (s, p, o) elif p == RDF.first and not pattern[0] and pattern[2]: sp = self._list_root(s) if sp: yield (sp[0], sp[1], o) finally: self._inside = False else: for t in super().triples(pattern): yield t
def run(self): self._set_base_uri() self._select_attrs_and_instances() g = rdflib.Graph() g.parse(self.temp, format="turtle") g.namespace_manager.bind("owl", "http://www.w3.org/2002/07/owl#") ns_type = rdflib.term.URIRef( 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type') for s, p, o in g: if o == self.the_object and p == ns_type: if any(word in s for word in ["ValueCode", "PropertyCode", "Procedure"]): attr_name, postfix = self._get_attr_name(attribute=s.n3()) attr = attr_name[0].lower() + attr_name[1:] instances = self.data.get(attr_name) if instances: instance_uris = [ self._generate_instance_uri( instance, postfix, attr) for instance in instances ] bn = BNode() g.add( (s, URIRef("http://www.w3.org/2002/07/owl#oneOf"), bn)) Collection(g, bn, instance_uris) return g
def handleConjunct(conjunction, owlGraph, o, conjunctVar=Variable('X')): for bodyTerm in Collection(owlGraph, o): negatedFormula = False addToConjunct = None for negatedFormula in owlGraph.objects(subject=bodyTerm, predicate=OWL_NS.complementOf): addToConjunct = Tc(owlGraph, negatedFormula) if negatedFormula: # addToConjunct will be the term we need to add to the conjunct conjunction.append(addToConjunct) else: normalizedBodyTerm = NormalizeBooleanClassOperand( bodyTerm, owlGraph) bodyUniTerm = Uniterm(RDF.type, [conjunctVar, normalizedBodyTerm], newNss=owlGraph.namespaces()) processedBodyTerm = Tb(owlGraph, bodyTerm, conjunctVar) classifyingClause = NormalizeClause( Clause(processedBodyTerm, bodyUniTerm)) # redundantClassifierClause = processedBodyTerm == bodyUniTerm if isinstance(normalizedBodyTerm, URIRef) and normalizedBodyTerm.find( SKOLEMIZED_CLASS_NS) == -1: conjunction.append(bodyUniTerm) elif (bodyTerm, OWL_NS.someValuesFrom, None) in owlGraph or\ (bodyTerm, OWL_NS.hasValue, None) in owlGraph: conjunction.extend(classifyingClause.body) elif (bodyTerm, OWL_NS.allValuesFrom, None) in owlGraph: raise MalformedDLPFormulaError( "Universal restrictions can only be used as the second argument to rdfs:subClassOf (GCIs)" ) elif (bodyTerm, OWL_NS.unionOf, None) in owlGraph: conjunction.append(classifyingClause.body) elif (bodyTerm, OWL_NS.intersectionOf, None) in owlGraph: conjunction.append(bodyUniTerm)
def handle_inout(tool, item_value, in_or_out): for ioD in item_value: # print(ioD) io_name = ioD['name'] if io_name is None: io_name = in_or_out _name = Preprocessor.io_name(io_name, onto) param_rdf = None if in_or_out == 'input': param = SagaInput(_name, prefLabel=locstr(io_name, lang='en')) # param = SagaInput(0,prefLabel=locstr(io_name, lang='en')) # blank node prefix with _: tool.input.append(param) param.isInput = True # rdflib param_rdf = URIRef(param.iri) with onto: g.add((param_rdf, RDF.type, Sh.NodeShape)) g.add((param_rdf, RDF.type, URIRef(SagaInput.iri))) else: param = SagaOutput(_name, prefLabel=locstr(io_name, lang='en')) # param =SagaOutput(0, prefLabel=locstr(io_name, lang='en')) tool.output.append(param) param.isOutput = True # rdflib param_rdf = URIRef(param.iri) with onto: g.add((param_rdf, RDF.type, Sh.NodeShape)) g.add((param_rdf, RDF.type, URIRef(SagaOutput.iri))) if ioD['dataType']: vr = re.match("[a-zA-Z ]+ (?=\([a-zA-Z ]+\))?", ioD['dataType']) dformat = vr.group().strip() if not get_format(dformat): continue param.supportsDataFormat.append(data[get_format(dformat)]) # rdflib formatshape = g.BNode() with onto: g.add((param_rdf, Sh.property, formatshape)) g.add((formatshape, RDF.type, Sh.PropertyShape)) g.add((formatshape, Sh.path, Cyber.supportsDataFormat)) formats = g.BNode() with onto: g.add((formats, RDF.first, [data[get_format(dformat)]])) g.add((formats, RDF.rest, RDF.nil)) c = Collection(g, formats) g.add((formatshape, Sh['in'], c)) param.identifier = ioD['name'] param.description.append(ioD['description']) param.flag = ioD['flag'] param.isOptional = ioD['isOptional'] OWLUtils.link_to_domain_concept(param, io_name.replace('_', ' ')) # shacl pshape = Sh.PropertyShape(0) pshape.path = onto.dataContent if not ioD['isOptional']: pshape.minCount = 1 pshape.message.append(ioD['name'] + " is required!")
def extractAtom(self, atom): args, op = self.atoms[atom] op = self.extractTerm(op) args = list(map(self.extractTerm, Collection(self.graph, args))) if len(args) > 2: raise NotImplementedError( "FuXi RIF Core parsing only supports subset involving binary/unary Atoms" ) return Uniterm(op, args)
def clone_list(l_node): cloned_node = rdflib.BNode() new_list = Collection(target_graph, cloned_node) for item in iter(graph.items(l_node)): cloned_item = clone_node(graph, item, target_graph, recursion=recursion + 1) new_list.append(cloned_item) return cloned_node
def extractFrame(self, frame): obj, slots = self.frames[frame] rt = [] for slot in Collection(self.graph, slots): k = self.extractTerm(first(self.graph.objects(slot, RIF_NS.slotkey))) v = self.extractTerm(first(self.graph.objects(slot, RIF_NS.slotvalue))) rt.append( Uniterm(k, [self.extractTerm(obj), v]) ) return rt
def _addTriple( self, s, p, o): if type(o) in [BNode, URIRef]: self.graph.add((s, p, o)) elif type(o) is list: o_list = BNode() self.graph.add((s, p, o_list)) os = Collection(self.graph, o_list) for item in o: os.append(Literal(item)) elif o != '': self.graph.add((s, p, Literal(o)))
def test_issue604(): EX = Namespace("http://ex.co/") g = Graph() bn = BNode() g.add((EX.s, EX.p, bn)) c = Collection(g, bn, map(Literal, [1, 2, 4])) c[2] = Literal(3) got = list(g.objects(bn, RDF.rest / RDF.rest / RDF.first)) expected = [Literal(3)] assert got == [Literal(3)], got
def values_collection(graph, value_list: list): """ convert value list to rdflib collection :param graph: rdflib graph :param value_list: a list of values :return: graph, collection, list_node(BNode) """ list_node = BNode() coll = Collection(graph, list_node, value_list) return graph, coll, list_node