def _add_attribute(self, class_iri, attribute_iri, default): """Add triples to add a single attribute to a class. Args: class_iri (URIRef): The URI of the class to add attributes to. attribute_iri (URIRef): The IRI of the attribute to add default (Any): The default value. """ bnode = rdflib.BNode() self.graph.add((class_iri, rdflib.RDFS.subClassOf, bnode)) self.graph.add((bnode, rdflib.RDF.type, rdflib.OWL.Restriction)) self.graph.add((bnode, rdflib.OWL.cardinality, rdflib.Literal(1, datatype=rdflib.XSD.integer))) self.graph.add((bnode, rdflib.OWL.onProperty, attribute_iri)) # if bnode1 is None: # bnode1 = rdflib.BNode() # self.graph.add((attribute_iri, rdflib.RDFS.domain, bnode1)) # self.graph.add((bnode1, rdflib.RDF.type, rdflib.OWL.Class)) # bnode2 = self.graph.value(bnode1, rdflib.OWL.unionOf) # if bnode2 is None: # bnode2 = rdflib.BNode() # self.graph.add((bnode1, rdflib.OWL.unionOf, bnode2)) # collection = rdflib.collection.Collection(self.graph, bnode2) # collection.append(class_iri) if default is not None: bnode = rdflib.BNode() self.graph.add((class_iri, rdflib_cuba._default, bnode)) self.graph.add( (bnode, rdflib_cuba._default_attribute, attribute_iri)) self.graph.add( (bnode, rdflib_cuba._default_value, rdflib.Literal(default)))
def filecontent_object_to_node(graph, n_content_facets, file_information): """ Unused: Create a node that will add the file content facet node to the graph :param graph: rdflib graph object for adding nodes to :param n_content_facets: Blank node to contain all of the content facet information :param file_information: Dictionary containing information about file being analysed :return: None """ byte_order_facet = rdflib.BNode() file_hash_facet = rdflib.BNode() graph.add( (n_content_facets, NS_RDF.type, NS_UCO_OBSERVABLE.ContentDataFacet)) graph.add( (n_content_facets, NS_UCO_OBSERVABLE.byteOrder, byte_order_facet)) graph.add(( byte_order_facet, NS_RDF.type, NS_UCO_VOCABULARY.EndiannessTypeVocab, )) graph.add((byte_order_facet, NS_UCO_VOCABULARY.value, rdflib.Literal("Big-endian"))) if 'mimetype' in file_information.keys(): graph.add((n_content_facets, NS_UCO_OBSERVABLE.mimeType, rdflib.Literal(file_information["mimetype"]))) if 'size' in file_information.keys(): graph.add((n_content_facets, NS_UCO_OBSERVABLE.sizeInBytes, rdflib.term.Literal(file_information["size"], datatype=NS_XSD.integer))) graph.add((n_content_facets, NS_UCO_OBSERVABLE.hash, file_hash_facet)) graph.add((file_hash_facet, NS_RDF.type, NS_UCO_TYPES.Hash))
def serialize(self, subject, *objects_or_combinators): """ object_combinators may also be URIRefs or Literals """ ec_s = rdflib.BNode() if self.operator is not None: if subject is not None: yield subject, self.predicate, ec_s yield from oc(ec_s) yield from self._list.serialize(ec_s, self.operator, *objects_or_combinators) else: for thing in objects_or_combinators: if isinstance(thing, Combinator): object = rdflib.BNode() #anything = list(thing(object)) #if anything: #[print(_) for _ in anything] hasType = False for t in thing(object): if t[1] == rdf.type: hasType = True yield t if not hasType: yield object, rdf.type, owl.Class else: object = thing yield subject, self.predicate, object
def add_triples(palm_values=[0,0,0],skin_colors=[0,0,0],fingers=5,gesture="none",action="none"): palm_node=rdflib.BNode() graph.add((palm_node,rdflib.namespace.RDF['type'],gezr_namespace['palm'])) skin_node = rdflib.BNode() graph.add((skin_node, rdflib.namespace.RDF['type'], gezr_namespace['skinColor'])) finger_node = rdflib.BNode() graph.add((finger_node, rdflib.namespace.RDF['type'], gezr_namespace['fingers'])) gesture_node = rdflib.BNode() graph.add((gesture_node, rdflib.namespace.RDF['type'], gezr_namespace['gesture'])) action_node = rdflib.BNode() graph.add((action_node, rdflib.namespace.RDF['type'], gezr_namespace['action'])) graph.add((palm_node, gezr_namespace['x'],rdflib.Literal(palm_values[0]))) graph.add((palm_node, gezr_namespace['y'], rdflib.Literal(palm_values[1]))) graph.add((palm_node, gezr_namespace['r'], rdflib.Literal(palm_values[2]))) graph.add((skin_node, gezr_namespace['r'], rdflib.Literal(skin_colors[0]))) graph.add((skin_node, gezr_namespace['g'], rdflib.Literal(skin_colors[1]))) graph.add((skin_node, gezr_namespace['b'], rdflib.Literal(skin_colors[2]))) graph.add((finger_node, gezr_namespace['amount'], rdflib.Literal(fingers))) graph.add((action_node, gezr_namespace['name'], rdflib.Literal(action))) graph.add((gesture_node, gezr_namespace['name'], rdflib.Literal(gesture))) graph.add((gesture_node, gezr_namespace['attachedPalm'], palm_node)) graph.add((gesture_node, gezr_namespace['attachedSkinColor'], skin_node)) graph.add((gesture_node, gezr_namespace['attachedFingers'], finger_node)) graph.add((gesture_node, gezr_namespace['attachedAction'], action_node))
def serialize(self, s, p, *objects_or_combinators): # FIXME for restrictions we can't pass the restriction in, we have to know the bnode in advance # OR list has to deal with restrictions which is NOT what we want at all... subject = rdflib.BNode() yield s, p, subject stop = len(objects_or_combinators) - 1 for i, object_combinator in enumerate(objects_or_combinators): if isinstance(object_combinator, types.FunctionType) or isinstance( object_combinator, Combinator): #if isinstance(object_combinator, POCombinator): #yield from object_combinator(subject) # in cases where rdf.first already specified #elif isinstance(object_combinator, ObjectCombinator): yield from object_combinator( subject, rdf.first) # combinator call must accept a predicate #else: #raise TypeError('Unknown Combinator type {object_combinator}') else: # assume that it is a URIRef or Literal yield subject, rdf.first, object_combinator if i < stop: # why would you design a list this way >_< next_subject = rdflib.BNode() else: next_subject = rdf.nil yield subject, rdf.rest, next_subject subject = next_subject
def derp(): b0 = rdflib.BNode() yield ilxtr.technique, owl.equivalentClass, b0 yield b0, rdf.type, owl.Class a, b, c = (rdflib.BNode() for _ in range(3)) yield b0, owl.intersectionOf, a b1 = rdflib.BNode() yield a, rdf.first, b1 r1 = restG( blankc(owl.onProperty, ilxtr.hasPrimaryParticipant), blankc(owl.maxQualifiedCardinality, rdflib.Literal(1, datatype=rdflib.XSD.nonNegativeInteger)), blankc(owl.onClass, BFO['0000004']))(b1) yield from r1 b2 = rdflib.BNode() yield b, rdf.first, b2 r2 = restG( blankc(owl.onProperty, ilxtr.hasPrimaryAspect), blankc(owl.maxQualifiedCardinality, rdflib.Literal(1, datatype=rdflib.XSD.nonNegativeInteger)), blankc(owl.onClass, ilxtr.aspect))(b2) yield from r2 b3 = rdflib.BNode() yield c, rdf.first, b3 r3 = restG( blankc(owl.onProperty, ilxtr.hasPrimaryAspect_dAdT), blankc(owl.maxQualifiedCardinality, rdflib.Literal(1, datatype=rdflib.XSD.nonNegativeInteger)), blankc(owl.onClass, ilxtr.changeType))(b3) yield from r3 for _1, _2 in ((a, b), (b, c), (c, rdf.nil)): yield _1, rdf.rest, _2
def _dcat_location(self, graph, selfnode): graph.bind('dcat', 'http://www.w3.org/ns/dcat#') graph.bind('dct', 'http://purl.org/dc/terms/') # template = ('dcat:distribution [ # a dcat:Distribution; # dcat:downloadURL <{}>; # dcat:mediaType [ # a dct:MediaType; # dct:identifier "application/x-netcdf" # ]; # dct:format [ # a dct:MediaType; # dct:identifier <http://vocab.nerc.ac.uk/collection/M01/current/NC/> # ] # ].') dcatnode = rdflib.BNode() dcfnode = rdflib.BNode() graph.add((selfnode, rdflib.URIRef('http://www.w3.org/ns/dcat#distribution'), dcatnode)) graph.add((dcatnode, rdflib.namespace.RDF.type, rdflib.URIRef('http://www.w3.org/ns/dcat#Distribution'))) if self.file_locator is not None: graph.add((dcatnode, rdflib.URIRef('http://www.w3.org/ns/dcat#downloadURL'), rdflib.URIRef(self.file_locator))) dcatmednode = rdflib.BNode() graph.add((dcatmednode, rdflib.namespace.RDF.type, rdflib.URIRef('http://www.w3.org/ns/dcat#MediaType'))) graph.add((dcatmednode, rdflib.URIRef('http://purl.org/dc/terms/identifier'), rdflib.Literal('application/x-netcdf'))) graph.add((dcatnode, rdflib.URIRef('http://www.w3.org/ns/dcat#mediaType'), dcatmednode)) graph.add((dcfnode, rdflib.namespace.RDF.type, rdflib.URIRef('http://purl.org/dc/terms/MediaType'))) graph.add((dcfnode, rdflib.URIRef('http://purl.org/dc/terms/identifier'), rdflib.URIRef('http://vocab.nerc.ac.uk/collection/M01/current/NC/'))) graph.add((selfnode, rdflib.URIRef('http://purl.org/dc/terms/format'), dcfnode))
def controlled_dictionary_object_to_node(graph, controlled_dict, n_exif_facet): """ Add controlled dictionary object to accept all of the Values in the extracted exif :param graph: rdflib graph object for adding nodes to :param controlled_dict: Dictionary containing the EXIF information from image :param n_controlled_dictionary: :return: None """ n_controlled_dictionary = rdflib.BNode() graph.add((n_exif_facet, NS_RDF.type, NS_UCO_OBSERVABLE.EXIFFacet)) graph.add( (n_exif_facet, NS_UCO_OBSERVABLE.exifData, n_controlled_dictionary)) graph.add((n_controlled_dictionary, NS_RDF.type, NS_UCO_TYPES.ControlledDictionary)) for key in sorted(controlled_dict.keys()): # :TODO stringing all values to ensure they are strings, open to input # here as maybe assertion or a better way to do this v_value = str(controlled_dict[key]) v_value = rdflib.Literal(v_value) try: assert isinstance(v_value, rdflib.Literal) except AssertionError: _logger.info("v_value = %r." % v_value) raise n_entry = rdflib.BNode() graph.add((n_controlled_dictionary, NS_UCO_TYPES.entry, n_entry)) graph.add( (n_entry, NS_RDF.type, NS_UCO_TYPES.ControlledDictionaryEntry)) graph.add((n_entry, NS_UCO_TYPES.key, rdflib.Literal(key))) graph.add((n_entry, NS_UCO_TYPES.value, v_value))
def write_wiring_components_graph(graph, behaviour, components, type): for key, component in six.iteritems(components[type]): component_view = rdflib.BNode() graph.add((component_view, rdflib.RDF.type, WIRE_M['ComponentView'])) graph.add((component_view, WIRE['type'], rdflib.Literal(type))) graph.add((component_view, WIRE['id'], rdflib.Literal(str(key)))) if component.get('collapsed', False): graph.add((component_view, WIRE_M['collapsed'], rdflib.Literal('true'))) if 'position' in component: write_position_graph(graph, component_view, component['position']) if 'endpoints' in component: if 'source' in component['endpoints']: for index, source in enumerate(component['endpoints']['source']): source_element = rdflib.BNode() graph.add((source_element, rdflib.RDF.type, WIRE_M['Source'])) graph.add((component_view, WIRE_M['hasSource'], source_element)) graph.add((source_element, RDFS['label'], rdflib.Literal(source))) graph.add((source_element, WIRE['index'], rdflib.Literal(str(index)))) if 'target' in component['endpoints']: for index, target in enumerate(component['endpoints']['target']): target_element = rdflib.BNode() graph.add((target_element, rdflib.RDF.type, WIRE_M['Target'])) graph.add((component_view, WIRE_M['hasTarget'], target_element)) graph.add((target_element, RDFS['label'], rdflib.Literal(target))) graph.add((target_element, WIRE['index'], rdflib.Literal(str(index)))) graph.add((behaviour, WIRE_M['hasComponentView'], component_view))
def all_classes(input, output, words={}): g = rdflib.Graph() TM = rdflib.Namespace("http://trandminer.org/ontology#") [g.load(file(inp, "r"), format=_find_format(inp)) for inp in input] expanded_results = g.query(ALL_CLASSES) expanded_graph = rdflib.ConjunctiveGraph() expanded_graph.bind("tm", TM) word_index = 0 if len(words.values()) != 0: word_index = max(words.values()) + 1 for binding in expanded_results.bindings: if not "class" in binding or not "user" in binding: continue if not binding['class'] in words: words[binding['class']] = word_index word_index += 1 discussion = rdflib.BNode() expanded_graph.add((discussion, TM['word'], binding['class'])) expanded_graph.add((discussion, TM['byuser'], binding['user'])) expanded_graph.add((discussion, TM['date'], binding['date'])) expanded_graph.add((discussion, TM['count'], binding['aggregated'])) article_count = rdflib.BNode() expanded_graph.add((article_count, TM['byuser'], binding['user'])) expanded_graph.add((article_count, TM['date'], binding['date'])) expanded_graph.add( (article_count, TM['article_count'], binding['article_count'])) return expanded_graph
def __init__(self, code_id): m = re.match(r"C(?P<code>\d{5})-(?P<ymd>\d{8})$", code_id) assert m, "code %s format error" % code_id self.code = m.group("code") self.csum = code_checksum(self.code) self.ymd = datetime.datetime.strptime(m.group("ymd"), "%Y%m%d").date() # e-Stat LOD ベースで採番する self.sac = JITI[code_id] g.add((self.sac, RDF["type"], JITIS["StandardAreaCode"])) g.add((self.sac, SKOS["closeMatch"], SAC[code_id])) g.add((self.sac, DCTERMS["identifier"], rdflib.Literal(self.code))) g.add((self.sac, DCTERMS["issued"], rdflib.Literal(self.ymd.strftime("%Y-%m-%d"), datatype=XSD.date))) # 6桁コードでリンクできるようにする g.add((self.sac, JITIS["code"], rdflib.Literal(self.code + self.csum))) # 共通語彙基盤 住所IEP : 現状は blank node での出力を強制する pref = rdflib.BNode() g.add((pref, RDF.type, IC["コード型"])) g.add( (pref, IC["識別値"], rdflib.Literal(self.code[:2], datatype=XSD.string))) g.add((self.sac, IC["都道府県コード"], pref)) ward = rdflib.BNode() g.add((ward, RDF.type, IC["コード型"])) g.add((ward, IC["識別値"], rdflib.Literal(self.code[2:] + self.csum, datatype=XSD.string))) g.add((self.sac, IC["市区町村コード"], ward))
def write_ttl_news(entries, out_file, template=None, subject_uri=None): """Write NEWS in Turtle format""" import rdflib import rdflib.namespace import rdflib.resource import datetime # Set up namespaces and make a graph for the output doap = rdflib.Namespace("http://usefulinc.com/ns/doap#") dcs = rdflib.Namespace("http://ontologi.es/doap-changeset#") rdfs = rdflib.Namespace("http://www.w3.org/2000/01/rdf-schema#") rdf = rdflib.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") xsd = rdflib.Namespace("http://www.w3.org/2001/XMLSchema#") g = rdflib.ConjunctiveGraph() ns = rdflib.namespace.NamespaceManager(g) ns.bind("doap", doap) ns.bind("dcs", dcs) # Load given template file if template is not None: g.load(template, format="turtle") if subject_uri is not None: # Use given subject uri subject = rdflib.URIRef(subject_uri) g.add((subject, rdf.type, doap.Project)) else: # Find project URI to use as subject, and optionally the maintainer subject = g.value(None, rdf.type, doap.Project) ensure(subject is not None, "Unable to find project URI for subject") maintainer = g.value(subject, doap.maintainer, None) for r, e in list(entries.items()): semver = parse_version(e["revision"]) ver_string = "%03d%03d%03d" % semver release = rdflib.BNode("r%s" % ver_string) g.add((subject, doap.release, release)) g.add((release, doap.revision, rdflib.Literal(e["revision"]))) if "dist" in e: g.add((release, doap["file-release"], rdflib.URIRef(e["dist"]))) utc_date = e["date"].astimezone(datetime.timezone.utc) date_str = utc_date.strftime("%Y-%m-%dT%H:%M:%S") + "Z" time = rdflib.Literal(date_str, datatype=xsd.dateTime, normalize=False) g.add((release, doap.created, time)) if maintainer is not None: g.add((release, dcs.blame, maintainer)) changeset = rdflib.BNode("c%s" % ver_string) g.add((release, dcs.changeset, changeset)) for index, item in enumerate(e["items"]): item_node = rdflib.BNode("i%s%08d" % (ver_string, index)) g.add((changeset, dcs.item, item_node)) g.add((item_node, rdfs.label, rdflib.Literal(item))) g.serialize(out_file, format="turtle")
def dbpedia(self, g, s): if s == None: return rdflib.BNode() if isinstance(s, L): n = rdflib.BNode() g.add((n, DCT['title'], rdflib.Literal(s))) else: n = rdflib.URIRef(DBP[s]) return n
def get_id(cls, src): if not isinstance(src, dict): return rdflib.BNode() if 'uri' in src: return src['uri'] elif 'id' in src: return src['id'] else: return rdflib.BNode()
def asNeurdf(self, identifier_function=lambda self: rdflib.BNode()): s = identifier_function(self) yield s, rdf.type, self.neurdf_type for phenotype in self: if isinstance(phenotype, PhenotypeCollection): linker = rdflib.BNode() yield s, ilxtr.subCell, linker yield from phenotype.asNeurdf(lambda self: linker) else: yield from phenotype.asNeurdf(s)
def parse_item_to_graph(self, item, g, n): # Adding to graph id = hashlib.md5(str(item).encode('utf-8')).hexdigest() # Parsing of direct subroot elements title = item.get('title', None) publish_date = parser.parse(item.get('published', None)) link = item.get('link', None) # Parsing from content_encode part content = item.get('content', item.get('conetent_encoded'))[0] affected_lines = self.__get_element_nonroot_xml( content.value, 'lines').split(',') categories = self.__get_element_nonroot_xml( content.value, 'type').replace(' ', ' ').split(',') from_date, to_date = self.__parse_duration( self.__get_element_nonroot_xml(content.value, 'duration'), publish_date) # Parsing full text description full_text_description = item.get('description', None) affects_on_lines = self.__parse_affects(full_text_description, affected_lines) record = n[id] g.add((record, RDF.type, n.TrafficChange)) g.add((record, n.title, Literal(title, datatype=XSD.string))) g.add((record, n.published, Literal(publish_date, datatype=XSD.datetime))) g.add((record, n.link, URIRef(link))) # g.add((record, n.fullTextDescHTML, Literal(item.get('description', None)))) # g.add((record, n.fullTextDesc, Literal(BeautifulSoup(item.get affects = rdflib.BNode() g.add((affects, RDF.type, RDF.Bag)) g.add((record, n.affect, affects)) for line in affected_lines: affect = rdflib.BNode() g.add((affects, RDF.li, affect)) g.add((affect, n.line, Literal(line, datatype=XSD.string))) if line in affects_on_lines: g.add((affect, n.reason, Literal(affects_on_lines[line], datatype=XSD.string))) categs = rdflib.BNode() g.add((categs, RDF.type, RDF.Bag)) g.add((record, n.catgory, categs)) for category in categories: g.add((categs, RDF.li, Literal(category, datatype=XSD.string))) duration = rdflib.BNode() g.add((record, n.duration, duration)) g.add((duration, n.from_date, Literal(from_date, datatype=XSD.datetime))) if to_date is not None: g.add((duration, n.to_date, Literal(to_date, datatype=XSD.datetime)))
def __call__(self, *args, **kwargs): # FIXME might get two subjects by accident... if (isinstance(self.outer_self, Combinator) and args and not isinstance(args[0], str) or self.args and self.args[0] is None): args = (rdflib.BNode(),) + args if self.args[0] is None: self.args = self.args[1:] elif not args and not self.args: args = rdflib.BNode(), yield from self.outer_self.__call__(*args, *self.args, **kwargs, **self.kwargs)
def make_assertion(base, index): assertion = list() assertion_node = rdflib.BNode() result_node = rdflib.BNode() assertion.append((assertion_node, RDF.type, EARL.Assertion)) assertion.append((assertion_node, EARL.assertedBy, DEVELOPER_URI)) assertion.append((assertion_node, EARL.subject, PYSHACL_URI)) assertion.append((assertion_node, EARL.result, result_node)) assertion.append((result_node, RDF.type, EARL.TestResult)) assertion.append((result_node, EARL.mode, EARL.automatic)) tests = tests_found_in_manifests[base] t = tests[index] test_uri_string = str(t.node) if platform.system() == "Windows": if test_uri_string.startswith("file:///"): test_uri_string = test_uri_string[8:] else: if test_uri_string.startswith("file://"): test_uri_string = test_uri_string[7:] test_uri_string = test_uri_string.replace(sht_files_dir, TEST_PREFIX) test_uri = rdflib.URIRef(test_uri_string) assertion.append((assertion_node, EARL.test, test_uri)) label = t.label data_file = t.data_graph shacl_file = t.shapes_graph sht_validate = (t.sht_graph, t.sht_result) if label and len(label) > 0: print("testing: {}".format(label)) try: val, _, v_text = pyshacl.validate(data_file, shacl_graph=shacl_file, inference='rdfs', check_sht_result=True, sht_validate=sht_validate, debug=True, meta_shacl=False) except (NotImplementedError, ReportableRuntimeError) as e: print(e) info_text = rdflib.Literal(str(e.args[0]), lang="en") assertion.append((result_node, EARL.info, info_text)) val = False v_text = info_text print(v_text) if v_text.startswith("Validation Failure"): info_text = rdflib.Literal(v_text, lang="en") assertion.append((result_node, EARL.info, info_text)) if val is True: assertion.append((result_node, EARL.outcome, PASSED)) else: print("FAILED {}".format(test_uri)) assertion.append((result_node, EARL.outcome, FAILED)) return assertion
def add_location(self, location): """Add location of the data Parameters ---------- location : str URL of distant endpoint """ self.graph.add((rdflib.BNode("graph"), rdflib.RDF.type, self.prov["Entity"])) self.graph.add((rdflib.BNode("graph"), self.prov.atLocation, rdflib.Literal(location))) self.graph.add((rdflib.BNode("graph"), self.prov.generatedAtTime, rdflib.Literal(datetime.now()))) self.graph.add((rdflib.BNode("graph"), self.prov.wasGeneratedBy, rdflib.URIRef("https://github.com/askomics/abstractor")))
def write_mashup_wiring_graph(graph, wiring, template_info): wiring_version = template_info['wiring'].get('version', '1.0') if wiring_version != '2.0': raise ValueError('This writer cannot serialize wiring status version %s' % wiring_version) graph.add((wiring, USDL['versionInfo'], rdflib.Literal('2.0'))) # Serialize operators for id_, operator in six.iteritems(template_info['wiring']['operators']): op = rdflib.BNode() graph.add((op, rdflib.RDF.type, WIRE_M['iOperator'])) graph.add((wiring, WIRE_M['hasiOperator'], op)) graph.add((op, DCTERMS['title'], rdflib.Literal(operator['name']))) graph.add((op, WIRE_M['iOperatorId'], rdflib.Literal(str(id_)))) for pref_name, pref in six.iteritems(operator['preferences']): element = rdflib.BNode() graph.add((element, rdflib.RDF.type, WIRE_M['iOperatorPreference'])) graph.add((op, WIRE_M['hasiOperatorPreference'], element)) graph.add((element, DCTERMS['title'], rdflib.Literal(pref_name))) if pref.get('value', None) is not None: graph.add((element, WIRE['value'], rdflib.Literal(pref['value']))) if pref.get('readonly', False): graph.add((element, WIRE_M['readonly'], rdflib.Literal('true'))) if pref.get('hidden', False): graph.add((element, WIRE_M['hidden'], rdflib.Literal('true'))) # Serialize connections for connection in template_info['wiring']['connections']: element = rdflib.BNode() graph.add((element, rdflib.RDF.type, WIRE_M['Connection'])) graph.add((wiring, WIRE_M['hasConnection'], element)) if connection.get('readonly', False): graph.add((element, WIRE_M['readonly'], rdflib.Literal('true'))) source = rdflib.BNode() graph.add((source, rdflib.RDF.type, WIRE_M['Source'])) graph.add((element, WIRE_M['hasSource'], source)) graph.add((source, WIRE['type'], rdflib.Literal(connection['source']['type']))) graph.add((source, WIRE_M['sourceId'], rdflib.Literal(str(connection['source']['id'])))) graph.add((source, WIRE_M['endpoint'], rdflib.Literal(connection['source']['endpoint']))) target = rdflib.BNode() graph.add((target, rdflib.RDF.type, WIRE_M['Target'])) graph.add((element, WIRE_M['hasTarget'], target)) graph.add((target, WIRE['type'], rdflib.Literal(connection['target']['type']))) graph.add((target, WIRE_M['targetId'], rdflib.Literal(str(connection['target']['id'])))) graph.add((target, WIRE_M['endpoint'], rdflib.Literal(connection['target']['endpoint']))) write_wiring_visualdescription_graph(graph, wiring, template_info)
def clone_list(graph, lnode, target_graph, keepid=False, recursion=0): if keepid: cloned_node = rdflib.BNode(str(lnode)) else: cloned_node = rdflib.BNode() new_list = Collection(target_graph, cloned_node) for item in iter(graph.items(lnode)): cloned_item = clone_node(graph, item, target_graph, recursion=recursion + 1) new_list.append(cloned_item) return cloned_node
def disjointUnionOf(graph, members): start = rdflib.BNode() current = start for member in members[:-1]: graph.add((current, rdflib.RDF.first, member)) next_ = rdflib.BNode() graph.add((current, rdflib.RDF.rest, next_)) current = next_ graph.add((current, rdflib.RDF.first, members[-1])) graph.add((current, rdflib.RDF.rest, rdflib.RDF.nil)) return start
def expandBNodeTriples(terms): """ expand [ ?p ?o ] syntax for implicit bnodes """ # import pdb; pdb.set_trace() try: if DEBUG: print "Bnode terms", terms print "1", terms[0] print "2", [rdflib.BNode()] + terms.asList()[0] return [expandTriples([rdflib.BNode()] + terms.asList()[0])] except Exception, e: if DEBUG: print ">>>>>>>>", e raise
def testBlankGraphIdentifier(self): g = rdflib.ConjunctiveGraph() g.add(TRIPLE + (rdflib.BNode(), )) out = g.serialize(format="trig", encoding='latin-1') graph_label_line = out.splitlines()[-4] self.assertTrue(re.match(br"^_:[a-zA-Z0-9]+ \{", graph_label_line))
def expandCollection(terms): """ expand ( 1 2 3 ) notation for collections """ if DEBUG: print "Collection: ", terms res = [] other = [] for x in terms: if isinstance(x, list): # is this a [ .. ] ? other += x x = x[0] b = rdflib.BNode() if res: res += [res[-3], rdflib.RDF.rest, b, b, rdflib.RDF.first, x] else: res += [b, rdflib.RDF.first, x] res += [b, rdflib.RDF.rest, rdflib.RDF.nil] res += other if DEBUG: print "CollectionOut", res return [res]
class AnnotationCombinator(Combinator): a_s = rdflib.BNode() outer_self = self existing = predicate_objects def __init__(self, triple): self.triple = triple @property def stored(self): for p, o in ((rdf.type, owl.Axiom), ) + self.existing: yield p, o def __call__(self, *predicate_objects): gen = self.stored # now runs as many times as we want a_p, a_o = next(gen) yield from self.outer_self.serialize(self.triple, a_p, a_o, a_s=self.a_s, first=True) for a_p, a_o in gen: yield from self.outer_self.serialize(self.triple, a_p, a_o, a_s=self.a_s) for a_p, a_o in predicate_objects: yield from self.outer_self.serialize(self.triple, a_p, a_o, a_s=self.a_s)
def add_sound(graph, path=None, title=None, author=None, composer=None, genre=None, rating=None, date=None, rigth=None, instrument=[], description=[], subject=[]): k = rdf.Namespace(u"urn:/streaming/") bnode_sound = rdf.BNode() graph = RDFHelper.add_sound_path(graph, bnode_sound, path=path) graph = RDFHelper.add_sound_title(graph, bnode_sound, title=title) graph = RDFHelper.add_sound_author(graph, bnode_sound, author=author) graph = RDFHelper.add_sound_composer(graph, bnode_sound, composer=composer) graph = RDFHelper.add_sound_genre(graph, bnode_sound, genre=genre) graph = RDFHelper.add_sound_rating(graph, bnode_sound, rating=rating) graph = RDFHelper.add_sound_date(graph, bnode_sound, date=date) graph = RDFHelper.add_sound_right(graph, bnode_sound, rigth=rigth) graph = RDFHelper.add_sound_instrument(graph, bnode_sound, instrument=instrument) graph = RDFHelper.add_sound_subject(graph, bnode_sound, subject=subject) graph = RDFHelper.add_sound_comment(graph, bnode_sound, description=description) graph.bind("strm", k)
def nx_to_n3(network, positive_nodes, n): logging.info('Building graph') p = set(positive_nodes) pun = p.union(n) ns1 = rdflib.Namespace('http://kt.ijs.si/hedwig#') ontology = rdflib.Graph() annotations = rdflib.Graph() for term in network.node: if term in pun: annotations.add((term, rdflib.RDF.type, ns1.Example)) for end in network.edge[term]: blank = rdflib.BNode() annotations.add((term, ns1.annotated_with, blank)) annotations.add((blank, ns1.annotation, end)) if term in p: annotations.add((term, ns1.class_label, rdflib.Literal('+'))) elif term in n: annotations.add((term, ns1.class_label, rdflib.Literal('-'))) else: raise Exception('Unexpected data set error.') else: for end in network.edge[term]: if end not in pun: ontology.add((term, network.edge[term][end]['type'], end)) return ontology, annotations
def value(self): """The adapted value for this field Desired output: <prov:wasDerivedFrom> <prv:DataItem> <dcterms:title>Title of dataset</dcterms:title> <foaf:isPrimaryTopicOf rdf:resource="http://organisation/urltodataset"/> <prov:wasAttributedTo rdf:respurce="uri of owner"/> </prv:DataItem> </prov:wasDerivedFrom> """ DataItem = self.session.get_class(surf.ns.PRV.DataItem) output = [] for _i, prov in enumerate(self.field.getAccessor(self.context)()): # prov is {'owner': u'http://www.eea.europa.eu', # 'link': u'http://www.eea.europa.eu/...', # 'title': u'Corine Land Cover 2000 - 2006 changes'} d = DataItem(rdflib.BNode()) d.dcterms_title = prov['title'] d.foaf_isPrimaryTopicOf = rdflib.URIRef(prov['link']) d.prov_wasAttributedTo = rdflib.URIRef(prov['owner']) d.update() output.append(d) return output
def _annotation(ap, ao, s, p, o): n0 = rdflib.BNode() yield n0, rdf.type, owl.Axiom yield n0, owl.annotatedSource, s yield n0, owl.annotatedProperty, p yield n0, owl.annotatedTarget, check_value(o) yield n0, ap, check_value(ao)