<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://info216.wiki.uib.no/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Bamos3003</id>
	<title>info216 - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://info216.wiki.uib.no/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Bamos3003"/>
	<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/Special:Contributions/Bamos3003"/>
	<updated>2026-04-20T08:19:50Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.44.2</generator>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2730</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2730"/>
		<updated>2026-02-09T10:40:30Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 2)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries]] (week 3 &#039;&#039;&#039;&#039;&#039;and 4&#039;&#039;&#039;&#039;&#039;)&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 5)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]] (week 6)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]] (week 7)&lt;br /&gt;
# [[Lab: JSON-LD]] (week 8)&lt;br /&gt;
# [[Lab: Ontop | Lab: Virtualisation with Ontop]] (week 9)&lt;br /&gt;
# [[Lab: Wikidata in RDF]] (week 10)&lt;br /&gt;
# [[Lab: OWL 1]] (week 11)&lt;br /&gt;
# [[Lab: OWL 2]] (week 12)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 13 and 14&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 15)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 15)&lt;br /&gt;
# Lab: Exam training (week 16)&lt;br /&gt;
&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL 2 | Lab: SPARQL updates]] (week 7, from 12/2)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2025, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2724</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2724"/>
		<updated>2026-01-14T16:39:30Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 2)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries]] (week 3 &#039;&#039;&#039;&#039;&#039;and 4&#039;&#039;&#039;&#039;&#039;)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 5)&lt;br /&gt;
# [[Lab: Ontop | Lab: Virtualisation with Ontop]] (week 6)&lt;br /&gt;
# [[Lab: JSON-LD]] (week 7)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]] (week 8)&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]] (week 9)&lt;br /&gt;
# [[Lab: Wikidata in RDF]] (week 10)&lt;br /&gt;
# [[Lab: OWL 1]] (week 11)&lt;br /&gt;
# [[Lab: OWL 2]] (week 12)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 13 and 14&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 15)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 15)&lt;br /&gt;
# Lab: Exam training (week 16)&lt;br /&gt;
&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL 2 | Lab: SPARQL updates]] (week 7, from 12/2)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2025, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2723</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2723"/>
		<updated>2026-01-14T16:35:22Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Here we will present suggested solutions after each lab. &#039;&#039;The page will be updated as the course progresses&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Getting started (Lab 1)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# The Mueller Investigation was lead by Robert Mueller&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))&lt;br /&gt;
&lt;br /&gt;
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))&lt;br /&gt;
&lt;br /&gt;
# Paul Manafort was business partner of Rick Gates&lt;br /&gt;
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))&lt;br /&gt;
&lt;br /&gt;
# He was campaign chairman for Donald Trump&lt;br /&gt;
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy and lying to FBI.&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;)) # To screen&lt;br /&gt;
#g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) # To file&lt;br /&gt;
&lt;br /&gt;
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate&lt;br /&gt;
for subject, object in g[ : ex.pleadGuiltyTo :]:&lt;br /&gt;
    print(subject, ex.pleadGuiltyTo, object)&lt;br /&gt;
&lt;br /&gt;
# --- IF you have more time tasks ---&lt;br /&gt;
&lt;br /&gt;
# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that submits your model for rendering and saves the returned image to file.&lt;br /&gt;
import requests&lt;br /&gt;
import shutil&lt;br /&gt;
&lt;br /&gt;
def graphToImage(graphInput):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graphInput, &amp;quot;from&amp;quot;:&amp;quot;ttl&amp;quot;, &amp;quot;to&amp;quot;:&amp;quot;png&amp;quot;}&lt;br /&gt;
    link = &amp;quot;http://www.ldf.fi/service/rdf-grapher&amp;quot;&lt;br /&gt;
    response = requests.get(link, params = data, stream=True)&lt;br /&gt;
    # print(response.content)&lt;br /&gt;
    print(response.raw)&lt;br /&gt;
    with open(&amp;quot;lab1.png&amp;quot;, &amp;quot;wb&amp;quot;) as file:&lt;br /&gt;
        shutil.copyfileobj(response.raw, file)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=RDF programming with RDFlib (Lab 2)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Getting the graph created in the first lab&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
# Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to Congress.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
# Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to the FBI.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Change your graph so it represents instances of lying as blank nodes.&lt;br /&gt;
# Remove the triples that will be duplicated&lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI)) &lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.remove((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
FlynnLying = BNode() &lt;br /&gt;
g.add((FlynnLying, ex.crime, ex.LyingToFBI))&lt;br /&gt;
g.add((FlynnLying, ex.pleadGulityOn, Literal(&amp;quot;2017-12-1&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((FlynnLying, ex.liedAbout, Literal(&amp;quot;His communications with a former Russian ambassador during the presidential transition&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((FlynnLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, FlynnLying))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
GatesLying = BNode()&lt;br /&gt;
Crimes = BNode()&lt;br /&gt;
Charged = BNode()&lt;br /&gt;
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])&lt;br /&gt;
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])&lt;br /&gt;
g.add((GatesLying, ex.crime, Crimes))&lt;br /&gt;
g.add((GatesLying, ex.chargedWith, Charged))&lt;br /&gt;
g.add((GatesLying, ex.pleadGulityOn, Literal(&amp;quot;2018-02-23&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((GatesLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, GatesLying))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
CohenLying = BNode()&lt;br /&gt;
g.add((CohenLying, ex.crime, ex.LyingToCongress))&lt;br /&gt;
g.add((CohenLying, ex.liedAbout, ex.TrumpRealEstateDeal))&lt;br /&gt;
g.add((CohenLying, ex.prosecutorsAlleged, Literal(&amp;quot;In an August 2017 letter Cohen sent to congressional committees investigating Russian election interference, he falsely stated that the project ended in January 2016&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.mullerInvestigationAlleged, Literal(&amp;quot;Cohen falsely stated that he had never agreed to travel to Russia for the real estate deal and that he did not recall any contact with the Russian government about the project&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.pleadGulityOn, Literal(&amp;quot;2018-11-29&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((CohenLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, CohenLying))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
#Save (serialize) your graph to a Turtle file.&lt;br /&gt;
# g.serialize(&amp;quot;lab2.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
#Add a few triples to the Turtle file with more information about Donald Trump.&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:postalCode 33480 ;&lt;br /&gt;
            ex:residence ex:Mar_a_Lago ;&lt;br /&gt;
            ex:state ex:Florida ;&lt;br /&gt;
            ex:streetName &amp;quot;1100 S Ocean Blvd&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:previousAddress [ ex:city ex:Washington_DC ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:phoneNumber &amp;quot;1 202 456 1414&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:postalCode &amp;quot;20500&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:residence ex:The_White_House ;&lt;br /&gt;
            ex:streetName &amp;quot;1600 Pennsylvania Ave.&amp;quot;^^xsd:string ];&lt;br /&gt;
    ex:marriedTo ex:Melania_Trump;&lt;br /&gt;
    ex:fatherTo (ex:Ivanka_Trump ex:Donald_Trump_Jr ex: ex:Tiffany_Trump ex:Eric_Trump ex:Barron_Trump).&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
#Read (parse) the Turtle file back into a Python program, and check that the new triples are there&lt;br /&gt;
def serialize_Graph():&lt;br /&gt;
    newGraph = Graph()&lt;br /&gt;
    newGraph.parse(&amp;quot;lab2.ttl&amp;quot;)&lt;br /&gt;
    print(newGraph.serialize())&lt;br /&gt;
&lt;br /&gt;
#Don&#039;t need this to run until after adding the triples above to the ttl file&lt;br /&gt;
# serialize_Graph() &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that starts with Donald Trump prints out a graph depth-first to show how the other graph nodes are connected to him&lt;br /&gt;
visited_nodes = set()&lt;br /&gt;
&lt;br /&gt;
def create_Tree(model, nodes):&lt;br /&gt;
    #Traverse the model breadth-first to create the tree.&lt;br /&gt;
    global visited_nodes&lt;br /&gt;
    tree = Graph()&lt;br /&gt;
    children = set()&lt;br /&gt;
    visited_nodes |= set(nodes)&lt;br /&gt;
    for s, p, o in model:&lt;br /&gt;
        if s in nodes and o not in visited_nodes:&lt;br /&gt;
            tree.add((s, p, o))&lt;br /&gt;
            visited_nodes.add(o)&lt;br /&gt;
            children.add(o)&lt;br /&gt;
        if o in nodes and s not in visited_nodes:&lt;br /&gt;
            invp = URIRef(f&#039;{p}_inv&#039;) #_inv represents inverse of&lt;br /&gt;
            tree.add((o, invp, s))&lt;br /&gt;
            visited_nodes.add(s)&lt;br /&gt;
            children.add(s)&lt;br /&gt;
    if len(children) &amp;gt; 0:&lt;br /&gt;
        children_tree = create_Tree(model, children)&lt;br /&gt;
        for triple in children_tree:&lt;br /&gt;
            tree.add(triple)&lt;br /&gt;
    return tree&lt;br /&gt;
&lt;br /&gt;
def print_Tree(tree, root, indent=0):&lt;br /&gt;
    #Print the tree depth-first.&lt;br /&gt;
    print(str(root))&lt;br /&gt;
    for s, p, o in tree:&lt;br /&gt;
        if s==root:&lt;br /&gt;
            print(&#039;    &#039;*indent + &#039;  &#039; + str(p), end=&#039; &#039;)&lt;br /&gt;
            print_Tree(tree, o, indent+1)&lt;br /&gt;
    &lt;br /&gt;
tree = create_Tree(g, [ex.Donald_Trump])&lt;br /&gt;
print_Tree(tree, ex.Donald_Trump)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL (Lab 3-4)=&lt;br /&gt;
===List all triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the first 100 triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT (COUNT(*) as ?count)&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of indictments===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT (COUNT(?ind) as ?amount)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:outcome ?ind;&lt;br /&gt;
      ns1:outcome ns1:indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who pleaded guilty, along with the name of the investigation===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?invname&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:investigation ?invname;&lt;br /&gt;
      ns1:outcome ns1:guilty-plea .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who were convicted, but who had their conviction overturned by which president===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?president&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:president ?president;&lt;br /&gt;
      ns1:outcome ns1:conviction;&lt;br /&gt;
      ns1:overturned ns1:true.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
ORDER BY DESC(?count)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each president, list the numbers of convictions and of pardons made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as&lt;br /&gt;
?pardons)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:president ?president;&lt;br /&gt;
      ns1:outcome ?outcome ;&lt;br /&gt;
      ns1:outcome ns1:conviction.&lt;br /&gt;
      OPTIONAL{&lt;br /&gt;
         ?s ns1:pardoned ?pardon .&lt;br /&gt;
         FILTER (?pardon = ns1:true)&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?president&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Rename mullerkg:name to something like muellerkg:person===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE{?s ns1:name ?o}&lt;br /&gt;
INSERT{?s ns1:person ?o}&lt;br /&gt;
WHERE {?s ns1:name ?o}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Persons&lt;br /&gt;
INSERT {?person foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:person ?person .&lt;br /&gt;
      BIND(REPLACE(STR(?person), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Presidents&lt;br /&gt;
INSERT {?president foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:president ?president .&lt;br /&gt;
      BIND(REPLACE(STR(?president), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use INSERT DATA updates to add these triples===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
     ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:pleadGuiltyTo ns1:LyingToFBI;&lt;br /&gt;
         ns1:sentencedTo ns1:Prison.&lt;br /&gt;
&lt;br /&gt;
     ns1:Roger_Stone a ns1:Republican;&lt;br /&gt;
         ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:officialTo ns1:Trump_Campaign;&lt;br /&gt;
         ns1:interactedWith ns1:Wikileaks;&lt;br /&gt;
         ns1:providedTestimony ns1:House_Intelligence_Committee;&lt;br /&gt;
         ns1:clearedOf ns1:AllCharges.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test if added&lt;br /&gt;
SELECT ?p ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                      ns1:WitnessTampering,&lt;br /&gt;
                                      ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#The task specifically requested DELETE DATA &amp;amp; INSERT DATA, put below is&lt;br /&gt;
a more efficient solution&lt;br /&gt;
&lt;br /&gt;
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
INSERT{&lt;br /&gt;
   ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                   ns1:WitnessTampering,&lt;br /&gt;
                                   ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a DESCRIBE query to show the updated information about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o.&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone.&lt;br /&gt;
}&lt;br /&gt;
WHERE {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o .&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a DELETE/INSERT statement to change one of the prefixes in your graph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX dbp: &amp;lt;https://dbpedia.org/page/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:person ?o1}&lt;br /&gt;
INSERT {?s ns1:person ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:person ?o1 .&lt;br /&gt;
   BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#This update changes the object in triples with ns1:person as the&lt;br /&gt;
predicate. It changes it&#039;s prefix of ns1 (which is the&lt;br /&gt;
&amp;quot;shortcut/shorthand&amp;quot; for example.org) to the prefix dbp (dbpedia.org)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write an INSERT statement to add at least one significant date to the Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT statement to change the date to a string, and a new DELETE/INSERT statement to change it back to xsd:date. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
#Whilst this solution is not exactly what the task asks for, I feel like&lt;br /&gt;
this is more appropiate given the dataset. The following update&lt;br /&gt;
changes the objects that uses the cp_date as predicate from a URI, to a&lt;br /&gt;
literal with date as it&#039;s datatype&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o3}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (replace(str(?o), str(ns1:), &amp;quot;&amp;quot;)  AS ?o2)&lt;br /&gt;
   BIND (STRDT(STR(?o2), xsd:date) AS ?o3)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test:&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o.&lt;br /&gt;
   FILTER(datatype(?o) = xsd:date)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To change it to an integer, use the following code, and to change it&lt;br /&gt;
back to date, swap &amp;quot;xsd:integer&amp;quot; to &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (STRDT(STR(?o), xsd:integer) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL Programming (Lab 5)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, RDF, FOAF&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;Russia_investigation_kg.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# ----- RDFLIB -----&lt;br /&gt;
ex = Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
&lt;br /&gt;
NS = {&lt;br /&gt;
    &#039;&#039;: ex,&lt;br /&gt;
    &#039;rdf&#039;: RDF,&lt;br /&gt;
    &#039;foaf&#039;: FOAF,&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
# Print out a list of all the predicates used in your graph.&lt;br /&gt;
task1 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT DISTINCT ?p WHERE{&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(list(task1))&lt;br /&gt;
&lt;br /&gt;
# Print out a sorted list of all the presidents represented in your graph.&lt;br /&gt;
task2 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT DISTINCT ?president WHERE{&lt;br /&gt;
    ?s :president ?president .&lt;br /&gt;
}&lt;br /&gt;
ORDER BY ?president&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(list(task2))&lt;br /&gt;
&lt;br /&gt;
# Create dictionary (Python dict) with all the represented presidents as keys. For each key, the value is a list of names of people indicted under that president.&lt;br /&gt;
task3_dic = {}&lt;br /&gt;
&lt;br /&gt;
task3 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT ?president ?person WHERE{&lt;br /&gt;
    ?s :president ?president;&lt;br /&gt;
       :name ?person;&lt;br /&gt;
       :outcome :indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
for president, person in task3:&lt;br /&gt;
    if president not in task3_dic:&lt;br /&gt;
        task3_dic[president] = [person]&lt;br /&gt;
    else:&lt;br /&gt;
        task3_dic[president].append(person)&lt;br /&gt;
&lt;br /&gt;
print(task3_dic)&lt;br /&gt;
&lt;br /&gt;
# Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.&lt;br /&gt;
&lt;br /&gt;
# This task is a lot trickier than it needs to be. As far as I&#039;m aware RDFLib has no HAVING support, so a query like this:&lt;br /&gt;
task4 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
ASK {&lt;br /&gt;
  	SELECT (COUNT(?s) as ?count) WHERE{&lt;br /&gt;
    	?s :pardoned :true;&lt;br /&gt;
   	   :president :Bill_Clinton  .&lt;br /&gt;
    }&lt;br /&gt;
    HAVING (?count &amp;gt; 5)&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(task4.askAnswer)&lt;br /&gt;
&lt;br /&gt;
# Which works fine in Blazegraph and is a valid SPARQL query will always provide false in RDFLib cause it uses HAVING. &lt;br /&gt;
# Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons,&lt;br /&gt;
# so I have instead chosen Bill Clinton with 13 to check if the query works. &lt;br /&gt;
&lt;br /&gt;
task4 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    ASK{&lt;br /&gt;
        SELECT ?count WHERE{{&lt;br /&gt;
  	        SELECT (COUNT(?s) as ?count) WHERE{&lt;br /&gt;
    	        ?s :pardoned :true;&lt;br /&gt;
                   :president :Bill_Clinton  .&lt;br /&gt;
                }}&lt;br /&gt;
        FILTER (?count &amp;gt; 5) &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(task4.askAnswer)&lt;br /&gt;
&lt;br /&gt;
# Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.&lt;br /&gt;
&lt;br /&gt;
# By all accounts, it seems DESCRIBE querires are yet to be implemented in RDFLib, but they are attempting to implement it:&lt;br /&gt;
# https://github.com/RDFLib/rdflib/pull/2221 &amp;lt;--- Issue and proposed solution rasied&lt;br /&gt;
# https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 &amp;lt;--- Solution commited to RDFLib&lt;br /&gt;
# This solution does not work. However, this proposed solution should work if DESCRIBE is implemented in RDFLib&lt;br /&gt;
&lt;br /&gt;
# task5 = g.query(&amp;quot;&amp;quot;&amp;quot; &lt;br /&gt;
# DESCRIBE :Donald_Trump&lt;br /&gt;
# &amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
# print(task5.serialize())&lt;br /&gt;
&lt;br /&gt;
# ----- SPARQLWrapper -----&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039; #Might need to replace this&lt;br /&gt;
REPOSITORY = &#039;Labs&#039; #Replace with your repository name&lt;br /&gt;
&lt;br /&gt;
# Query Endpoint&lt;br /&gt;
sparql = SPARQLWrapper(f&#039;{SERVER}/repositories/{REPOSITORY}&#039;) &lt;br /&gt;
# Update Endpoint&lt;br /&gt;
sparqlUpdate = SPARQLWrapper(f&#039;{SERVER}/repositories/{REPOSITORY}/statements&#039;)&lt;br /&gt;
&lt;br /&gt;
# Ask whether there was an ongoing indictment on the date 1990-01-01.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    ASK {&lt;br /&gt;
        SELECT ?end ?start&lt;br /&gt;
        WHERE{&lt;br /&gt;
            ?s ns1:investigation_end ?end;&lt;br /&gt;
               ns1:investigation_start ?start;&lt;br /&gt;
               ns1:outcome ns1:indictment.&lt;br /&gt;
            FILTER(?start &amp;lt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date &amp;amp;&amp;amp; ?end &amp;gt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date) &lt;br /&gt;
	    }&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(f&amp;quot;Are there any investigation on the 1990-01-01: {results[&#039;boolean&#039;]}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# List ongoing indictments on that date 1990-01-01.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    SELECT ?s&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation_end ?end;&lt;br /&gt;
           ns1:investigation_start ?start;&lt;br /&gt;
           ns1:outcome ns1:indictment.&lt;br /&gt;
        FILTER(?start &amp;lt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date &amp;amp;&amp;amp; ?end &amp;gt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date) &lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;The ongoing investigations on the 1990-01-01 are:&amp;quot;)&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;s&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Describe investigation number 100 (muellerkg:investigation_100).&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    DESCRIBE ns1:investigation_100&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
print(results)&lt;br /&gt;
&lt;br /&gt;
# Print out a list of all the types used in your graph.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT DISTINCT ?types&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s rdf:type ?types . &lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
rdf_Types = []&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    rdf_Types.append(result[&amp;quot;types&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
print(rdf_Types)&lt;br /&gt;
&lt;br /&gt;
# Update the graph to that every resource that is an object in a muellerkg:investigation triple has the rdf:type muellerkg:Investigation.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?invest rdf:type ns1:Investigation .&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation ?invest .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#To Test&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    ASK{&lt;br /&gt;
        ns1:watergate rdf:type ns1:Investigation.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results[&#039;boolean&#039;])&lt;br /&gt;
&lt;br /&gt;
# Update the graph to that every resource that is an object in a muellerkg:person triple has the rdf:type muellerkg:IndictedPerson.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?person rdf:type ns1:IndictedPerson .&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:name ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson&lt;br /&gt;
&lt;br /&gt;
# Update the graph so all the investigation nodes (such as muellerkg:watergate) become the subject in a dc:title triple with the corresponding string (watergate) as the literal.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX dc: &amp;lt;http://purl.org/dc/elements/1.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?invest dc:title ?investString.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation ?invest .&lt;br /&gt;
        BIND (replace(str(?invest), str(ns1:), &amp;quot;&amp;quot;)  AS ?investString)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#Same test as above, replace it with e.g. ns1:watergate dc:title &amp;quot;watergate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Print out a sorted list of all the indicted persons represented in your graph.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?name&lt;br /&gt;
    WHERE{&lt;br /&gt;
    ?s  ns1:name ?name;&lt;br /&gt;
            ns1:outcome ns1:indictment.&lt;br /&gt;
    }&lt;br /&gt;
    ORDER BY ?name&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
names = []&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    names.append(result[&amp;quot;name&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
print(names)&lt;br /&gt;
&lt;br /&gt;
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{&lt;br /&gt;
        ?s  ns1:indictment_days ?days;&lt;br /&gt;
            ns1:outcome ns1:indictment.&lt;br /&gt;
    &lt;br /&gt;
    BIND (replace(str(?days), str(ns1:), &amp;quot;&amp;quot;)  AS ?daysR)&lt;br /&gt;
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(f&#039;The longest an investigation lasted was: {result[&amp;quot;max&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
    print(f&#039;The shortest an investigation lasted was: {result[&amp;quot;min&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
    print(f&#039;The average investigation lasted: {result[&amp;quot;avg&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
&lt;br /&gt;
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{&lt;br /&gt;
    ?s  ns1:indictment_days ?days;&lt;br /&gt;
        ns1:outcome ns1:indictment;&lt;br /&gt;
        ns1:investigation ?investigation.&lt;br /&gt;
    &lt;br /&gt;
    BIND (replace(str(?days), str(ns1:), &amp;quot;&amp;quot;)  AS ?daysR)&lt;br /&gt;
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)&lt;br /&gt;
    }&lt;br /&gt;
    GROUP BY ?investigation&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(f&#039;{result[&amp;quot;investigation&amp;quot;][&amp;quot;value&amp;quot;]} - min: {result[&amp;quot;min&amp;quot;][&amp;quot;value&amp;quot;]}, max: {result[&amp;quot;max&amp;quot;][&amp;quot;value&amp;quot;]}, avg: {result[&amp;quot;avg&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Wikidata SPARQL (Lab 6)=&lt;br /&gt;
===Use a DESCRIBE query to retrieve some triples about your entity===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
DESCRIBE wd:Q42 LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a SELECT query to retrieve the first 100 triples about your entity===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
  wd:Q42 ?p ?o .&lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a local SELECT query that embeds a SERVICE query to retrieve the first 100 triples about your entity to your local machine===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
            wd:Q42 ?p ?o .&lt;br /&gt;
        } LIMIT 100&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
} WHERE {&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
            wd:Q42 ?p ?o .&lt;br /&gt;
        } LIMIT 100&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a FILTER statement to only SELECT primary triples in this sense.===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use Wikidata&#039;s in-built SERVICE wikibase:label to get labels for all the object resources===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE xsd:string.===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (&lt;br /&gt;
      STRSTARTS(STR(?o), STR(wd:)) ||  # comment out this whole line to see only string literals!&lt;br /&gt;
      DATATYPE(?o) = xsd:string&lt;br /&gt;
    )&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Relax the FILTER expression again so it also returns triples with these three predicates (rdfs:label, skos:altLabel and schema:description) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (&lt;br /&gt;
      (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;  # comment out these three lines to see only fingerprint literals!&lt;br /&gt;
       STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
      ||&lt;br /&gt;
      (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
       DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
    )&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Try to restrict the FILTER expression again so that, when the predicate is rdfs:label, skos:altLabel and schema:description, the object must have LANG &amp;quot;en&amp;quot; ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
        wd:Q42 ?p ?o .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
          (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
          ||&lt;br /&gt;
          (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
           DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 100&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
  wd:Q42 ?p ?o .&lt;br /&gt;
  ?o rdfs:label ?oLabel .&lt;br /&gt;
} WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
        wd:Q42 ?p ?o .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
          (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
          ||&lt;br /&gt;
          (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
           DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 500&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If you have more time ==&lt;br /&gt;
===You must therefore REPLACE all wdt: prefixes of properties with wd: prefixes and BIND the new URI AS a new variable, for example ?pw. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?pwLabel ?oLabel WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
 &lt;br /&gt;
    BIND (IRI(REPLACE(STR(?p), STR(wdt:), STR(wd:))) AS ?pw)&lt;br /&gt;
&lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Now you can go back to the SELECT statement that returned primary triples with only resource objects (not literal objects or fingerprints). Extend it so it also includes primary triples &amp;quot;one step out&amp;quot;, i.e., triples where the subjects are objects of triples involving your reference entity. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
  wd:Q42 ?p1 ?o1 .&lt;br /&gt;
  ?o1 rdfs:label ?o1Label .&lt;br /&gt;
  ?o1 ?p2 ?o2 .&lt;br /&gt;
  ?o2 rdfs:label ?o2Label .&lt;br /&gt;
} WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p1 ?o1Label ?o1 ?p2 ?o2Label ?o2 WHERE {&lt;br /&gt;
        wd:Q42 ?p1 ?o1 .&lt;br /&gt;
        ?o1 ?p2 ?o2 .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
           STRSTARTS(STR(?p1), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o1), STR(wd:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?p2), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o2), STR(wd:))&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 500&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=CSV to RDF (Lab 7)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Imports&lt;br /&gt;
import re&lt;br /&gt;
from pandas import *&lt;br /&gt;
from numpy import nan&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, RDF, XSD, FOAF&lt;br /&gt;
from spotlight import SpotlightException, annotate&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
# Test around with the confidence, and see how many names changes depending on the confidence.&lt;br /&gt;
# However, be aware that anything lower than this (0.83) it will replace James W. McCord and other names that includes James with LeBron James&lt;br /&gt;
CONFIDENCE = 0.83 &lt;br /&gt;
&lt;br /&gt;
# This function uses DBpedia Spotlight, which was not a part of the CSV lab this year.  &lt;br /&gt;
def annotate_entity(entity, filters={&#039;types&#039;: &#039;DBpedia:Person&#039;}):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = annotate(address=SERVER, text=entity, confidence=CONFIDENCE, filters=filters)&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
#Pandas&#039; read_csv function to load russia-investigation.csv&lt;br /&gt;
df = read_csv(&amp;quot;russia-investigation.csv&amp;quot;)&lt;br /&gt;
#Replaces all instances of nan to None type with numpy&#039;s nan&lt;br /&gt;
df = df.replace(nan, None)&lt;br /&gt;
&lt;br /&gt;
#Function that prepares the values to be added to the graph as a URI (ex infront) or Literal&lt;br /&gt;
def prepareValue(row):&lt;br /&gt;
	if row == None: #none type&lt;br /&gt;
		value = Literal(row)&lt;br /&gt;
	elif isinstance(row, str) and re.match(r&#039;\d{4}-\d{2}-\d{2}&#039;, row): #date&lt;br /&gt;
		value = Literal(row, datatype=XSD.date)&lt;br /&gt;
	elif isinstance(row, bool): #boolean value (true / false)&lt;br /&gt;
		value = Literal(row, datatype=XSD.boolean)&lt;br /&gt;
	elif isinstance(row, int): #integer&lt;br /&gt;
		value = Literal(row, datatype=XSD.integer)&lt;br /&gt;
	elif isinstance(row, str): #string&lt;br /&gt;
		value = URIRef(ex + row.replace(&#039;&amp;quot;&#039;, &#039;&#039;).replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;).replace(&amp;quot;,&amp;quot;,&amp;quot;&amp;quot;).replace(&amp;quot;-&amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	elif isinstance(row, float): #float&lt;br /&gt;
		value = Literal(row, datatype=XSD.float)&lt;br /&gt;
&lt;br /&gt;
	return value&lt;br /&gt;
&lt;br /&gt;
#Convert the non-semantic CSV dataset into a semantic RDF &lt;br /&gt;
def csv_to_rdf(df):&lt;br /&gt;
	for index, row in df.iterrows():&lt;br /&gt;
		id = URIRef(ex + &amp;quot;Investigation_&amp;quot; + str(index))&lt;br /&gt;
		investigation = prepareValue(row[&amp;quot;investigation&amp;quot;])&lt;br /&gt;
		investigation_start = prepareValue(row[&amp;quot;investigation-start&amp;quot;])&lt;br /&gt;
		investigation_end = prepareValue(row[&amp;quot;investigation-end&amp;quot;])&lt;br /&gt;
		investigation_days = prepareValue(row[&amp;quot;investigation-days&amp;quot;])&lt;br /&gt;
		indictment_days = prepareValue(row[&amp;quot;indictment-days &amp;quot;])&lt;br /&gt;
		cp_date = prepareValue(row[&amp;quot;cp-date&amp;quot;])&lt;br /&gt;
		cp_days = prepareValue(row[&amp;quot;cp-days&amp;quot;])&lt;br /&gt;
		overturned = prepareValue(row[&amp;quot;overturned&amp;quot;])&lt;br /&gt;
		pardoned = prepareValue(row[&amp;quot;pardoned&amp;quot;])&lt;br /&gt;
		american = prepareValue(row[&amp;quot;american&amp;quot;])&lt;br /&gt;
		outcome = prepareValue(row[&amp;quot;type&amp;quot;])&lt;br /&gt;
		name_ex = prepareValue(row[&amp;quot;name&amp;quot;])&lt;br /&gt;
		president_ex = prepareValue(row[&amp;quot;president&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
		#Spotlight Search&lt;br /&gt;
		name = annotate_entity(str(row[&#039;name&#039;]))&lt;br /&gt;
		president = annotate_entity(str(row[&#039;president&#039;]).replace(&amp;quot;.&amp;quot;, &amp;quot;&amp;quot;))&lt;br /&gt;
		&lt;br /&gt;
		#Adds the tripples to the graph&lt;br /&gt;
		g.add((id, RDF.type, ex.Investigation))&lt;br /&gt;
		g.add((id, ex.investigation, investigation))&lt;br /&gt;
		g.add((id, ex.investigation_start, investigation_start))&lt;br /&gt;
		g.add((id, ex.investigation_end, investigation_end))&lt;br /&gt;
		g.add((id, ex.investigation_days, investigation_days))&lt;br /&gt;
		g.add((id, ex.indictment_days, indictment_days))&lt;br /&gt;
		g.add((id, ex.cp_date, cp_date))&lt;br /&gt;
		g.add((id, ex.cp_days, cp_days))&lt;br /&gt;
		g.add((id, ex.overturned, overturned))&lt;br /&gt;
		g.add((id, ex.pardoned, pardoned))&lt;br /&gt;
		g.add((id, ex.american, american))&lt;br /&gt;
		g.add((id, ex.outcome, outcome))&lt;br /&gt;
&lt;br /&gt;
		#Spotlight search&lt;br /&gt;
		#Name&lt;br /&gt;
		try:&lt;br /&gt;
			g.add((id, ex.person, URIRef(name[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
		except:&lt;br /&gt;
			g.add((id, ex.person, name_ex))&lt;br /&gt;
&lt;br /&gt;
		#President&lt;br /&gt;
		try:&lt;br /&gt;
			g.add((id, ex.president, URIRef(president[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
		except:&lt;br /&gt;
			g.add((id, ex.president, president_ex))&lt;br /&gt;
&lt;br /&gt;
csv_to_rdf(df)&lt;br /&gt;
print(g.serialize())&lt;br /&gt;
g.serialize(&amp;quot;lab7.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=JSON-LD (Lab 8)=&lt;br /&gt;
== Task 1) Basic JSON-LD ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;JSON-LD&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;@context&amp;quot;: {&lt;br /&gt;
        &amp;quot;@base&amp;quot;: &amp;quot;http://example.org/&amp;quot;,&lt;br /&gt;
        &amp;quot;edges&amp;quot;: &amp;quot;http://example.org/triple&amp;quot;,&lt;br /&gt;
        &amp;quot;start&amp;quot;: &amp;quot;http://example.org/source&amp;quot;,&lt;br /&gt;
        &amp;quot;rel&amp;quot;: &amp;quot;http://exaxmple.org/predicate&amp;quot;,&lt;br /&gt;
        &amp;quot;end&amp;quot;: &amp;quot;http://example.org/object&amp;quot;,&lt;br /&gt;
        &amp;quot;Person&amp;quot; : &amp;quot;http://example.org/Person&amp;quot;,&lt;br /&gt;
        &amp;quot;birthday&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/birthday&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot; : &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameEng&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/en/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;en&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameFr&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/fr/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;fr&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameCh&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/ch/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;ch&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;age&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/age&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot; : &amp;quot;xsd:int&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;likes&amp;quot; : &amp;quot;http://example.org/games/likes&amp;quot;,&lt;br /&gt;
        &amp;quot;haircolor&amp;quot; : &amp;quot;http://example.org/games/haircolor&amp;quot;&lt;br /&gt;
    },&lt;br /&gt;
    &amp;quot;@graph&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;1987.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;nameEng&amp;quot; : &amp;quot;Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 26&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;2001.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;nameCh&amp;quot; : &amp;quot;Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 22,&lt;br /&gt;
            &amp;quot;likes&amp;quot; : &amp;quot;bastketball&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;1978.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;haircolor&amp;quot; : &amp;quot;Black&amp;quot;,&lt;br /&gt;
            &amp;quot;nameFr&amp;quot; : &amp;quot;Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 45&lt;br /&gt;
        },&lt;br /&gt;
        {&amp;quot;edges&amp;quot; : [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Louis&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;teaches&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Ju&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;plays&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Jeremy&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;plays&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        }&lt;br /&gt;
        ]}&lt;br /&gt;
    ]&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Task 2 &amp;amp; 3) Retrieving JSON-LD from ConceptNet / Programming JSON-LD in Python ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
CN_BASE = &#039;http://api.conceptnet.io/c/en/&#039;&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
g.parse(CN_BASE+&#039;indictment&#039;, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# To download JSON object:&lt;br /&gt;
&lt;br /&gt;
import json&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
json_obj = requests.get(CN_BASE+&#039;indictment&#039;).json()&lt;br /&gt;
&lt;br /&gt;
# To change the @context:&lt;br /&gt;
&lt;br /&gt;
context = {&lt;br /&gt;
     &amp;quot;@base&amp;quot;: &amp;quot;http://ex.org/&amp;quot;,&lt;br /&gt;
     &amp;quot;edges&amp;quot;: &amp;quot;http://ex.org/triple/&amp;quot;,&lt;br /&gt;
     &amp;quot;start&amp;quot;: &amp;quot;http://ex.org/s/&amp;quot;,&lt;br /&gt;
     &amp;quot;rel&amp;quot;: &amp;quot;http://ex.org/p/&amp;quot;,&lt;br /&gt;
     &amp;quot;end&amp;quot;: &amp;quot;http://ex.org/o/&amp;quot;,&lt;br /&gt;
     &amp;quot;label&amp;quot;: &amp;quot;http://ex.org/label&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
json_obj[&#039;@context&#039;] = context&lt;br /&gt;
json_str = json.dumps(json_obj)&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
g.parse(data=json_str, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# To extract triples (here with labels):&lt;br /&gt;
&lt;br /&gt;
r = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         SELECT ?s ?sLabel ?p ?o ?oLabel WHERE {&lt;br /&gt;
             ?edge&lt;br /&gt;
                 &amp;lt;http://ex.org/s/&amp;gt; ?s ;&lt;br /&gt;
                 &amp;lt;http://ex.org/p/&amp;gt; ?p ;&lt;br /&gt;
                 &amp;lt;http://ex.org/o/&amp;gt; ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
}&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;, initNs={&#039;cn&#039;: CN_BASE})&lt;br /&gt;
print(r.serialize(format=&#039;txt&#039;).decode())&lt;br /&gt;
&lt;br /&gt;
# Construct a new graph:&lt;br /&gt;
&lt;br /&gt;
r = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         CONSTRUCT {&lt;br /&gt;
             ?s ?p ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
         } WHERE {&lt;br /&gt;
             ?edge &amp;lt;http://ex.org/s/&amp;gt; ?s ;&lt;br /&gt;
                   &amp;lt;http://ex.org/p/&amp;gt; ?p ;&lt;br /&gt;
                   &amp;lt;http://ex.org/o/&amp;gt; ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
}&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;, initNs={&#039;cn&#039;: CN_BASE})&lt;br /&gt;
&lt;br /&gt;
print(r.graph.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SHACL (Lab 9)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from pyshacl import validate&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
data_graph = Graph()&lt;br /&gt;
# parses the Turtle example from the task&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
prefixes = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
shape_graph = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
ex:PUI_Shape&lt;br /&gt;
    a sh:NodeShape ;&lt;br /&gt;
    sh:targetClass ex:PersonUnderInvestigation ;&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path foaf:name ;&lt;br /&gt;
        sh:minCount 1 ; #Every person under investigation has exactly one name. &lt;br /&gt;
        sh:maxCount 1 ; #Every person under investigation has exactly one name.&lt;br /&gt;
        sh:datatype rdf:langString ; #All person names must be language-tagged&lt;br /&gt;
    ] ;&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:chargedWith ;&lt;br /&gt;
        sh:nodeKind sh:IRI ; #The object of a charged with property must be a URI.&lt;br /&gt;
        sh:class ex:Offense ; #The object of a charged with property must be an offense.&lt;br /&gt;
    ] .&lt;br /&gt;
&lt;br /&gt;
# --- If you have more time tasks ---&lt;br /&gt;
ex:User_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    # The only allowed values for ex:american are true, false or unknown.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:american;&lt;br /&gt;
        sh:pattern &amp;quot;(true|false|unknown)&amp;quot; ;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # The value of a property that counts days must be an integer.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:indictment_days;&lt;br /&gt;
        sh:datatype xsd:integer;&lt;br /&gt;
    ];   &lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_days;&lt;br /&gt;
        sh:datatype xsd:integer;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # The value of a property that indicates a start date must be xsd:date.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_start;&lt;br /&gt;
        sh:datatype xsd:date;&lt;br /&gt;
    ];&lt;br /&gt;
&lt;br /&gt;
    # The value of a property that indicates an end date must be xsd:date or unknown (tip: you can use sh:or (...) ).&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_end;&lt;br /&gt;
        sh:or (&lt;br /&gt;
         [ sh:datatype xsd:date ]&lt;br /&gt;
         [ sh:hasValue &amp;quot;unknown&amp;quot; ]&lt;br /&gt;
    )];&lt;br /&gt;
    &lt;br /&gt;
    # Every indictment must have exactly one FOAF name for the investigated person.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path foaf:name;&lt;br /&gt;
        sh:minCount 1;&lt;br /&gt;
        sh:maxCount 1;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigatedPerson ;&lt;br /&gt;
        sh:minCount 1 ;&lt;br /&gt;
        sh:maxCount 1 ;&lt;br /&gt;
        sh:class ex:PersonUnderInvestigation ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
    ] ;&lt;br /&gt;
&lt;br /&gt;
    # No URI-s can contain hyphens (&#039;-&#039;).&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:outcome ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
        sh:pattern &amp;quot;^[^-]*$&amp;quot; ;&lt;br /&gt;
    ] ;&lt;br /&gt;
&lt;br /&gt;
    # Presidents must be identified with URIs.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:president ;&lt;br /&gt;
        sh:minCount 1 ;&lt;br /&gt;
        sh:class ex:President ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
    ] .&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
shacl_graph = Graph()&lt;br /&gt;
# parses the contents of a shape_graph you made in the previous task&lt;br /&gt;
shacl_graph.parse(data=prefixes+shape_graph)&lt;br /&gt;
&lt;br /&gt;
# uses pySHACL&#039;s validate method to apply the shape_graph constraints to the data_graph&lt;br /&gt;
results = validate(&lt;br /&gt;
    data_graph,&lt;br /&gt;
    shacl_graph=shacl_graph,&lt;br /&gt;
    inference=&#039;both&#039;&lt;br /&gt;
)&lt;br /&gt;
&lt;br /&gt;
# prints out the validation result&lt;br /&gt;
boolean_value, results_graph, results_text = results&lt;br /&gt;
&lt;br /&gt;
# print(boolean_value)&lt;br /&gt;
print(results_graph.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
# print(results_text)&lt;br /&gt;
&lt;br /&gt;
#Write a SPARQL query to print out each distinct sh:resultMessage in the results_graph&lt;br /&gt;
distinct_messages = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
SELECT DISTINCT ?message WHERE {&lt;br /&gt;
    [] sh:result / sh:resultMessage ?message .&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
messages = results_graph.query(distinct_messages)&lt;br /&gt;
for row in messages:&lt;br /&gt;
    print(row.message)&lt;br /&gt;
&lt;br /&gt;
#each sh:resultMessage in the results_graph once, along with the number of times that message has been repeated in the results&lt;br /&gt;
count_messages = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {&lt;br /&gt;
    [] sh:result ?result .&lt;br /&gt;
    ?result sh:resultMessage ?message ;&lt;br /&gt;
            sh:focusNode ?node .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?message&lt;br /&gt;
ORDER BY DESC(?count) ?message&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
messages = results_graph.query(count_messages)&lt;br /&gt;
for row in messages:&lt;br /&gt;
    print(&amp;quot;COUNT    MESSAGE&amp;quot;)&lt;br /&gt;
    print(row.num_messages, &amp;quot;      &amp;quot;, row.message)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDFS (Lab 10)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, Literal, XSD, FOAF, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
NS = {&lt;br /&gt;
    &#039;ex&#039;: ex,&lt;br /&gt;
    &#039;rdf&#039;: RDF,&lt;br /&gt;
    &#039;rdfs&#039;: RDFS,&lt;br /&gt;
    &#039;foaf&#039;: FOAF,&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Write a small function that computes the RDFS closure on your graph.&lt;br /&gt;
def flush():&lt;br /&gt;
    engine = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
    engine.closure()&lt;br /&gt;
    engine.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
#Rick Gates was charged with money laundering and tax evasion.&lt;br /&gt;
g.add((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
&lt;br /&gt;
#When one thing that is charged with another thing,&lt;br /&gt;
g.add((ex.chargedWith, RDFS.domain, ex.PersonUnderInvestigation))  #the first thing (subject) is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing (object) is an offense.&lt;br /&gt;
&lt;br /&gt;
#Write a SPARQL query that checks the RDF type(s) of Rick Gates and money laundering in your RDF graph.&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
#A person under investigation is a FOAF person&lt;br /&gt;
g.add((ex.PersonUnderInvestigation, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
#Paul Manafort was convicted for tax evasion.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxEvasion))&lt;br /&gt;
#the first thing is also charged with the second thing&lt;br /&gt;
g.add((ex.convictedFor, RDFS.subPropertyOf, ex.chargedWith)) &lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize())&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=OWL 1 (Lab 11)=&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, RDFS, Namespace, RDF, FOAF, BNode, OWL, URIRef, Literal, XSD&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&#039;http://schema.org/&#039;)&lt;br /&gt;
dbr = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
# g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# Donald Trump and Robert Mueller are two different persons.&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.differentFrom, ex.Robert_Mueller))&lt;br /&gt;
&lt;br /&gt;
# Actually, all the names mentioned in connection with the Mueller investigation refer to different people.&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Robert_Mueller, ex.Paul_Manafort, ex.Rick_Gates, ex.George_Papadopoulos, ex.Michael_Flynn, ex.Michael_Cohen, ex.Roger_Stone, ex.Donald_Trump])&lt;br /&gt;
g.add((b1, RDF.type, OWL.AllDifferent))&lt;br /&gt;
g.add((b1, OWL.distinctMembers, b2))&lt;br /&gt;
&lt;br /&gt;
# All these people are foaf:Persons as well as schema:Persons&lt;br /&gt;
g.add((FOAF.Person, OWL.equivalentClass, schema.Person))&lt;br /&gt;
&lt;br /&gt;
# Tax evation is a kind of bank and tax fraud.&lt;br /&gt;
g.add((ex.TaxEvation, RDFS.subClassOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.TaxEvation, RDFS.subClassOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# The Donald Trump involved in the Mueller investigation is dbpedia:Donald_Trump and not dbpedia:Donald_Trump_Jr.&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.sameAs, dbr.Donald_Trump))&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.differentFrom, URIRef(dbr + &amp;quot;Donald_Trump_Jr.&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Congress, FBI and the Mueller investigation are foaf:Organizations.&lt;br /&gt;
g.add((ex.Congress, RDF.type, FOAF.Organization))&lt;br /&gt;
g.add((ex.FBI, RDF.type, FOAF.Organization))&lt;br /&gt;
g.add((ex.Mueller_Investigation, RDF.type, FOAF.Organization))&lt;br /&gt;
&lt;br /&gt;
# Nothing can be both a person and an organization.&lt;br /&gt;
g.add((FOAF.Person, OWL.disjointWith, FOAF.Organization))&lt;br /&gt;
&lt;br /&gt;
# Leading an organization is a way of being involved in an organization.&lt;br /&gt;
g.add((ex.leading, RDFS.subPropertyOf, ex.involved))&lt;br /&gt;
&lt;br /&gt;
# Being a campaign manager or an advisor for is a way of supporting someone.&lt;br /&gt;
g.add((ex.campaignManagerTo, RDFS.subPropertyOf, ex.supports))&lt;br /&gt;
g.add((ex.advisorTo, RDFS.subPropertyOf, ex.supports))&lt;br /&gt;
&lt;br /&gt;
# Donald Trump is a politician and a Republican.&lt;br /&gt;
g.add((ex.Donald_Trump, RDF.type, ex.Politician))&lt;br /&gt;
g.add((ex.Donald_Trump, RDF.type, ex.Republican))&lt;br /&gt;
&lt;br /&gt;
# A Republican politician is both a politician and a Republican.&lt;br /&gt;
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Politician))&lt;br /&gt;
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Republican))&lt;br /&gt;
&lt;br /&gt;
#hasBusinessPartner&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.hasBusinessPartner, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.hasBusinessPartner, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.hasBusinessPartner, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
#adviserTo&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.adviserTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
# Not necessarily asymmetric as it&#039;s not a given that they couldn&#039;t be advisors to each other  &lt;br /&gt;
&lt;br /&gt;
#wasLyingTo&lt;br /&gt;
g.add((ex.Rick_Gates_Lying, ex.wasLyingTo, ex.FBI))&lt;br /&gt;
g.add((ex.wasLyingTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
# Not asymmetric as the subject and object could lie to each other; also in this context, the FBI can lie to you&lt;br /&gt;
&lt;br /&gt;
#presidentOf&lt;br /&gt;
g.add((ex.Donald_Trump, ex.presidentOf, ex.USA))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.FunctionalProperty)) #can only be president of one country&lt;br /&gt;
#not inversefunctionalproperty as Bosnia has 3 presidents https://www.culturalworld.org/do-any-countries-have-more-than-one-president.htm&lt;br /&gt;
&lt;br /&gt;
#hasPresident&lt;br /&gt;
g.add((ex.USA, ex.hasPresident, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.InverseFunctionalProperty)) #countries do not share their president with another&lt;br /&gt;
#not functionalproperty as a country (Bosnia) can have more than one president&lt;br /&gt;
&lt;br /&gt;
#Closure&lt;br /&gt;
owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)&lt;br /&gt;
&lt;br /&gt;
#Serialization&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab8.xml&amp;quot;, format=&amp;quot;xml&amp;quot;) #serializes to XML file&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=OWL 2 (Lab 12)=&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@prefix : &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
@prefix dc: &amp;lt;http://purl.org/dc/terms#&amp;gt; .&lt;br /&gt;
@prefix io: &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
@prefix dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt; .&lt;br /&gt;
@prefix owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
@prefix xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix prov: &amp;lt;http://www.w3.org/ns/prov#&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
@base &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
&amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology&amp;gt; rdf:type owl:Ontology .&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Object Properties&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#indictedIn&lt;br /&gt;
io:indictedIn rdf:type owl:ObjectProperty ;&lt;br /&gt;
              rdfs:subPropertyOf io:involvedIn ;&lt;br /&gt;
              rdfs:domain io:InvestigatedPerson ;&lt;br /&gt;
              rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#investigating&lt;br /&gt;
io:investigating rdf:type owl:ObjectProperty ;&lt;br /&gt;
                 rdfs:subPropertyOf io:involvedIn ;&lt;br /&gt;
                 rdfs:domain io:Investigator ;&lt;br /&gt;
                 rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#involvedIn&lt;br /&gt;
io:involvedIn rdf:type owl:ObjectProperty ;&lt;br /&gt;
              rdfs:domain foaf:Person ;&lt;br /&gt;
              rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#leading&lt;br /&gt;
io:leading rdf:type owl:ObjectProperty ;&lt;br /&gt;
           rdfs:subPropertyOf io:investigating ;&lt;br /&gt;
           rdfs:domain io:InvestigationLeader ;&lt;br /&gt;
           rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Data properties&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://purl.org/dc/elements/1.1/description&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/description&amp;gt; rdf:type owl:DatatypeProperty ;&lt;br /&gt;
                                              rdfs:domain io:Investigation ;&lt;br /&gt;
                                              rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.w3.org/ns/prov#endedAtTime&lt;br /&gt;
prov:endedAtTime rdf:type owl:DatatypeProperty ,&lt;br /&gt;
                          owl:FunctionalProperty ;&lt;br /&gt;
                 rdfs:domain io:Investigation ;&lt;br /&gt;
                 rdfs:range xsd:dateTime .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.w3.org/ns/prov#startedAtTime&lt;br /&gt;
prov:startedAtTime rdf:type owl:DatatypeProperty ,&lt;br /&gt;
                            owl:FunctionalProperty ;&lt;br /&gt;
                   rdfs:domain io:Investigation ;&lt;br /&gt;
                   rdfs:range xsd:dateTime .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/name&lt;br /&gt;
foaf:name rdf:type owl:DatatypeProperty ;&lt;br /&gt;
          rdfs:domain foaf:Person ;&lt;br /&gt;
          rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/title&lt;br /&gt;
foaf:title rdf:type owl:DatatypeProperty ;&lt;br /&gt;
           rdfs:domain io:Investigation ;&lt;br /&gt;
           rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Classes&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigatedPerson&lt;br /&gt;
io:InvestigatedPerson rdf:type owl:Class ;&lt;br /&gt;
                      rdfs:subClassOf io:Person ;&lt;br /&gt;
                      owl:disjointWith io:Investigator .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation&lt;br /&gt;
io:Investigation rdf:type owl:Class .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigationLeader&lt;br /&gt;
io:InvestigationLeader rdf:type owl:Class ;&lt;br /&gt;
                       rdfs:subClassOf io:Investigator .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigator&lt;br /&gt;
io:Investigator rdf:type owl:Class ;&lt;br /&gt;
                rdfs:subClassOf io:Person .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Person&lt;br /&gt;
io:Person rdf:type owl:Class ;&lt;br /&gt;
          rdfs:subClassOf foaf:Person .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/Person&lt;br /&gt;
foaf:Person rdf:type owl:Class .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Individuals&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Donald_Trump&lt;br /&gt;
dbr:Donald_Trump rdf:type owl:NamedIndividual ;&lt;br /&gt;
                 foaf:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Elizabeth_Prelogar&lt;br /&gt;
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ;&lt;br /&gt;
                       io:investigating &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                       foaf:name &amp;quot;Elizabeth Prelogar&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Michael_Flynn&lt;br /&gt;
dbr:Michael_Flynn rdf:type owl:NamedIndividual ;&lt;br /&gt;
                  foaf:name &amp;quot;Michael Flynn&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Paul_Manafort&lt;br /&gt;
dbr:Paul_Manafort rdf:type owl:NamedIndividual ;&lt;br /&gt;
                  io:indictedIn &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                  foaf:name &amp;quot;Paul Manafort&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Robert_Mueller&lt;br /&gt;
dbr:Robert_Mueller rdf:type owl:NamedIndividual ;&lt;br /&gt;
                   io:leading &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                   foaf:name &amp;quot;Robert Mueller&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Roger_Stone&lt;br /&gt;
dbr:Roger_Stone rdf:type owl:NamedIndividual ;&lt;br /&gt;
                foaf:name &amp;quot;Roger Stone&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                                        foaf:title &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    General axioms&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
[ rdf:type owl:AllDifferent ;&lt;br /&gt;
  owl:distinctMembers ( dbr:Donald_Trump&lt;br /&gt;
                        dbr:Elizabeth_Prelogar&lt;br /&gt;
                        dbr:Michael_Flynn&lt;br /&gt;
                        dbr:Paul_Manafort&lt;br /&gt;
                        dbr:Robert_Mueller&lt;br /&gt;
                        dbr:Roger_Stone&lt;br /&gt;
                      )&lt;br /&gt;
] .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  Generated by the OWL API (version 4.5.25.2023-02-15T19:15:49Z) https://github.com/owlcs/owlapi&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Using Graph Embeddings (Lab 13)=&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1WkRJUeUBVF5yVv7o0pOKfsd4pqG6369k&lt;br /&gt;
&lt;br /&gt;
=Training Graph Embeddings (Lab 14)=&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q&lt;br /&gt;
 --&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2721</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2721"/>
		<updated>2026-01-07T15:39:27Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 2)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries]] (week 3 &#039;&#039;&#039;&#039;&#039;and 4&#039;&#039;&#039;&#039;&#039;)&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 5)&lt;br /&gt;
# [[Lab: Ontop | Lab: Virtualisation with Ontop]] (week 6)&lt;br /&gt;
# [[Lab: JSON-LD]] (week 7)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]] (week 8)&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]] (week 9)&lt;br /&gt;
# [[Lab: Wikidata in RDF]] (week 10)&lt;br /&gt;
# [[Lab: OWL 1]] (week 11)&lt;br /&gt;
# [[Lab: OWL 2]] (week 12)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 13 and 14&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 15)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 15)&lt;br /&gt;
# Lab: Exam training (week 16)&lt;br /&gt;
&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL 2 | Lab: SPARQL updates]] (week 7, from 12/2)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2025, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2720</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2720"/>
		<updated>2026-01-07T15:36:29Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
Here we will present suggested solutions after each lab. &#039;&#039;The page will be updated as the course progresses&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
=Getting started (Lab 1)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# The Mueller Investigation was lead by Robert Mueller&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))&lt;br /&gt;
&lt;br /&gt;
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))&lt;br /&gt;
&lt;br /&gt;
# Paul Manafort was business partner of Rick Gates&lt;br /&gt;
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))&lt;br /&gt;
&lt;br /&gt;
# He was campaign chairman for Donald Trump&lt;br /&gt;
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy and lying to FBI.&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;)) # To screen&lt;br /&gt;
#g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) # To file&lt;br /&gt;
&lt;br /&gt;
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate&lt;br /&gt;
for subject, object in g[ : ex.pleadGuiltyTo :]:&lt;br /&gt;
    print(subject, ex.pleadGuiltyTo, object)&lt;br /&gt;
&lt;br /&gt;
# --- IF you have more time tasks ---&lt;br /&gt;
&lt;br /&gt;
# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that submits your model for rendering and saves the returned image to file.&lt;br /&gt;
import requests&lt;br /&gt;
import shutil&lt;br /&gt;
&lt;br /&gt;
def graphToImage(graphInput):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graphInput, &amp;quot;from&amp;quot;:&amp;quot;ttl&amp;quot;, &amp;quot;to&amp;quot;:&amp;quot;png&amp;quot;}&lt;br /&gt;
    link = &amp;quot;http://www.ldf.fi/service/rdf-grapher&amp;quot;&lt;br /&gt;
    response = requests.get(link, params = data, stream=True)&lt;br /&gt;
    # print(response.content)&lt;br /&gt;
    print(response.raw)&lt;br /&gt;
    with open(&amp;quot;lab1.png&amp;quot;, &amp;quot;wb&amp;quot;) as file:&lt;br /&gt;
        shutil.copyfileobj(response.raw, file)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDF programming with RDFlib (Lab 2)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Getting the graph created in the first lab&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
# Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to Congress.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
# Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to the FBI.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Change your graph so it represents instances of lying as blank nodes.&lt;br /&gt;
# Remove the triples that will be duplicated&lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI)) &lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.remove((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
FlynnLying = BNode() &lt;br /&gt;
g.add((FlynnLying, ex.crime, ex.LyingToFBI))&lt;br /&gt;
g.add((FlynnLying, ex.pleadGulityOn, Literal(&amp;quot;2017-12-1&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((FlynnLying, ex.liedAbout, Literal(&amp;quot;His communications with a former Russian ambassador during the presidential transition&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((FlynnLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, FlynnLying))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
GatesLying = BNode()&lt;br /&gt;
Crimes = BNode()&lt;br /&gt;
Charged = BNode()&lt;br /&gt;
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])&lt;br /&gt;
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])&lt;br /&gt;
g.add((GatesLying, ex.crime, Crimes))&lt;br /&gt;
g.add((GatesLying, ex.chargedWith, Charged))&lt;br /&gt;
g.add((GatesLying, ex.pleadGulityOn, Literal(&amp;quot;2018-02-23&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((GatesLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, GatesLying))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
CohenLying = BNode()&lt;br /&gt;
g.add((CohenLying, ex.crime, ex.LyingToCongress))&lt;br /&gt;
g.add((CohenLying, ex.liedAbout, ex.TrumpRealEstateDeal))&lt;br /&gt;
g.add((CohenLying, ex.prosecutorsAlleged, Literal(&amp;quot;In an August 2017 letter Cohen sent to congressional committees investigating Russian election interference, he falsely stated that the project ended in January 2016&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.mullerInvestigationAlleged, Literal(&amp;quot;Cohen falsely stated that he had never agreed to travel to Russia for the real estate deal and that he did not recall any contact with the Russian government about the project&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.pleadGulityOn, Literal(&amp;quot;2018-11-29&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((CohenLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, CohenLying))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
#Save (serialize) your graph to a Turtle file.&lt;br /&gt;
# g.serialize(&amp;quot;lab2.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
#Add a few triples to the Turtle file with more information about Donald Trump.&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:postalCode 33480 ;&lt;br /&gt;
            ex:residence ex:Mar_a_Lago ;&lt;br /&gt;
            ex:state ex:Florida ;&lt;br /&gt;
            ex:streetName &amp;quot;1100 S Ocean Blvd&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:previousAddress [ ex:city ex:Washington_DC ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:phoneNumber &amp;quot;1 202 456 1414&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:postalCode &amp;quot;20500&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:residence ex:The_White_House ;&lt;br /&gt;
            ex:streetName &amp;quot;1600 Pennsylvania Ave.&amp;quot;^^xsd:string ];&lt;br /&gt;
    ex:marriedTo ex:Melania_Trump;&lt;br /&gt;
    ex:fatherTo (ex:Ivanka_Trump ex:Donald_Trump_Jr ex: ex:Tiffany_Trump ex:Eric_Trump ex:Barron_Trump).&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
#Read (parse) the Turtle file back into a Python program, and check that the new triples are there&lt;br /&gt;
def serialize_Graph():&lt;br /&gt;
    newGraph = Graph()&lt;br /&gt;
    newGraph.parse(&amp;quot;lab2.ttl&amp;quot;)&lt;br /&gt;
    print(newGraph.serialize())&lt;br /&gt;
&lt;br /&gt;
#Don&#039;t need this to run until after adding the triples above to the ttl file&lt;br /&gt;
# serialize_Graph() &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that starts with Donald Trump prints out a graph depth-first to show how the other graph nodes are connected to him&lt;br /&gt;
visited_nodes = set()&lt;br /&gt;
&lt;br /&gt;
def create_Tree(model, nodes):&lt;br /&gt;
    #Traverse the model breadth-first to create the tree.&lt;br /&gt;
    global visited_nodes&lt;br /&gt;
    tree = Graph()&lt;br /&gt;
    children = set()&lt;br /&gt;
    visited_nodes |= set(nodes)&lt;br /&gt;
    for s, p, o in model:&lt;br /&gt;
        if s in nodes and o not in visited_nodes:&lt;br /&gt;
            tree.add((s, p, o))&lt;br /&gt;
            visited_nodes.add(o)&lt;br /&gt;
            children.add(o)&lt;br /&gt;
        if o in nodes and s not in visited_nodes:&lt;br /&gt;
            invp = URIRef(f&#039;{p}_inv&#039;) #_inv represents inverse of&lt;br /&gt;
            tree.add((o, invp, s))&lt;br /&gt;
            visited_nodes.add(s)&lt;br /&gt;
            children.add(s)&lt;br /&gt;
    if len(children) &amp;gt; 0:&lt;br /&gt;
        children_tree = create_Tree(model, children)&lt;br /&gt;
        for triple in children_tree:&lt;br /&gt;
            tree.add(triple)&lt;br /&gt;
    return tree&lt;br /&gt;
&lt;br /&gt;
def print_Tree(tree, root, indent=0):&lt;br /&gt;
    #Print the tree depth-first.&lt;br /&gt;
    print(str(root))&lt;br /&gt;
    for s, p, o in tree:&lt;br /&gt;
        if s==root:&lt;br /&gt;
            print(&#039;    &#039;*indent + &#039;  &#039; + str(p), end=&#039; &#039;)&lt;br /&gt;
            print_Tree(tree, o, indent+1)&lt;br /&gt;
    &lt;br /&gt;
tree = create_Tree(g, [ex.Donald_Trump])&lt;br /&gt;
print_Tree(tree, ex.Donald_Trump)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL (Lab 3-4)=&lt;br /&gt;
===List all triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the first 100 triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT (COUNT(*) as ?count)&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of indictments===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT (COUNT(?ind) as ?amount)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:outcome ?ind;&lt;br /&gt;
      ns1:outcome ns1:indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who pleaded guilty, along with the name of the investigation===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?invname&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:investigation ?invname;&lt;br /&gt;
      ns1:outcome ns1:guilty-plea .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who were convicted, but who had their conviction overturned by which president===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?president&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:president ?president;&lt;br /&gt;
      ns1:outcome ns1:conviction;&lt;br /&gt;
      ns1:overturned ns1:true.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
ORDER BY DESC(?count)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each president, list the numbers of convictions and of pardons made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as&lt;br /&gt;
?pardons)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:president ?president;&lt;br /&gt;
      ns1:outcome ?outcome ;&lt;br /&gt;
      ns1:outcome ns1:conviction.&lt;br /&gt;
      OPTIONAL{&lt;br /&gt;
         ?s ns1:pardoned ?pardon .&lt;br /&gt;
         FILTER (?pardon = ns1:true)&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?president&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Rename mullerkg:name to something like muellerkg:person===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE{?s ns1:name ?o}&lt;br /&gt;
INSERT{?s ns1:person ?o}&lt;br /&gt;
WHERE {?s ns1:name ?o}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Persons&lt;br /&gt;
INSERT {?person foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:person ?person .&lt;br /&gt;
      BIND(REPLACE(STR(?person), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Presidents&lt;br /&gt;
INSERT {?president foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:president ?president .&lt;br /&gt;
      BIND(REPLACE(STR(?president), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use INSERT DATA updates to add these triples===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
     ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:pleadGuiltyTo ns1:LyingToFBI;&lt;br /&gt;
         ns1:sentencedTo ns1:Prison.&lt;br /&gt;
&lt;br /&gt;
     ns1:Roger_Stone a ns1:Republican;&lt;br /&gt;
         ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:officialTo ns1:Trump_Campaign;&lt;br /&gt;
         ns1:interactedWith ns1:Wikileaks;&lt;br /&gt;
         ns1:providedTestimony ns1:House_Intelligence_Committee;&lt;br /&gt;
         ns1:clearedOf ns1:AllCharges.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test if added&lt;br /&gt;
SELECT ?p ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                      ns1:WitnessTampering,&lt;br /&gt;
                                      ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#The task specifically requested DELETE DATA &amp;amp; INSERT DATA, put below is&lt;br /&gt;
a more efficient solution&lt;br /&gt;
&lt;br /&gt;
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
INSERT{&lt;br /&gt;
   ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                   ns1:WitnessTampering,&lt;br /&gt;
                                   ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a DESCRIBE query to show the updated information about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o.&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone.&lt;br /&gt;
}&lt;br /&gt;
WHERE {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o .&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a DELETE/INSERT statement to change one of the prefixes in your graph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX dbp: &amp;lt;https://dbpedia.org/page/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:person ?o1}&lt;br /&gt;
INSERT {?s ns1:person ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:person ?o1 .&lt;br /&gt;
   BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#This update changes the object in triples with ns1:person as the&lt;br /&gt;
predicate. It changes it&#039;s prefix of ns1 (which is the&lt;br /&gt;
&amp;quot;shortcut/shorthand&amp;quot; for example.org) to the prefix dbp (dbpedia.org)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write an INSERT statement to add at least one significant date to the Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT statement to change the date to a string, and a new DELETE/INSERT statement to change it back to xsd:date. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
#Whilst this solution is not exactly what the task asks for, I feel like&lt;br /&gt;
this is more appropiate given the dataset. The following update&lt;br /&gt;
changes the objects that uses the cp_date as predicate from a URI, to a&lt;br /&gt;
literal with date as it&#039;s datatype&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o3}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (replace(str(?o), str(ns1:), &amp;quot;&amp;quot;)  AS ?o2)&lt;br /&gt;
   BIND (STRDT(STR(?o2), xsd:date) AS ?o3)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test:&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o.&lt;br /&gt;
   FILTER(datatype(?o) = xsd:date)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To change it to an integer, use the following code, and to change it&lt;br /&gt;
back to date, swap &amp;quot;xsd:integer&amp;quot; to &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (STRDT(STR(?o), xsd:integer) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL Programming (Lab 5)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, RDF, FOAF&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;Russia_investigation_kg.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# ----- RDFLIB -----&lt;br /&gt;
ex = Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
&lt;br /&gt;
NS = {&lt;br /&gt;
    &#039;&#039;: ex,&lt;br /&gt;
    &#039;rdf&#039;: RDF,&lt;br /&gt;
    &#039;foaf&#039;: FOAF,&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
# Print out a list of all the predicates used in your graph.&lt;br /&gt;
task1 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT DISTINCT ?p WHERE{&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(list(task1))&lt;br /&gt;
&lt;br /&gt;
# Print out a sorted list of all the presidents represented in your graph.&lt;br /&gt;
task2 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT DISTINCT ?president WHERE{&lt;br /&gt;
    ?s :president ?president .&lt;br /&gt;
}&lt;br /&gt;
ORDER BY ?president&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(list(task2))&lt;br /&gt;
&lt;br /&gt;
# Create dictionary (Python dict) with all the represented presidents as keys. For each key, the value is a list of names of people indicted under that president.&lt;br /&gt;
task3_dic = {}&lt;br /&gt;
&lt;br /&gt;
task3 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT ?president ?person WHERE{&lt;br /&gt;
    ?s :president ?president;&lt;br /&gt;
       :name ?person;&lt;br /&gt;
       :outcome :indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
for president, person in task3:&lt;br /&gt;
    if president not in task3_dic:&lt;br /&gt;
        task3_dic[president] = [person]&lt;br /&gt;
    else:&lt;br /&gt;
        task3_dic[president].append(person)&lt;br /&gt;
&lt;br /&gt;
print(task3_dic)&lt;br /&gt;
&lt;br /&gt;
# Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.&lt;br /&gt;
&lt;br /&gt;
# This task is a lot trickier than it needs to be. As far as I&#039;m aware RDFLib has no HAVING support, so a query like this:&lt;br /&gt;
task4 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
ASK {&lt;br /&gt;
  	SELECT (COUNT(?s) as ?count) WHERE{&lt;br /&gt;
    	?s :pardoned :true;&lt;br /&gt;
   	   :president :Bill_Clinton  .&lt;br /&gt;
    }&lt;br /&gt;
    HAVING (?count &amp;gt; 5)&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(task4.askAnswer)&lt;br /&gt;
&lt;br /&gt;
# Which works fine in Blazegraph and is a valid SPARQL query will always provide false in RDFLib cause it uses HAVING. &lt;br /&gt;
# Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons,&lt;br /&gt;
# so I have instead chosen Bill Clinton with 13 to check if the query works. &lt;br /&gt;
&lt;br /&gt;
task4 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    ASK{&lt;br /&gt;
        SELECT ?count WHERE{{&lt;br /&gt;
  	        SELECT (COUNT(?s) as ?count) WHERE{&lt;br /&gt;
    	        ?s :pardoned :true;&lt;br /&gt;
                   :president :Bill_Clinton  .&lt;br /&gt;
                }}&lt;br /&gt;
        FILTER (?count &amp;gt; 5) &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(task4.askAnswer)&lt;br /&gt;
&lt;br /&gt;
# Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.&lt;br /&gt;
&lt;br /&gt;
# By all accounts, it seems DESCRIBE querires are yet to be implemented in RDFLib, but they are attempting to implement it:&lt;br /&gt;
# https://github.com/RDFLib/rdflib/pull/2221 &amp;lt;--- Issue and proposed solution rasied&lt;br /&gt;
# https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 &amp;lt;--- Solution commited to RDFLib&lt;br /&gt;
# This solution does not work. However, this proposed solution should work if DESCRIBE is implemented in RDFLib&lt;br /&gt;
&lt;br /&gt;
# task5 = g.query(&amp;quot;&amp;quot;&amp;quot; &lt;br /&gt;
# DESCRIBE :Donald_Trump&lt;br /&gt;
# &amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
# print(task5.serialize())&lt;br /&gt;
&lt;br /&gt;
# ----- SPARQLWrapper -----&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039; #Might need to replace this&lt;br /&gt;
REPOSITORY = &#039;Labs&#039; #Replace with your repository name&lt;br /&gt;
&lt;br /&gt;
# Query Endpoint&lt;br /&gt;
sparql = SPARQLWrapper(f&#039;{SERVER}/repositories/{REPOSITORY}&#039;) &lt;br /&gt;
# Update Endpoint&lt;br /&gt;
sparqlUpdate = SPARQLWrapper(f&#039;{SERVER}/repositories/{REPOSITORY}/statements&#039;)&lt;br /&gt;
&lt;br /&gt;
# Ask whether there was an ongoing indictment on the date 1990-01-01.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    ASK {&lt;br /&gt;
        SELECT ?end ?start&lt;br /&gt;
        WHERE{&lt;br /&gt;
            ?s ns1:investigation_end ?end;&lt;br /&gt;
               ns1:investigation_start ?start;&lt;br /&gt;
               ns1:outcome ns1:indictment.&lt;br /&gt;
            FILTER(?start &amp;lt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date &amp;amp;&amp;amp; ?end &amp;gt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date) &lt;br /&gt;
	    }&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(f&amp;quot;Are there any investigation on the 1990-01-01: {results[&#039;boolean&#039;]}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# List ongoing indictments on that date 1990-01-01.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    SELECT ?s&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation_end ?end;&lt;br /&gt;
           ns1:investigation_start ?start;&lt;br /&gt;
           ns1:outcome ns1:indictment.&lt;br /&gt;
        FILTER(?start &amp;lt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date &amp;amp;&amp;amp; ?end &amp;gt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date) &lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;The ongoing investigations on the 1990-01-01 are:&amp;quot;)&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;s&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Describe investigation number 100 (muellerkg:investigation_100).&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    DESCRIBE ns1:investigation_100&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
print(results)&lt;br /&gt;
&lt;br /&gt;
# Print out a list of all the types used in your graph.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT DISTINCT ?types&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s rdf:type ?types . &lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
rdf_Types = []&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    rdf_Types.append(result[&amp;quot;types&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
print(rdf_Types)&lt;br /&gt;
&lt;br /&gt;
# Update the graph to that every resource that is an object in a muellerkg:investigation triple has the rdf:type muellerkg:Investigation.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?invest rdf:type ns1:Investigation .&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation ?invest .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#To Test&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    ASK{&lt;br /&gt;
        ns1:watergate rdf:type ns1:Investigation.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results[&#039;boolean&#039;])&lt;br /&gt;
&lt;br /&gt;
# Update the graph to that every resource that is an object in a muellerkg:person triple has the rdf:type muellerkg:IndictedPerson.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?person rdf:type ns1:IndictedPerson .&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:name ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson&lt;br /&gt;
&lt;br /&gt;
# Update the graph so all the investigation nodes (such as muellerkg:watergate) become the subject in a dc:title triple with the corresponding string (watergate) as the literal.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX dc: &amp;lt;http://purl.org/dc/elements/1.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?invest dc:title ?investString.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation ?invest .&lt;br /&gt;
        BIND (replace(str(?invest), str(ns1:), &amp;quot;&amp;quot;)  AS ?investString)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#Same test as above, replace it with e.g. ns1:watergate dc:title &amp;quot;watergate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Print out a sorted list of all the indicted persons represented in your graph.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?name&lt;br /&gt;
    WHERE{&lt;br /&gt;
    ?s  ns1:name ?name;&lt;br /&gt;
            ns1:outcome ns1:indictment.&lt;br /&gt;
    }&lt;br /&gt;
    ORDER BY ?name&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
names = []&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    names.append(result[&amp;quot;name&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
print(names)&lt;br /&gt;
&lt;br /&gt;
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{&lt;br /&gt;
        ?s  ns1:indictment_days ?days;&lt;br /&gt;
            ns1:outcome ns1:indictment.&lt;br /&gt;
    &lt;br /&gt;
    BIND (replace(str(?days), str(ns1:), &amp;quot;&amp;quot;)  AS ?daysR)&lt;br /&gt;
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(f&#039;The longest an investigation lasted was: {result[&amp;quot;max&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
    print(f&#039;The shortest an investigation lasted was: {result[&amp;quot;min&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
    print(f&#039;The average investigation lasted: {result[&amp;quot;avg&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
&lt;br /&gt;
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{&lt;br /&gt;
    ?s  ns1:indictment_days ?days;&lt;br /&gt;
        ns1:outcome ns1:indictment;&lt;br /&gt;
        ns1:investigation ?investigation.&lt;br /&gt;
    &lt;br /&gt;
    BIND (replace(str(?days), str(ns1:), &amp;quot;&amp;quot;)  AS ?daysR)&lt;br /&gt;
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)&lt;br /&gt;
    }&lt;br /&gt;
    GROUP BY ?investigation&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(f&#039;{result[&amp;quot;investigation&amp;quot;][&amp;quot;value&amp;quot;]} - min: {result[&amp;quot;min&amp;quot;][&amp;quot;value&amp;quot;]}, max: {result[&amp;quot;max&amp;quot;][&amp;quot;value&amp;quot;]}, avg: {result[&amp;quot;avg&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Wikidata SPARQL (Lab 6)=&lt;br /&gt;
===Use a DESCRIBE query to retrieve some triples about your entity===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
DESCRIBE wd:Q42 LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a SELECT query to retrieve the first 100 triples about your entity===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
  wd:Q42 ?p ?o .&lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a local SELECT query that embeds a SERVICE query to retrieve the first 100 triples about your entity to your local machine===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
            wd:Q42 ?p ?o .&lt;br /&gt;
        } LIMIT 100&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
} WHERE {&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
            wd:Q42 ?p ?o .&lt;br /&gt;
        } LIMIT 100&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a FILTER statement to only SELECT primary triples in this sense.===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use Wikidata&#039;s in-built SERVICE wikibase:label to get labels for all the object resources===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE xsd:string.===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (&lt;br /&gt;
      STRSTARTS(STR(?o), STR(wd:)) ||  # comment out this whole line to see only string literals!&lt;br /&gt;
      DATATYPE(?o) = xsd:string&lt;br /&gt;
    )&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Relax the FILTER expression again so it also returns triples with these three predicates (rdfs:label, skos:altLabel and schema:description) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (&lt;br /&gt;
      (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;  # comment out these three lines to see only fingerprint literals!&lt;br /&gt;
       STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
      ||&lt;br /&gt;
      (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
       DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
    )&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Try to restrict the FILTER expression again so that, when the predicate is rdfs:label, skos:altLabel and schema:description, the object must have LANG &amp;quot;en&amp;quot; ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
        wd:Q42 ?p ?o .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
          (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
          ||&lt;br /&gt;
          (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
           DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 100&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
  wd:Q42 ?p ?o .&lt;br /&gt;
  ?o rdfs:label ?oLabel .&lt;br /&gt;
} WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
        wd:Q42 ?p ?o .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
          (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
          ||&lt;br /&gt;
          (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
           DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 500&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If you have more time ==&lt;br /&gt;
===You must therefore REPLACE all wdt: prefixes of properties with wd: prefixes and BIND the new URI AS a new variable, for example ?pw. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?pwLabel ?oLabel WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
 &lt;br /&gt;
    BIND (IRI(REPLACE(STR(?p), STR(wdt:), STR(wd:))) AS ?pw)&lt;br /&gt;
&lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Now you can go back to the SELECT statement that returned primary triples with only resource objects (not literal objects or fingerprints). Extend it so it also includes primary triples &amp;quot;one step out&amp;quot;, i.e., triples where the subjects are objects of triples involving your reference entity. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
  wd:Q42 ?p1 ?o1 .&lt;br /&gt;
  ?o1 rdfs:label ?o1Label .&lt;br /&gt;
  ?o1 ?p2 ?o2 .&lt;br /&gt;
  ?o2 rdfs:label ?o2Label .&lt;br /&gt;
} WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p1 ?o1Label ?o1 ?p2 ?o2Label ?o2 WHERE {&lt;br /&gt;
        wd:Q42 ?p1 ?o1 .&lt;br /&gt;
        ?o1 ?p2 ?o2 .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
           STRSTARTS(STR(?p1), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o1), STR(wd:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?p2), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o2), STR(wd:))&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 500&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=CSV to RDF (Lab 7)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Imports&lt;br /&gt;
import re&lt;br /&gt;
from pandas import *&lt;br /&gt;
from numpy import nan&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, RDF, XSD, FOAF&lt;br /&gt;
from spotlight import SpotlightException, annotate&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
# Test around with the confidence, and see how many names changes depending on the confidence.&lt;br /&gt;
# However, be aware that anything lower than this (0.83) it will replace James W. McCord and other names that includes James with LeBron James&lt;br /&gt;
CONFIDENCE = 0.83 &lt;br /&gt;
&lt;br /&gt;
# This function uses DBpedia Spotlight, which was not a part of the CSV lab this year.  &lt;br /&gt;
def annotate_entity(entity, filters={&#039;types&#039;: &#039;DBpedia:Person&#039;}):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = annotate(address=SERVER, text=entity, confidence=CONFIDENCE, filters=filters)&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
#Pandas&#039; read_csv function to load russia-investigation.csv&lt;br /&gt;
df = read_csv(&amp;quot;russia-investigation.csv&amp;quot;)&lt;br /&gt;
#Replaces all instances of nan to None type with numpy&#039;s nan&lt;br /&gt;
df = df.replace(nan, None)&lt;br /&gt;
&lt;br /&gt;
#Function that prepares the values to be added to the graph as a URI (ex infront) or Literal&lt;br /&gt;
def prepareValue(row):&lt;br /&gt;
	if row == None: #none type&lt;br /&gt;
		value = Literal(row)&lt;br /&gt;
	elif isinstance(row, str) and re.match(r&#039;\d{4}-\d{2}-\d{2}&#039;, row): #date&lt;br /&gt;
		value = Literal(row, datatype=XSD.date)&lt;br /&gt;
	elif isinstance(row, bool): #boolean value (true / false)&lt;br /&gt;
		value = Literal(row, datatype=XSD.boolean)&lt;br /&gt;
	elif isinstance(row, int): #integer&lt;br /&gt;
		value = Literal(row, datatype=XSD.integer)&lt;br /&gt;
	elif isinstance(row, str): #string&lt;br /&gt;
		value = URIRef(ex + row.replace(&#039;&amp;quot;&#039;, &#039;&#039;).replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;).replace(&amp;quot;,&amp;quot;,&amp;quot;&amp;quot;).replace(&amp;quot;-&amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	elif isinstance(row, float): #float&lt;br /&gt;
		value = Literal(row, datatype=XSD.float)&lt;br /&gt;
&lt;br /&gt;
	return value&lt;br /&gt;
&lt;br /&gt;
#Convert the non-semantic CSV dataset into a semantic RDF &lt;br /&gt;
def csv_to_rdf(df):&lt;br /&gt;
	for index, row in df.iterrows():&lt;br /&gt;
		id = URIRef(ex + &amp;quot;Investigation_&amp;quot; + str(index))&lt;br /&gt;
		investigation = prepareValue(row[&amp;quot;investigation&amp;quot;])&lt;br /&gt;
		investigation_start = prepareValue(row[&amp;quot;investigation-start&amp;quot;])&lt;br /&gt;
		investigation_end = prepareValue(row[&amp;quot;investigation-end&amp;quot;])&lt;br /&gt;
		investigation_days = prepareValue(row[&amp;quot;investigation-days&amp;quot;])&lt;br /&gt;
		indictment_days = prepareValue(row[&amp;quot;indictment-days &amp;quot;])&lt;br /&gt;
		cp_date = prepareValue(row[&amp;quot;cp-date&amp;quot;])&lt;br /&gt;
		cp_days = prepareValue(row[&amp;quot;cp-days&amp;quot;])&lt;br /&gt;
		overturned = prepareValue(row[&amp;quot;overturned&amp;quot;])&lt;br /&gt;
		pardoned = prepareValue(row[&amp;quot;pardoned&amp;quot;])&lt;br /&gt;
		american = prepareValue(row[&amp;quot;american&amp;quot;])&lt;br /&gt;
		outcome = prepareValue(row[&amp;quot;type&amp;quot;])&lt;br /&gt;
		name_ex = prepareValue(row[&amp;quot;name&amp;quot;])&lt;br /&gt;
		president_ex = prepareValue(row[&amp;quot;president&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
		#Spotlight Search&lt;br /&gt;
		name = annotate_entity(str(row[&#039;name&#039;]))&lt;br /&gt;
		president = annotate_entity(str(row[&#039;president&#039;]).replace(&amp;quot;.&amp;quot;, &amp;quot;&amp;quot;))&lt;br /&gt;
		&lt;br /&gt;
		#Adds the tripples to the graph&lt;br /&gt;
		g.add((id, RDF.type, ex.Investigation))&lt;br /&gt;
		g.add((id, ex.investigation, investigation))&lt;br /&gt;
		g.add((id, ex.investigation_start, investigation_start))&lt;br /&gt;
		g.add((id, ex.investigation_end, investigation_end))&lt;br /&gt;
		g.add((id, ex.investigation_days, investigation_days))&lt;br /&gt;
		g.add((id, ex.indictment_days, indictment_days))&lt;br /&gt;
		g.add((id, ex.cp_date, cp_date))&lt;br /&gt;
		g.add((id, ex.cp_days, cp_days))&lt;br /&gt;
		g.add((id, ex.overturned, overturned))&lt;br /&gt;
		g.add((id, ex.pardoned, pardoned))&lt;br /&gt;
		g.add((id, ex.american, american))&lt;br /&gt;
		g.add((id, ex.outcome, outcome))&lt;br /&gt;
&lt;br /&gt;
		#Spotlight search&lt;br /&gt;
		#Name&lt;br /&gt;
		try:&lt;br /&gt;
			g.add((id, ex.person, URIRef(name[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
		except:&lt;br /&gt;
			g.add((id, ex.person, name_ex))&lt;br /&gt;
&lt;br /&gt;
		#President&lt;br /&gt;
		try:&lt;br /&gt;
			g.add((id, ex.president, URIRef(president[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
		except:&lt;br /&gt;
			g.add((id, ex.president, president_ex))&lt;br /&gt;
&lt;br /&gt;
csv_to_rdf(df)&lt;br /&gt;
print(g.serialize())&lt;br /&gt;
g.serialize(&amp;quot;lab7.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=JSON-LD (Lab 8)=&lt;br /&gt;
== Task 1) Basic JSON-LD ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;JSON-LD&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;@context&amp;quot;: {&lt;br /&gt;
        &amp;quot;@base&amp;quot;: &amp;quot;http://example.org/&amp;quot;,&lt;br /&gt;
        &amp;quot;edges&amp;quot;: &amp;quot;http://example.org/triple&amp;quot;,&lt;br /&gt;
        &amp;quot;start&amp;quot;: &amp;quot;http://example.org/source&amp;quot;,&lt;br /&gt;
        &amp;quot;rel&amp;quot;: &amp;quot;http://exaxmple.org/predicate&amp;quot;,&lt;br /&gt;
        &amp;quot;end&amp;quot;: &amp;quot;http://example.org/object&amp;quot;,&lt;br /&gt;
        &amp;quot;Person&amp;quot; : &amp;quot;http://example.org/Person&amp;quot;,&lt;br /&gt;
        &amp;quot;birthday&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/birthday&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot; : &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameEng&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/en/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;en&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameFr&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/fr/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;fr&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameCh&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/ch/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;ch&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;age&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/age&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot; : &amp;quot;xsd:int&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;likes&amp;quot; : &amp;quot;http://example.org/games/likes&amp;quot;,&lt;br /&gt;
        &amp;quot;haircolor&amp;quot; : &amp;quot;http://example.org/games/haircolor&amp;quot;&lt;br /&gt;
    },&lt;br /&gt;
    &amp;quot;@graph&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;1987.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;nameEng&amp;quot; : &amp;quot;Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 26&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;2001.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;nameCh&amp;quot; : &amp;quot;Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 22,&lt;br /&gt;
            &amp;quot;likes&amp;quot; : &amp;quot;bastketball&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;1978.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;haircolor&amp;quot; : &amp;quot;Black&amp;quot;,&lt;br /&gt;
            &amp;quot;nameFr&amp;quot; : &amp;quot;Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 45&lt;br /&gt;
        },&lt;br /&gt;
        {&amp;quot;edges&amp;quot; : [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Louis&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;teaches&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Ju&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;plays&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Jeremy&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;plays&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        }&lt;br /&gt;
        ]}&lt;br /&gt;
    ]&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Task 2 &amp;amp; 3) Retrieving JSON-LD from ConceptNet / Programming JSON-LD in Python ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
CN_BASE = &#039;http://api.conceptnet.io/c/en/&#039;&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
g.parse(CN_BASE+&#039;indictment&#039;, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# To download JSON object:&lt;br /&gt;
&lt;br /&gt;
import json&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
json_obj = requests.get(CN_BASE+&#039;indictment&#039;).json()&lt;br /&gt;
&lt;br /&gt;
# To change the @context:&lt;br /&gt;
&lt;br /&gt;
context = {&lt;br /&gt;
     &amp;quot;@base&amp;quot;: &amp;quot;http://ex.org/&amp;quot;,&lt;br /&gt;
     &amp;quot;edges&amp;quot;: &amp;quot;http://ex.org/triple/&amp;quot;,&lt;br /&gt;
     &amp;quot;start&amp;quot;: &amp;quot;http://ex.org/s/&amp;quot;,&lt;br /&gt;
     &amp;quot;rel&amp;quot;: &amp;quot;http://ex.org/p/&amp;quot;,&lt;br /&gt;
     &amp;quot;end&amp;quot;: &amp;quot;http://ex.org/o/&amp;quot;,&lt;br /&gt;
     &amp;quot;label&amp;quot;: &amp;quot;http://ex.org/label&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
json_obj[&#039;@context&#039;] = context&lt;br /&gt;
json_str = json.dumps(json_obj)&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
g.parse(data=json_str, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# To extract triples (here with labels):&lt;br /&gt;
&lt;br /&gt;
r = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         SELECT ?s ?sLabel ?p ?o ?oLabel WHERE {&lt;br /&gt;
             ?edge&lt;br /&gt;
                 &amp;lt;http://ex.org/s/&amp;gt; ?s ;&lt;br /&gt;
                 &amp;lt;http://ex.org/p/&amp;gt; ?p ;&lt;br /&gt;
                 &amp;lt;http://ex.org/o/&amp;gt; ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
}&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;, initNs={&#039;cn&#039;: CN_BASE})&lt;br /&gt;
print(r.serialize(format=&#039;txt&#039;).decode())&lt;br /&gt;
&lt;br /&gt;
# Construct a new graph:&lt;br /&gt;
&lt;br /&gt;
r = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         CONSTRUCT {&lt;br /&gt;
             ?s ?p ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
         } WHERE {&lt;br /&gt;
             ?edge &amp;lt;http://ex.org/s/&amp;gt; ?s ;&lt;br /&gt;
                   &amp;lt;http://ex.org/p/&amp;gt; ?p ;&lt;br /&gt;
                   &amp;lt;http://ex.org/o/&amp;gt; ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
}&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;, initNs={&#039;cn&#039;: CN_BASE})&lt;br /&gt;
&lt;br /&gt;
print(r.graph.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SHACL (Lab 9)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from pyshacl import validate&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
data_graph = Graph()&lt;br /&gt;
# parses the Turtle example from the task&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
prefixes = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
shape_graph = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
ex:PUI_Shape&lt;br /&gt;
    a sh:NodeShape ;&lt;br /&gt;
    sh:targetClass ex:PersonUnderInvestigation ;&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path foaf:name ;&lt;br /&gt;
        sh:minCount 1 ; #Every person under investigation has exactly one name. &lt;br /&gt;
        sh:maxCount 1 ; #Every person under investigation has exactly one name.&lt;br /&gt;
        sh:datatype rdf:langString ; #All person names must be language-tagged&lt;br /&gt;
    ] ;&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:chargedWith ;&lt;br /&gt;
        sh:nodeKind sh:IRI ; #The object of a charged with property must be a URI.&lt;br /&gt;
        sh:class ex:Offense ; #The object of a charged with property must be an offense.&lt;br /&gt;
    ] .&lt;br /&gt;
&lt;br /&gt;
# --- If you have more time tasks ---&lt;br /&gt;
ex:User_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    # The only allowed values for ex:american are true, false or unknown.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:american;&lt;br /&gt;
        sh:pattern &amp;quot;(true|false|unknown)&amp;quot; ;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # The value of a property that counts days must be an integer.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:indictment_days;&lt;br /&gt;
        sh:datatype xsd:integer;&lt;br /&gt;
    ];   &lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_days;&lt;br /&gt;
        sh:datatype xsd:integer;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # The value of a property that indicates a start date must be xsd:date.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_start;&lt;br /&gt;
        sh:datatype xsd:date;&lt;br /&gt;
    ];&lt;br /&gt;
&lt;br /&gt;
    # The value of a property that indicates an end date must be xsd:date or unknown (tip: you can use sh:or (...) ).&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_end;&lt;br /&gt;
        sh:or (&lt;br /&gt;
         [ sh:datatype xsd:date ]&lt;br /&gt;
         [ sh:hasValue &amp;quot;unknown&amp;quot; ]&lt;br /&gt;
    )];&lt;br /&gt;
    &lt;br /&gt;
    # Every indictment must have exactly one FOAF name for the investigated person.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path foaf:name;&lt;br /&gt;
        sh:minCount 1;&lt;br /&gt;
        sh:maxCount 1;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigatedPerson ;&lt;br /&gt;
        sh:minCount 1 ;&lt;br /&gt;
        sh:maxCount 1 ;&lt;br /&gt;
        sh:class ex:PersonUnderInvestigation ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
    ] ;&lt;br /&gt;
&lt;br /&gt;
    # No URI-s can contain hyphens (&#039;-&#039;).&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:outcome ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
        sh:pattern &amp;quot;^[^-]*$&amp;quot; ;&lt;br /&gt;
    ] ;&lt;br /&gt;
&lt;br /&gt;
    # Presidents must be identified with URIs.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:president ;&lt;br /&gt;
        sh:minCount 1 ;&lt;br /&gt;
        sh:class ex:President ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
    ] .&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
shacl_graph = Graph()&lt;br /&gt;
# parses the contents of a shape_graph you made in the previous task&lt;br /&gt;
shacl_graph.parse(data=prefixes+shape_graph)&lt;br /&gt;
&lt;br /&gt;
# uses pySHACL&#039;s validate method to apply the shape_graph constraints to the data_graph&lt;br /&gt;
results = validate(&lt;br /&gt;
    data_graph,&lt;br /&gt;
    shacl_graph=shacl_graph,&lt;br /&gt;
    inference=&#039;both&#039;&lt;br /&gt;
)&lt;br /&gt;
&lt;br /&gt;
# prints out the validation result&lt;br /&gt;
boolean_value, results_graph, results_text = results&lt;br /&gt;
&lt;br /&gt;
# print(boolean_value)&lt;br /&gt;
print(results_graph.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
# print(results_text)&lt;br /&gt;
&lt;br /&gt;
#Write a SPARQL query to print out each distinct sh:resultMessage in the results_graph&lt;br /&gt;
distinct_messages = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
SELECT DISTINCT ?message WHERE {&lt;br /&gt;
    [] sh:result / sh:resultMessage ?message .&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
messages = results_graph.query(distinct_messages)&lt;br /&gt;
for row in messages:&lt;br /&gt;
    print(row.message)&lt;br /&gt;
&lt;br /&gt;
#each sh:resultMessage in the results_graph once, along with the number of times that message has been repeated in the results&lt;br /&gt;
count_messages = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {&lt;br /&gt;
    [] sh:result ?result .&lt;br /&gt;
    ?result sh:resultMessage ?message ;&lt;br /&gt;
            sh:focusNode ?node .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?message&lt;br /&gt;
ORDER BY DESC(?count) ?message&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
messages = results_graph.query(count_messages)&lt;br /&gt;
for row in messages:&lt;br /&gt;
    print(&amp;quot;COUNT    MESSAGE&amp;quot;)&lt;br /&gt;
    print(row.num_messages, &amp;quot;      &amp;quot;, row.message)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDFS (Lab 10)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, Literal, XSD, FOAF, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
NS = {&lt;br /&gt;
    &#039;ex&#039;: ex,&lt;br /&gt;
    &#039;rdf&#039;: RDF,&lt;br /&gt;
    &#039;rdfs&#039;: RDFS,&lt;br /&gt;
    &#039;foaf&#039;: FOAF,&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Write a small function that computes the RDFS closure on your graph.&lt;br /&gt;
def flush():&lt;br /&gt;
    engine = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
    engine.closure()&lt;br /&gt;
    engine.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
#Rick Gates was charged with money laundering and tax evasion.&lt;br /&gt;
g.add((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
&lt;br /&gt;
#When one thing that is charged with another thing,&lt;br /&gt;
g.add((ex.chargedWith, RDFS.domain, ex.PersonUnderInvestigation))  #the first thing (subject) is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing (object) is an offense.&lt;br /&gt;
&lt;br /&gt;
#Write a SPARQL query that checks the RDF type(s) of Rick Gates and money laundering in your RDF graph.&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
#A person under investigation is a FOAF person&lt;br /&gt;
g.add((ex.PersonUnderInvestigation, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
#Paul Manafort was convicted for tax evasion.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxEvasion))&lt;br /&gt;
#the first thing is also charged with the second thing&lt;br /&gt;
g.add((ex.convictedFor, RDFS.subPropertyOf, ex.chargedWith)) &lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize())&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=OWL 1 (Lab 11)=&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, RDFS, Namespace, RDF, FOAF, BNode, OWL, URIRef, Literal, XSD&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&#039;http://schema.org/&#039;)&lt;br /&gt;
dbr = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
# g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# Donald Trump and Robert Mueller are two different persons.&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.differentFrom, ex.Robert_Mueller))&lt;br /&gt;
&lt;br /&gt;
# Actually, all the names mentioned in connection with the Mueller investigation refer to different people.&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Robert_Mueller, ex.Paul_Manafort, ex.Rick_Gates, ex.George_Papadopoulos, ex.Michael_Flynn, ex.Michael_Cohen, ex.Roger_Stone, ex.Donald_Trump])&lt;br /&gt;
g.add((b1, RDF.type, OWL.AllDifferent))&lt;br /&gt;
g.add((b1, OWL.distinctMembers, b2))&lt;br /&gt;
&lt;br /&gt;
# All these people are foaf:Persons as well as schema:Persons&lt;br /&gt;
g.add((FOAF.Person, OWL.equivalentClass, schema.Person))&lt;br /&gt;
&lt;br /&gt;
# Tax evation is a kind of bank and tax fraud.&lt;br /&gt;
g.add((ex.TaxEvation, RDFS.subClassOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.TaxEvation, RDFS.subClassOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# The Donald Trump involved in the Mueller investigation is dbpedia:Donald_Trump and not dbpedia:Donald_Trump_Jr.&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.sameAs, dbr.Donald_Trump))&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.differentFrom, URIRef(dbr + &amp;quot;Donald_Trump_Jr.&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Congress, FBI and the Mueller investigation are foaf:Organizations.&lt;br /&gt;
g.add((ex.Congress, RDF.type, FOAF.Organization))&lt;br /&gt;
g.add((ex.FBI, RDF.type, FOAF.Organization))&lt;br /&gt;
g.add((ex.Mueller_Investigation, RDF.type, FOAF.Organization))&lt;br /&gt;
&lt;br /&gt;
# Nothing can be both a person and an organization.&lt;br /&gt;
g.add((FOAF.Person, OWL.disjointWith, FOAF.Organization))&lt;br /&gt;
&lt;br /&gt;
# Leading an organization is a way of being involved in an organization.&lt;br /&gt;
g.add((ex.leading, RDFS.subPropertyOf, ex.involved))&lt;br /&gt;
&lt;br /&gt;
# Being a campaign manager or an advisor for is a way of supporting someone.&lt;br /&gt;
g.add((ex.campaignManagerTo, RDFS.subPropertyOf, ex.supports))&lt;br /&gt;
g.add((ex.advisorTo, RDFS.subPropertyOf, ex.supports))&lt;br /&gt;
&lt;br /&gt;
# Donald Trump is a politician and a Republican.&lt;br /&gt;
g.add((ex.Donald_Trump, RDF.type, ex.Politician))&lt;br /&gt;
g.add((ex.Donald_Trump, RDF.type, ex.Republican))&lt;br /&gt;
&lt;br /&gt;
# A Republican politician is both a politician and a Republican.&lt;br /&gt;
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Politician))&lt;br /&gt;
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Republican))&lt;br /&gt;
&lt;br /&gt;
#hasBusinessPartner&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.hasBusinessPartner, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.hasBusinessPartner, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.hasBusinessPartner, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
#adviserTo&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.adviserTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
# Not necessarily asymmetric as it&#039;s not a given that they couldn&#039;t be advisors to each other  &lt;br /&gt;
&lt;br /&gt;
#wasLyingTo&lt;br /&gt;
g.add((ex.Rick_Gates_Lying, ex.wasLyingTo, ex.FBI))&lt;br /&gt;
g.add((ex.wasLyingTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
# Not asymmetric as the subject and object could lie to each other; also in this context, the FBI can lie to you&lt;br /&gt;
&lt;br /&gt;
#presidentOf&lt;br /&gt;
g.add((ex.Donald_Trump, ex.presidentOf, ex.USA))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.FunctionalProperty)) #can only be president of one country&lt;br /&gt;
#not inversefunctionalproperty as Bosnia has 3 presidents https://www.culturalworld.org/do-any-countries-have-more-than-one-president.htm&lt;br /&gt;
&lt;br /&gt;
#hasPresident&lt;br /&gt;
g.add((ex.USA, ex.hasPresident, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.InverseFunctionalProperty)) #countries do not share their president with another&lt;br /&gt;
#not functionalproperty as a country (Bosnia) can have more than one president&lt;br /&gt;
&lt;br /&gt;
#Closure&lt;br /&gt;
owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)&lt;br /&gt;
&lt;br /&gt;
#Serialization&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab8.xml&amp;quot;, format=&amp;quot;xml&amp;quot;) #serializes to XML file&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=OWL 2 (Lab 12)=&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@prefix : &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
@prefix dc: &amp;lt;http://purl.org/dc/terms#&amp;gt; .&lt;br /&gt;
@prefix io: &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
@prefix dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt; .&lt;br /&gt;
@prefix owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
@prefix xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix prov: &amp;lt;http://www.w3.org/ns/prov#&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
@base &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
&amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology&amp;gt; rdf:type owl:Ontology .&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Object Properties&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#indictedIn&lt;br /&gt;
io:indictedIn rdf:type owl:ObjectProperty ;&lt;br /&gt;
              rdfs:subPropertyOf io:involvedIn ;&lt;br /&gt;
              rdfs:domain io:InvestigatedPerson ;&lt;br /&gt;
              rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#investigating&lt;br /&gt;
io:investigating rdf:type owl:ObjectProperty ;&lt;br /&gt;
                 rdfs:subPropertyOf io:involvedIn ;&lt;br /&gt;
                 rdfs:domain io:Investigator ;&lt;br /&gt;
                 rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#involvedIn&lt;br /&gt;
io:involvedIn rdf:type owl:ObjectProperty ;&lt;br /&gt;
              rdfs:domain foaf:Person ;&lt;br /&gt;
              rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#leading&lt;br /&gt;
io:leading rdf:type owl:ObjectProperty ;&lt;br /&gt;
           rdfs:subPropertyOf io:investigating ;&lt;br /&gt;
           rdfs:domain io:InvestigationLeader ;&lt;br /&gt;
           rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Data properties&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://purl.org/dc/elements/1.1/description&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/description&amp;gt; rdf:type owl:DatatypeProperty ;&lt;br /&gt;
                                              rdfs:domain io:Investigation ;&lt;br /&gt;
                                              rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.w3.org/ns/prov#endedAtTime&lt;br /&gt;
prov:endedAtTime rdf:type owl:DatatypeProperty ,&lt;br /&gt;
                          owl:FunctionalProperty ;&lt;br /&gt;
                 rdfs:domain io:Investigation ;&lt;br /&gt;
                 rdfs:range xsd:dateTime .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.w3.org/ns/prov#startedAtTime&lt;br /&gt;
prov:startedAtTime rdf:type owl:DatatypeProperty ,&lt;br /&gt;
                            owl:FunctionalProperty ;&lt;br /&gt;
                   rdfs:domain io:Investigation ;&lt;br /&gt;
                   rdfs:range xsd:dateTime .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/name&lt;br /&gt;
foaf:name rdf:type owl:DatatypeProperty ;&lt;br /&gt;
          rdfs:domain foaf:Person ;&lt;br /&gt;
          rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/title&lt;br /&gt;
foaf:title rdf:type owl:DatatypeProperty ;&lt;br /&gt;
           rdfs:domain io:Investigation ;&lt;br /&gt;
           rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Classes&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigatedPerson&lt;br /&gt;
io:InvestigatedPerson rdf:type owl:Class ;&lt;br /&gt;
                      rdfs:subClassOf io:Person ;&lt;br /&gt;
                      owl:disjointWith io:Investigator .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation&lt;br /&gt;
io:Investigation rdf:type owl:Class .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigationLeader&lt;br /&gt;
io:InvestigationLeader rdf:type owl:Class ;&lt;br /&gt;
                       rdfs:subClassOf io:Investigator .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigator&lt;br /&gt;
io:Investigator rdf:type owl:Class ;&lt;br /&gt;
                rdfs:subClassOf io:Person .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Person&lt;br /&gt;
io:Person rdf:type owl:Class ;&lt;br /&gt;
          rdfs:subClassOf foaf:Person .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/Person&lt;br /&gt;
foaf:Person rdf:type owl:Class .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Individuals&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Donald_Trump&lt;br /&gt;
dbr:Donald_Trump rdf:type owl:NamedIndividual ;&lt;br /&gt;
                 foaf:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Elizabeth_Prelogar&lt;br /&gt;
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ;&lt;br /&gt;
                       io:investigating &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                       foaf:name &amp;quot;Elizabeth Prelogar&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Michael_Flynn&lt;br /&gt;
dbr:Michael_Flynn rdf:type owl:NamedIndividual ;&lt;br /&gt;
                  foaf:name &amp;quot;Michael Flynn&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Paul_Manafort&lt;br /&gt;
dbr:Paul_Manafort rdf:type owl:NamedIndividual ;&lt;br /&gt;
                  io:indictedIn &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                  foaf:name &amp;quot;Paul Manafort&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Robert_Mueller&lt;br /&gt;
dbr:Robert_Mueller rdf:type owl:NamedIndividual ;&lt;br /&gt;
                   io:leading &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                   foaf:name &amp;quot;Robert Mueller&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Roger_Stone&lt;br /&gt;
dbr:Roger_Stone rdf:type owl:NamedIndividual ;&lt;br /&gt;
                foaf:name &amp;quot;Roger Stone&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                                        foaf:title &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    General axioms&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
[ rdf:type owl:AllDifferent ;&lt;br /&gt;
  owl:distinctMembers ( dbr:Donald_Trump&lt;br /&gt;
                        dbr:Elizabeth_Prelogar&lt;br /&gt;
                        dbr:Michael_Flynn&lt;br /&gt;
                        dbr:Paul_Manafort&lt;br /&gt;
                        dbr:Robert_Mueller&lt;br /&gt;
                        dbr:Roger_Stone&lt;br /&gt;
                      )&lt;br /&gt;
] .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  Generated by the OWL API (version 4.5.25.2023-02-15T19:15:49Z) https://github.com/owlcs/owlapi&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Using Graph Embeddings (Lab 13)=&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1WkRJUeUBVF5yVv7o0pOKfsd4pqG6369k&lt;br /&gt;
&lt;br /&gt;
=Training Graph Embeddings (Lab 14)=&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q&lt;br /&gt;
 --&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=INFO216_Wiki&amp;diff=2719</id>
		<title>INFO216 Wiki</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=INFO216_Wiki&amp;diff=2719"/>
		<updated>2026-01-07T15:34:25Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This wiki contains resources related to the course &#039;&#039;INFO216: Knowledge Graphs&#039;&#039;. See also the course pages in &lt;br /&gt;
[https://mitt.uib.no/courses/46884 the study portal &amp;lt;https://mitt.uib.no&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;These are the wiki pages from 2024 and 2025. There will be changes for 2026, and the pages will be updated continuously as the course progresses.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
* [[Readings]] for each lecture&lt;br /&gt;
* [[Examples from the lectures]]&lt;br /&gt;
* [[Python Labs | Lab exercises]]&lt;br /&gt;
* [[Lab Solutions | Lab solutions]]&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2025, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2584</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2584"/>
		<updated>2024-05-20T09:40:36Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: /* For each president, list the numbers of convictions and of pardons made */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present suggested solutions after each lab. &#039;&#039;The page will be updated as the course progresses&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
=Getting started (Lab 1)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# The Mueller Investigation was lead by Robert Mueller&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))&lt;br /&gt;
&lt;br /&gt;
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))&lt;br /&gt;
&lt;br /&gt;
# Paul Manafort was business partner of Rick Gates&lt;br /&gt;
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))&lt;br /&gt;
&lt;br /&gt;
# He was campaign chairman for Donald Trump&lt;br /&gt;
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy and lying to FBI.&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;)) # To screen&lt;br /&gt;
#g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) # To file&lt;br /&gt;
&lt;br /&gt;
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate&lt;br /&gt;
for subject, object in g[ : ex.pleadGuiltyTo :]:&lt;br /&gt;
    print(subject, ex.pleadGuiltyTo, object)&lt;br /&gt;
&lt;br /&gt;
# --- IF you have more time tasks ---&lt;br /&gt;
&lt;br /&gt;
# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that submits your model for rendering and saves the returned image to file.&lt;br /&gt;
import requests&lt;br /&gt;
import shutil&lt;br /&gt;
&lt;br /&gt;
def graphToImage(graphInput):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graphInput, &amp;quot;from&amp;quot;:&amp;quot;ttl&amp;quot;, &amp;quot;to&amp;quot;:&amp;quot;png&amp;quot;}&lt;br /&gt;
    link = &amp;quot;http://www.ldf.fi/service/rdf-grapher&amp;quot;&lt;br /&gt;
    response = requests.get(link, params = data, stream=True)&lt;br /&gt;
    # print(response.content)&lt;br /&gt;
    print(response.raw)&lt;br /&gt;
    with open(&amp;quot;lab1.png&amp;quot;, &amp;quot;wb&amp;quot;) as file:&lt;br /&gt;
        shutil.copyfileobj(response.raw, file)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDF programming with RDFlib (Lab 2)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Getting the graph created in the first lab&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
# Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to Congress.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
# Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to the FBI.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Change your graph so it represents instances of lying as blank nodes.&lt;br /&gt;
# Remove the triples that will be duplicated&lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI)) &lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.remove((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
FlynnLying = BNode() &lt;br /&gt;
g.add((FlynnLying, ex.crime, ex.LyingToFBI))&lt;br /&gt;
g.add((FlynnLying, ex.pleadGulityOn, Literal(&amp;quot;2017-12-1&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((FlynnLying, ex.liedAbout, Literal(&amp;quot;His communications with a former Russian ambassador during the presidential transition&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((FlynnLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, FlynnLying))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
GatesLying = BNode()&lt;br /&gt;
Crimes = BNode()&lt;br /&gt;
Charged = BNode()&lt;br /&gt;
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])&lt;br /&gt;
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])&lt;br /&gt;
g.add((GatesLying, ex.crime, Crimes))&lt;br /&gt;
g.add((GatesLying, ex.chargedWith, Charged))&lt;br /&gt;
g.add((GatesLying, ex.pleadGulityOn, Literal(&amp;quot;2018-02-23&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((GatesLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, GatesLying))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
CohenLying = BNode()&lt;br /&gt;
g.add((CohenLying, ex.crime, ex.LyingToCongress))&lt;br /&gt;
g.add((CohenLying, ex.liedAbout, ex.TrumpRealEstateDeal))&lt;br /&gt;
g.add((CohenLying, ex.prosecutorsAlleged, Literal(&amp;quot;In an August 2017 letter Cohen sent to congressional committees investigating Russian election interference, he falsely stated that the project ended in January 2016&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.mullerInvestigationAlleged, Literal(&amp;quot;Cohen falsely stated that he had never agreed to travel to Russia for the real estate deal and that he did not recall any contact with the Russian government about the project&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.pleadGulityOn, Literal(&amp;quot;2018-11-29&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((CohenLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, CohenLying))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
#Save (serialize) your graph to a Turtle file.&lt;br /&gt;
# g.serialize(&amp;quot;lab2.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
#Add a few triples to the Turtle file with more information about Donald Trump.&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:postalCode 33480 ;&lt;br /&gt;
            ex:residence ex:Mar_a_Lago ;&lt;br /&gt;
            ex:state ex:Florida ;&lt;br /&gt;
            ex:streetName &amp;quot;1100 S Ocean Blvd&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:previousAddress [ ex:city ex:Washington_DC ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:phoneNumber &amp;quot;1 202 456 1414&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:postalCode &amp;quot;20500&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:residence ex:The_White_House ;&lt;br /&gt;
            ex:streetName &amp;quot;1600 Pennsylvania Ave.&amp;quot;^^xsd:string ];&lt;br /&gt;
    ex:marriedTo ex:Melania_Trump;&lt;br /&gt;
    ex:fatherTo (ex:Ivanka_Trump ex:Donald_Trump_Jr ex: ex:Tiffany_Trump ex:Eric_Trump ex:Barron_Trump).&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
#Read (parse) the Turtle file back into a Python program, and check that the new triples are there&lt;br /&gt;
def serialize_Graph():&lt;br /&gt;
    newGraph = Graph()&lt;br /&gt;
    newGraph.parse(&amp;quot;lab2.ttl&amp;quot;)&lt;br /&gt;
    print(newGraph.serialize())&lt;br /&gt;
&lt;br /&gt;
#Don&#039;t need this to run until after adding the triples above to the ttl file&lt;br /&gt;
# serialize_Graph() &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that starts with Donald Trump prints out a graph depth-first to show how the other graph nodes are connected to him&lt;br /&gt;
visited_nodes = set()&lt;br /&gt;
&lt;br /&gt;
def create_Tree(model, nodes):&lt;br /&gt;
    #Traverse the model breadth-first to create the tree.&lt;br /&gt;
    global visited_nodes&lt;br /&gt;
    tree = Graph()&lt;br /&gt;
    children = set()&lt;br /&gt;
    visited_nodes |= set(nodes)&lt;br /&gt;
    for s, p, o in model:&lt;br /&gt;
        if s in nodes and o not in visited_nodes:&lt;br /&gt;
            tree.add((s, p, o))&lt;br /&gt;
            visited_nodes.add(o)&lt;br /&gt;
            children.add(o)&lt;br /&gt;
        if o in nodes and s not in visited_nodes:&lt;br /&gt;
            invp = URIRef(f&#039;{p}_inv&#039;) #_inv represents inverse of&lt;br /&gt;
            tree.add((o, invp, s))&lt;br /&gt;
            visited_nodes.add(s)&lt;br /&gt;
            children.add(s)&lt;br /&gt;
    if len(children) &amp;gt; 0:&lt;br /&gt;
        children_tree = create_Tree(model, children)&lt;br /&gt;
        for triple in children_tree:&lt;br /&gt;
            tree.add(triple)&lt;br /&gt;
    return tree&lt;br /&gt;
&lt;br /&gt;
def print_Tree(tree, root, indent=0):&lt;br /&gt;
    #Print the tree depth-first.&lt;br /&gt;
    print(str(root))&lt;br /&gt;
    for s, p, o in tree:&lt;br /&gt;
        if s==root:&lt;br /&gt;
            print(&#039;    &#039;*indent + &#039;  &#039; + str(p), end=&#039; &#039;)&lt;br /&gt;
            print_Tree(tree, o, indent+1)&lt;br /&gt;
    &lt;br /&gt;
tree = create_Tree(g, [ex.Donald_Trump])&lt;br /&gt;
print_Tree(tree, ex.Donald_Trump)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL (Lab 3-4)=&lt;br /&gt;
===List all triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the first 100 triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT (COUNT(*) as ?count)&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of indictments===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT (COUNT(?ind) as ?amount)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:outcome ?ind;&lt;br /&gt;
      ns1:outcome ns1:indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who pleaded guilty, along with the name of the investigation===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?invname&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:investigation ?invname;&lt;br /&gt;
      ns1:outcome ns1:guilty-plea .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who were convicted, but who had their conviction overturned by which president===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?president&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:president ?president;&lt;br /&gt;
      ns1:outcome ns1:conviction;&lt;br /&gt;
      ns1:overturned ns1:true.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
ORDER BY DESC(?count)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each president, list the numbers of convictions and of pardons made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as&lt;br /&gt;
?pardons)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:president ?president;&lt;br /&gt;
      ns1:outcome ?outcome ;&lt;br /&gt;
      ns1:outcome ns1:conviction.&lt;br /&gt;
      OPTIONAL{&lt;br /&gt;
         ?s ns1:pardoned ?pardon .&lt;br /&gt;
         FILTER (?pardon = true)&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?president&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Rename mullerkg:name to something like muellerkg:person===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE{?s ns1:name ?o}&lt;br /&gt;
INSERT{?s ns1:person ?o}&lt;br /&gt;
WHERE {?s ns1:name ?o}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Persons&lt;br /&gt;
INSERT {?person foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:person ?person .&lt;br /&gt;
      BIND(REPLACE(STR(?person), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Presidents&lt;br /&gt;
INSERT {?president foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:president ?president .&lt;br /&gt;
      BIND(REPLACE(STR(?president), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use INSERT DATA updates to add these triples===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
     ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:pleadGuiltyTo ns1:LyingToFBI;&lt;br /&gt;
         ns1:sentencedTo ns1:Prison.&lt;br /&gt;
&lt;br /&gt;
     ns1:Roger_Stone a ns1:Republican;&lt;br /&gt;
         ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:officialTo ns1:Trump_Campaign;&lt;br /&gt;
         ns1:interactedWith ns1:Wikileaks;&lt;br /&gt;
         ns1:providedTestimony ns1:House_Intelligence_Committee;&lt;br /&gt;
         ns1:clearedOf ns1:AllCharges.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test if added&lt;br /&gt;
SELECT ?p ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                      ns1:WitnessTampering,&lt;br /&gt;
                                      ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#The task specifically requested DELETE DATA &amp;amp; INSERT DATA, put below is&lt;br /&gt;
a more efficient solution&lt;br /&gt;
&lt;br /&gt;
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
INSERT{&lt;br /&gt;
   ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                   ns1:WitnessTampering,&lt;br /&gt;
                                   ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a DESCRIBE query to show the updated information about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o.&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone.&lt;br /&gt;
}&lt;br /&gt;
WHERE {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o .&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a DELETE/INSERT statement to change one of the prefixes in your graph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX dbp: &amp;lt;https://dbpedia.org/page/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:person ?o1}&lt;br /&gt;
INSERT {?s ns1:person ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:person ?o1 .&lt;br /&gt;
   BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#This update changes the object in triples with ns1:person as the&lt;br /&gt;
predicate. It changes it&#039;s prefix of ns1 (which is the&lt;br /&gt;
&amp;quot;shortcut/shorthand&amp;quot; for example.org) to the prefix dbp (dbpedia.org)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write an INSERT statement to add at least one significant date to the Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT statement to change the date to a string, and a new DELETE/INSERT statement to change it back to xsd:date. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
#Whilst this solution is not exactly what the task asks for, I feel like&lt;br /&gt;
this is more appropiate given the dataset. The following update&lt;br /&gt;
changes the objects that uses the cp_date as predicate from a URI, to a&lt;br /&gt;
literal with date as it&#039;s datatype&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o3}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (replace(str(?o), str(ns1:), &amp;quot;&amp;quot;)  AS ?o2)&lt;br /&gt;
   BIND (STRDT(STR(?o2), xsd:date) AS ?o3)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test:&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o.&lt;br /&gt;
   FILTER(datatype(?o) = xsd:date)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To change it to an integer, use the following code, and to change it&lt;br /&gt;
back to date, swap &amp;quot;xsd:integer&amp;quot; to &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (STRDT(STR(?o), xsd:integer) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL Programming (Lab 5)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace, RDF, FOAF&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;Russia_investigation_kg.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# ----- RDFLIB -----&lt;br /&gt;
ex = Namespace(&#039;http://example.org#&#039;)&lt;br /&gt;
&lt;br /&gt;
NS = {&lt;br /&gt;
    &#039;&#039;: ex,&lt;br /&gt;
    &#039;rdf&#039;: RDF,&lt;br /&gt;
    &#039;foaf&#039;: FOAF,&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
# Print out a list of all the predicates used in your graph.&lt;br /&gt;
task1 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT DISTINCT ?p WHERE{&lt;br /&gt;
    ?s ?p ?o .&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(list(task1))&lt;br /&gt;
&lt;br /&gt;
# Print out a sorted list of all the presidents represented in your graph.&lt;br /&gt;
task2 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT DISTINCT ?president WHERE{&lt;br /&gt;
    ?s :president ?president .&lt;br /&gt;
}&lt;br /&gt;
ORDER BY ?president&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(list(task2))&lt;br /&gt;
&lt;br /&gt;
# Create dictionary (Python dict) with all the represented presidents as keys. For each key, the value is a list of names of people indicted under that president.&lt;br /&gt;
task3_dic = {}&lt;br /&gt;
&lt;br /&gt;
task3 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
SELECT ?president ?person WHERE{&lt;br /&gt;
    ?s :president ?president;&lt;br /&gt;
       :name ?person;&lt;br /&gt;
       :outcome :indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
for president, person in task3:&lt;br /&gt;
    if president not in task3_dic:&lt;br /&gt;
        task3_dic[president] = [person]&lt;br /&gt;
    else:&lt;br /&gt;
        task3_dic[president].append(person)&lt;br /&gt;
&lt;br /&gt;
print(task3_dic)&lt;br /&gt;
&lt;br /&gt;
# Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.&lt;br /&gt;
&lt;br /&gt;
# This task is a lot trickier than it needs to be. As far as I&#039;m aware RDFLib has no HAVING support, so a query like this:&lt;br /&gt;
task4 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
ASK {&lt;br /&gt;
  	SELECT (COUNT(?s) as ?count) WHERE{&lt;br /&gt;
    	?s :pardoned :true;&lt;br /&gt;
   	   :president :Bill_Clinton  .&lt;br /&gt;
    }&lt;br /&gt;
    HAVING (?count &amp;gt; 5)&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(task4.askAnswer)&lt;br /&gt;
&lt;br /&gt;
# Which works fine in Blazegraph and is a valid SPARQL query will always provide false in RDFLib cause it uses HAVING. &lt;br /&gt;
# Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons,&lt;br /&gt;
# so I have instead chosen Bill Clinton with 13 to check if the query works. &lt;br /&gt;
&lt;br /&gt;
task4 = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    ASK{&lt;br /&gt;
        SELECT ?count WHERE{{&lt;br /&gt;
  	        SELECT (COUNT(?s) as ?count) WHERE{&lt;br /&gt;
    	        ?s :pardoned :true;&lt;br /&gt;
                   :president :Bill_Clinton  .&lt;br /&gt;
                }}&lt;br /&gt;
        FILTER (?count &amp;gt; 5) &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
print(task4.askAnswer)&lt;br /&gt;
&lt;br /&gt;
# Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.&lt;br /&gt;
&lt;br /&gt;
# By all accounts, it seems DESCRIBE querires are yet to be implemented in RDFLib, but they are attempting to implement it:&lt;br /&gt;
# https://github.com/RDFLib/rdflib/pull/2221 &amp;lt;--- Issue and proposed solution rasied&lt;br /&gt;
# https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 &amp;lt;--- Solution commited to RDFLib&lt;br /&gt;
# This solution does not work. However, this proposed solution should work if DESCRIBE is implemented in RDFLib&lt;br /&gt;
&lt;br /&gt;
# task5 = g.query(&amp;quot;&amp;quot;&amp;quot; &lt;br /&gt;
# DESCRIBE :Donald_Trump&lt;br /&gt;
# &amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
# print(task5.serialize())&lt;br /&gt;
&lt;br /&gt;
# ----- SPARQLWrapper -----&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039; #Might need to replace this&lt;br /&gt;
REPOSITORY = &#039;Labs&#039; #Replace with your repository name&lt;br /&gt;
&lt;br /&gt;
# Query Endpoint&lt;br /&gt;
sparql = SPARQLWrapper(f&#039;{SERVER}/repositories/{REPOSITORY}&#039;) &lt;br /&gt;
# Update Endpoint&lt;br /&gt;
sparqlUpdate = SPARQLWrapper(f&#039;{SERVER}/repositories/{REPOSITORY}/statements&#039;)&lt;br /&gt;
&lt;br /&gt;
# Ask whether there was an ongoing indictment on the date 1990-01-01.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    ASK {&lt;br /&gt;
        SELECT ?end ?start&lt;br /&gt;
        WHERE{&lt;br /&gt;
            ?s ns1:investigation_end ?end;&lt;br /&gt;
               ns1:investigation_start ?start;&lt;br /&gt;
               ns1:outcome ns1:indictment.&lt;br /&gt;
            FILTER(?start &amp;lt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date &amp;amp;&amp;amp; ?end &amp;gt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date) &lt;br /&gt;
	    }&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(f&amp;quot;Are there any investigation on the 1990-01-01: {results[&#039;boolean&#039;]}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# List ongoing indictments on that date 1990-01-01.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    SELECT ?s&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation_end ?end;&lt;br /&gt;
           ns1:investigation_start ?start;&lt;br /&gt;
           ns1:outcome ns1:indictment.&lt;br /&gt;
        FILTER(?start &amp;lt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date &amp;amp;&amp;amp; ?end &amp;gt;= &amp;quot;1990-01-01&amp;quot;^^xsd:date) &lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
print(&amp;quot;The ongoing investigations on the 1990-01-01 are:&amp;quot;)&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;s&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
# Describe investigation number 100 (muellerkg:investigation_100).&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    DESCRIBE ns1:investigation_100&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(TURTLE)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
print(results)&lt;br /&gt;
&lt;br /&gt;
# Print out a list of all the types used in your graph.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT DISTINCT ?types&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s rdf:type ?types . &lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
rdf_Types = []&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    rdf_Types.append(result[&amp;quot;types&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
print(rdf_Types)&lt;br /&gt;
&lt;br /&gt;
# Update the graph to that every resource that is an object in a muellerkg:investigation triple has the rdf:type muellerkg:Investigation.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?invest rdf:type ns1:Investigation .&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation ?invest .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#To Test&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    ASK{&lt;br /&gt;
        ns1:watergate rdf:type ns1:Investigation.&lt;br /&gt;
    }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
print(results[&#039;boolean&#039;])&lt;br /&gt;
&lt;br /&gt;
# Update the graph to that every resource that is an object in a muellerkg:person triple has the rdf:type muellerkg:IndictedPerson.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?person rdf:type ns1:IndictedPerson .&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:name ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson&lt;br /&gt;
&lt;br /&gt;
# Update the graph so all the investigation nodes (such as muellerkg:watergate) become the subject in a dc:title triple with the corresponding string (watergate) as the literal.&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX dc: &amp;lt;http://purl.org/dc/elements/1.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?invest dc:title ?investString.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:investigation ?invest .&lt;br /&gt;
        BIND (replace(str(?invest), str(ns1:), &amp;quot;&amp;quot;)  AS ?investString)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparqlUpdate.setQuery(update_str)&lt;br /&gt;
sparqlUpdate.setMethod(POST)&lt;br /&gt;
sparqlUpdate.query()&lt;br /&gt;
&lt;br /&gt;
#Same test as above, replace it with e.g. ns1:watergate dc:title &amp;quot;watergate&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# Print out a sorted list of all the indicted persons represented in your graph.&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
    PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?name&lt;br /&gt;
    WHERE{&lt;br /&gt;
    ?s  ns1:name ?name;&lt;br /&gt;
            ns1:outcome ns1:indictment.&lt;br /&gt;
    }&lt;br /&gt;
    ORDER BY ?name&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
names = []&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    names.append(result[&amp;quot;name&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
print(names)&lt;br /&gt;
&lt;br /&gt;
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{&lt;br /&gt;
        ?s  ns1:indictment_days ?days;&lt;br /&gt;
            ns1:outcome ns1:indictment.&lt;br /&gt;
    &lt;br /&gt;
    BIND (replace(str(?days), str(ns1:), &amp;quot;&amp;quot;)  AS ?daysR)&lt;br /&gt;
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(f&#039;The longest an investigation lasted was: {result[&amp;quot;max&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
    print(f&#039;The shortest an investigation lasted was: {result[&amp;quot;min&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
    print(f&#039;The average investigation lasted: {result[&amp;quot;avg&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
&lt;br /&gt;
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
    PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{&lt;br /&gt;
    ?s  ns1:indictment_days ?days;&lt;br /&gt;
        ns1:outcome ns1:indictment;&lt;br /&gt;
        ns1:investigation ?investigation.&lt;br /&gt;
    &lt;br /&gt;
    BIND (replace(str(?days), str(ns1:), &amp;quot;&amp;quot;)  AS ?daysR)&lt;br /&gt;
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)&lt;br /&gt;
    }&lt;br /&gt;
    GROUP BY ?investigation&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
sparql.setReturnFormat(JSON)&lt;br /&gt;
results = sparql.query().convert()&lt;br /&gt;
&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(f&#039;{result[&amp;quot;investigation&amp;quot;][&amp;quot;value&amp;quot;]} - min: {result[&amp;quot;min&amp;quot;][&amp;quot;value&amp;quot;]}, max: {result[&amp;quot;max&amp;quot;][&amp;quot;value&amp;quot;]}, avg: {result[&amp;quot;avg&amp;quot;][&amp;quot;value&amp;quot;]}&#039;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Wikidata SPARQL (Lab 6)=&lt;br /&gt;
===Use a DESCRIBE query to retrieve some triples about your entity===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
DESCRIBE wd:Q42 LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a SELECT query to retrieve the first 100 triples about your entity===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
  wd:Q42 ?p ?o .&lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a local SELECT query that embeds a SERVICE query to retrieve the first 100 triples about your entity to your local machine===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
            wd:Q42 ?p ?o .&lt;br /&gt;
        } LIMIT 100&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
} WHERE {&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
            wd:Q42 ?p ?o .&lt;br /&gt;
        } LIMIT 100&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a FILTER statement to only SELECT primary triples in this sense.===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use Wikidata&#039;s in-built SERVICE wikibase:label to get labels for all the object resources===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE xsd:string.===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (&lt;br /&gt;
      STRSTARTS(STR(?o), STR(wd:)) ||  # comment out this whole line to see only string literals!&lt;br /&gt;
      DATATYPE(?o) = xsd:string&lt;br /&gt;
    )&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Relax the FILTER expression again so it also returns triples with these three predicates (rdfs:label, skos:altLabel and schema:description) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (&lt;br /&gt;
      (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;  # comment out these three lines to see only fingerprint literals!&lt;br /&gt;
       STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
      ||&lt;br /&gt;
      (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
       DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
    )&lt;br /&gt;
 &lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Try to restrict the FILTER expression again so that, when the predicate is rdfs:label, skos:altLabel and schema:description, the object must have LANG &amp;quot;en&amp;quot; ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
        wd:Q42 ?p ?o .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
          (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
          ||&lt;br /&gt;
          (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
           DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 100&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
  wd:Q42 ?p ?o .&lt;br /&gt;
  ?o rdfs:label ?oLabel .&lt;br /&gt;
} WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p ?oLabel ?o WHERE {&lt;br /&gt;
        wd:Q42 ?p ?o .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
          (STRSTARTS(STR(?p), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)&lt;br /&gt;
          ||&lt;br /&gt;
          (?p IN (rdfs:label, skos:altLabel, schema:description) &amp;amp;&amp;amp;&lt;br /&gt;
           DATATYPE(?o) = rdf:langString &amp;amp;&amp;amp; LANG(?o) = &amp;quot;en&amp;quot;)&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 500&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If you have more time ==&lt;br /&gt;
===You must therefore REPLACE all wdt: prefixes of properties with wd: prefixes and BIND the new URI AS a new variable, for example ?pw. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?pwLabel ?oLabel WHERE {&lt;br /&gt;
    wd:Q42 ?p ?o .&lt;br /&gt;
 &lt;br /&gt;
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))&lt;br /&gt;
    FILTER (STRSTARTS(STR(?o), STR(wd:)))&lt;br /&gt;
 &lt;br /&gt;
    BIND (IRI(REPLACE(STR(?p), STR(wdt:), STR(wd:))) AS ?pw)&lt;br /&gt;
&lt;br /&gt;
    SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
 &lt;br /&gt;
} LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Now you can go back to the SELECT statement that returned primary triples with only resource objects (not literal objects or fingerprints). Extend it so it also includes primary triples &amp;quot;one step out&amp;quot;, i.e., triples where the subjects are objects of triples involving your reference entity. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wikibase: &amp;lt;http://wikiba.se/ontology#&amp;gt;&lt;br /&gt;
PREFIX bd: &amp;lt;http://www.bigdata.com/rdf#&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt;&lt;br /&gt;
PREFIX skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt;&lt;br /&gt;
PREFIX schema: &amp;lt;http://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT {&lt;br /&gt;
  wd:Q42 ?p1 ?o1 .&lt;br /&gt;
  ?o1 rdfs:label ?o1Label .&lt;br /&gt;
  ?o1 ?p2 ?o2 .&lt;br /&gt;
  ?o2 rdfs:label ?o2Label .&lt;br /&gt;
} WHERE {&lt;br /&gt;
  SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
    SELECT ?p1 ?o1Label ?o1 ?p2 ?o2Label ?o2 WHERE {&lt;br /&gt;
        wd:Q42 ?p1 ?o1 .&lt;br /&gt;
        ?o1 ?p2 ?o2 .&lt;br /&gt;
&lt;br /&gt;
        FILTER (&lt;br /&gt;
           STRSTARTS(STR(?p1), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o1), STR(wd:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?p2), STR(wdt:)) &amp;amp;&amp;amp;&lt;br /&gt;
           STRSTARTS(STR(?o2), STR(wd:))&lt;br /&gt;
        )&lt;br /&gt;
&lt;br /&gt;
        SERVICE wikibase:label { bd:serviceParam wikibase:language &amp;quot;[AUTO_LANGUAGE],en&amp;quot;. }&lt;br /&gt;
&lt;br /&gt;
    } LIMIT 500&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=CSV to RDF (Lab 7)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Imports&lt;br /&gt;
import re&lt;br /&gt;
from pandas import *&lt;br /&gt;
from numpy import nan&lt;br /&gt;
from rdflib import Graph, Namespace, URIRef, Literal, RDF, XSD, FOAF&lt;br /&gt;
from spotlight import SpotlightException, annotate&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
# Test around with the confidence, and see how many names changes depending on the confidence.&lt;br /&gt;
# However, be aware that anything lower than this (0.83) it will replace James W. McCord and other names that includes James with LeBron James&lt;br /&gt;
CONFIDENCE = 0.83 &lt;br /&gt;
&lt;br /&gt;
# This function uses DBpedia Spotlight, which was not a part of the CSV lab this year.  &lt;br /&gt;
def annotate_entity(entity, filters={&#039;types&#039;: &#039;DBpedia:Person&#039;}):&lt;br /&gt;
	annotations = []&lt;br /&gt;
	try:&lt;br /&gt;
		annotations = annotate(address=SERVER, text=entity, confidence=CONFIDENCE, filters=filters)&lt;br /&gt;
	except SpotlightException as e:&lt;br /&gt;
		print(e)&lt;br /&gt;
	return annotations&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
#Pandas&#039; read_csv function to load russia-investigation.csv&lt;br /&gt;
df = read_csv(&amp;quot;russia-investigation.csv&amp;quot;)&lt;br /&gt;
#Replaces all instances of nan to None type with numpy&#039;s nan&lt;br /&gt;
df = df.replace(nan, None)&lt;br /&gt;
&lt;br /&gt;
#Function that prepares the values to be added to the graph as a URI (ex infront) or Literal&lt;br /&gt;
def prepareValue(row):&lt;br /&gt;
	if row == None: #none type&lt;br /&gt;
		value = Literal(row)&lt;br /&gt;
	elif isinstance(row, str) and re.match(r&#039;\d{4}-\d{2}-\d{2}&#039;, row): #date&lt;br /&gt;
		value = Literal(row, datatype=XSD.date)&lt;br /&gt;
	elif isinstance(row, bool): #boolean value (true / false)&lt;br /&gt;
		value = Literal(row, datatype=XSD.boolean)&lt;br /&gt;
	elif isinstance(row, int): #integer&lt;br /&gt;
		value = Literal(row, datatype=XSD.integer)&lt;br /&gt;
	elif isinstance(row, str): #string&lt;br /&gt;
		value = URIRef(ex + row.replace(&#039;&amp;quot;&#039;, &#039;&#039;).replace(&amp;quot; &amp;quot;, &amp;quot;_&amp;quot;).replace(&amp;quot;,&amp;quot;,&amp;quot;&amp;quot;).replace(&amp;quot;-&amp;quot;, &amp;quot;_&amp;quot;))&lt;br /&gt;
	elif isinstance(row, float): #float&lt;br /&gt;
		value = Literal(row, datatype=XSD.float)&lt;br /&gt;
&lt;br /&gt;
	return value&lt;br /&gt;
&lt;br /&gt;
#Convert the non-semantic CSV dataset into a semantic RDF &lt;br /&gt;
def csv_to_rdf(df):&lt;br /&gt;
	for index, row in df.iterrows():&lt;br /&gt;
		id = URIRef(ex + &amp;quot;Investigation_&amp;quot; + str(index))&lt;br /&gt;
		investigation = prepareValue(row[&amp;quot;investigation&amp;quot;])&lt;br /&gt;
		investigation_start = prepareValue(row[&amp;quot;investigation-start&amp;quot;])&lt;br /&gt;
		investigation_end = prepareValue(row[&amp;quot;investigation-end&amp;quot;])&lt;br /&gt;
		investigation_days = prepareValue(row[&amp;quot;investigation-days&amp;quot;])&lt;br /&gt;
		indictment_days = prepareValue(row[&amp;quot;indictment-days &amp;quot;])&lt;br /&gt;
		cp_date = prepareValue(row[&amp;quot;cp-date&amp;quot;])&lt;br /&gt;
		cp_days = prepareValue(row[&amp;quot;cp-days&amp;quot;])&lt;br /&gt;
		overturned = prepareValue(row[&amp;quot;overturned&amp;quot;])&lt;br /&gt;
		pardoned = prepareValue(row[&amp;quot;pardoned&amp;quot;])&lt;br /&gt;
		american = prepareValue(row[&amp;quot;american&amp;quot;])&lt;br /&gt;
		outcome = prepareValue(row[&amp;quot;type&amp;quot;])&lt;br /&gt;
		name_ex = prepareValue(row[&amp;quot;name&amp;quot;])&lt;br /&gt;
		president_ex = prepareValue(row[&amp;quot;president&amp;quot;])&lt;br /&gt;
&lt;br /&gt;
		#Spotlight Search&lt;br /&gt;
		name = annotate_entity(str(row[&#039;name&#039;]))&lt;br /&gt;
		president = annotate_entity(str(row[&#039;president&#039;]).replace(&amp;quot;.&amp;quot;, &amp;quot;&amp;quot;))&lt;br /&gt;
		&lt;br /&gt;
		#Adds the tripples to the graph&lt;br /&gt;
		g.add((id, RDF.type, ex.Investigation))&lt;br /&gt;
		g.add((id, ex.investigation, investigation))&lt;br /&gt;
		g.add((id, ex.investigation_start, investigation_start))&lt;br /&gt;
		g.add((id, ex.investigation_end, investigation_end))&lt;br /&gt;
		g.add((id, ex.investigation_days, investigation_days))&lt;br /&gt;
		g.add((id, ex.indictment_days, indictment_days))&lt;br /&gt;
		g.add((id, ex.cp_date, cp_date))&lt;br /&gt;
		g.add((id, ex.cp_days, cp_days))&lt;br /&gt;
		g.add((id, ex.overturned, overturned))&lt;br /&gt;
		g.add((id, ex.pardoned, pardoned))&lt;br /&gt;
		g.add((id, ex.american, american))&lt;br /&gt;
		g.add((id, ex.outcome, outcome))&lt;br /&gt;
&lt;br /&gt;
		#Spotlight search&lt;br /&gt;
		#Name&lt;br /&gt;
		try:&lt;br /&gt;
			g.add((id, ex.person, URIRef(name[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
		except:&lt;br /&gt;
			g.add((id, ex.person, name_ex))&lt;br /&gt;
&lt;br /&gt;
		#President&lt;br /&gt;
		try:&lt;br /&gt;
			g.add((id, ex.president, URIRef(president[0][&amp;quot;URI&amp;quot;])))&lt;br /&gt;
		except:&lt;br /&gt;
			g.add((id, ex.president, president_ex))&lt;br /&gt;
&lt;br /&gt;
csv_to_rdf(df)&lt;br /&gt;
print(g.serialize())&lt;br /&gt;
g.serialize(&amp;quot;lab7.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=JSON-LD (Lab 8)=&lt;br /&gt;
== Task 1) Basic JSON-LD ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;JSON-LD&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;@context&amp;quot;: {&lt;br /&gt;
        &amp;quot;@base&amp;quot;: &amp;quot;http://example.org/&amp;quot;,&lt;br /&gt;
        &amp;quot;edges&amp;quot;: &amp;quot;http://example.org/triple&amp;quot;,&lt;br /&gt;
        &amp;quot;start&amp;quot;: &amp;quot;http://example.org/source&amp;quot;,&lt;br /&gt;
        &amp;quot;rel&amp;quot;: &amp;quot;http://exaxmple.org/predicate&amp;quot;,&lt;br /&gt;
        &amp;quot;end&amp;quot;: &amp;quot;http://example.org/object&amp;quot;,&lt;br /&gt;
        &amp;quot;Person&amp;quot; : &amp;quot;http://example.org/Person&amp;quot;,&lt;br /&gt;
        &amp;quot;birthday&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/birthday&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot; : &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameEng&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/en/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;en&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameFr&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/fr/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;fr&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;nameCh&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/ch/name&amp;quot;,&lt;br /&gt;
            &amp;quot;@language&amp;quot; : &amp;quot;ch&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;age&amp;quot; : {&lt;br /&gt;
            &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/age&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot; : &amp;quot;xsd:int&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        &amp;quot;likes&amp;quot; : &amp;quot;http://example.org/games/likes&amp;quot;,&lt;br /&gt;
        &amp;quot;haircolor&amp;quot; : &amp;quot;http://example.org/games/haircolor&amp;quot;&lt;br /&gt;
    },&lt;br /&gt;
    &amp;quot;@graph&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;1987.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;nameEng&amp;quot; : &amp;quot;Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 26&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;2001.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;nameCh&amp;quot; : &amp;quot;Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 22,&lt;br /&gt;
            &amp;quot;likes&amp;quot; : &amp;quot;bastketball&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;@id&amp;quot;: &amp;quot;people/Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
            &amp;quot;birthday&amp;quot; : &amp;quot;1978.1.1&amp;quot;,&lt;br /&gt;
            &amp;quot;haircolor&amp;quot; : &amp;quot;Black&amp;quot;,&lt;br /&gt;
            &amp;quot;nameFr&amp;quot; : &amp;quot;Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;age&amp;quot; : 45&lt;br /&gt;
        },&lt;br /&gt;
        {&amp;quot;edges&amp;quot; : [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Louis&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Louis&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;teaches&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Ju&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;plays&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Jeremy&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;start&amp;quot; : &amp;quot;people/Ju&amp;quot;,&lt;br /&gt;
            &amp;quot;rel&amp;quot; : &amp;quot;plays&amp;quot;,&lt;br /&gt;
            &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        }&lt;br /&gt;
        ]}&lt;br /&gt;
    ]&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Task 2 &amp;amp; 3) Retrieving JSON-LD from ConceptNet / Programming JSON-LD in Python ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import rdflib&lt;br /&gt;
&lt;br /&gt;
CN_BASE = &#039;http://api.conceptnet.io/c/en/&#039;&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
g.parse(CN_BASE+&#039;indictment&#039;, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# To download JSON object:&lt;br /&gt;
&lt;br /&gt;
import json&lt;br /&gt;
import requests&lt;br /&gt;
&lt;br /&gt;
json_obj = requests.get(CN_BASE+&#039;indictment&#039;).json()&lt;br /&gt;
&lt;br /&gt;
# To change the @context:&lt;br /&gt;
&lt;br /&gt;
context = {&lt;br /&gt;
     &amp;quot;@base&amp;quot;: &amp;quot;http://ex.org/&amp;quot;,&lt;br /&gt;
     &amp;quot;edges&amp;quot;: &amp;quot;http://ex.org/triple/&amp;quot;,&lt;br /&gt;
     &amp;quot;start&amp;quot;: &amp;quot;http://ex.org/s/&amp;quot;,&lt;br /&gt;
     &amp;quot;rel&amp;quot;: &amp;quot;http://ex.org/p/&amp;quot;,&lt;br /&gt;
     &amp;quot;end&amp;quot;: &amp;quot;http://ex.org/o/&amp;quot;,&lt;br /&gt;
     &amp;quot;label&amp;quot;: &amp;quot;http://ex.org/label&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
json_obj[&#039;@context&#039;] = context&lt;br /&gt;
json_str = json.dumps(json_obj)&lt;br /&gt;
&lt;br /&gt;
g = rdflib.Graph()&lt;br /&gt;
g.parse(data=json_str, format=&#039;json-ld&#039;)&lt;br /&gt;
&lt;br /&gt;
# To extract triples (here with labels):&lt;br /&gt;
&lt;br /&gt;
r = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         SELECT ?s ?sLabel ?p ?o ?oLabel WHERE {&lt;br /&gt;
             ?edge&lt;br /&gt;
                 &amp;lt;http://ex.org/s/&amp;gt; ?s ;&lt;br /&gt;
                 &amp;lt;http://ex.org/p/&amp;gt; ?p ;&lt;br /&gt;
                 &amp;lt;http://ex.org/o/&amp;gt; ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
}&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;, initNs={&#039;cn&#039;: CN_BASE})&lt;br /&gt;
print(r.serialize(format=&#039;txt&#039;).decode())&lt;br /&gt;
&lt;br /&gt;
# Construct a new graph:&lt;br /&gt;
&lt;br /&gt;
r = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
         CONSTRUCT {&lt;br /&gt;
             ?s ?p ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
         } WHERE {&lt;br /&gt;
             ?edge &amp;lt;http://ex.org/s/&amp;gt; ?s ;&lt;br /&gt;
                   &amp;lt;http://ex.org/p/&amp;gt; ?p ;&lt;br /&gt;
                   &amp;lt;http://ex.org/o/&amp;gt; ?o .&lt;br /&gt;
             ?s &amp;lt;http://ex.org/label&amp;gt; ?sLabel .&lt;br /&gt;
             ?o &amp;lt;http://ex.org/label&amp;gt; ?oLabel .&lt;br /&gt;
}&lt;br /&gt;
         &amp;quot;&amp;quot;&amp;quot;, initNs={&#039;cn&#039;: CN_BASE})&lt;br /&gt;
&lt;br /&gt;
print(r.graph.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SHACL (Lab 9)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from pyshacl import validate&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
data_graph = Graph()&lt;br /&gt;
# parses the Turtle example from the task&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
prefixes = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
shape_graph = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
ex:PUI_Shape&lt;br /&gt;
    a sh:NodeShape ;&lt;br /&gt;
    sh:targetClass ex:PersonUnderInvestigation ;&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path foaf:name ;&lt;br /&gt;
        sh:minCount 1 ; #Every person under investigation has exactly one name. &lt;br /&gt;
        sh:maxCount 1 ; #Every person under investigation has exactly one name.&lt;br /&gt;
        sh:datatype rdf:langString ; #All person names must be language-tagged&lt;br /&gt;
    ] ;&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:chargedWith ;&lt;br /&gt;
        sh:nodeKind sh:IRI ; #The object of a charged with property must be a URI.&lt;br /&gt;
        sh:class ex:Offense ; #The object of a charged with property must be an offense.&lt;br /&gt;
    ] .&lt;br /&gt;
&lt;br /&gt;
# --- If you have more time tasks ---&lt;br /&gt;
ex:User_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    # The only allowed values for ex:american are true, false or unknown.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:american;&lt;br /&gt;
        sh:pattern &amp;quot;(true|false|unknown)&amp;quot; ;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # The value of a property that counts days must be an integer.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:indictment_days;&lt;br /&gt;
        sh:datatype xsd:integer;&lt;br /&gt;
    ];   &lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_days;&lt;br /&gt;
        sh:datatype xsd:integer;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # The value of a property that indicates a start date must be xsd:date.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_start;&lt;br /&gt;
        sh:datatype xsd:date;&lt;br /&gt;
    ];&lt;br /&gt;
&lt;br /&gt;
    # The value of a property that indicates an end date must be xsd:date or unknown (tip: you can use sh:or (...) ).&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigation_end;&lt;br /&gt;
        sh:or (&lt;br /&gt;
         [ sh:datatype xsd:date ]&lt;br /&gt;
         [ sh:hasValue &amp;quot;unknown&amp;quot; ]&lt;br /&gt;
    )];&lt;br /&gt;
    &lt;br /&gt;
    # Every indictment must have exactly one FOAF name for the investigated person.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path foaf:name;&lt;br /&gt;
        sh:minCount 1;&lt;br /&gt;
        sh:maxCount 1;&lt;br /&gt;
    ];&lt;br /&gt;
    &lt;br /&gt;
    # Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:investigatedPerson ;&lt;br /&gt;
        sh:minCount 1 ;&lt;br /&gt;
        sh:maxCount 1 ;&lt;br /&gt;
        sh:class ex:PersonUnderInvestigation ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
    ] ;&lt;br /&gt;
&lt;br /&gt;
    # No URI-s can contain hyphens (&#039;-&#039;).&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:outcome ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
        sh:pattern &amp;quot;^[^-]*$&amp;quot; ;&lt;br /&gt;
    ] ;&lt;br /&gt;
&lt;br /&gt;
    # Presidents must be identified with URIs.&lt;br /&gt;
    sh:property [&lt;br /&gt;
        sh:path ex:president ;&lt;br /&gt;
        sh:minCount 1 ;&lt;br /&gt;
        sh:class ex:President ;&lt;br /&gt;
        sh:nodeKind sh:IRI ;&lt;br /&gt;
    ] .&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
shacl_graph = Graph()&lt;br /&gt;
# parses the contents of a shape_graph you made in the previous task&lt;br /&gt;
shacl_graph.parse(data=prefixes+shape_graph)&lt;br /&gt;
&lt;br /&gt;
# uses pySHACL&#039;s validate method to apply the shape_graph constraints to the data_graph&lt;br /&gt;
results = validate(&lt;br /&gt;
    data_graph,&lt;br /&gt;
    shacl_graph=shacl_graph,&lt;br /&gt;
    inference=&#039;both&#039;&lt;br /&gt;
)&lt;br /&gt;
&lt;br /&gt;
# prints out the validation result&lt;br /&gt;
boolean_value, results_graph, results_text = results&lt;br /&gt;
&lt;br /&gt;
# print(boolean_value)&lt;br /&gt;
print(results_graph.serialize(format=&#039;ttl&#039;))&lt;br /&gt;
# print(results_text)&lt;br /&gt;
&lt;br /&gt;
#Write a SPARQL query to print out each distinct sh:resultMessage in the results_graph&lt;br /&gt;
distinct_messages = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
SELECT DISTINCT ?message WHERE {&lt;br /&gt;
    [] sh:result / sh:resultMessage ?message .&lt;br /&gt;
}&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
messages = results_graph.query(distinct_messages)&lt;br /&gt;
for row in messages:&lt;br /&gt;
    print(row.message)&lt;br /&gt;
&lt;br /&gt;
#each sh:resultMessage in the results_graph once, along with the number of times that message has been repeated in the results&lt;br /&gt;
count_messages = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; &lt;br /&gt;
&lt;br /&gt;
SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {&lt;br /&gt;
    [] sh:result ?result .&lt;br /&gt;
    ?result sh:resultMessage ?message ;&lt;br /&gt;
            sh:focusNode ?node .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?message&lt;br /&gt;
ORDER BY DESC(?count) ?message&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
messages = results_graph.query(count_messages)&lt;br /&gt;
for row in messages:&lt;br /&gt;
    print(&amp;quot;COUNT    MESSAGE&amp;quot;)&lt;br /&gt;
    print(row.num_messages, &amp;quot;      &amp;quot;, row.message)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDFS (Lab 10)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, Literal, XSD, FOAF, RDFS&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
NS = {&lt;br /&gt;
    &#039;ex&#039;: ex,&lt;br /&gt;
    &#039;rdf&#039;: RDF,&lt;br /&gt;
    &#039;rdfs&#039;: RDFS,&lt;br /&gt;
    &#039;foaf&#039;: FOAF,&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Write a small function that computes the RDFS closure on your graph.&lt;br /&gt;
def flush():&lt;br /&gt;
    engine = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)&lt;br /&gt;
    engine.closure()&lt;br /&gt;
    engine.flush_stored_triples()&lt;br /&gt;
&lt;br /&gt;
#Rick Gates was charged with money laundering and tax evasion.&lt;br /&gt;
g.add((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
&lt;br /&gt;
#When one thing that is charged with another thing,&lt;br /&gt;
g.add((ex.chargedWith, RDFS.domain, ex.PersonUnderInvestigation))  #the first thing (subject) is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing (object) is an offense.&lt;br /&gt;
&lt;br /&gt;
#Write a SPARQL query that checks the RDF type(s) of Rick Gates and money laundering in your RDF graph.&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
#A person under investigation is a FOAF person&lt;br /&gt;
g.add((ex.PersonUnderInvestigation, RDFS.subClassOf, FOAF.Person))&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
#Paul Manafort was convicted for tax evasion.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxEvasion))&lt;br /&gt;
#the first thing is also charged with the second thing&lt;br /&gt;
g.add((ex.convictedFor, RDFS.subPropertyOf, ex.chargedWith)) &lt;br /&gt;
flush()&lt;br /&gt;
print(g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize())&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=OWL 1 (Lab 11)=&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, RDFS, Namespace, RDF, FOAF, BNode, OWL, URIRef, Literal, XSD&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
import owlrl&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
schema = Namespace(&#039;http://schema.org/&#039;)&lt;br /&gt;
dbr = Namespace(&#039;https://dbpedia.org/page/&#039;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
# g.bind(&amp;quot;schema&amp;quot;, schema)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# Donald Trump and Robert Mueller are two different persons.&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.differentFrom, ex.Robert_Mueller))&lt;br /&gt;
&lt;br /&gt;
# Actually, all the names mentioned in connection with the Mueller investigation refer to different people.&lt;br /&gt;
b1 = BNode()&lt;br /&gt;
b2 = BNode()&lt;br /&gt;
Collection(g, b2, [ex.Robert_Mueller, ex.Paul_Manafort, ex.Rick_Gates, ex.George_Papadopoulos, ex.Michael_Flynn, ex.Michael_Cohen, ex.Roger_Stone, ex.Donald_Trump])&lt;br /&gt;
g.add((b1, RDF.type, OWL.AllDifferent))&lt;br /&gt;
g.add((b1, OWL.distinctMembers, b2))&lt;br /&gt;
&lt;br /&gt;
# All these people are foaf:Persons as well as schema:Persons&lt;br /&gt;
g.add((FOAF.Person, OWL.equivalentClass, schema.Person))&lt;br /&gt;
&lt;br /&gt;
# Tax evation is a kind of bank and tax fraud.&lt;br /&gt;
g.add((ex.TaxEvation, RDFS.subClassOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.TaxEvation, RDFS.subClassOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# The Donald Trump involved in the Mueller investigation is dbpedia:Donald_Trump and not dbpedia:Donald_Trump_Jr.&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.sameAs, dbr.Donald_Trump))&lt;br /&gt;
g.add((ex.Donald_Trump, OWL.differentFrom, URIRef(dbr + &amp;quot;Donald_Trump_Jr.&amp;quot;)))&lt;br /&gt;
&lt;br /&gt;
# Congress, FBI and the Mueller investigation are foaf:Organizations.&lt;br /&gt;
g.add((ex.Congress, RDF.type, FOAF.Organization))&lt;br /&gt;
g.add((ex.FBI, RDF.type, FOAF.Organization))&lt;br /&gt;
g.add((ex.Mueller_Investigation, RDF.type, FOAF.Organization))&lt;br /&gt;
&lt;br /&gt;
# Nothing can be both a person and an organization.&lt;br /&gt;
g.add((FOAF.Person, OWL.disjointWith, FOAF.Organization))&lt;br /&gt;
&lt;br /&gt;
# Leading an organization is a way of being involved in an organization.&lt;br /&gt;
g.add((ex.leading, RDFS.subPropertyOf, ex.involved))&lt;br /&gt;
&lt;br /&gt;
# Being a campaign manager or an advisor for is a way of supporting someone.&lt;br /&gt;
g.add((ex.campaignManagerTo, RDFS.subPropertyOf, ex.supports))&lt;br /&gt;
g.add((ex.advisorTo, RDFS.subPropertyOf, ex.supports))&lt;br /&gt;
&lt;br /&gt;
# Donald Trump is a politician and a Republican.&lt;br /&gt;
g.add((ex.Donald_Trump, RDF.type, ex.Politician))&lt;br /&gt;
g.add((ex.Donald_Trump, RDF.type, ex.Republican))&lt;br /&gt;
&lt;br /&gt;
# A Republican politician is both a politician and a Republican.&lt;br /&gt;
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Politician))&lt;br /&gt;
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Republican))&lt;br /&gt;
&lt;br /&gt;
#hasBusinessPartner&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.hasBusinessPartner, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.hasBusinessPartner, RDF.type, OWL.SymmetricProperty))&lt;br /&gt;
g.add((ex.hasBusinessPartner, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&lt;br /&gt;
#adviserTo&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.adviserTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
# Not necessarily asymmetric as it&#039;s not a given that they couldn&#039;t be advisors to each other  &lt;br /&gt;
&lt;br /&gt;
#wasLyingTo&lt;br /&gt;
g.add((ex.Rick_Gates_Lying, ex.wasLyingTo, ex.FBI))&lt;br /&gt;
g.add((ex.wasLyingTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
# Not asymmetric as the subject and object could lie to each other; also in this context, the FBI can lie to you&lt;br /&gt;
&lt;br /&gt;
#presidentOf&lt;br /&gt;
g.add((ex.Donald_Trump, ex.presidentOf, ex.USA))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.presidentOf, RDF.type, OWL.FunctionalProperty)) #can only be president of one country&lt;br /&gt;
#not inversefunctionalproperty as Bosnia has 3 presidents https://www.culturalworld.org/do-any-countries-have-more-than-one-president.htm&lt;br /&gt;
&lt;br /&gt;
#hasPresident&lt;br /&gt;
g.add((ex.USA, ex.hasPresident, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.AsymmetricProperty))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
g.add((ex.hasPresident, RDF.type, OWL.InverseFunctionalProperty)) #countries do not share their president with another&lt;br /&gt;
#not functionalproperty as a country (Bosnia) can have more than one president&lt;br /&gt;
&lt;br /&gt;
#Closure&lt;br /&gt;
owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)&lt;br /&gt;
&lt;br /&gt;
#Serialization&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab8.xml&amp;quot;, format=&amp;quot;xml&amp;quot;) #serializes to XML file&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=OWL 2 (Lab 12)=&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@prefix : &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
@prefix dc: &amp;lt;http://purl.org/dc/terms#&amp;gt; .&lt;br /&gt;
@prefix io: &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
@prefix dbr: &amp;lt;http://dbpedia.org/resource/&amp;gt; .&lt;br /&gt;
@prefix owl: &amp;lt;http://www.w3.org/2002/07/owl#&amp;gt; .&lt;br /&gt;
@prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
@prefix xml: &amp;lt;http://www.w3.org/XML/1998/namespace&amp;gt; .&lt;br /&gt;
@prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
@prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
@prefix prov: &amp;lt;http://www.w3.org/ns/prov#&amp;gt; .&lt;br /&gt;
@prefix rdfs: &amp;lt;http://www.w3.org/2000/01/rdf-schema#&amp;gt; .&lt;br /&gt;
@base &amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
&amp;lt;http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology&amp;gt; rdf:type owl:Ontology .&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Object Properties&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#indictedIn&lt;br /&gt;
io:indictedIn rdf:type owl:ObjectProperty ;&lt;br /&gt;
              rdfs:subPropertyOf io:involvedIn ;&lt;br /&gt;
              rdfs:domain io:InvestigatedPerson ;&lt;br /&gt;
              rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#investigating&lt;br /&gt;
io:investigating rdf:type owl:ObjectProperty ;&lt;br /&gt;
                 rdfs:subPropertyOf io:involvedIn ;&lt;br /&gt;
                 rdfs:domain io:Investigator ;&lt;br /&gt;
                 rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#involvedIn&lt;br /&gt;
io:involvedIn rdf:type owl:ObjectProperty ;&lt;br /&gt;
              rdfs:domain foaf:Person ;&lt;br /&gt;
              rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#leading&lt;br /&gt;
io:leading rdf:type owl:ObjectProperty ;&lt;br /&gt;
           rdfs:subPropertyOf io:investigating ;&lt;br /&gt;
           rdfs:domain io:InvestigationLeader ;&lt;br /&gt;
           rdfs:range io:Investigation .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Data properties&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://purl.org/dc/elements/1.1/description&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/description&amp;gt; rdf:type owl:DatatypeProperty ;&lt;br /&gt;
                                              rdfs:domain io:Investigation ;&lt;br /&gt;
                                              rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.w3.org/ns/prov#endedAtTime&lt;br /&gt;
prov:endedAtTime rdf:type owl:DatatypeProperty ,&lt;br /&gt;
                          owl:FunctionalProperty ;&lt;br /&gt;
                 rdfs:domain io:Investigation ;&lt;br /&gt;
                 rdfs:range xsd:dateTime .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.w3.org/ns/prov#startedAtTime&lt;br /&gt;
prov:startedAtTime rdf:type owl:DatatypeProperty ,&lt;br /&gt;
                            owl:FunctionalProperty ;&lt;br /&gt;
                   rdfs:domain io:Investigation ;&lt;br /&gt;
                   rdfs:range xsd:dateTime .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/name&lt;br /&gt;
foaf:name rdf:type owl:DatatypeProperty ;&lt;br /&gt;
          rdfs:domain foaf:Person ;&lt;br /&gt;
          rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/title&lt;br /&gt;
foaf:title rdf:type owl:DatatypeProperty ;&lt;br /&gt;
           rdfs:domain io:Investigation ;&lt;br /&gt;
           rdfs:range xsd:string .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Classes&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigatedPerson&lt;br /&gt;
io:InvestigatedPerson rdf:type owl:Class ;&lt;br /&gt;
                      rdfs:subClassOf io:Person ;&lt;br /&gt;
                      owl:disjointWith io:Investigator .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation&lt;br /&gt;
io:Investigation rdf:type owl:Class .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigationLeader&lt;br /&gt;
io:InvestigationLeader rdf:type owl:Class ;&lt;br /&gt;
                       rdfs:subClassOf io:Investigator .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigator&lt;br /&gt;
io:Investigator rdf:type owl:Class ;&lt;br /&gt;
                rdfs:subClassOf io:Person .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Person&lt;br /&gt;
io:Person rdf:type owl:Class ;&lt;br /&gt;
          rdfs:subClassOf foaf:Person .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://xmlns.com/foaf/0.1/Person&lt;br /&gt;
foaf:Person rdf:type owl:Class .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    Individuals&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Donald_Trump&lt;br /&gt;
dbr:Donald_Trump rdf:type owl:NamedIndividual ;&lt;br /&gt;
                 foaf:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Elizabeth_Prelogar&lt;br /&gt;
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ;&lt;br /&gt;
                       io:investigating &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                       foaf:name &amp;quot;Elizabeth Prelogar&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Michael_Flynn&lt;br /&gt;
dbr:Michael_Flynn rdf:type owl:NamedIndividual ;&lt;br /&gt;
                  foaf:name &amp;quot;Michael Flynn&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Paul_Manafort&lt;br /&gt;
dbr:Paul_Manafort rdf:type owl:NamedIndividual ;&lt;br /&gt;
                  io:indictedIn &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                  foaf:name &amp;quot;Paul Manafort&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Robert_Mueller&lt;br /&gt;
dbr:Robert_Mueller rdf:type owl:NamedIndividual ;&lt;br /&gt;
                   io:leading &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&lt;br /&gt;
                   foaf:name &amp;quot;Robert Mueller&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Roger_Stone&lt;br /&gt;
dbr:Roger_Stone rdf:type owl:NamedIndividual ;&lt;br /&gt;
                foaf:name &amp;quot;Roger Stone&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                                        foaf:title &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
#################################################################&lt;br /&gt;
#    General axioms&lt;br /&gt;
#################################################################&lt;br /&gt;
&lt;br /&gt;
[ rdf:type owl:AllDifferent ;&lt;br /&gt;
  owl:distinctMembers ( dbr:Donald_Trump&lt;br /&gt;
                        dbr:Elizabeth_Prelogar&lt;br /&gt;
                        dbr:Michael_Flynn&lt;br /&gt;
                        dbr:Paul_Manafort&lt;br /&gt;
                        dbr:Robert_Mueller&lt;br /&gt;
                        dbr:Roger_Stone&lt;br /&gt;
                      )&lt;br /&gt;
] .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  Generated by the OWL API (version 4.5.25.2023-02-15T19:15:49Z) https://github.com/owlcs/owlapi&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Using Graph Embeddings (Lab 13)=&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1WkRJUeUBVF5yVv7o0pOKfsd4pqG6369k&lt;br /&gt;
&lt;br /&gt;
=Training Graph Embeddings (Lab 14)=&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2541</id>
		<title>Lab: Using Graph Embeddings</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2541"/>
		<updated>2024-05-02T12:03:29Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Topics==&lt;br /&gt;
Using knowledge graph embeddings with TorchKGE.&lt;br /&gt;
&lt;br /&gt;
==Useful readings==&lt;br /&gt;
* [https://torchkge.readthedocs.io/en/latest/ Welcome to TorchKGE’ s documentation!]&lt;br /&gt;
* The following TorchKGE classes are central:&lt;br /&gt;
** &#039;&#039;KnowledgeGraph&#039;&#039; - contains the knowledge graph (KG)&lt;br /&gt;
** &#039;&#039;Model&#039;&#039; - contains the embeddings (entity and relation vectors) for some KG&lt;br /&gt;
* [https://pytorch.org/docs/stable/tensors.html PyTorch Tensor Documentation]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task: knowledge graph&#039;&#039;&#039;:&lt;br /&gt;
* Use a [https://torchkge.readthedocs.io/en/latest/reference/utils.html#pre-trained-models dataset loader] to load a KG you want to work with. Freebase FB15k237 is a good choice. (You will need a pre-trained model for your KG later, to choose one of FB15k, FB15k237, WDV5, WN18RR, or Yago3-10. This lab has mostly been tested on FB15k.)&lt;br /&gt;
* Use the methods provided by the [https://torchkge.readthedocs.io/en/latest/reference/data.html#knowledge-graph KnowledgeGraph class] to inspect the KG. &lt;br /&gt;
** Print out the numbers of entities, relations, and facts in the training, validation, and testing sets. &lt;br /&gt;
** Print the identifiers for the first 10 entities and relations (&#039;&#039;tip:&#039;&#039; ent2ix and rel2ix).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task: external identifiers&#039;&#039;&#039;:&lt;br /&gt;
* Download a dataset that provides more understandable labels for the entities (and perhaps relations) in your KnowledgeGraph&lt;br /&gt;
** If you use FB15k, the relation names are not so bad, but the entity identifiers do not give much meaning. Same with WordNet. [https://github.com/villmow/datasets_knowledge_embedding This repository] contains mappings for the Freebase and WordNet datasets.&lt;br /&gt;
** If you use a Wikidata graph, the entities and relations are all P- and Q-codes. To get labels, you can try a combination of [https://query.wikidata.org/ SPARQL queries] and [https://pypi.org/project/Wikidata/ this API].&lt;br /&gt;
* Create mappings from external labels to entity ids (and perhaps relation ids) in the KnowledgeGraph. Also create the inverse mappings.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task: test entities and relations&#039;&#039;&#039;:&lt;br /&gt;
* Get the KG indexes for a few entities and relations. If you use the Freebase or Wikidata graphs, you can try &#039;J. K. Rowling&#039; and &#039;WALL·E&#039; as entities (&#039;&#039;note&#039;&#039; that the dot in &#039;WALL·E&#039; is not a hyphen or usual period.) For relations you can try &#039;influenced by&#039; and &#039;genre&#039;. (&#039;&#039;tip&#039;&#039;: to check names of entites and relations, open the train.txt file you cloned) &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task: model&#039;&#039;&#039;:&lt;br /&gt;
* Load a [https://torchkge.readthedocs.io/en/latest/reference/utils.html#pre-trained-models pre-trained TransE model] that matches your KnowledgeGraph.&lt;br /&gt;
** Print out the numbers of entities, relations, and [https://torchkge.readthedocs.io/en/latest/reference/models.html#transe the dimensions] of the entity and relation vectors. Do they match your KnowledgeGraph. &lt;br /&gt;
* Get the vectors for your test entities and relations (for example, &#039;J. K. Rowling&#039; and &#039;influenced by&#039;).&lt;br /&gt;
* Find vectors for a few more entities (both unrelated and related ones, e.g., &#039;J. R. R. Tolkien&#039;, &#039;C. S. Lewis&#039;, ...). Use the [https://torchkge.readthedocs.io/en/latest/reference/models.html#translationalmodels model.dissimilarity()-method] to estimate how semantically close your entities are. Do the distances make sense?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task: K-nearest neighbours&#039;&#039;&#039;:&lt;br /&gt;
* Find the indexes of the 10 entity vectors that are nearest neighbours to your entity of choice. You can use [https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html sciKit-learn&#039;s sklearn.neighbors.NearestNeighbors.kneighbors()-method] for this.&lt;br /&gt;
* Map the indexes of the 10-nearest neighbouring entities back into human-understandable labels. Does this make sense? Try the same thing with another entity (e.g., &#039;WALL·E&#039;).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task: translation&#039;&#039;&#039;:&lt;br /&gt;
* Add together the vectors for an entity and a relation that that gives meaning for the entity (e.g., &#039;J. K. Rowling&#039; - &#039;influenced by&#039;, &#039;WALL·E&#039; - &#039;genre&#039;). Find the 10-nearest neighbouring entities for the vector sum. Does this make sense? Try more entities and relations. Try to find examples that work and that do not work well.&lt;br /&gt;
&lt;br /&gt;
==Code to get started==&lt;br /&gt;
With graph embeddings, we ideally want to work with ipynb files. The code below is prepared in the following link: https://colab.research.google.com/drive/1gS2D1XYSviAmhkS8moJIpY0N8ltJFM3C&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
!pip install torchkge&lt;br /&gt;
!pip install sklearn&lt;br /&gt;
!git clone https://github.com/villmow/datasets_knowledge_embedding.git&lt;br /&gt;
&lt;br /&gt;
from torchkge.utils.datasets import load_fb15k237&lt;br /&gt;
&lt;br /&gt;
kg_train, kg_val, kg_test = load_fb15k237()&lt;br /&gt;
&lt;br /&gt;
print(list(kg_train.ent2ix.keys())[-10:])&lt;br /&gt;
print(list(kg_train.rel2ix.keys())[-10:])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;Download files with human-readable labels for (most) Freebase entities used in the dataset. &lt;br /&gt;
Labels seem to be missing for some entities used in FB15k-237.&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
import json&lt;br /&gt;
&lt;br /&gt;
TEXT_TRIPLES_DIR = &#039;datasets_knowledge_embedding/FB15k-237/&#039;&lt;br /&gt;
with open(TEXT_TRIPLES_DIR+&#039;entity2wikidata.json&#039;) as file:&lt;br /&gt;
    _entity2wikidata = json.load(file)&lt;br /&gt;
&lt;br /&gt;
 ent2lbl = {&lt;br /&gt;
    ent: wd[&#039;label&#039;]&lt;br /&gt;
    for ent, wd in _entity2wikidata.items()&lt;br /&gt;
}&lt;br /&gt;
lbl2ent = {lbl: ent for ent, lbl in ent2lbl.items()}&lt;br /&gt;
&lt;br /&gt;
print([&lt;br /&gt;
    ent2lbl[ent] &lt;br /&gt;
    for ent in kg_train.ent2ix.keys()&lt;br /&gt;
    if ent in ent2lbl][-10:])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If You Have More Time==&lt;br /&gt;
* Try it out with different datasets, for example one you create youreself using SPARQL queries on an open KG.&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_JSON-LD&amp;diff=2493</id>
		<title>Lab: JSON-LD</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_JSON-LD&amp;diff=2493"/>
		<updated>2024-03-12T11:08:51Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Topics==&lt;br /&gt;
JSON-LD @context and processing in the JSON-LD Playground.&lt;br /&gt;
&lt;br /&gt;
Using a Web APIs to retrieve JSON-LD data from ConceptNet, parse them programmatically, use JSON-LD to turn them into RDF.&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://json-ld.org/ JSON for Linking Data]&lt;br /&gt;
* [https://github.com/commonsense/conceptnet5/wiki/API ConceptNet API]&lt;br /&gt;
* [https://www.w3.org/TR/json-ld11/#basic-concepts Guide on JSON-LD]&lt;br /&gt;
&lt;br /&gt;
Imports:&lt;br /&gt;
* import json&lt;br /&gt;
* import json-ld&lt;br /&gt;
* import rdflib&lt;br /&gt;
* import requests&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
===Part 1: Basic JSON-LD===&lt;br /&gt;
&lt;br /&gt;
In the first part of the lab you will start with an existing JSON-LD document:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
  &amp;quot;@context&amp;quot;: {&lt;br /&gt;
    &amp;quot;@base&amp;quot;: &amp;quot;http://example.org/&amp;quot;,&lt;br /&gt;
    &amp;quot;edges&amp;quot;: &amp;quot;http://example.org/triple&amp;quot;,&lt;br /&gt;
      &amp;quot;start&amp;quot;: &amp;quot;http://example.org/source&amp;quot;,&lt;br /&gt;
      &amp;quot;rel&amp;quot;: &amp;quot;http://example.org/predicate&amp;quot;,&lt;br /&gt;
      &amp;quot;end&amp;quot;: &amp;quot;http://example.org/object&amp;quot;,&lt;br /&gt;
    &amp;quot;Person&amp;quot; : &amp;quot;http://example.org/Person&amp;quot;,&lt;br /&gt;
    &amp;quot;birthday&amp;quot; : {&lt;br /&gt;
      &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/birthday&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot; : &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
    },&lt;br /&gt;
    &amp;quot;nameEng&amp;quot; : {&lt;br /&gt;
      &amp;quot;@id&amp;quot; : &amp;quot;http://example.org/en/name&amp;quot;,&lt;br /&gt;
      &amp;quot;@language&amp;quot; : &amp;quot;en&amp;quot;&lt;br /&gt;
  }&lt;br /&gt;
  },&lt;br /&gt;
  &amp;quot;@graph&amp;quot;: [&lt;br /&gt;
    {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;,&lt;br /&gt;
      &amp;quot;birthday&amp;quot; : &amp;quot;1987.1.1&amp;quot;,&lt;br /&gt;
      &amp;quot;nameEng&amp;quot; : &amp;quot;Jeremy&amp;quot;&lt;br /&gt;
    },&lt;br /&gt;
    {&lt;br /&gt;
      &amp;quot;@id&amp;quot;: &amp;quot;people/Tom&amp;quot;,&lt;br /&gt;
      &amp;quot;@type&amp;quot;: &amp;quot;Person&amp;quot;&lt;br /&gt;
    },&lt;br /&gt;
    {&amp;quot;edges&amp;quot; : [&lt;br /&gt;
      {&lt;br /&gt;
      &amp;quot;start&amp;quot; : &amp;quot;people/Jeremy&amp;quot;,&lt;br /&gt;
        &amp;quot;rel&amp;quot; : &amp;quot;knows&amp;quot;,&lt;br /&gt;
        &amp;quot;end&amp;quot; : &amp;quot;people/Tom&amp;quot;&lt;br /&gt;
        &lt;br /&gt;
      }&lt;br /&gt;
    ]}&lt;br /&gt;
  ]&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Using the JSON-LD document as a starting point, complete the following tasks:&lt;br /&gt;
&lt;br /&gt;
* Create a new property named age, that has an integer type, and add it to the people already in the graph.&lt;br /&gt;
* Add the following 2 more people to the graph, make sure that their names&#039; languages follow their nationality:&lt;br /&gt;
  * Ju: chinese, 22 years old, likes to play basketball&lt;br /&gt;
  * Louis: french, 45 years old, and has black hair&lt;br /&gt;
* Add the following edges to the graph:&lt;br /&gt;
  * Tom knows Louis&lt;br /&gt;
  * Louis teaches Ju&lt;br /&gt;
  * Ju plays basketball with Jeremy and Tom&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
In a web browser, go to [http://json-ld.org http://json-ld.org] and continue to the &#039;&#039;Playground&#039;&#039;. Copy the JSON-LD document into the &#039;&#039;JSON-LD Input&#039;&#039; form.&lt;br /&gt;
&lt;br /&gt;
In the &#039;&#039;Compacted&#039;&#039; form below the input form you will see a processed version of the JSON-LD input. Compare the information about Jeremy in the Input and Compacted output. Many of the keys and values in the output have been expanded according to mappings defined in the &#039;&#039;@context&#039;&#039; object at the beginning of the document.&lt;br /&gt;
&lt;br /&gt;
[http://json-ld.org http://json-ld.org] provides many other processed variants of the JSON-LD, but &#039;&#039;Compacted&#039;&#039; may be easiest to start with.&lt;br /&gt;
&lt;br /&gt;
===Part 2: Retrieving JSON-LD from ConceptNet===&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
In a web browser, go to [http://conceptnet.io http://conceptnet.io] and search for a term you are interested in. (It is good to take concept related to the Mueller investigation, for example &#039;indictment&#039;.)&lt;br /&gt;
&lt;br /&gt;
The same URL, but with &#039;&#039;https://api.conceptnet.io/&#039;&#039; instead of just &#039;&#039;https://conceptnet.io/&#039;&#039; returns the data as JSON-LD. It looks awfully detailed, but it will be easy to simplify it!&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
In another web browser tab, go to [http://json-ld.org http://json-ld.org] again and continue to the &#039;&#039;Playground&#039;&#039;. Copy your JSON-LD data from the &#039;&#039;ConceptNet&#039;&#039; tab to the &#039;&#039;JSON-LD Input&#039;&#039; form.&lt;br /&gt;
&lt;br /&gt;
In the &#039;&#039;Expanded&#039;&#039; form you again will see a processed version of the JSON-LD input. This time the keys and values in the output have been expanded according to mappings defined in the &#039;&#039;@context&#039;&#039; file [http://api.conceptnet.io/ld/conceptnet5.7/context.ld.json http://api.conceptnet.io/ld/conceptnet5.7/context.ld.json], as specified in the beginning of the JSON-LD input:&lt;br /&gt;
&lt;br /&gt;
   &amp;quot;@context&amp;quot;: [&lt;br /&gt;
       &amp;quot;http://api.conceptnet.io/ld/conceptnet5.7/context.ld.json&amp;quot;&lt;br /&gt;
   ],&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Instead of a file, we will write our own simpler &#039;&#039;@context&#039;&#039; object into the JSON-LD Input. It should look like this instead:&lt;br /&gt;
&lt;br /&gt;
   &amp;quot;@context&amp;quot;: {&lt;br /&gt;
        &amp;quot;current_key&amp;quot;: &amp;quot;url_we_want_the_key_mapped_to&amp;quot;,&lt;br /&gt;
        ...&lt;br /&gt;
   },&lt;br /&gt;
&lt;br /&gt;
We are interested in these keys: edges, start, rel, end. Map them to simple URLs, like &#039;&#039;http://ex.org/t&#039;&#039; (for triple), &#039;&#039;http://ex.org/s&#039;&#039;, &#039;&#039;http://ex.org/p&#039;&#039; and &#039;&#039;http://ex.org/o&#039;&#039;. These are the basic triples we are most interested in!&lt;br /&gt;
&lt;br /&gt;
Look at the Expanded version again. It is much simpler now: the JSON-LD processor ignores regular keys that are not mapped (but the special keys with &#039;&#039;@&#039;&#039; are still there.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Remove the line that maps the &#039;&#039;edges&#039;&#039; key. What happens and why? Put the &#039;&#039;edges&#039;&#039; mapping back in again.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
In addition to the &#039;&#039;Expanded&#039;&#039; tab, the Playground can show &#039;&#039;Compacted&#039;&#039; and &#039;&#039;Flattened&#039;&#039; versions of the JSON-LD Input too. They are different ways of processing the same data, each of them useful for different purposes.&lt;br /&gt;
&lt;br /&gt;
Which one do you prefer for reading? Which one would be easiest to program as JSON?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
We have lost the labels again!&lt;br /&gt;
&lt;br /&gt;
Map &#039;&#039;label&#039;&#039; to &#039;&#039;http://www.w3.org/2000/01/rdf-schema#label&#039;&#039; and see what happens.&lt;br /&gt;
&lt;br /&gt;
===Part 3: Programming JSON-LD in Python===&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Install the &#039;&#039;rdflib-jsonld&#039;&#039; package in the same environment as you have &#039;&#039;rdflib&#039;&#039; installed.&lt;br /&gt;
&lt;br /&gt;
Create a graph object and parse the &#039;&#039;https://api.conceptnet.io/...&#039;&#039; URL you used to download JSON-LD data earlier. You need to add the argument &#039;&#039;format=&amp;quot;json-ld&amp;quot;&#039;&#039; when you call &#039;&#039;parse(...)&#039;&#039;, but you should not need to &#039;&#039;import&#039;&#039; more than &#039;&#039;rdflib&#039;&#039; as before.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Inspect the graph object using simple SPARQL queries to find the distinct predicates and types used.&lt;br /&gt;
&lt;br /&gt;
You can also count the number of triples in the graph:&lt;br /&gt;
 print(len(g))&lt;br /&gt;
or iterate through all the triples&lt;br /&gt;
 for s, p, o in g:&lt;br /&gt;
     print(s, p, o)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Unfortunately, the graph is much more complex than we need and it is not easy to pick out the triples we want. We want to add our own context object like we did in the Playground. Instead of parsing a graph directly from a URL, we first download it as a JSON object, for example:&lt;br /&gt;
&lt;br /&gt;
 import json&lt;br /&gt;
 import requests&lt;br /&gt;
 &lt;br /&gt;
 CN_BASE = &#039;http://api.conceptnet.io/c/en/&#039;&lt;br /&gt;
 &lt;br /&gt;
 json_obj = requests.get(CN_BASE+&#039;indictment&#039;).json()&lt;br /&gt;
&lt;br /&gt;
Now, &#039;&#039;json_obj[&#039;@context&#039;]&#039;&#039; contains the @context object. Define your own context object in Python similar to the one you used in the play ground, and assign it to &#039;&#039;json_obj[&#039;@context&#039;]&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
First parse the modified JSON object into a JSON string (&#039;&#039;import json&#039;&#039; and &#039;&#039;json.dumps(...)&#039;&#039;). Then create another graph object and parse the JSON string. You need to add the argument &#039;&#039;data=...&#039;&#039; in addition to &#039;&#039;format=&amp;quot;json-ld&amp;quot;&#039;&#039; when you call &#039;&#039;parse(...)&#039;&#039; because you are no longer parsing from a file or URL, but from a string.&lt;br /&gt;
&lt;br /&gt;
Save the JSON string for later, so you do not have to retrieve the same data over and over from ConceptNet.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Create a new SPARQL SELECT query that lists all the &#039;&#039;(s, p, o)&#039;&#039; triples in your graph.&lt;br /&gt;
&lt;br /&gt;
The URLs for predicates should be fine now, but the URLs of subjects and objects can be improved by mapping the special &#039;&#039;@base&#039;&#039; key in the &#039;&#039;@context&#039;&#039; object to a simple URL like &#039;&#039;http://ex.org/&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Extend the SELECT query so that it also lists all the labels of subjects and objects.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Change the SELECT query into a CONSTRUCT query that return a new graph of all the basic triples in the original JSON-LD data. Save it to file and look at it in a visualiser you like.&lt;br /&gt;
&lt;br /&gt;
==If you have more time...==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Merge the new triples with your existing graph if they fit there.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Wrap the code you have written into a function &#039;&#039;describe_concept(...)&#039;&#039; that takes a concept name as argument (e.g., &#039;indictment&#039;) and returns a ConceptNet subgraph that describes the concept.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
The original JSON-LD data from &#039;&#039;https://api.conceptnet.io/...&#039;&#039; contains a &#039;&#039;view&#039;&#039; object at the end. Check it out!&lt;br /&gt;
&lt;br /&gt;
By default, the API only returns 20 edges at a time. You can modify that by adding a &#039;&#039;?limit=...&#039;&#039; argument to your URL.&lt;br /&gt;
&lt;br /&gt;
Modify your &#039;&#039;describe_concept(...)&#039;&#039; method to take an extra argument that controls how many edges are downloaded.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
You still have way too many triples. Use &#039;&#039;FILTER&#039;&#039; and &#039;&#039;STRENDS&#039;&#039; to ignore some predicates like &#039;&#039;Synonym&#039;&#039; and general &#039;&#039;RelatedTo&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Modify your &#039;&#039;@context&#039;&#039; and query so you can remove triples with concepts that are not in English language (&#039;&#039;en&#039;&#039;).&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2445</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2445"/>
		<updated>2024-02-19T13:25:09Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present suggested solutions after each lab. &#039;&#039;The page will be updated as the course progresses&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
=Getting started (Lab 1)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# The Mueller Investigation was lead by Robert Mueller&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))&lt;br /&gt;
&lt;br /&gt;
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))&lt;br /&gt;
&lt;br /&gt;
# Paul Manafort was business partner of Rick Gates&lt;br /&gt;
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))&lt;br /&gt;
&lt;br /&gt;
# He was campaign chairman for Donald Trump&lt;br /&gt;
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy and lying to FBI.&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;)) # To screen&lt;br /&gt;
#g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) # To file&lt;br /&gt;
&lt;br /&gt;
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate&lt;br /&gt;
for subject, object in g[ : ex.pleadGuiltyTo :]:&lt;br /&gt;
    print(subject, ex.pleadGuiltyTo, object)&lt;br /&gt;
&lt;br /&gt;
# --- IF you have more time tasks ---&lt;br /&gt;
&lt;br /&gt;
# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that submits your model for rendering and saves the returned image to file.&lt;br /&gt;
import requests&lt;br /&gt;
import shutil&lt;br /&gt;
&lt;br /&gt;
def graphToImage(graphInput):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graphInput, &amp;quot;from&amp;quot;:&amp;quot;ttl&amp;quot;, &amp;quot;to&amp;quot;:&amp;quot;png&amp;quot;}&lt;br /&gt;
    link = &amp;quot;http://www.ldf.fi/service/rdf-grapher&amp;quot;&lt;br /&gt;
    response = requests.get(link, params = data, stream=True)&lt;br /&gt;
    # print(response.content)&lt;br /&gt;
    print(response.raw)&lt;br /&gt;
    with open(&amp;quot;lab1.png&amp;quot;, &amp;quot;wb&amp;quot;) as file:&lt;br /&gt;
        shutil.copyfileobj(response.raw, file)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDF programming with RDFlib (Lab 2)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Getting the graph created in the first lab&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
# Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to Congress.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
# Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to the FBI.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Change your graph so it represents instances of lying as blank nodes.&lt;br /&gt;
# Remove the triples that will be duplicated&lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI)) &lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.remove((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
FlynnLying = BNode() &lt;br /&gt;
g.add((FlynnLying, ex.crime, ex.LyingToFBI))&lt;br /&gt;
g.add((FlynnLying, ex.pleadGulityOn, Literal(&amp;quot;2017-12-1&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((FlynnLying, ex.liedAbout, Literal(&amp;quot;His communications with a former Russian ambassador during the presidential transition&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((FlynnLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, FlynnLying))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
GatesLying = BNode()&lt;br /&gt;
Crimes = BNode()&lt;br /&gt;
Charged = BNode()&lt;br /&gt;
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])&lt;br /&gt;
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])&lt;br /&gt;
g.add((GatesLying, ex.crime, Crimes))&lt;br /&gt;
g.add((GatesLying, ex.chargedWith, Charged))&lt;br /&gt;
g.add((GatesLying, ex.pleadGulityOn, Literal(&amp;quot;2018-02-23&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((GatesLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, GatesLying))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
CohenLying = BNode()&lt;br /&gt;
g.add((CohenLying, ex.crime, ex.LyingToCongress))&lt;br /&gt;
g.add((CohenLying, ex.liedAbout, ex.TrumpRealEstateDeal))&lt;br /&gt;
g.add((CohenLying, ex.prosecutorsAlleged, Literal(&amp;quot;In an August 2017 letter Cohen sent to congressional committees investigating Russian election interference, he falsely stated that the project ended in January 2016&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.mullerInvestigationAlleged, Literal(&amp;quot;Cohen falsely stated that he had never agreed to travel to Russia for the real estate deal and that he did not recall any contact with the Russian government about the project&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.pleadGulityOn, Literal(&amp;quot;2018-11-29&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((CohenLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, CohenLying))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
#Save (serialize) your graph to a Turtle file.&lt;br /&gt;
# g.serialize(&amp;quot;lab2.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
#Add a few triples to the Turtle file with more information about Donald Trump.&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:postalCode 33480 ;&lt;br /&gt;
            ex:residence ex:Mar_a_Lago ;&lt;br /&gt;
            ex:state ex:Florida ;&lt;br /&gt;
            ex:streetName &amp;quot;1100 S Ocean Blvd&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:previousAddress [ ex:city ex:Washington_DC ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:phoneNumber &amp;quot;1 202 456 1414&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:postalCode &amp;quot;20500&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:residence ex:The_White_House ;&lt;br /&gt;
            ex:streetName &amp;quot;1600 Pennsylvania Ave.&amp;quot;^^xsd:string ];&lt;br /&gt;
    ex:marriedTo ex:Melania_Trump;&lt;br /&gt;
    ex:fatherTo (ex:Ivanka_Trump ex:Donald_Trump_Jr ex: ex:Tiffany_Trump ex:Eric_Trump ex:Barron_Trump).&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
#Read (parse) the Turtle file back into a Python program, and check that the new triples are there&lt;br /&gt;
def serialize_Graph():&lt;br /&gt;
    newGraph = Graph()&lt;br /&gt;
    newGraph.parse(&amp;quot;lab2.ttl&amp;quot;)&lt;br /&gt;
    print(newGraph.serialize())&lt;br /&gt;
&lt;br /&gt;
#Don&#039;t need this to run until after adding the triples above to the ttl file&lt;br /&gt;
# serialize_Graph() &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that starts with Donald Trump prints out a graph depth-first to show how the other graph nodes are connected to him&lt;br /&gt;
visited_nodes = set()&lt;br /&gt;
&lt;br /&gt;
def create_Tree(model, nodes):&lt;br /&gt;
    #Traverse the model breadth-first to create the tree.&lt;br /&gt;
    global visited_nodes&lt;br /&gt;
    tree = Graph()&lt;br /&gt;
    children = set()&lt;br /&gt;
    visited_nodes |= set(nodes)&lt;br /&gt;
    for s, p, o in model:&lt;br /&gt;
        if s in nodes and o not in visited_nodes:&lt;br /&gt;
            tree.add((s, p, o))&lt;br /&gt;
            visited_nodes.add(o)&lt;br /&gt;
            children.add(o)&lt;br /&gt;
        if o in nodes and s not in visited_nodes:&lt;br /&gt;
            invp = URIRef(f&#039;{p}_inv&#039;) #_inv represents inverse of&lt;br /&gt;
            tree.add((o, invp, s))&lt;br /&gt;
            visited_nodes.add(s)&lt;br /&gt;
            children.add(s)&lt;br /&gt;
    if len(children) &amp;gt; 0:&lt;br /&gt;
        children_tree = create_Tree(model, children)&lt;br /&gt;
        for triple in children_tree:&lt;br /&gt;
            tree.add(triple)&lt;br /&gt;
    return tree&lt;br /&gt;
&lt;br /&gt;
def print_Tree(tree, root, indent=0):&lt;br /&gt;
    #Print the tree depth-first.&lt;br /&gt;
    print(str(root))&lt;br /&gt;
    for s, p, o in tree:&lt;br /&gt;
        if s==root:&lt;br /&gt;
            print(&#039;    &#039;*indent + &#039;  &#039; + str(p), end=&#039; &#039;)&lt;br /&gt;
            print_Tree(tree, o, indent+1)&lt;br /&gt;
    &lt;br /&gt;
tree = create_Tree(g, [ex.Donald_Trump])&lt;br /&gt;
print_Tree(tree, ex.Donald_Trump)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=SPARQL (Lab 3-4)=&lt;br /&gt;
===List all triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the first 100 triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT (COUNT(*) as ?count)&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of indictments===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT (COUNT(?ind) as ?amount)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:outcome ?ind;&lt;br /&gt;
      ns1:outcome ns1:indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who pleaded guilty, along with the name of the investigation===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?invname&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:investigation ?invname;&lt;br /&gt;
      ns1:outcome ns1:guilty-plea .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who were convicted, but who had their conviction overturned by which president===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?president&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:president ?president;&lt;br /&gt;
      ns1:outcome ns1:conviction;&lt;br /&gt;
      ns1:overturned ns1:true.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
ORDER BY DESC(?count)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each president, list the numbers of convictions and of pardons made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as&lt;br /&gt;
?pardons)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:president ?president;&lt;br /&gt;
      ns1:outcome ?outcome ;&lt;br /&gt;
      ns1:outcome ns1:conviction.&lt;br /&gt;
      OPTIONAL{&lt;br /&gt;
         ?s ns1:pardoned ?pardon .&lt;br /&gt;
         FILTER (?pardon = ns1:true)&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?president&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Rename mullerkg:name to something like muellerkg:person===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE{?s ns1:name ?o}&lt;br /&gt;
INSERT{?s ns1:person ?o}&lt;br /&gt;
WHERE {?s ns1:name ?o}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Persons&lt;br /&gt;
INSERT {?person foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:person ?person .&lt;br /&gt;
      BIND(REPLACE(STR(?person), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Presidents&lt;br /&gt;
INSERT {?president foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:president ?president .&lt;br /&gt;
      BIND(REPLACE(STR(?president), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use INSERT DATA updates to add these triples===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
     ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:pleadGuiltyTo ns1:LyingToFBI;&lt;br /&gt;
         ns1:sentencedTo ns1:Prison.&lt;br /&gt;
&lt;br /&gt;
     ns1:Roger_Stone a ns1:Republican;&lt;br /&gt;
         ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:officialTo ns1:Trump_Campaign;&lt;br /&gt;
         ns1:interactedWith ns1:Wikileaks;&lt;br /&gt;
         ns1:providedTestimony ns1:House_Intelligence_Committee;&lt;br /&gt;
         ns1:clearedOf ns1:AllCharges.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test if added&lt;br /&gt;
SELECT ?p ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                      ns1:WitnessTampering,&lt;br /&gt;
                                      ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#The task specifically requested DELETE DATA &amp;amp; INSERT DATA, put below is&lt;br /&gt;
a more efficient solution&lt;br /&gt;
&lt;br /&gt;
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
INSERT{&lt;br /&gt;
   ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                   ns1:WitnessTampering,&lt;br /&gt;
                                   ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a DESCRIBE query to show the updated information about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a CONSTRUCT query to create a new RDF group with triples only&lt;br /&gt;
about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o.&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone.&lt;br /&gt;
}&lt;br /&gt;
WHERE {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o .&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a DELETE/INSERT statement to change one of the prefixes in your graph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX dbp: &amp;lt;https://dbpedia.org/page/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:person ?o1}&lt;br /&gt;
INSERT {?s ns1:person ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:person ?o1 .&lt;br /&gt;
   BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#This update changes the object in triples with ns1:person as the&lt;br /&gt;
predicate. It changes it&#039;s prefix of ns1 (which is the&lt;br /&gt;
&amp;quot;shortcut/shorthand&amp;quot; for example.org) to the prefix dbp (dbpedia.org)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write an INSERT statement to add at least one significant date to the Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT statement to change the date to a string, and a new DELETE/INSERT statement to change it back to xsd:date. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
#Whilst this solution is not exactly what the task asks for, I feel like&lt;br /&gt;
this is more appropiate given the dataset. The following update&lt;br /&gt;
changes the objects that uses the cp_date as predicate from a URI, to a&lt;br /&gt;
literal with date as it&#039;s datatype&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o3}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (replace(str(?o), str(ns1:), &amp;quot;&amp;quot;)  AS ?o2)&lt;br /&gt;
   BIND (STRDT(STR(?o2), xsd:date) AS ?o3)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test:&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o.&lt;br /&gt;
   FILTER(datatype(?o) = xsd:date)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To change it to an integer, use the following code, and to change it&lt;br /&gt;
back to date, swap &amp;quot;xsd:integer&amp;quot; to &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (STRDT(STR(?o), xsd:integer) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2444</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2444"/>
		<updated>2024-02-19T13:21:05Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present suggested solutions after each lab. &#039;&#039;The page will be updated as the course progresses&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
=Getting started (Lab 1)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
from rdflib import Graph, Namespace&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
&lt;br /&gt;
# The Mueller Investigation was lead by Robert Mueller&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))&lt;br /&gt;
&lt;br /&gt;
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))&lt;br /&gt;
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))&lt;br /&gt;
&lt;br /&gt;
# Paul Manafort was business partner of Rick Gates&lt;br /&gt;
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))&lt;br /&gt;
&lt;br /&gt;
# He was campaign chairman for Donald Trump&lt;br /&gt;
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))&lt;br /&gt;
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy and lying to FBI.&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;)) # To screen&lt;br /&gt;
#g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) # To file&lt;br /&gt;
&lt;br /&gt;
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate&lt;br /&gt;
for subject, object in g[ : ex.pleadGuiltyTo :]:&lt;br /&gt;
    print(subject, ex.pleadGuiltyTo, object)&lt;br /&gt;
&lt;br /&gt;
# --- IF you have more time tasks ---&lt;br /&gt;
&lt;br /&gt;
# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that submits your model for rendering and saves the returned image to file.&lt;br /&gt;
import requests&lt;br /&gt;
import shutil&lt;br /&gt;
&lt;br /&gt;
def graphToImage(graphInput):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graphInput, &amp;quot;from&amp;quot;:&amp;quot;ttl&amp;quot;, &amp;quot;to&amp;quot;:&amp;quot;png&amp;quot;}&lt;br /&gt;
    link = &amp;quot;http://www.ldf.fi/service/rdf-grapher&amp;quot;&lt;br /&gt;
    response = requests.get(link, params = data, stream=True)&lt;br /&gt;
    # print(response.content)&lt;br /&gt;
    print(response.raw)&lt;br /&gt;
    with open(&amp;quot;lab1.png&amp;quot;, &amp;quot;wb&amp;quot;) as file:&lt;br /&gt;
        shutil.copyfileobj(response.raw, file)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=RDF programming with RDFlib (Lab 2)=&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
&lt;br /&gt;
# Getting the graph created in the first lab&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&amp;quot;http://example.org/&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
g.bind(&amp;quot;ex&amp;quot;, ex)&lt;br /&gt;
g.bind(&amp;quot;foaf&amp;quot;, FOAF)&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
# Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to Congress.&lt;br /&gt;
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
# Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))&lt;br /&gt;
# He pleaded guilty for lying to the FBI.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))&lt;br /&gt;
&lt;br /&gt;
# Change your graph so it represents instances of lying as blank nodes.&lt;br /&gt;
# Remove the triples that will be duplicated&lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI)) &lt;br /&gt;
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.remove((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.remove((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
FlynnLying = BNode() &lt;br /&gt;
g.add((FlynnLying, ex.crime, ex.LyingToFBI))&lt;br /&gt;
g.add((FlynnLying, ex.pleadGulityOn, Literal(&amp;quot;2017-12-1&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((FlynnLying, ex.liedAbout, Literal(&amp;quot;His communications with a former Russian ambassador during the presidential transition&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((FlynnLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, FlynnLying))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
GatesLying = BNode()&lt;br /&gt;
Crimes = BNode()&lt;br /&gt;
Charged = BNode()&lt;br /&gt;
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])&lt;br /&gt;
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])&lt;br /&gt;
g.add((GatesLying, ex.crime, Crimes))&lt;br /&gt;
g.add((GatesLying, ex.chargedWith, Charged))&lt;br /&gt;
g.add((GatesLying, ex.pleadGulityOn, Literal(&amp;quot;2018-02-23&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((GatesLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, GatesLying))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Cohen ---&lt;br /&gt;
CohenLying = BNode()&lt;br /&gt;
g.add((CohenLying, ex.crime, ex.LyingToCongress))&lt;br /&gt;
g.add((CohenLying, ex.liedAbout, ex.TrumpRealEstateDeal))&lt;br /&gt;
g.add((CohenLying, ex.prosecutorsAlleged, Literal(&amp;quot;In an August 2017 letter Cohen sent to congressional committees investigating Russian election interference, he falsely stated that the project ended in January 2016&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.mullerInvestigationAlleged, Literal(&amp;quot;Cohen falsely stated that he had never agreed to travel to Russia for the real estate deal and that he did not recall any contact with the Russian government about the project&amp;quot;, datatype=XSD.string)))&lt;br /&gt;
g.add((CohenLying, ex.pleadGulityOn, Literal(&amp;quot;2018-11-29&amp;quot;, datatype=XSD.date)))&lt;br /&gt;
g.add((CohenLying, ex.pleaBargain, Literal(&amp;quot;true&amp;quot;, datatype=XSD.boolean)))&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, CohenLying))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
#Save (serialize) your graph to a Turtle file.&lt;br /&gt;
# g.serialize(&amp;quot;lab2.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
#Add a few triples to the Turtle file with more information about Donald Trump.&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:postalCode 33480 ;&lt;br /&gt;
            ex:residence ex:Mar_a_Lago ;&lt;br /&gt;
            ex:state ex:Florida ;&lt;br /&gt;
            ex:streetName &amp;quot;1100 S Ocean Blvd&amp;quot;^^xsd:string ] ;&lt;br /&gt;
    ex:previousAddress [ ex:city ex:Washington_DC ;&lt;br /&gt;
            ex:country ex:United_States ;&lt;br /&gt;
            ex:phoneNumber &amp;quot;1 202 456 1414&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:postalCode &amp;quot;20500&amp;quot;^^xsd:integer ;&lt;br /&gt;
            ex:residence ex:The_White_House ;&lt;br /&gt;
            ex:streetName &amp;quot;1600 Pennsylvania Ave.&amp;quot;^^xsd:string ];&lt;br /&gt;
    ex:marriedTo ex:Melania_Trump;&lt;br /&gt;
    ex:fatherTo (ex:Ivanka_Trump ex:Donald_Trump_Jr ex: ex:Tiffany_Trump ex:Eric_Trump ex:Barron_Trump).&lt;br /&gt;
&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
#Read (parse) the Turtle file back into a Python program, and check that the new triples are there&lt;br /&gt;
def serialize_Graph():&lt;br /&gt;
    newGraph = Graph()&lt;br /&gt;
    newGraph.parse(&amp;quot;lab2.ttl&amp;quot;)&lt;br /&gt;
    print(newGraph.serialize())&lt;br /&gt;
&lt;br /&gt;
#Don&#039;t need this to run until after adding the triples above to the ttl file&lt;br /&gt;
# serialize_Graph() &lt;br /&gt;
&lt;br /&gt;
#Write a method (function) that starts with Donald Trump prints out a graph depth-first to show how the other graph nodes are connected to him&lt;br /&gt;
visited_nodes = set()&lt;br /&gt;
&lt;br /&gt;
def create_Tree(model, nodes):&lt;br /&gt;
    #Traverse the model breadth-first to create the tree.&lt;br /&gt;
    global visited_nodes&lt;br /&gt;
    tree = Graph()&lt;br /&gt;
    children = set()&lt;br /&gt;
    visited_nodes |= set(nodes)&lt;br /&gt;
    for s, p, o in model:&lt;br /&gt;
        if s in nodes and o not in visited_nodes:&lt;br /&gt;
            tree.add((s, p, o))&lt;br /&gt;
            visited_nodes.add(o)&lt;br /&gt;
            children.add(o)&lt;br /&gt;
        if o in nodes and s not in visited_nodes:&lt;br /&gt;
            invp = URIRef(f&#039;{p}_inv&#039;) #_inv represents inverse of&lt;br /&gt;
            tree.add((o, invp, s))&lt;br /&gt;
            visited_nodes.add(s)&lt;br /&gt;
            children.add(s)&lt;br /&gt;
    if len(children) &amp;gt; 0:&lt;br /&gt;
        children_tree = create_Tree(model, children)&lt;br /&gt;
        for triple in children_tree:&lt;br /&gt;
            tree.add(triple)&lt;br /&gt;
    return tree&lt;br /&gt;
&lt;br /&gt;
def print_Tree(tree, root, indent=0):&lt;br /&gt;
    #Print the tree depth-first.&lt;br /&gt;
    print(str(root))&lt;br /&gt;
    for s, p, o in tree:&lt;br /&gt;
        if s==root:&lt;br /&gt;
            print(&#039;    &#039;*indent + &#039;  &#039; + str(p), end=&#039; &#039;)&lt;br /&gt;
            print_Tree(tree, o, indent+1)&lt;br /&gt;
    &lt;br /&gt;
tree = create_Tree(g, [ex.Donald_Trump])&lt;br /&gt;
print_Tree(tree, ex.Donald_Trump)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL (Lab 3)==&lt;br /&gt;
===List all triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the first 100 triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT ?s ?p ?o&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
LIMIT 100&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of triples===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
SELECT (COUNT(*) as ?count)&lt;br /&gt;
WHERE {?s ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Count the number of indictments===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT (COUNT(?ind) as ?amount)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:outcome ?ind;&lt;br /&gt;
      ns1:outcome ns1:indictment.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who pleaded guilty, along with the name of&lt;br /&gt;
the investigation===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?invname&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:investigation ?invname;&lt;br /&gt;
      ns1:outcome ns1:guilty-plea .&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===List the names of everyone who were convicted, but who had their&lt;br /&gt;
conviction overturned by which president===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?name ?president&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:name ?name;&lt;br /&gt;
      ns1:president ?president;&lt;br /&gt;
      ns1:outcome ns1:conviction;&lt;br /&gt;
      ns1:overturned ns1:true.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation, list the number of indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of&lt;br /&gt;
indictments made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each investigation with multiple indictments, list the number of&lt;br /&gt;
indictments made, sorted with the most indictments first===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?invs (COUNT(?invs) as ?count)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:investigation ?invs;&lt;br /&gt;
      ns1:outcome ns1:indictment .&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?invs&lt;br /&gt;
HAVING(?count &amp;gt; 1)&lt;br /&gt;
ORDER BY DESC(?count)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For each president, list the numbers of convictions and of pardons&lt;br /&gt;
made===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as&lt;br /&gt;
?pardons)&lt;br /&gt;
WHERE {&lt;br /&gt;
   ?s ns1:president ?president;&lt;br /&gt;
      ns1:outcome ?outcome ;&lt;br /&gt;
      ns1:outcome ns1:conviction.&lt;br /&gt;
      OPTIONAL{&lt;br /&gt;
         ?s ns1:pardoned ?pardon .&lt;br /&gt;
         FILTER (?pardon = ns1:true)&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
GROUP BY ?president&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Rename mullerkg:name to something like muellerkg:person===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE{?s ns1:name ?o}&lt;br /&gt;
INSERT{?s ns1:person ?o}&lt;br /&gt;
WHERE {?s ns1:name ?o}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Update the graph so all the investigated person and president nodes&lt;br /&gt;
become the subjects in foaf:name triples with the corresponding strings===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#Persons&lt;br /&gt;
INSERT {?person foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:person ?person .&lt;br /&gt;
      BIND(REPLACE(STR(?person), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Presidents&lt;br /&gt;
INSERT {?president foaf:name ?name}&lt;br /&gt;
WHERE {&lt;br /&gt;
      ?investigation ns1:president ?president .&lt;br /&gt;
      BIND(REPLACE(STR(?president), STR(ns1:), &amp;quot;&amp;quot;) AS ?name)&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use INSERT DATA updates to add these triples===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
     ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:pleadGuiltyTo ns1:LyingToFBI;&lt;br /&gt;
         ns1:sentencedTo ns1:Prison.&lt;br /&gt;
&lt;br /&gt;
     ns1:Roger_Stone a ns1:Republican;&lt;br /&gt;
         ns1:adviserTo ns1:Donald_Trump;&lt;br /&gt;
         ns1:officialTo ns1:Trump_Campaign;&lt;br /&gt;
         ns1:interactedWith ns1:Wikileaks;&lt;br /&gt;
         ns1:providedTestimony ns1:House_Intelligence_Committee;&lt;br /&gt;
         ns1:clearedOf ns1:AllCharges.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test if added&lt;br /&gt;
SELECT ?p ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ?p ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use DELETE DATA and then INSERT DATA updates to correct that Roger&lt;br /&gt;
Stone was cleared of all charges===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {&lt;br /&gt;
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                      ns1:WitnessTampering,&lt;br /&gt;
                                      ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#The task specifically requested DELETE DATA &amp;amp; INSERT DATA, put below is&lt;br /&gt;
a more efficient solution&lt;br /&gt;
&lt;br /&gt;
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
INSERT{&lt;br /&gt;
   ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,&lt;br /&gt;
                                   ns1:WitnessTampering,&lt;br /&gt;
                                   ns1:FalseStatements.&lt;br /&gt;
}&lt;br /&gt;
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a DESCRIBE query to show the updated information about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DESCRIBE ?o&lt;br /&gt;
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Use a CONSTRUCT query to create a new RDF group with triples only&lt;br /&gt;
about Roger Stone===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
CONSTRUCT {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o.&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone.&lt;br /&gt;
}&lt;br /&gt;
WHERE {&lt;br /&gt;
   ns1:Roger_Stone ?p ?o .&lt;br /&gt;
   ?s ?p2 ns1:Roger_Stone&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write a DELETE/INSERT statement to change one of the prefixes in your&lt;br /&gt;
graph===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
PREFIX dbp: &amp;lt;https://dbpedia.org/page/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:person ?o1}&lt;br /&gt;
INSERT {?s ns1:person ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:person ?o1 .&lt;br /&gt;
   BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#This update changes the object in triples with ns1:person as the&lt;br /&gt;
predicate. It changes it&#039;s prefix of ns1 (which is the&lt;br /&gt;
&amp;quot;shortcut/shorthand&amp;quot; for example.org) to the prefix dbp (dbpedia.org)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Write an INSERT statement to add at least one significant date to the&lt;br /&gt;
Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT&lt;br /&gt;
statement to change the date to a string, and a new DELETE/INSERT&lt;br /&gt;
statement to change it back to xsd:date. ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
#Whilst this solution is not exactly what the task asks for, I feel like&lt;br /&gt;
this is more appropiate given the dataset. The following update&lt;br /&gt;
changes the objects that uses the cp_date as predicate from a URI, to a&lt;br /&gt;
literal with date as it&#039;s datatype&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o3}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (replace(str(?o), str(ns1:), &amp;quot;&amp;quot;)  AS ?o2)&lt;br /&gt;
   BIND (STRDT(STR(?o2), xsd:date) AS ?o3)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To test:&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SELECT ?s ?o&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o.&lt;br /&gt;
   FILTER(datatype(?o) = xsd:date)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#To change it to an integer, use the following code, and to change it&lt;br /&gt;
back to date, swap &amp;quot;xsd:integer&amp;quot; to &amp;quot;xsd:date&amp;quot;&lt;br /&gt;
&lt;br /&gt;
PREFIX xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt;&lt;br /&gt;
PREFIX ns1: &amp;lt;http://example.org#&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DELETE {?s ns1:cp_date ?o}&lt;br /&gt;
INSERT{?s ns1:cp_date ?o2}&lt;br /&gt;
WHERE{&lt;br /&gt;
   ?s ns1:cp_date ?o .&lt;br /&gt;
   BIND (STRDT(STR(?o), xsd:integer) AS ?o2)&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_Programming&amp;diff=2443</id>
		<title>Lab: SPARQL Programming</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_Programming&amp;diff=2443"/>
		<updated>2024-02-19T12:58:10Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
SPARQL programming in Python: &lt;br /&gt;
* with &#039;&#039;rdflib&#039;&#039;: to manage an rdflib Graph internally in a program&lt;br /&gt;
* with &#039;&#039;SPARQLWrapper&#039;&#039; and &#039;&#039;GraphDB&#039;&#039;: to manage an RDF graph stored externally in GraphDB (on your own local machine, but in principle it could be anywhere on the internet)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Motivation:&#039;&#039; Last week we entered SPARQL queries and updates manually from the web interface. But in the majority of cases we want to &#039;&#039;program&#039;&#039; the management of triples in our graphs, for example to handle automatic or scheduled updates.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Important:&#039;&#039; There were quite a lot of SPARQL tasks in the last exercise. There are a lot of tasks in this exercise too, but the important thing is that you get to try the different types of SPARQL programming. How many SPARK queries and updates you do is a little up to you, but you must try at least one query and one update both using rdflib and SPARQLWrapper. And it is best if you try several different types of SPARQL queries too: both a SELECT, a CONSTRUCT or DESCRIBE, and an ASK.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
*[https://github.com/RDFLib/sparqlwrapper SPARQLWrapper]&lt;br /&gt;
*[https://rdflib.readthedocs.io/en/stable/intro_to_sparql.html RDFlib - Querying with SPARQL]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===SPARQL programming in Python with rdflib===&lt;br /&gt;
&#039;&#039;&#039;Getting ready:&#039;&#039;&#039;&lt;br /&gt;
No additional installation is needed. You are already running Python and rdflib.&lt;br /&gt;
&lt;br /&gt;
Parse the file &#039;&#039;russia_investigation_kg.ttl&#039;&#039; into an rdflib Graph. (The original file is available here: [[File:russia_investigation_kg.txt]]. Rename it from &#039;&#039;.txt&#039;&#039; to &#039;&#039;.ttl&#039;&#039;). &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Write the following queries and updates with Python and rdflib. See boilerplate examples below.&lt;br /&gt;
* Print out a list of all the predicates used in your graph. &lt;br /&gt;
* Print out a sorted list of all the presidents represented in your graph. &lt;br /&gt;
* Create dictionary (Python &#039;&#039;dict&#039;&#039;) with all the represented presidents as keys. For each key, the value is a list of names of people indicted under that president.&lt;br /&gt;
* Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.&lt;br /&gt;
* Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.&lt;br /&gt;
&lt;br /&gt;
Note that different types of queries return objects with different contents. You can use core completion in your IDE or Python&#039;s &#039;&#039;dir()&#039;&#039; function to explore this further (for example &#039;&#039;dir(results)&#039;&#039;).&lt;br /&gt;
* SELECT: returns an object you can iterate over (among other things) to get the table rows (the result object also contains table headers)&lt;br /&gt;
* ASK: returns an object that contains a single logical value (&#039;&#039;True&#039;&#039; or &#039;&#039;False&#039;&#039;)&lt;br /&gt;
* DESCRIBE and CONSTRUCT: return an rdflib Graph&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Contents of the file &#039;spouses.ttl&#039;:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix schema: &amp;lt;https://schema.org/&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Donald_Trump schema:spouse ( ex:IvanaTrump ex:MarlaMaples ex:MelaniaTrump ) .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for rdflib query:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;spouses.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
result = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX schema: &amp;lt;https://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?spouse WHERE {&lt;br /&gt;
        ex:Donald_Trump schema:spouse / rdf:rest* / rdf:first ?spouse .&lt;br /&gt;
    }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for row in result:&lt;br /&gt;
    print(&amp;quot;Donald has spouse %s&amp;quot; % row)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for rdflib update&#039;&#039;&#039;&lt;br /&gt;
(using the KG4News graph again):&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX dct: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {    &lt;br /&gt;
    kg:paper_123 rdf:type ss:Paper ;&lt;br /&gt;
               ss:title &amp;quot;Semantic Knowledge Graphs for the News: A Review&amp;quot;@en ;&lt;br /&gt;
            kg:year 2022 ;&lt;br /&gt;
            dct:contributor kg:auth_456, kg:auth_789 . &lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.update(update_str)&lt;br /&gt;
print(g.serialize(format=&#039;ttl&#039;))  # format=’turtle’ also works&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SPARQL programming in Python with SPARQLWrapper and GraphDB===&lt;br /&gt;
&#039;&#039;&#039;Getting ready:&#039;&#039;&#039;&lt;br /&gt;
You need a running &#039;&#039;and activated&#039;&#039; GraphDB repository as in [[Lab: SPARQL | Exercise 3: SPARQL]]. You will run GraphDB locally to keep things simple. &lt;br /&gt;
&lt;br /&gt;
Install SPARQLWrapper (in your virtual environment):&lt;br /&gt;
 pip install SPARQLWrapper&lt;br /&gt;
Some older versions also require you to install &#039;&#039;requests&#039;&#039; API. The [https://github.com/RDFLib/sparqlwrapper SPARQLWrapper page on GitHub] contains more information.&lt;br /&gt;
&lt;br /&gt;
Continue with the &#039;&#039;russia_investigation_kg.ttl&#039;&#039; example. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Program the following queries and updates with SPARQLWrapper and GraphDB.&lt;br /&gt;
* Ask whether there was an ongoing investigation on the date 1990-01-01.&lt;br /&gt;
* List ongoing investigations on that date 1990-01-01.&lt;br /&gt;
* Describe investigation number 100 (&#039;&#039;muellerkg:investigation_100&#039;&#039;).&lt;br /&gt;
* Print out a list of all the types used in your graph.&lt;br /&gt;
* Update the graph to that every resource that is an object in a &#039;&#039;muellerkg:investigation&#039;&#039; triple has the &#039;&#039;rdf:type&#039;&#039; &#039;&#039;muellerkg:Investigation&#039;&#039;.&lt;br /&gt;
* Update the graph to that every resource that is an object in a &#039;&#039;muellerkg:person&#039;&#039; triple has the &#039;&#039;rdf:type&#039;&#039; &#039;&#039;muellerkg:IndictedPerson&#039;&#039;.&lt;br /&gt;
* Update the graph so all the investigation nodes (such as &#039;&#039;muellerkg:watergate&#039;&#039;) become the subject in a &#039;&#039;dc:title&#039;&#039; triple with the corresponding string (&#039;&#039;watergate&#039;&#039;) as the literal.&lt;br /&gt;
* Print out a sorted list of all the indicted persons represented in your graph.&lt;br /&gt;
* Print out the minimum, average and maximum indictment days for all the indictments in the graph.&lt;br /&gt;
* Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.&lt;br /&gt;
&lt;br /&gt;
Note that different types of queries return different data formats with different structures: &lt;br /&gt;
* SELECT and ASK: return a SPARQL Results Document in either XML, JSON, or CSV/TSV format.&lt;br /&gt;
* DESCRIBE and CONSTRUCT: return an RDF graph serialised in TURTLE or RDF/XML syntax, for example.&lt;br /&gt;
* Use a DESCRIBE query to create an rdflib Graph about Oliver Stone. Print the graph out in Turtle format.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for SPARQLWrapper query:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039;  # you may want to change this&lt;br /&gt;
REPOSITORY = &#039;lab04&#039;               # you most likely want to change this&lt;br /&gt;
&lt;br /&gt;
endpoint = f&#039;{SERVER}/repositories/{REPOSITORY}&#039;  # standard path for GraphDB queries&lt;br /&gt;
&lt;br /&gt;
query = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX schema: &amp;lt;https://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?spouse WHERE {&lt;br /&gt;
 	 	ex:Donald_Trump schema:spouse / rdf:rest* / rdf:first ?spouse .&lt;br /&gt;
    }&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    &lt;br /&gt;
client = SPARQLWrapper(endpoint)&lt;br /&gt;
client.setReturnFormat(&#039;json&#039;)&lt;br /&gt;
client.setQuery(query)&lt;br /&gt;
&lt;br /&gt;
print(&#039;Spouses:&#039;)&lt;br /&gt;
results = client.queryAndConvert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;spouse&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for SPARQLWrapper update:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039;  # you may want to change this&lt;br /&gt;
REPOSITORY = &#039;lab04&#039;               # you most likely want to change this&lt;br /&gt;
&lt;br /&gt;
endpoint = f&#039;{SERVER}/repositories/{REPOSITORY}/statements&#039;  # standard path for GraphDB updates&lt;br /&gt;
&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX dct: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {    &lt;br /&gt;
    kg:paper_123 rdf:type ss:Paper ;&lt;br /&gt;
               ss:title &amp;quot;Semantic Knowledge Graphs for the News: A Review&amp;quot;@en ;&lt;br /&gt;
            kg:year 2023 ;&lt;br /&gt;
            dct:contributor kg:auth_654, kg:auth_789 . &lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
client = SPARQLWrapper(endpoint)&lt;br /&gt;
client.setMethod(&#039;POST&#039;)&lt;br /&gt;
client.setQuery(update_str)&lt;br /&gt;
res = client.queryAndConvert()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
Continue with the &#039;&#039;russia_investigation_kg.ttl&#039;&#039; example. Use either rdflib or SPARQLWrapper as you prefer - or both :-) &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write a query that lists all the resources in your graph that have Wikidata prefixes (i.e., &#039;&#039;http://www.wikidata.org/entity/&#039;&#039;). Use the result to generate a list of Wikidata entity identifiers (i.e., Q-codes like these &#039;&#039;[&#039;Q13&#039;, &#039;Q42&#039;, &#039;Q80&#039;]&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Install the [https://pypi.org/project/Wikidata/ wikidata] API:&lt;br /&gt;
 pip install wikidata&lt;br /&gt;
Check out the following code:&lt;br /&gt;
 from wikidata.client import Client&lt;br /&gt;
 &lt;br /&gt;
 client = Client()&lt;br /&gt;
 q80 = client.get(&#039;Q80&#039;)&lt;br /&gt;
Use the API to extend your local graph, for example with &#039;&#039;descriptions&#039;&#039; of some of your resources.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
The &#039;&#039;wikidata&#039;&#039; API is good for simple tasks, but SPARQL is must more powerful. To explore available Wikidata properties, you can go to the [http:query.wikidata.org web GUI] and try &lt;br /&gt;
 DESCRIBE wd:Q80  # or Q7358961...&lt;br /&gt;
You want to use prefixes like these (predefined in Wikidata query interface):&lt;br /&gt;
 PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;        # for resources&lt;br /&gt;
 PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;  # for properties&lt;br /&gt;
Stay away from the &#039;&#039;p:&#039;&#039; and &#039;&#039;wds:&#039;&#039; prefixes for now.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Write an embedded query that extends your local graph further, for example with more resource types. Property &#039;&#039;P31&#039;&#039; in Wikidata corresponds to &#039;&#039;rdf:type&#039;&#039; in your local graph. &#039;&#039;Use LIMIT, and make sure the query runs in the web GUI before you embed it.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
For resources that are humans (entity &#039;&#039;Q5&#039;&#039;), you can add further information, for example about &#039;&#039;party affiliation&#039;&#039; and about &#039;&#039;significant events&#039;&#039; the person has been involved in.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate for embedded Wikidata queries:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;        # for Wikidata resources&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;  # for Wikidata properties&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
&lt;br /&gt;
    # your local query heere, which binds the Wikidata identifier ?wdresource&lt;br /&gt;
    # ?wdresource must be a URI that starts with http://www.wikidata.org/entity/&lt;br /&gt;
&lt;br /&gt;
    # test binding:&lt;br /&gt;
    BIND(wd:Q80 AS ?wdresource)&lt;br /&gt;
&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        # return the Wikidata types of ?wd resource&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
             ?wdresource wdt:P31 ?wdtype .&lt;br /&gt;
        }&lt;br /&gt;
        LIMIT 5  # always use limit in remote queries&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    # possible to continue local query here &lt;br /&gt;
}&lt;br /&gt;
LIMIT 10&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
You can also try to connect to the [http://info216.i2s.uib.no/ INFO216 Sandbox] (read/write) and [http://kg4news.newsangler.uib.no KG4News Server] (read-only). &lt;br /&gt;
&lt;br /&gt;
Both SPARQL endpoints run [https://blazegraph.com/ Blazegraph], which uses &amp;quot;namespaces&amp;quot; instead of &amp;quot;repositories&amp;quot;, so the URLs are a little different. In the web UI , the &amp;quot;NAMESPACES&amp;quot; tab lets you select an existing or create a new namespace to use.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SERVER = &#039;http://info216.i2s.uib.no/bigdata/&#039;  # you may want to change this&lt;br /&gt;
NAMESPACE  = &#039;lab04&#039;                           # you most likely want to change this&lt;br /&gt;
&lt;br /&gt;
endpoint = f&#039;{SERVER}namespace/{NAMESPACE}/sparql&#039;  # standard path for Blazegraph queries (and updates)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_Programming&amp;diff=2442</id>
		<title>Lab: SPARQL Programming</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_Programming&amp;diff=2442"/>
		<updated>2024-02-16T12:14:45Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
SPARQL programming in Python: &lt;br /&gt;
* with &#039;&#039;rdflib&#039;&#039;: to manage an rdflib Graph internally in a program&lt;br /&gt;
* with &#039;&#039;SPARQLWrapper&#039;&#039; and &#039;&#039;GraphDB&#039;&#039;: to manage an RDF graph stored externally in GraphDB (on your own local machine, but in principle it could be anywhere on the internet)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Motivation:&#039;&#039; Last week we entered SPARQL queries and updates manually from the web interface. But in the majority of cases we want to &#039;&#039;program&#039;&#039; the management of triples in our graphs, for example to handle automatic or scheduled updates.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Important:&#039;&#039; There were quite a lot of SPARQL tasks in the last exercise. There are a lot of tasks in this exercise too, but the important thing is that you get to try the different types of SPARQL programming. How many SPARK queries and updates you do is a little up to you, but you must try at least one query and one update both using rdflib and SPARQLWrapper. And it is best if you try several different types of SPARQL queries too: both a SELECT, a CONSTRUCT or DESCRIBE, and an ASK.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
*[https://github.com/RDFLib/sparqlwrapper SPARQLWrapper]&lt;br /&gt;
*[https://rdflib.readthedocs.io/en/stable/intro_to_sparql.html RDFlib - Querying with SPARQL]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===SPARQL programming in Python with rdflib===&lt;br /&gt;
&#039;&#039;&#039;Getting ready:&#039;&#039;&#039;&lt;br /&gt;
No additional installation is needed. You are already running Python and rdflib.&lt;br /&gt;
&lt;br /&gt;
Parse the file &#039;&#039;russia_investigation_kg.ttl&#039;&#039; into an rdflib Graph. (The original file is available here: [[File:russia_investigation_kg.txt]]. Rename it from &#039;&#039;.txt&#039;&#039; to &#039;&#039;.ttl&#039;&#039;). &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Write the following queries and updates with Python and rdflib. See boilerplate examples below.&lt;br /&gt;
* Print out a list of all the predicates used in your graph. &lt;br /&gt;
* Print out a sorted list of all the presidents represented in your graph. &lt;br /&gt;
* Create dictionary (Python &#039;&#039;dict&#039;&#039;) with all the represented presidents as keys. For each key, the value is a list of names of people indicted under that president.&lt;br /&gt;
* Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.&lt;br /&gt;
* Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.&lt;br /&gt;
&lt;br /&gt;
Note that different types of queries return objects with different contents. You can use core completion in your IDE or Python&#039;s &#039;&#039;dir()&#039;&#039; function to explore this further (for example &#039;&#039;dir(results)&#039;&#039;).&lt;br /&gt;
* SELECT: returns an object you can iterate over (among other things) to get the table rows (the result object also contains table headers)&lt;br /&gt;
* ASK: returns an object that contains a single logical value (&#039;&#039;True&#039;&#039; or &#039;&#039;False&#039;&#039;)&lt;br /&gt;
* DESCRIBE and CONSTRUCT: return an rdflib Graph&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Contents of the file &#039;spouses.ttl&#039;:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
@prefix schema: &amp;lt;https://schema.org/&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Donald_Trump schema:spouse ( ex:IvanaTrump ex:MarlaMaples ex:MelaniaTrump ) .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for rdflib query:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;spouses.ttl&amp;quot;, format=&#039;ttl&#039;)&lt;br /&gt;
result = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX schema: &amp;lt;https://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?spouse WHERE {&lt;br /&gt;
        ex:Donald_Trump schema:spouse / rdf:rest* / rdf:first ?spouse .&lt;br /&gt;
    }&amp;quot;&amp;quot;&amp;quot;)&lt;br /&gt;
for row in result:&lt;br /&gt;
    print(&amp;quot;Donald has spouse %s&amp;quot; % row)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for rdflib update&#039;&#039;&#039;&lt;br /&gt;
(using the KG4News graph again):&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph&lt;br /&gt;
&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX dct: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {    &lt;br /&gt;
    kg:paper_123 rdf:type ss:Paper ;&lt;br /&gt;
               ss:title &amp;quot;Semantic Knowledge Graphs for the News: A Review&amp;quot;@en ;&lt;br /&gt;
            kg:year 2022 ;&lt;br /&gt;
            dct:contributor kg:auth_456, kg:auth_789 . &lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.update(update_str)&lt;br /&gt;
print(g.serialize(format=&#039;ttl&#039;))  # format=’turtle’ also works&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SPARQL programming in Python with SPARQLWrapper and GraphDB===&lt;br /&gt;
&#039;&#039;&#039;Getting ready:&#039;&#039;&#039;&lt;br /&gt;
You need a running &#039;&#039;and activated&#039;&#039; GraphDB repository as in [[Lab: SPARQL | Exercise 3: SPARQL]]. You will run GraphDB locally to keep things simple. &lt;br /&gt;
&lt;br /&gt;
Install SPARQLWrapper (in your virtual environment):&lt;br /&gt;
 pip install SPARQLWrapper&lt;br /&gt;
Some older versions also require you to install &#039;&#039;requests&#039;&#039; API. The [https://github.com/RDFLib/sparqlwrapper SPARQLWrapper page on GitHub] contains more information.&lt;br /&gt;
&lt;br /&gt;
Continue with the &#039;&#039;russia_investigation_kg.ttl&#039;&#039; example. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Program the following queries and updates with SPARQLWrapper and GraphDB.&lt;br /&gt;
* Ask whether there was an ongoing investigation on the date 1990-01-01.&lt;br /&gt;
* List ongoing investigations on that date 1990-01-01.&lt;br /&gt;
* Describe investigation number 100 (&#039;&#039;muellerkg:investigation_100&#039;&#039;).&lt;br /&gt;
* Print out a list of all the types used in your graph.&lt;br /&gt;
* Update the graph to that every resource that is an object in a &#039;&#039;muellerkg:investigation&#039;&#039; triple has the &#039;&#039;rdf:type&#039;&#039; &#039;&#039;muellerkg:Investigation&#039;&#039;.&lt;br /&gt;
* Update the graph to that every resource that is an object in a &#039;&#039;muellerkg:person&#039;&#039; triple has the &#039;&#039;rdf:type&#039;&#039; &#039;&#039;muellerkg:IndictedPerson&#039;&#039;.&lt;br /&gt;
* Update the graph so all the investigation nodes (such as &#039;&#039;muellerkg:watergate&#039;&#039;) become the subject in a &#039;&#039;dc:title&#039;&#039; triple with the corresponding string (&#039;&#039;watergate&#039;&#039;) as the literal.&lt;br /&gt;
* Print out a sorted list of all the indicted persons represented in your graph.&lt;br /&gt;
* Print out the minimum, average and maximum indictment days for all the indictments in the graph.&lt;br /&gt;
* Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.&lt;br /&gt;
&lt;br /&gt;
Note that different types of queries return different data formats with different structures: &lt;br /&gt;
* SELECT and ASK: return a SPARQL Results Document in either XML, JSON, or CSV/TSV format.&lt;br /&gt;
* DESCRIBE and CONSTRUCT: return an RDF graph serialised in TURTLE or RDF/XML syntax, for example.&lt;br /&gt;
* Use a DESCRIBE query to create an rdflib Graph about Oliver Stone. Print the graph out in Turtle format.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for SPARQLWrapper query:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039;  # you may want to change this&lt;br /&gt;
REPOSITORY = &#039;lab04&#039;               # you most likely want to change this&lt;br /&gt;
&lt;br /&gt;
endpoint = f&#039;{SERVER}/repositories/{REPOSITORY}&#039;  # standard path for GraphDB queries&lt;br /&gt;
&lt;br /&gt;
query = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    PREFIX ex: &amp;lt;http://example.org/&amp;gt;&lt;br /&gt;
    PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
    PREFIX schema: &amp;lt;https://schema.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    SELECT ?spouse WHERE {&lt;br /&gt;
 	 	ex:Donald_Trump schema:spouse / rdf:rest* / rdf:first ?spouse .&lt;br /&gt;
    }&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    &lt;br /&gt;
client = SPARQLWrapper(endpoint)&lt;br /&gt;
client.setReturnFormat(&#039;json&#039;)&lt;br /&gt;
client.setQuery(query)&lt;br /&gt;
&lt;br /&gt;
print(&#039;Spouses:&#039;)&lt;br /&gt;
results = client.queryAndConvert()&lt;br /&gt;
for result in results[&amp;quot;results&amp;quot;][&amp;quot;bindings&amp;quot;]:&lt;br /&gt;
    print(result[&amp;quot;spouse&amp;quot;][&amp;quot;value&amp;quot;])&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate code for SPARQLWrapper update:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;python&amp;quot;&amp;gt;&lt;br /&gt;
from SPARQLWrapper import SPARQLWrapper&lt;br /&gt;
&lt;br /&gt;
SERVER = &#039;http://localhost:7200&#039;  # you may want to change this&lt;br /&gt;
REPOSITORY = &#039;lab04&#039;               # you most likely want to change this&lt;br /&gt;
&lt;br /&gt;
endpoint = f&#039;{SERVER}/repositories/{REPOSITORY}&#039;  # standard path for GraphDB updates&lt;br /&gt;
&lt;br /&gt;
update_str = &amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
PREFIX rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt;&lt;br /&gt;
PREFIX dct: &amp;lt;http://purl.org/dc/terms/&amp;gt;&lt;br /&gt;
PREFIX kg: &amp;lt;http://i2s.uib.no/kg4news/&amp;gt;&lt;br /&gt;
PREFIX ss: &amp;lt;http://semanticscholar.org/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
INSERT DATA {    &lt;br /&gt;
    kg:paper_123 rdf:type ss:Paper ;&lt;br /&gt;
               ss:title &amp;quot;Semantic Knowledge Graphs for the News: A Review&amp;quot;@en ;&lt;br /&gt;
            kg:year 2023 ;&lt;br /&gt;
            dct:contributor kg:auth_654, kg:auth_789 . &lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
client = SPARQLWrapper(endpoint)&lt;br /&gt;
client.setMethod(&#039;POST&#039;)&lt;br /&gt;
client.setQuery(update_str)&lt;br /&gt;
res = client.queryAndConvert()&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
Continue with the &#039;&#039;russia_investigation_kg.ttl&#039;&#039; example. Use either rdflib or SPARQLWrapper as you prefer - or both :-) &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write a query that lists all the resources in your graph that have Wikidata prefixes (i.e., &#039;&#039;http://www.wikidata.org/entity/&#039;&#039;). Use the result to generate a list of Wikidata entity identifiers (i.e., Q-codes like these &#039;&#039;[&#039;Q13&#039;, &#039;Q42&#039;, &#039;Q80&#039;]&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Install the [https://pypi.org/project/Wikidata/ wikidata] API:&lt;br /&gt;
 pip install wikidata&lt;br /&gt;
Check out the following code:&lt;br /&gt;
 from wikidata.client import Client&lt;br /&gt;
 &lt;br /&gt;
 client = Client()&lt;br /&gt;
 q80 = client.get(&#039;Q80&#039;)&lt;br /&gt;
Use the API to extend your local graph, for example with &#039;&#039;descriptions&#039;&#039; of some of your resources.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
The &#039;&#039;wikidata&#039;&#039; API is good for simple tasks, but SPARQL is must more powerful. To explore available Wikidata properties, you can go to the [http:query.wikidata.org web GUI] and try &lt;br /&gt;
 DESCRIBE wd:Q80  # or Q7358961...&lt;br /&gt;
You want to use prefixes like these (predefined in Wikidata query interface):&lt;br /&gt;
 PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;        # for resources&lt;br /&gt;
 PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;  # for properties&lt;br /&gt;
Stay away from the &#039;&#039;p:&#039;&#039; and &#039;&#039;wds:&#039;&#039; prefixes for now.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Write an embedded query that extends your local graph further, for example with more resource types. Property &#039;&#039;P31&#039;&#039; in Wikidata corresponds to &#039;&#039;rdf:type&#039;&#039; in your local graph. &#039;&#039;Use LIMIT, and make sure the query runs in the web GUI before you embed it.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
For resources that are humans (entity &#039;&#039;Q5&#039;&#039;), you can add further information, for example about &#039;&#039;party affiliation&#039;&#039; and about &#039;&#039;significant events&#039;&#039; the person has been involved in.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Boilerplate for embedded Wikidata queries:&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;SPARQL&amp;quot;&amp;gt;&lt;br /&gt;
PREFIX wd: &amp;lt;http://www.wikidata.org/entity/&amp;gt;        # for Wikidata resources&lt;br /&gt;
PREFIX wdt: &amp;lt;http://www.wikidata.org/prop/direct/&amp;gt;  # for Wikidata properties&lt;br /&gt;
&lt;br /&gt;
SELECT * WHERE {&lt;br /&gt;
&lt;br /&gt;
    # your local query heere, which binds the Wikidata identifier ?wdresource&lt;br /&gt;
    # ?wdresource must be a URI that starts with http://www.wikidata.org/entity/&lt;br /&gt;
&lt;br /&gt;
    # test binding:&lt;br /&gt;
    BIND(wd:Q80 AS ?wdresource)&lt;br /&gt;
&lt;br /&gt;
    SERVICE &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; {&lt;br /&gt;
        # return the Wikidata types of ?wd resource&lt;br /&gt;
        SELECT * WHERE {&lt;br /&gt;
             ?wdresource wdt:P31 ?wdtype .&lt;br /&gt;
        }&lt;br /&gt;
        LIMIT 5  # always use limit in remote queries&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    # possible to continue local query here &lt;br /&gt;
}&lt;br /&gt;
LIMIT 10&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
You can also try to connect to the [http://info216.i2s.uib.no/ INFO216 Sandbox] (read/write) and [http://kg4news.newsangler.uib.no KG4News Server] (read-only). &lt;br /&gt;
&lt;br /&gt;
Both SPARQL endpoints run [https://blazegraph.com/ Blazegraph], which uses &amp;quot;namespaces&amp;quot; instead of &amp;quot;repositories&amp;quot;, so the URLs are a little different. In the web UI , the &amp;quot;NAMESPACES&amp;quot; tab lets you select an existing or create a new namespace to use.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
SERVER = &#039;http://info216.i2s.uib.no/bigdata/&#039;  # you may want to change this&lt;br /&gt;
NAMESPACE  = &#039;lab04&#039;                           # you most likely want to change this&lt;br /&gt;
&lt;br /&gt;
endpoint = f&#039;{SERVER}namespace/{NAMESPACE}/sparql&#039;  # standard path for Blazegraph queries (and updates)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_2&amp;diff=2426</id>
		<title>Lab: SPARQL 2</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL_2&amp;diff=2426"/>
		<updated>2024-02-11T10:52:37Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: Created page with &amp;quot;==Topics== * SPARQL updates * SPARQL insertions * SPARQL deletions * DESCRIBE and CONSTRUCT  ==Useful materials== GraphDB documentation: * [https://graphdb.ontotext.com/docume...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* SPARQL updates&lt;br /&gt;
* SPARQL insertions&lt;br /&gt;
* SPARQL deletions&lt;br /&gt;
* DESCRIBE and CONSTRUCT&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
GraphDB documentation:&lt;br /&gt;
* [https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html GraphDB 10.0 Quick Start Guide]&lt;br /&gt;
* [https://graphdb.ontotext.com/documentation/10.5/ GraphDB 10.5 Documentation]&lt;br /&gt;
&lt;br /&gt;
SPARQL reference:&lt;br /&gt;
* [https://www.w3.org/TR/sparql11-query/ SPARQL Query Documentation]&lt;br /&gt;
* [http://www.w3.org/TR/sparql11-update/ SPARQL Update Documentation]&lt;br /&gt;
* [https://en.wikibooks.org/wiki/SPARQL/Expressions_and_Functions SPARQL Expressions and Functions]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Write the following SPARQL updates:&lt;br /&gt;
* The &#039;&#039;muellerkg:name&#039;&#039; property is misnamed, because the object in those triples is always a resource. Rename it to something like &#039;&#039;muellerkg:person&#039;&#039;.&lt;br /&gt;
* Update the graph so all the investigated person and president nodes (such as &#039;&#039;muellerkg:G._Gordon_Liddy&#039;&#039; and  &#039;&#039;muellerkg:Richard_Nizon&#039;&#039;) become the subjects in &#039;&#039;foaf:name&#039;&#039; triples with the corresponding strings (&#039;&#039;G. Gordon Liddy&#039;&#039; and &#039;&#039;Richard Nixon&#039;&#039;) as the literals. (&#039;&#039;Tip:&#039;&#039; Use &#039;&#039;STR(kgmueller:)&#039;&#039; inside a REPLACE in a BIND statement to remove the URI path.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Load the RDF graph you created in exercises 1 and 2. (Maybe you want to create a new namespace in GraphDB first.) Use INSERT DATA updates to add these triples to your graph:&lt;br /&gt;
* George Papadopoulos was adviser to the Trump campaign.&lt;br /&gt;
** He pleaded guilty to lying to the FBI.&lt;br /&gt;
** He was sentenced to prison. &lt;br /&gt;
* Roger Stone is a Republican.&lt;br /&gt;
** He was adviser to Trump.&lt;br /&gt;
** He was an official in the Trump campaign.&lt;br /&gt;
** He interacted with Wikileaks.&lt;br /&gt;
** He made a testimony for the House Intelligence Committee.&lt;br /&gt;
** He was cleared of all charges.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges. Actually,&lt;br /&gt;
* He was indicted for making false statements, witness tampering, and obstruction of justice.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
* Use a DESCRIBE query to show the updated information about Roger Stone.&lt;br /&gt;
* Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone (in other words, having Roger Stone as the subject.)&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
In the &#039;&#039;russia_investigation_kg.ttl&#039;&#039; dataset, the &#039;&#039;muellerkg:name&#039;&#039; property used as predicate is already covered by a standard term from an estalished vocabulary in the LOD cloud: &#039;&#039;foaf:name&#039;&#039;, where &#039;&#039;foaf:&#039;&#039; is &#039;&#039;http://xmlns.com/foaf/0.1/&#039;&#039;. &lt;br /&gt;
* If you have not done so already: write a SPARQL DELETE/INSERT update to change every &#039;&#039;muellerkg:name&#039;&#039; predicate in your graph to &#039;&#039;foaf:name&#039;&#039;. (It is easy to destroy your RDF graph when you do this, so it is good you saved a copy in the previous task.)&lt;br /&gt;
* Otherwise: find another resource to rename everywhere. For example, you can change your local URI for a public person to a standard [https://wikidata.org Wikidata] URI.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write a DELETE/INSERT statement to change one of the prefixes in your graph, renaming all the resources that use that prefix.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write an INSERT statement to add at least one significant date to the Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT statement to change the date to a string, and a new DELETE/INSERT statement to change it back to xsd:date.&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2425</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2425"/>
		<updated>2024-02-11T10:48:13Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &#039;&#039;The page will be updated as the course progresses.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 4, from 22/1)&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries]] (week 6, from 5/2)&lt;br /&gt;
# [[Lab: SPARQL 2 | Lab: SPARQL updates]] (week 7, from 12/2)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 8, from 19/2)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 9, from 26/2)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]]  (week 10, from 4/3)&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]]  (week 11, from 11/3)&lt;br /&gt;
# [[Lab: OWL 1]] (week 12, from 18/3)&lt;br /&gt;
# [[Lab: OWL 2]] (week 15, from 8/4)&lt;br /&gt;
# [[Lab: OWL-DL]] (week 16, from 15/4)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 17, from 22/4, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 19, from 6/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Web APIs and JSON-LD]] (week 20, from 13/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;No exercises in weeks 13-14 and 18.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2024, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2424</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2424"/>
		<updated>2024-02-11T10:47:16Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &#039;&#039;The page will be updated as the course progresses.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 4, from 22/1)&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries]] (week 6, from 5/2)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL updates]] (week 7, from 12/2)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 8, from 19/2)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 9, from 26/2)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]]  (week 10, from 4/3)&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]]  (week 11, from 11/3)&lt;br /&gt;
# [[Lab: OWL 1]] (week 12, from 18/3)&lt;br /&gt;
# [[Lab: OWL 2]] (week 15, from 8/4)&lt;br /&gt;
# [[Lab: OWL-DL]] (week 16, from 15/4)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 17, from 22/4, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 19, from 6/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Web APIs and JSON-LD]] (week 20, from 13/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;No exercises in weeks 13-14 and 18.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2024, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=2423</id>
		<title>Lab: SPARQL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=2423"/>
		<updated>2024-02-11T10:46:10Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Setting up GraphDB&lt;br /&gt;
* SPARQL queries and updates&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
GraphDB documentation:&lt;br /&gt;
* [https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html GraphDB 10.0 Quick Start Guide]&lt;br /&gt;
* [https://graphdb.ontotext.com/documentation/10.5/ GraphDB 10.5 Documentation]&lt;br /&gt;
&lt;br /&gt;
SPARQL reference:&lt;br /&gt;
* [https://www.w3.org/TR/sparql11-query/ SPARQL Query Documentation]&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [http://www.w3.org/TR/sparql11-update/ SPARQL Update Documentation]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
* [https://en.wikibooks.org/wiki/SPARQL/Expressions_and_Functions SPARQL Expressions and Functions]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Registering for GraphDB Free===&lt;br /&gt;
To retrieve a download link for Ontotext&#039;s GraphDB Free tool, you first need to register. Here is the [https://www.ontotext.com/products/graphdb/download/?utm_source=adwords&amp;amp;utm_medium=ppc&amp;amp;utm_term=ontotext%20graphdb&amp;amp;utm_campaign=Search+Graphdb&amp;amp;hsa_cam=19852701758&amp;amp;hsa_mt=p&amp;amp;hsa_ver=3&amp;amp;hsa_src=g&amp;amp;hsa_ad=651747487851&amp;amp;hsa_net=adwords&amp;amp;hsa_tgt=kwd-1467556044238&amp;amp;hsa_acc=9129462532&amp;amp;hsa_grp=148766495402&amp;amp;hsa_kw=ontotext%20graphdb&amp;amp;gad_source=1&amp;amp;gclid=Cj0KCQiAh8OtBhCQARIsAIkWb69Mvno3kVHLrHHpZ_FV2_vnwf9IWoMa207bd43maPDUOm2R53UAuYYaAgCxEALw_wcB registration link] (or search for &amp;quot;ontotext graphdb registration&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;If you do not like registering for proprietary software, it is still possible to do most of the exercises using Blazegraph, which you can [https://blazegraph.com/ download here] (requires Java). Blazegraph is a powerful open-source tool, but GraphDB offers even more functionality and is what the lab leaders will prepare for this semester.&lt;br /&gt;
&lt;br /&gt;
===Installing and running GraphDB===&lt;br /&gt;
When you have received the download link in an email from the &#039;&#039;GraphDB Team&#039;&#039;, you can proceed to install and run GraphDB in the following manner, depending on your system:&lt;br /&gt;
* On Windows:&lt;br /&gt;
** Download the GraphDB Desktop .msi installer file.&lt;br /&gt;
** Double-click the application file and follow the on-screen installer prompts.&lt;br /&gt;
** Locate the GraphDB Desktop application in the Windows Start menu and start it. The GraphDB Workbench opens at http://localhost:7200/.&lt;br /&gt;
&lt;br /&gt;
* On MacOS&lt;br /&gt;
** Download the GraphDB Desktop .dmg file.&lt;br /&gt;
** Double-click it and get a virtual disk on your desktop. Copy the program from the virtual disk to your hard disk Applications folder, and you’re set.&lt;br /&gt;
** Start GraphDB Desktop by clicking the application icon. The GraphDB Workbench opens at http://localhost:7200/.&lt;br /&gt;
&lt;br /&gt;
* On Linux&lt;br /&gt;
** Download the GraphDB Desktop .deb or .rpm file.&lt;br /&gt;
** Install the package with sudo dpkg -i or sudo rpm -i and the name of the downloaded package. Alternatively, you can double-click the package name.&lt;br /&gt;
** Start GraphDB Desktop by clicking the application icon. The GraphDB Workbench opens at http://localhost:7200/.&lt;br /&gt;
&lt;br /&gt;
For more information about setting up GraphDB you can check out their quick start guide:&lt;br /&gt;
[https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html Quick Start Guide].&lt;br /&gt;
&lt;br /&gt;
===Setting up a repository===&lt;br /&gt;
Follow the &#039;&#039;Create a Repository&#039;&#039; section in the [https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html Quick Start Guide].&lt;br /&gt;
Create a new GraphDB Repository called, for example, &#039;&#039;info216_lab3_NN&#039;&#039;, where &#039;&#039;NN&#039;&#039; are your initials. Choose &#039;&#039;No inference&#039;&#039; for now.&lt;br /&gt;
Otherwise, the default parameters are fine.&lt;br /&gt;
&lt;br /&gt;
Connect to the new repository and pin it as your default repository.&lt;br /&gt;
&lt;br /&gt;
===Load data===&lt;br /&gt;
Download the Turtle file [[File:russia_investigation_kg.txt]], and save it with the correct extension, as &#039;&#039;russia_investigation_kg.ttl&#039;&#039; (not &#039;&#039;.txt&#039;&#039;). (You can also experiment with the Turtle file you saved after exercises 1 and 2.) Load the Russia_investigation data through the GraphDB Workbench as described in the QuickStart guide.&lt;br /&gt;
&lt;br /&gt;
You can use &#039;&#039;http://example.org/&#039;&#039; as Base IRI.&lt;br /&gt;
&lt;br /&gt;
===Graph visualisation===&lt;br /&gt;
Go to &#039;&#039;Explore&#039;&#039; -&amp;gt; &#039;&#039;Visual graph&#039;&#039; and create an &#039;&#039;Easy graph&#039;&#039; around the resource &#039;&#039;http://example.org#investigation_0&#039;&#039;. Double-click on nodes to expand them. Are there any more investigations related to &#039;&#039;Richard Nixon&#039;&#039;?&lt;br /&gt;
&lt;br /&gt;
===SPARQL tasks===&lt;br /&gt;
Go to the &#039;&#039;SPARQL Query &amp;amp; Update&#039;&#039; tab.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Using the data in &#039;&#039;russia_investigation_kg.ttl&#039;&#039;, write the following SPARQL SELECT queries. &lt;br /&gt;
([[Russian investigation KG | This page explains]] the Russian investigation KG a bit more.)&lt;br /&gt;
* List all triples in your graph. &lt;br /&gt;
* List the first 100 triples in your graph. &lt;br /&gt;
* Count the number of triples in your graph.&lt;br /&gt;
* Count the number of indictments in your graph.&lt;br /&gt;
* List everyone who pleaded guilty, along with the name of the investigation.&lt;br /&gt;
* List everyone who were convicted, but who had their conviction overturned by which president.&lt;br /&gt;
* For each investigation, list the number of indictments made.&lt;br /&gt;
* For each investigation with multiple indictments, list the number of indictments made.&lt;br /&gt;
* For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first.&lt;br /&gt;
* For each president, list the numbers of convictions and of pardons made after conviction.&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Try to program some of the queries in a Python program (this will be the topic of later labs). You have two options:&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Using rdflib:&#039;&#039;&lt;br /&gt;
Read the Turtle file into an rdflib Graph and use the &#039;&#039;query()&#039;&#039; method. &lt;br /&gt;
 g = Graph()&lt;br /&gt;
 g.parse(..., format=&#039;ttl&#039;)&lt;br /&gt;
 r = g.query(...your_query_string...)&lt;br /&gt;
The hard part is picking the results out of the object &#039;&#039;r&#039;&#039;...&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Using SPARQLwrapper:&#039;&#039;&lt;br /&gt;
You can use SPARQLwrapper (another Python API) to connect to your running GraphDB endpoint. See the Python example page for how to do this.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; If you want to explore more, try out the Wikidata Query Service (WDQS):&lt;br /&gt;
* [https://query.wikidata.org/ Wikidata Query Service]&lt;br /&gt;
&lt;br /&gt;
WDQS tutorials:&lt;br /&gt;
* [https://www.wikidata.org/wiki/Wikidata:SPARQL_tutorial Wikidata SPARQL tutorial]&lt;br /&gt;
* [https://wdqs-tutorial.toolforge.org/ Interactive WDQS tutorial]&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=2416</id>
		<title>Lab: SPARQL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SPARQL&amp;diff=2416"/>
		<updated>2024-02-05T07:02:11Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Setting up GraphDB&lt;br /&gt;
* SPARQL queries and updates&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
GraphDB documentation:&lt;br /&gt;
* [https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html GraphDB 10.0 Quick Start Guide]&lt;br /&gt;
* [https://graphdb.ontotext.com/documentation/10.5/ GraphDB 10.5 Documentation]&lt;br /&gt;
&lt;br /&gt;
SPARQL reference:&lt;br /&gt;
* [https://www.w3.org/TR/sparql11-query/ SPARQL Query Documentation]&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [http://www.w3.org/TR/sparql11-update/ SPARQL Update Documentation]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
* [https://en.wikibooks.org/wiki/SPARQL/Expressions_and_Functions SPARQL Expressions and Functions]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Registering for GraphDB Free===&lt;br /&gt;
To retrieve a download link for Ontotext&#039;s GraphDB Free tool, you first need to register. Here is the [https://www.ontotext.com/products/graphdb/download/?utm_source=adwords&amp;amp;utm_medium=ppc&amp;amp;utm_term=ontotext%20graphdb&amp;amp;utm_campaign=Search+Graphdb&amp;amp;hsa_cam=19852701758&amp;amp;hsa_mt=p&amp;amp;hsa_ver=3&amp;amp;hsa_src=g&amp;amp;hsa_ad=651747487851&amp;amp;hsa_net=adwords&amp;amp;hsa_tgt=kwd-1467556044238&amp;amp;hsa_acc=9129462532&amp;amp;hsa_grp=148766495402&amp;amp;hsa_kw=ontotext%20graphdb&amp;amp;gad_source=1&amp;amp;gclid=Cj0KCQiAh8OtBhCQARIsAIkWb69Mvno3kVHLrHHpZ_FV2_vnwf9IWoMa207bd43maPDUOm2R53UAuYYaAgCxEALw_wcB registration link] (or search for &amp;quot;ontotext graphdb registration&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;If you do not like registering for proprietary software, it is still possible to do most of the exercises using Blazegraph, which you can [https://blazegraph.com/ download here] (requires Java). Blazegraph is a powerful open-source tool, but GraphDB offers even more functionality and is what the lab leaders will prepare for this semester.&lt;br /&gt;
&lt;br /&gt;
===Installing and running GraphDB===&lt;br /&gt;
When you have received the download link in an email from the &#039;&#039;GraphDB Team&#039;&#039;, you can proceed to install and run GraphDB according to this [https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html Quick Start Guide]. Follow the guide up to and including the section &lt;br /&gt;
&#039;&#039;Run GraphDB as a Standalone Server¶&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
===Setting up a repository===&lt;br /&gt;
Jump forward in the [https://graphdb.ontotext.com/documentation/10.0/quick-start-guide.html Quick Start Guide] to the section &#039;&#039;Create a Repository&#039;&#039;.&lt;br /&gt;
Create a new GraphDB Repository called, for example, &#039;&#039;info216_lab3_NN&#039;&#039;, where &#039;&#039;NN&#039;&#039; are your initials. Choose &#039;&#039;No inference&#039;&#039; for now.&lt;br /&gt;
Otherwise, the default parameters are fine.&lt;br /&gt;
&lt;br /&gt;
Connect to the new repository and pin it as your default repository.&lt;br /&gt;
&lt;br /&gt;
===Load data===&lt;br /&gt;
Download the Turtle file [[File:russia_investigation_kg.txt]], and save it with the correct extension, as &#039;&#039;russia_investigation_kg.ttl&#039;&#039; (not &#039;&#039;.txt&#039;&#039;). (You can also experiment with the Turtle file you saved after exercises 1 and 2.) Load the Russia_investigation data through the GraphDB Workbench as described in the QuickStart guide.&lt;br /&gt;
&lt;br /&gt;
You can use &#039;&#039;http://example.org/&#039;&#039; as Base IRI.&lt;br /&gt;
&lt;br /&gt;
===Graph visualisation===&lt;br /&gt;
Go to &#039;&#039;Explore&#039;&#039; -&amp;gt; &#039;&#039;Visual graph&#039;&#039; and create an &#039;&#039;Easy graph&#039;&#039; around the resource &#039;&#039;http://example.org#Roger_Stone&#039;&#039;. Double-click on nodes to expand them. Have there been more investigations involving &#039;&#039;Russia&#039;&#039;?&lt;br /&gt;
&lt;br /&gt;
===SPARQL tasks===&lt;br /&gt;
Go to the &#039;&#039;SPARQL Query &amp;amp; Update&#039;&#039; tab.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Using the data in &#039;&#039;russia_investigation_kg.ttl&#039;&#039;, write the following SPARQL SELECT queries. &lt;br /&gt;
([[Russian investigation KG | This page explains]] the Russian investigation KG a bit more.)&lt;br /&gt;
* List all triples in your graph. &lt;br /&gt;
* List the first 100 triples in your graph. &lt;br /&gt;
* Count the number of triples in your graph.&lt;br /&gt;
* Count the number of indictments in your graph.&lt;br /&gt;
* List everyone who pleaded guilty, along with the name of the investigation.&lt;br /&gt;
* List everyone who were convicted, but who had their conviction overturned by which president.&lt;br /&gt;
* For each investigation, list the number of indictments made.&lt;br /&gt;
* For each investigation with multiple indictments, list the number of indictments made.&lt;br /&gt;
* For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first.&lt;br /&gt;
* For each president, list the numbers of convictions and of pardons made after conviction.&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Write the following SPARQL updates:&lt;br /&gt;
* The &#039;&#039;muellerkg:name&#039;&#039; property is misnamed, because the object in those triples is always a resource. Rename it to something like &#039;&#039;muellerkg:person&#039;&#039;.&lt;br /&gt;
* Update the graph so all the investigated person and president nodes (such as &#039;&#039;muellerkg:G._Gordon_Liddy&#039;&#039; and  &#039;&#039;muellerkg:Richard_Nizon&#039;&#039;) become the subjects in &#039;&#039;foaf:name&#039;&#039; triples with the corresponding strings (&#039;&#039;G. Gordon Liddy&#039;&#039; and &#039;&#039;Richard Nixon&#039;&#039;) as the literals. (&#039;&#039;Tip:&#039;&#039; Use &#039;&#039;STR(kgmueller:)&#039;&#039; inside a REPLACE in a BIND statement to remove the URI path.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Load the RDF graph you created in exercises 1 and 2. (Maybe you want to create a new namespace in GraphDB first.) Use INSERT DATA updates to add these triples to your graph:&lt;br /&gt;
* George Papadopoulos was adviser to the Trump campaign.&lt;br /&gt;
** He pleaded guilty to lying to the FBI.&lt;br /&gt;
** He was sentenced to prison. &lt;br /&gt;
* Roger Stone is a Republican.&lt;br /&gt;
** He was adviser to Trump.&lt;br /&gt;
** He was an official in the Trump campaign.&lt;br /&gt;
** He interacted with Wikileaks.&lt;br /&gt;
** He made a testimony for the House Intelligence Committee.&lt;br /&gt;
** He was cleared of all charges.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges. Actually,&lt;br /&gt;
* He was indicted for making false statements, witness tampering, and obstruction of justice.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
* Use a DESCRIBE query to show the updated information about Roger Stone.&lt;br /&gt;
* Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone (in other words, having Roger Stone as the subject.)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
In the &#039;&#039;russia_investigation_kg.ttl&#039;&#039; dataset, the &#039;&#039;muellerkg:name&#039;&#039; property used as predicate is already covered by a standard term from an estalished vocabulary in the LOD cloud: &#039;&#039;foaf:name&#039;&#039;, where &#039;&#039;foaf:&#039;&#039; is &#039;&#039;http://xmlns.com/foaf/0.1/&#039;&#039;. &lt;br /&gt;
* If you have not done so already: write a SPARQL DELETE/INSERT update to change every &#039;&#039;muellerkg:name&#039;&#039; predicate in your graph to &#039;&#039;foaf:name&#039;&#039;. (It is easy to destroy your RDF graph when you do this, so it is good you saved a copy in the previous task.)&lt;br /&gt;
* Otherwise: find another resource to rename everywhere. For example, you can change your local URI for a public person to a standard [https://wikidata.org Wikidata] URI.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write a DELETE/INSERT statement to change one of the prefixes in your graph, renaming all the resources that use that prefix.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write an INSERT statement to add at least one significant date to the Mueller investigation, with literal type xsd:date. Write a DELETE/INSERT statement to change the date to a string, and a new DELETE/INSERT statement to change it back to xsd:date.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Try to program some of the queries in a Python program (this will be the topic of later labs). You have two options:&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Using rdflib:&#039;&#039;&lt;br /&gt;
Read the Turtle file into an rdflib Graph and use the &#039;&#039;query()&#039;&#039; method. &lt;br /&gt;
 g = Graph()&lt;br /&gt;
 g.parse(..., format=&#039;ttl&#039;)&lt;br /&gt;
 r = g.query(...your_query_string...)&lt;br /&gt;
The hard part is picking the results out of the object &#039;&#039;r&#039;&#039;...&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Using SPARQLwrapper:&#039;&#039;&lt;br /&gt;
You can use SPARQLwrapper (another Python API) to connect to your running GraphDB endpoint. See the Python example page for how to do this.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; If you want to explore more, try out the Wikidata Query Service (WDQS):&lt;br /&gt;
* [https://query.wikidata.org/ Wikidata Query Service]&lt;br /&gt;
&lt;br /&gt;
WDQS tutorials:&lt;br /&gt;
* [https://www.wikidata.org/wiki/Wikidata:SPARQL_tutorial Wikidata SPARQL tutorial]&lt;br /&gt;
* [https://wdqs-tutorial.toolforge.org/ Interactive WDQS tutorial]&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2415</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2415"/>
		<updated>2024-02-05T06:58:14Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &#039;&#039;The page will be updated as the course progresses.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 4, from 22/1)&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries]] (week 6, from 5/2)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# Lab: SPARQL updates (week 7, from 12/2)&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 8, from 19/2)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 9, from 26/2)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]]  (week 10, from 4/3)&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]]  (week 11, from 11/3)&lt;br /&gt;
# [[Lab: OWL 1]] (week 12, from 18/3)&lt;br /&gt;
# [[Lab: OWL 2]] (week 15, from 8/4)&lt;br /&gt;
# [[Lab: OWL-DL]] (week 16, from 15/4)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 17, from 22/4, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 19, from 6/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Web APIs and JSON-LD]] (week 20, from 13/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;No exercises in weeks 13-14 and 18.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2024, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2414</id>
		<title>Lab Exercises</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Exercises&amp;diff=2414"/>
		<updated>2024-02-05T06:56:26Z</updated>

		<summary type="html">&lt;p&gt;Bamos3003: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Here we will present new lab exercises each week. &#039;&#039;The page will be updated as the course progresses.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
# [[Lab: Getting started with VSCode, Python and RDFlib]] (week 4, from 22/1)&lt;br /&gt;
# [[Lab: RDF programming with RDFlib]] (week 5, from 29/1)&lt;br /&gt;
# [[Lab: SPARQL | Lab: SPARQL queries and updates]] (week 6, from 5/2)&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
# Lab: SPARQL queries and updates continues (week 7, from 12/2)&lt;br /&gt;
# [[Lab: SPARQL Programming | Lab: SPARQL programming]] (week 8, from 19/2)&lt;br /&gt;
# [[Lab: Semantic Lifting - CSV | Lab: From CSV to RDF]] (week 9, from 26/2)&lt;br /&gt;
# [[Lab: SHACL | Lab: SHACL constraints]]  (week 10, from 4/3)&lt;br /&gt;
# [[Lab: RDFS | Lab: RDFS rules]]  (week 11, from 11/3)&lt;br /&gt;
# [[Lab: OWL 1]] (week 12, from 18/3)&lt;br /&gt;
# [[Lab: OWL 2]] (week 15, from 8/4)&lt;br /&gt;
# [[Lab: OWL-DL]] (week 16, from 15/4)&lt;br /&gt;
# [[Lab: Using Graph Embeddings]] (week 17, from 22/4, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Training Graph Embeddings]] (week 19, from 6/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
# [[Lab: Web APIs and JSON-LD]] (week 20, from 13/5, &#039;&#039;preliminary&#039;&#039;)&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;No exercises in weeks 13-14 and 18.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;amp;nbsp;&lt;br /&gt;
&amp;lt;div class=&amp;quot;credits&amp;quot; style=&amp;quot;text-align: right; direction: ltr; margin-left: 1em;&amp;quot;&amp;gt;&#039;&#039;INFO216, UiB, 2017-2024, Andreas L. Opdahl (c)&#039;&#039;&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Bamos3003</name></author>
	</entry>
</feed>