<?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=Rbo027</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=Rbo027"/>
	<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/Special:Contributions/Rbo027"/>
	<updated>2026-05-25T04:07:02Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.44.2</generator>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2583</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2583"/>
		<updated>2024-05-19T13:25:50Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for lab 14 - Training Graph Embeddings&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 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2574</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2574"/>
		<updated>2024-05-10T10:30:53Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 13 (Using Graph Embeddings)&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2540</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2540"/>
		<updated>2024-04-27T12:44:09Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 12 - OWL 2&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2534</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2534"/>
		<updated>2024-04-19T11:59:47Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 11 - OWL&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2526</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2526"/>
		<updated>2024-04-14T10:03:15Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed solution for Lab 10 - RDFS&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2514</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2514"/>
		<updated>2024-03-22T15:51:37Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 9 - SHACL&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_SHACL&amp;diff=2508</id>
		<title>Lab: SHACL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_SHACL&amp;diff=2508"/>
		<updated>2024-03-19T13:13:49Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Validating RDF graphs with SHACL&lt;br /&gt;
* Running pySHACL&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
SHACL:&lt;br /&gt;
* Section 7.4 &#039;&#039;Expectation in RDF&#039;&#039; in Allemang, Hendler &amp;amp; Gandon&#039;s textbook (&#039;&#039;Semantic Web for the Working Ontologist&#039;&#039;)&lt;br /&gt;
* [https://book.validatingrdf.com/bookHtml011.html Chapter 5 &#039;&#039;SHACL&#039;&#039;] in [https://book.validatingrdf.com/index.html Validating RDF] (available online)&lt;br /&gt;
* Interactive, online [https://shacl.org/playground/ SHACL Playground]&lt;br /&gt;
* [https://docs.google.com/presentation/d/1weO9SzssxgYp3g_44X1LZsVtL0i6FurQ3KbIKZ8iriQ/ Lab presentation containing a short overview of SHACL and pySHACL]&lt;br /&gt;
&lt;br /&gt;
pySHACL:&lt;br /&gt;
* [https://pypi.org/project/pyshacl/ pySHACL at PyPi.org] &#039;&#039;(after installation, go straight to &amp;quot;Python Module Use&amp;quot;.)&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; &lt;br /&gt;
Go to the interactive, online [https://shacl.org/playground/ SHACL Playground]. Cut-and-paste the Turtle triples below into the Data Graph text field, and click &#039;&#039;Update&#039;&#039;.&lt;br /&gt;
&amp;lt;syntaxhighlight&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 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 skos: &amp;lt;http://www.w3.org/2004/02/skos/core#&amp;gt; .&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Paul_Manafort &lt;br /&gt;
    a ex:PersonUnderInvestigation ;&lt;br /&gt;
    foaf:name &lt;br /&gt;
        &amp;quot;Paul Manafort&amp;quot;@en ;  &lt;br /&gt;
    ex:hasBusinessPartner ex:Rick_Gates .&lt;br /&gt;
&lt;br /&gt;
ex:Rick_Gates &lt;br /&gt;
    a ex:PersonUnderInvestigation ;&lt;br /&gt;
    foaf:name &lt;br /&gt;
        &amp;quot;Rick Gates&amp;quot;@en ;  &lt;br /&gt;
    skos:altLabel &lt;br /&gt;
        &amp;quot;Richard William Gates III&amp;quot;@en ;  &lt;br /&gt;
    ex:chargedWith &lt;br /&gt;
        ex:ForeignLobbying ,  &lt;br /&gt;
        ex:MoneyLaundering ,&lt;br /&gt;
        ex:TaxEvasion ;&lt;br /&gt;
    ex:pleadedGuilty &lt;br /&gt;
        ex:Conspiracy, [&lt;br /&gt;
                a ex:Lying ;&lt;br /&gt;
                ex:wasLyingTo ex:FBI &lt;br /&gt;
            ] .&lt;br /&gt;
&lt;br /&gt;
ex:ForeignLobbying a ex:Offense .  &lt;br /&gt;
ex:MoneyLaundering a ex:Offense .  &lt;br /&gt;
ex:TaxEvasion a ex:Offense .  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
The example is based on Exercises 1 and 2. Take some time to look at it in Turtle and also in JSON-LD, using the drop-down menu next to the &#039;&#039;Data Graph&#039;&#039; heading.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; &lt;br /&gt;
Write Shapes Graphs in Turtle (recommended) or JSON-LD for each of the constraints below. Keep copies of your Shape Graphs in a separate text editor and file. You will need them later. Each time you have entered a Shape Graph into the text field, click &#039;&#039;Update&#039;&#039; to validate the contents of the Data Graph.&lt;br /&gt;
&lt;br /&gt;
You can use the following prefixes:&lt;br /&gt;
 @prefix rdf: &amp;lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&amp;gt; .&lt;br /&gt;
 @prefix xsd: &amp;lt;http://www.w3.org/2001/XMLSchema#&amp;gt; .&lt;br /&gt;
 @prefix sh: &amp;lt;http://www.w3.org/ns/shacl#&amp;gt; .&lt;br /&gt;
 @prefix foaf: &amp;lt;http://xmlns.com/foaf/0.1/&amp;gt; .&lt;br /&gt;
 @prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
Constraints:&lt;br /&gt;
* Every person under investigation has exactly one name.&lt;br /&gt;
* The object of a charged with property must be a URI.&lt;br /&gt;
* The object of a charged with property must be an offense.&lt;br /&gt;
* All person names must be language-tagged (&#039;&#039;hint:&#039;&#039; rdf:langString is a datatype!).&lt;br /&gt;
&lt;br /&gt;
Change the &#039;&#039;data_graph&#039;&#039; to remove the detected errors as you go along (it is easier to read the outputs then).&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; &lt;br /&gt;
Write a Python program using rdflib and pySHACL, which:&lt;br /&gt;
# parses the Turtle example above into a &#039;&#039;data_graph&#039;&#039; (&#039;&#039;tip:&#039;&#039; you can either save it to file, or parse directly from a string using &#039;&#039;graph.parse(data=turtle_data, format=&#039;ttl&#039;)&#039;&#039;),&lt;br /&gt;
# parses the contents of a &#039;&#039;shape_graph&#039;&#039; you made in the previous task (for example checking that every person under investigation has exactly one name),&lt;br /&gt;
# uses pySHACL&#039;s validate method to apply the &#039;&#039;shape_graph&#039;&#039; constraints to the  &#039;&#039;data_graph&#039;&#039;, and&lt;br /&gt;
# prints out the validation result (a boolean value, a &#039;&#039;results_graph&#039;&#039;, and a &#039;&#039;result_text&#039;&#039;).&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Add the Turtle triples below (from exercise 3-5) to your &#039;&#039;data_graph&#039;&#039;. &lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
ex:investigation_162 a ex:Indictment ;&lt;br /&gt;
    ex:american &amp;quot;unknown&amp;quot; ;&lt;br /&gt;
    ex:cp_date &amp;quot;2018-02-23&amp;quot;^^xsd:date ;&lt;br /&gt;
    ex:cp_days 282 ;&lt;br /&gt;
    ex:indictment_days 166 ;&lt;br /&gt;
    ex:investigation ex:russia ;&lt;br /&gt;
    ex:investigation_days 659 ;&lt;br /&gt;
    ex:investigation_end &amp;quot;unknown&amp;quot; ;&lt;br /&gt;
    ex:investigation_start &amp;quot;2017-05-17&amp;quot;^^xsd:date ;&lt;br /&gt;
    foaf:name &amp;quot;Rick Gates&amp;quot; ;&lt;br /&gt;
    ex:investigatedPerson ex:Rick_Gates ;&lt;br /&gt;
    ex:outcome ex:guilty_plea ;&lt;br /&gt;
    ex:overturned false ;&lt;br /&gt;
    ex:pardoned false ;&lt;br /&gt;
    ex:president ex:Donald_Trump .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Extend your shapes graph for each of these constraints:&lt;br /&gt;
* The only allowed values for &#039;&#039;ex:american&#039;&#039; are &#039;&#039;true&#039;&#039;, &#039;&#039;false&#039;&#039; or &#039;&#039;unknown&#039;&#039;.&lt;br /&gt;
* The value of a property that counts days must be an integer.&lt;br /&gt;
* The value of a property that indicates a start date must be &#039;&#039;xsd:date&#039;&#039;.&lt;br /&gt;
* The value of a property that indicates an end date must be &#039;&#039;xsd:date&#039;&#039; or &#039;&#039;unknown&#039;&#039; (&#039;&#039;tip:&#039;&#039; you can use &#039;&#039;sh:or (...)&#039;&#039; ).&lt;br /&gt;
* Every indictment must have exactly one FOAF name for the investigated person.&lt;br /&gt;
* Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.&lt;br /&gt;
* No URI-s can contain hyphens (&#039;-&#039;).&lt;br /&gt;
* Presidents must be identified with URIs.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
When you run SHACL on large data graphs, the &#039;&#039;results_graph&#039;&#039; and &#039;&#039;result_text&#039;&#039; will report the same error many times (but for different nodes). Write a SPARQL query to print out each distinct &#039;&#039;sh:resultMessage&#039;&#039; in the &#039;&#039;results_graph&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Modify the above query so it prints out each &#039;&#039;sh:resultMessage&#039;&#039; in the &#039;&#039;results_graph&#039;&#039; once, along with the number of times that message has been repeated in the results.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2507</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2507"/>
		<updated>2024-03-15T23:32:36Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 8 - JSON-LD&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_JSON-LD&amp;diff=2494</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=2494"/>
		<updated>2024-03-13T07:16:46Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: &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;
* [https://docs.google.com/presentation/d/1pRuO-6FZJbq3fAdXVfOU0vIP0VoAKG6kbmosf0qaK8Y/edit?usp=sharing JSON-LD Lab Presentation]&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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_JSON-LD&amp;diff=2492</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=2492"/>
		<updated>2024-03-10T19:17:58Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added resource&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://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;
  },&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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2485</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2485"/>
		<updated>2024-03-08T18:47:03Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed solution for Lab 7 (CSV to RDF)&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 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&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2471</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2471"/>
		<updated>2024-03-01T14:00:47Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 6&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Wikidata_in_RDF&amp;diff=2468</id>
		<title>Lab: Wikidata in RDF</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Wikidata_in_RDF&amp;diff=2468"/>
		<updated>2024-02-26T12:43:25Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
Wikidata in RDF: &lt;br /&gt;
* retrieve primary triples about a Wikidata entity&lt;br /&gt;
* load the semantic data and metadata into GraphDB&lt;br /&gt;
* visualise the semantic data and metadata&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Motivation:&#039;&#039; So far you have built your own knowledge graph and worked on a small grap you were given. This week we will look at how to retrieve knowledge graphs from Wikidata, which can then be merged with your own graph to provide additional context. This is not a trivial problem because Wikidata most likely contains a lot more data - and in particular metadata - than you need. &lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
* [https://www.wikidata.org/wiki/Wikidata:SPARQL_query_service/A_gentle_introduction_to_the_Wikidata_Query_Service A gentle introduction to the Wikidata Query Service] (Simple)&lt;br /&gt;
* [https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format RDF Dump Format]&lt;br /&gt;
* [https://en.wikibooks.org/wiki/SPARQL/Expressions_and_Functions SPARQL Expressions and Functions] - you will need this a lot&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Getting ready:&#039;&#039;&#039;&lt;br /&gt;
In a web browser, go to [http://query.wikidata.org Wikidata&#039;s Query Service (WDQS)]. Be careful to &#039;&#039;always use a limit like LIMIT 100 when you test things&#039;&#039;. Otherwise, you risk being blocked from the query service or, worse, you risk blocking out a whole subdomain.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Emergency data:&#039;&#039; &lt;br /&gt;
If Wikdata&#039;s Query Service is unavailable, you can load [[:File:Q42-extended.tar | this Turtle file]] into GraphDB instead, and continue there using &#039;&#039;Q42&#039;&#039; as your example entity. (Remember to rename the file from &#039;&#039;.tar&#039;&#039; to &#039;&#039;.ttl&#039;&#039; - it is not a &#039;&#039;.tar&#039;&#039;-file.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
From [https://www.wikidata.org/ Wikidata&#039;s ordinary UI], find the Q-code of one of the people or entities involved in the Mueller investigation. Use that entity as your reference in the rest of this lab. (The Q-code should look like this &#039;&#039;https://www.wikidata.org/entity/Q42&#039;&#039; or &#039;&#039;wd:Q42&#039;&#039;.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Use a DESCRIBE query to retrieve some triples about your entity (remember LIMIT 100, although it is less critical on DESCRIBE queries). &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Use a SELECT query to retrieve the first 100 triples about your entity. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; Always save your queries and updates as soon as they succeed. You may need to go back to them later.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Start GraphDB on your local machine. Create a new repository (&#039;&#039;No inference&#039;&#039; needed), and activate it. Write a local SELECT query that embeds a &amp;lt;https://query.wikidata.org/bigdata/namespace/wdq/sparql&amp;gt; SERVICE query to retrieve the first 100 triples about your entity &#039;&#039;to your local machine&#039;&#039;. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; &#039;&#039;wd:&#039;&#039; is a PREFIX for &#039;&#039;&amp;lt;http://www.wikidata.org/entity/&amp;gt;&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; To make LIMIT work inside a SERVICE query, you have to add another SELECT inside it, like this:&lt;br /&gt;
&lt;br /&gt;
 SELECT ... {  # the local query&lt;br /&gt;
     SERVICE ... {  # the remote service&lt;br /&gt;
         SELECT ... {&lt;br /&gt;
             ...&lt;br /&gt;
         } LIMIT 100  # this limit works on the remote service&lt;br /&gt;
     }&lt;br /&gt;
 }  # a limit here would work on your local service, &lt;br /&gt;
    # but is not strictly necessary when you already have an inner LIMIT&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository. Use a local ASK and/or SELECT query to check that the triples have actually been added.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Go back to the [http://query.wikidata.org Wikidata Query Service (WDQS)]. (You can run the rest of the lab using a remote SERVICE inside GraphDB, but using WDQS might give you better error messages etc.)&lt;br /&gt;
&lt;br /&gt;
Primary Wikidata statements use the prefix &#039;&#039;wd:&#039;&#039; for resources and &#039;&#039;wdt:&#039;&#039; for predicates. Use a FILTER statement to only SELECT primary triples in this sense.&lt;br /&gt;
&lt;br /&gt;
These PREFIXes are built into WDQS, but you will need them if you run inside GraphDB:&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;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Use Wikidata&#039;s in-built &#039;&#039;SERVICE wikibase:label&#039;&#039; to get labels for all the object resources. (Autocompletion with Ctrl-Space will help you set up the service.)&lt;br /&gt;
&lt;br /&gt;
Afterwards, instead of &#039;&#039;SELECT *&#039;&#039; or &#039;&#039;SELECT ?p ?o&#039;&#039;, you can write &#039;&#039;SELECT ?p ?o ?oLabel&#039;&#039; to see the labels for all resource objects.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
You now have labels for all the resource objects, but you have no primary triples with literal values. Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE &#039;&#039;xsd:string&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
You still do not have the &amp;quot;fingerprint&amp;quot; triples, i.e., the label, aliases and description of your reference entity. Wikidata uses special properties like &#039;&#039;rdfs:label&#039;&#039;, &#039;&#039;skos:altLabel&#039;&#039; and &#039;&#039;schema:description&#039;&#039; for these. Relax the FILTER expression again so it also returns triples with these three predicates.&lt;br /&gt;
&lt;br /&gt;
PREFIXes you may need:&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;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Now you may have too many fingerprint triples! Try to restrict the FILTER expression again so that, when the predicate is &#039;&#039;rdfs:label&#039;&#039;, &#039;&#039;skos:altLabel&#039;&#039; and &#039;&#039;schema:description&#039;&#039;, the object must have LANG &amp;quot;en&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Go back to your local GraphDB, and run your Wikidata SELECT query inside a SERVICE statement like you did before. (You must declare all PREFIXes now.)&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&lt;br /&gt;
Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository. Go to &#039;&#039;Explorer -&amp;gt; Graph view&#039;&#039; and enter the URI (Q-code) of your reference entity. You can click the cogwheel to extend the number of relations shown for the reference node.&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;
An earlier task returned labels for all the resource objects, but predicates have labels too. Unfortunately, the wikibase:label SERVICE only provides labels for entities with a &#039;&#039;wd:&#039;&#039; prefix. You must therefore REPLACE all &#039;&#039;wdt:&#039;&#039; prefixes of properties with &#039;&#039;wd:&#039;&#039; prefixes and BIND the new URI AS a new variable, for example &#039;&#039;?pw&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; Use the STR(...) and IRI(...) functions carefully: URIs and prefixes are not strings, and strings are not URIs.&lt;br /&gt;
&lt;br /&gt;
Afterwards, instead of &#039;&#039;SELECT ?p ?o ?oLabel&#039;&#039;, you can write &#039;&#039;SELECT ?p ?pwLabel ?o ?oLabel&#039;&#039; to see the labels for both predicates and resource objects.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039;&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 &#039;&#039;subjects&#039;&#039; are &#039;&#039;objects&#039;&#039; of triples involving your reference entity.&lt;br /&gt;
&lt;br /&gt;
In your local GraphDB, use an INSERT statement to add the triples to your local repository. Use &#039;&#039;Explorer&#039;&#039; and &#039;&#039;Graph view&#039;&#039; to visualise the extended graph. You can click on nodes and &#039;&#039;Extend&#039;&#039; them to see their neighbouring nodes.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2467</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2467"/>
		<updated>2024-02-24T13:14:01Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution to Lab 5 - SPARQL Programming&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 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2446</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2446"/>
		<updated>2024-02-21T07:12:09Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Minor headline fix&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 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2413</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2413"/>
		<updated>2024-02-04T23:24:13Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 2 - RDF&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_RDF_programming_with_RDFlib&amp;diff=2387</id>
		<title>Lab: RDF programming with RDFlib</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_RDF_programming_with_RDFlib&amp;diff=2387"/>
		<updated>2024-01-28T13:20:08Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added lab 1 and 2 presentation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* RDF graph programming with RDFlib&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
RDFLib:&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_creating_rdf.html Creating Triples]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/rdf_terms.html RDF Terms]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/namespaces_and_bindings.html Namespaces and Bindings]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_graphs.html Navigating Graphs]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_parsing.html Serialising and parsing]&lt;br /&gt;
&lt;br /&gt;
Lab Presentations:&lt;br /&gt;
* [https://docs.google.com/presentation/d/1blXlTTTsL8jqeV5sRLhQuZ-nssNZqH_bjSgjj-kougE/edit?usp=sharing Lab 1 - RDF Presentation]&lt;br /&gt;
* [https://docs.google.com/presentation/d/17yuNqn66fhEIHPE65PyFC0H359q1k6CquE6ojDV0NB4/edit?usp=sharing Lab 2 - More RDF Presentation]&lt;br /&gt;
&lt;br /&gt;
RDFlib classes/interfaces: &lt;br /&gt;
* from rdflib import Graph, Namespace, URIRef, BNode, Literal&lt;br /&gt;
* from rdflib.namespace import RDF, FOAF, XSD&lt;br /&gt;
* from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
RDFlib methods: &lt;br /&gt;
* Graph: add(), remove(), triples(), serialize(), parse(), bind()&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Continue with the graph you created in [[Lab: Getting started with VSCode, Python and RDFlib | Exercise 1]].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Continue to extend your graph:&lt;br /&gt;
* Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
** He pleaded guilty for lying to Congress.&lt;br /&gt;
* Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
** He pleaded guilty for lying to the FBI.&lt;br /&gt;
** He negotiated a plea agreement.&lt;br /&gt;
If you want, you can try to use properties and types from standard vocabularies like FOAF (friend-of-a-friend) and DC (Dublin Core), but this is something we will look at in later exercises.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; According to [https://www.pbs.org/wgbh/frontline/article/the-mueller-investigation-explained-2/ this FRONTLINE article], Gates&#039;, Cohen&#039;s and Flynn&#039;s lying were different and are described in different detail. &lt;br /&gt;
* How can you represent &amp;quot;different instances of lying&amp;quot; as triples?&lt;br /&gt;
* How can you modify your knowledge graph to account for this?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; It is possible to solve the task above without blank (or anonymous nodes). But to do so, you need to create a URI for each &amp;quot;instance of lying&amp;quot;. This is a situation where blank nodes may be more suitable. Change your graph so it represents instances of lying as blank nodes.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Save (&#039;&#039;serialize&#039;&#039;) your graph to a Turtle file. Add a few triples &#039;&#039;to the Turtle file&#039;&#039; with more information about Donald Trump. For example, you can add that Donald Trump is married to Melania and has several children. You can also use blank nodes to represent two of Trump&#039;s addresses when he was president:&lt;br /&gt;
* The White House, 1600 Pennsylvania Ave., NW Washington, DC 20500, United States, phone: 1-202-456-1414&lt;br /&gt;
* Mar-a-Lago Club, 1100 S Ocean Blvd, Palm Beach, FL 33480, United States&lt;br /&gt;
Visualise the result if you want. Read (&#039;&#039;parse&#039;&#039;) the Turtle file back into a Python program, and check that the new triples are there.&lt;br /&gt;
&lt;br /&gt;
==If you have more time...==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; 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. An excerpt of the output could be:&lt;br /&gt;
 ex:Donald_Trump&lt;br /&gt;
     &amp;lt;== ex:campaignManager ex:Paul_Manafort&lt;br /&gt;
         ==&amp;gt; ex:convictedFor ex:BankAndTaxFraud&lt;br /&gt;
         ...&lt;br /&gt;
     &amp;lt;== ex:attorneyFor ex:Michael_Cohen&lt;br /&gt;
         ==&amp;gt; ex:pleadedGuilty ex:LyingToCongress&lt;br /&gt;
&lt;br /&gt;
Here, the &amp;lt;== and ==&amp;gt; arrows are printed to indicate the reverse of a property. We do that with a &#039;&#039;print()&#039;&#039; statement in Python, not from inside rdflib. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Note:&#039;&#039; Because you must follow triples in both subject-to-predicate and predicate-to-subject direction, you must keep a list of already visited nodes, and never return to a previously visited one.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Note:&#039;&#039; If you want a neat solution, it may be best to combine two graph traversals: first traverse the model breadth-first to create a new tree-shaped model, and then traverse the tree-shaped model depth-first to print it out with indentation. (The point of the first breadth-first step is to find the shortest path to each node.)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Triples you can extend for the tasks (turtle format)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Mueller_Investigation ex:involved ex:George_Papadopoulos,&lt;br /&gt;
        ex:Michael_Cohen,&lt;br /&gt;
        ex:Michael_Flynn,&lt;br /&gt;
        ex:Paul_Manafort,&lt;br /&gt;
        ex:Rick_Gates,&lt;br /&gt;
        ex:Roger_Stone ;&lt;br /&gt;
    ex:leadBy ex:Robert_Muller .&lt;br /&gt;
&lt;br /&gt;
ex:Paul_Manafort ex:businessManager ex:Rick_Gates ;&lt;br /&gt;
    ex:campaignChairman ex:Donald_Trump ;&lt;br /&gt;
    ex:chargedWith ex:ForeignLobbying,&lt;br /&gt;
        ex:MoneyLaundering,&lt;br /&gt;
        ex:TaxEvasion ;&lt;br /&gt;
    ex:convictedFor ex:BankFraud,&lt;br /&gt;
        ex:TaxFraud ;&lt;br /&gt;
    ex:negoiated ex:PleaBargain ;&lt;br /&gt;
    ex:pleadGuiltyTo ex:Conspiracy ;&lt;br /&gt;
    ex:sentencedTo ex:Prison .&lt;br /&gt;
&lt;br /&gt;
ex:Rick_Gates ex:chargedWith ex:ForeignLobbying,&lt;br /&gt;
        ex:MoneyLaundering,&lt;br /&gt;
        ex:TaxEvasion ;&lt;br /&gt;
    ex:pleadGuiltyTo ex:Conspiracy,&lt;br /&gt;
        ex:LyingToFBI .&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2386</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2386"/>
		<updated>2024-01-25T15:34:16Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for Lab 1&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Getting_started_with_VSCode,_Python_and_RDFlib&amp;diff=2377</id>
		<title>Lab: Getting started with VSCode, Python and RDFlib</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Getting_started_with_VSCode,_Python_and_RDFlib&amp;diff=2377"/>
		<updated>2024-01-19T13:18:28Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added lab presentation to useful materials&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics== &lt;br /&gt;
# Prepare for programming knowledge graphs with rdflib in Python.&lt;br /&gt;
# Get started with basic RDF programming.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
VSCode:&lt;br /&gt;
* [https://code.visualstudio.com/docs/python/python-tutorial Getting Started with Python in VS Code]&lt;br /&gt;
* [https://code.visualstudio.com/docs/python/environments# Using Python environments in VS Code] (pip is easiest to start with)&lt;br /&gt;
&lt;br /&gt;
RDFlib:&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/gettingstarted.html Intro to RDFlib]&lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_creating_rdf.html  Intro to creating triples] &lt;br /&gt;
* [https://rdflib.readthedocs.io/en/stable/intro_to_parsing.html Serialising and parsing]&lt;br /&gt;
* [https://www.youtube.com/watch?v=sCU214rbRZ0 8 min introduction video to RDFlib]&lt;br /&gt;
&lt;br /&gt;
Lab Presentations:&lt;br /&gt;
* [https://docs.google.com/presentation/d/1blXlTTTsL8jqeV5sRLhQuZ-nssNZqH_bjSgjj-kougE/edit?usp=sharing Lab 1 - RDF Presentation]&lt;br /&gt;
&lt;br /&gt;
RDFlib classes/interfaces and methods:&lt;br /&gt;
* Graph (add, close, and perhaps remove methods)&lt;br /&gt;
* URIRef&lt;br /&gt;
* Literal&lt;br /&gt;
* Namespace&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
===Install Python, Pip, VSCode, and RDFlib===&lt;br /&gt;
&#039;&#039;&#039;1)&#039;&#039;&#039; You need to have Python version &amp;gt;= 3.7 on your computer. Use the command &#039;&#039;python --version&#039;&#039; in a command/terminal window to check. You can download Python and Pip [https://www.python.org/downloads/ here]. To ensure you have the most recent Pip, you can do&lt;br /&gt;
 python -m pip install --upgrade pip&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;2)&#039;&#039;&#039; You need to have an Integrated Development Environment (IDE) that supports Python. If you are unsure, you can download the free and open source Visual Studio Code (VSCode) [https://code.visualstudio.com/Download here].&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;3)&#039;&#039;&#039; Create a folder for INFO216. Start VSCode and &#039;&#039;create a workspace&#039;&#039; in the file menu (File Menu --&amp;gt; Save Workspace As) and save it in your folder. Afterwards, on the left side of VSCode, click on the document icon (explorer). Click Open Folder, and open your INFO216 folder. Create a new file with &#039;&#039;.py&#039;&#039; extension. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;4)&#039;&#039;&#039; You will be asked to install the Python extension, install it. If you weren&#039;t asked, on the left side of VSCode click on the 4 cubes (extension manager). Within here search for Microsoft&#039;s Python extension and install it. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;5)&#039;&#039;&#039; If you don&#039;t have your terminal open, go to the top menu and click on terminal, and then &#039;&#039;New Terminal&#039;&#039;. Check where your terminal window is currently located. The bottom line starting with &#039;&#039;PS&#039;&#039; or &#039;&#039;(base)&#039;&#039; shows where it&#039;s located. If you added the folder earlier, then you should be located in your INFO216 folder. However, if the destination after PS is not your INFO216 folder, you need to locate to this folder. You can move through folders with the &#039;&#039;cd&#039;&#039; command in the terminal. For instance, if you are at &#039;&#039;PS C:\Users\YourName&amp;gt;&#039;&#039; and your INFO216 folder is at your desktop, you could type the following &#039;&#039;cd .\Desktop\INFO216\&#039;&#039;.     &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;6)&#039;&#039;&#039; If you are correctly located, type in the following command into your terminal window &lt;br /&gt;
&lt;br /&gt;
(Windows)&lt;br /&gt;
 py -3 -m venv .venv&lt;br /&gt;
 .venv\scripts\activate&lt;br /&gt;
&lt;br /&gt;
(Mac / Linux)&lt;br /&gt;
 python3 -m venv .venv&lt;br /&gt;
 source .venv/bin/activate&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;7)&#039;&#039;&#039; If you get the message &#039;&#039;&amp;quot;... is not digitally signed. You cannot run this script on the current system.&amp;quot;&#039;&#039; copy and paste the following in the terminal, and repeat step 6:&lt;br /&gt;
 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;8)&#039;&#039;&#039; This should now have created a virtual environment in your folder called &#039;&#039;.venv&#039;&#039;. In the bottom right corner you will receive a notification asking your to select the new environment for the workspace folder, select yes. You should now see a &#039;&#039;(.venv)&#039;&#039; in front of PS/(base) in the terminal window. Your virtual environment should now automatically be selected when you open your workspace. However, sometimes you might need to open a new terminal for the (.venv) to appear.  &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;9)&#039;&#039;&#039; In the terminal, type the following to install RDFlib:&lt;br /&gt;
 pip install rdflib&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;10)&#039;&#039;&#039; You might need to close and reopen VSCode for RDFlib to work. You can now &#039;&#039;import rdflib&#039;&#039; into your &#039;&#039;.py&#039;&#039; file, or import specific classes/inferfaces such as &#039;&#039;from rdflib import Namespace, Graph&#039;&#039;. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;11)&#039;&#039;&#039; Right click in your code and click &amp;quot;Run Current File in Interactive Window&amp;quot;. When running your program for the first time, you might be asked to install &#039;&#039;ipykernel package&#039;&#039;, install it. &lt;br /&gt;
&lt;br /&gt;
===Programming tasks===&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; &lt;br /&gt;
Represent the sentences below as triples. Note that some sentences can result in several triples. &lt;br /&gt;
* The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
** It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.&lt;br /&gt;
* Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
** He was campaign chairman for Donald Trump&lt;br /&gt;
** He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
** He was convicted for bank and tax fraud.&lt;br /&gt;
** He pleaded guilty to conspiracy.&lt;br /&gt;
** He was sentenced to prison.  &lt;br /&gt;
** He negotiated a plea agreement.&lt;br /&gt;
* Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&lt;br /&gt;
** He pleaded guilty to conspiracy and lying to FBI.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write a program that creates an RDF graph and adds the triples you just created. &lt;br /&gt;
&lt;br /&gt;
For the URIs, you can just use an example path like &#039;&#039;http://example.org/&#039;&#039;. &lt;br /&gt;
So if you want to represent Donald Trump, the URI could be &#039;&#039;http://example.org/Donald_Trump&#039;&#039;, and you can create the resource like this:&lt;br /&gt;
 from rdflib import URIRef&lt;br /&gt;
 &lt;br /&gt;
 donaldTrump = URIRef(&#039;http://example.org/Donald_Trump&#039;)&lt;br /&gt;
&lt;br /&gt;
You can even use a Namespace so you don&#039;t have to write the full URI every time:&lt;br /&gt;
 from rdflib import Namespace&lt;br /&gt;
 &lt;br /&gt;
 ex = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
 donaldTrump = ex.Donald_Trump&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Use the &#039;&#039;serialize&#039;&#039; method of &#039;&#039;rdflib.Graph&#039;&#039; to write out the model in different formats (on screen or to file):&lt;br /&gt;
* Turtle (format=&#039;ttl&#039;)&lt;br /&gt;
* N-Triple (format=&#039;nt&#039;)&lt;br /&gt;
* JSON-LD (format=&#039;json-ld&#039;)&lt;br /&gt;
* RDF-XML (format=&#039;xml&#039;)&lt;br /&gt;
&lt;br /&gt;
Which one is easiest to read? What are the pros and cons of the different formats?&lt;br /&gt;
We will look more at some of them later in the course!&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Use the simple [https://www.ldf.fi/service/rdf-grapher online RDF grapher] to visualise your model. :isSemantic offers [https://issemantic.net/rdf-visualizer a more advanced RDF visualiser] that you can also test if you want.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Loop through the triples in the model to print out all triples that have &#039;&#039;pleading guilty&#039;&#039; as predicate. If you have been inconsistent about some predicate or other term, you can first write loops that correct wrong terms everywhere in the model. (&#039;&#039;Tip:&#039;&#039; to correct a term in a model, you typically have to first &#039;&#039;remove&#039;&#039; the old triple and then &#039;&#039;add&#039;&#039; a new one.)&lt;br /&gt;
&lt;br /&gt;
==If you have more time...==&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; If you have more time you can continue extending your graph:&lt;br /&gt;
* Michael Cohen was Donald Trump&#039;s attorney.&lt;br /&gt;
** He pleaded guilty for lying to Congress.&lt;br /&gt;
* Michael Flynn was adviser to Donald Trump.&lt;br /&gt;
** He pleaded guilty for lying to the FBI.&lt;br /&gt;
** He negotiated a plea agreement.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; According to [https://www.pbs.org/wgbh/frontline/article/the-mueller-investigation-explained-2/ this FRONTLINE article], Gates&#039;, Cohen&#039;s and Flynn&#039;s lying were different and are described in different detail. How can you modify your knowledge graph to account for this?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task:&#039;&#039;&#039; Write a method (function) that submits your model to https://www.ldf.fi/service/rdf-grapher for rendering and saves the returned image to file.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2338</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2338"/>
		<updated>2023-05-05T09:54:44Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed solution for Lab 13 - Web APIs and JSON-LD&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&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;
#################################################################&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&lt;br /&gt;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &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;
== OWL-DL (Lab 10)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#specialProsecutor&lt;br /&gt;
io:specialProsecutor rdf:type owl:ObjectProperty ;&lt;br /&gt;
                     rdfs:subPropertyOf io:leading .&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; rdf:type owl:DatatypeProperty ;&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;
#################################################################&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://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#SpecialCounselInvestigation&lt;br /&gt;
io:SpecialCounselInvestigation rdf:type owl:Class ;&lt;br /&gt;
                               owl:equivalentClass [ rdf:type owl:Restriction ;&lt;br /&gt;
                                                     owl:onProperty [ owl:inverseOf io:specialProsecutor&lt;br /&gt;
                                                                    ] ;&lt;br /&gt;
                                                     owl:someValuesFrom owl:Thing&lt;br /&gt;
                                                   ] ;&lt;br /&gt;
                               rdfs:subClassOf io:Investigation .&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:Investigator ;&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/Jack_Smith_(politician)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                      io:specialProsecutor io:Investigation_of_Trumps_Handling_Graded_Documents ,&lt;br /&gt;
                                                                           io:Investigation_of_Trumps_Role_US_Capital_Attack .&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;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Handling_Graded_Documents&lt;br /&gt;
io:Investigation_of_Trumps_Handling_Graded_Documents rdf:type owl:NamedIndividual .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Role_US_Capital_Attack&lt;br /&gt;
io:Investigation_of_Trumps_Role_US_Capital_Attack rdf:type owl:NamedIndividual .&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;
                        &amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt;&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 11)==&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1a0lpmpjngXY2zsKRFcRWeXwVFMM5NO_O?usp=sharing&lt;br /&gt;
&lt;br /&gt;
==Training Graph Embeddings (Lab 12)==&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q&lt;br /&gt;
&lt;br /&gt;
==Web APIs and JSON-LD (Lab 13)==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import requests&lt;br /&gt;
from rdflib import FOAF, Namespace, Literal, RDF, Graph&lt;br /&gt;
&lt;br /&gt;
r = requests.get(&#039;http://api.open-notify.org/astros.json&#039;).json()&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;
NS = {&lt;br /&gt;
    &amp;quot;ex&amp;quot;: ex,&lt;br /&gt;
    &amp;quot;foaf&amp;quot;:FOAF&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
#Write a small program that queries the Open Notify Astros API&lt;br /&gt;
for item in r[&#039;people&#039;]:&lt;br /&gt;
    craft = item[&#039;craft&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    person = item[&#039;name&#039;].replace(&amp;quot; &amp;quot;,&amp;quot;_&amp;quot;)&lt;br /&gt;
    g.add((ex[person], ex.onCraft, ex[craft]))&lt;br /&gt;
    g.add((ex[person], RDF.type, FOAF.Person))&lt;br /&gt;
    g.add((ex[person], FOAF.name, Literal(item[&#039;name&#039;])))&lt;br /&gt;
    g.add((ex[craft], FOAF.name, Literal(item[&#039;craft&#039;])))&lt;br /&gt;
&lt;br /&gt;
res = g.query(&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
    CONSTRUCT {?person1 foaf:knows ?person2}&lt;br /&gt;
    WHERE {&lt;br /&gt;
        ?person1 ex:onCraft ?craft .&lt;br /&gt;
        ?person2 ex:onCraft ?craft .&lt;br /&gt;
        }&lt;br /&gt;
&amp;quot;&amp;quot;&amp;quot;, initNs=NS)&lt;br /&gt;
&lt;br /&gt;
for triplet in res:&lt;br /&gt;
    # (we don&#039;t need to add that they know themselves)&lt;br /&gt;
    if (triplet[0] != triplet[2]):&lt;br /&gt;
        g.add((triplet))&lt;br /&gt;
&lt;br /&gt;
#Serialise the graph to JSON-LD     &lt;br /&gt;
print(g.serialize(format=&amp;quot;json-ld&amp;quot;))&lt;br /&gt;
&lt;br /&gt;
#DBpedia Spotlight was worked on Lab 5 (CSV to RDF).&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2337</id>
		<title>Lab: Web APIs and JSON-LD</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2337"/>
		<updated>2023-05-03T20:13:09Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added link to exam presentation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) Web APIs (RESTful web services) with JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, parse them programmatically, where possible link the resources to established DBpedia ones and finally create a RDFLib graph with the data.&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ Reading and writing with JSON - stackabuse.com]&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples Examples]&lt;br /&gt;
* [https://realpython.com/python-requests/ Requests - realpython.com]&lt;br /&gt;
* [https://json-ld.org/ JSON for Linking Data]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;br /&gt;
* [https://docs.google.com/presentation/d/1GpzP6825dxau-W21t4Nj0bccd4nbFplGTyMjRBbiXTU/edit?usp=sharing Exam Presentation]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Imports:&#039;&#039;&#039;&lt;br /&gt;
* import json&lt;br /&gt;
* import rdflib&lt;br /&gt;
* import requests&lt;br /&gt;
* import spotlight&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
=== Task 1 ===&lt;br /&gt;
Write a small program that queries the Open Notify Astros API (link below) for the people currently in space. Create a graph from the response connecting each astronaut to the craft they are currently on, for instance using http://example.com/onCraft as a property. Also as the space station is not too big, it is safe to assume that two people who spent time on it at the same time know each other, so add this to the graph.&lt;br /&gt;
&lt;br /&gt;
* Astros API url: http://api.open-notify.org/astros.json&lt;br /&gt;
* Documentation: http://open-notify.org/Open-Notify-API/People-In-Space/&lt;br /&gt;
* Requests Quickstart: https://docs.python-requests.org/en/latest/user/quickstart/&lt;br /&gt;
&lt;br /&gt;
The response from the API follows the format&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;message&amp;quot;: &amp;quot;success&amp;quot;,&lt;br /&gt;
    &amp;quot;number&amp;quot;: 7,&lt;br /&gt;
    &amp;quot;people&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Sergey Ryzhikov&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Kate Rubins&amp;quot;&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;
We only need to think about whats inside the list of the &amp;quot;people&amp;quot;-value.&lt;br /&gt;
To create the graph you can iteratively extract the values of craft and name and add them. As none of the names or craft is a valid URI, they can be crated using the example-namespace.&lt;br /&gt;
&lt;br /&gt;
=== Task 2 ===&lt;br /&gt;
Serialise the graph to JSON-LD, set the context of the JSON-LD object to represent the properties for knows and onCraft.&lt;br /&gt;
&lt;br /&gt;
To do this you need to pip install the json-ld portion of rdflib if you have not already:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install rdflib-jsonld&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== If you have more time ==&lt;br /&gt;
DBpedia Spotlight is a tool for automatically annotating mentions of DBpedia resources in text, providing a solution for linking unstructured information sources to the Linked Open Data cloud through DBpedia.&lt;br /&gt;
&lt;br /&gt;
Build upon the program using the DBpedia Spotlight API (example code below) to use a DBpedia-resource in your graph if one is available. You can add some simple error-handling for cases where no DBpedia resource is found - use an example-entity in stead. Keep in mind that some resources may represent other people with the same name, so try to change the types-parameter so you only get astronauts in return, the confidence-parameter might also help you with this.&lt;br /&gt;
&lt;br /&gt;
The response from DBpedia Spotlight is a list of dictionaries, where each dictionary contains the URI of the resource, its types and some other metadata we will not use now. Set the type of the resouce to the types listed in the response.&lt;br /&gt;
&lt;br /&gt;
=== Example code for DBpedia Spotlight query ===&lt;br /&gt;
First pip install &amp;lt;b&amp;gt;pyspotlight&amp;lt;/b&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import spotlight&lt;br /&gt;
# Note that althoug we import spotlight in python, we need to pip install pyspotlight to get the correct package&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
annotations = spotlight.annotate(SERVER, &amp;quot;str_to_be_annotated&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2336</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2336"/>
		<updated>2023-05-01T13:03:55Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for lab 12&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&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;
#################################################################&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&lt;br /&gt;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &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;
== OWL-DL (Lab 10)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#specialProsecutor&lt;br /&gt;
io:specialProsecutor rdf:type owl:ObjectProperty ;&lt;br /&gt;
                     rdfs:subPropertyOf io:leading .&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; rdf:type owl:DatatypeProperty ;&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;
#################################################################&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://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#SpecialCounselInvestigation&lt;br /&gt;
io:SpecialCounselInvestigation rdf:type owl:Class ;&lt;br /&gt;
                               owl:equivalentClass [ rdf:type owl:Restriction ;&lt;br /&gt;
                                                     owl:onProperty [ owl:inverseOf io:specialProsecutor&lt;br /&gt;
                                                                    ] ;&lt;br /&gt;
                                                     owl:someValuesFrom owl:Thing&lt;br /&gt;
                                                   ] ;&lt;br /&gt;
                               rdfs:subClassOf io:Investigation .&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:Investigator ;&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/Jack_Smith_(politician)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                      io:specialProsecutor io:Investigation_of_Trumps_Handling_Graded_Documents ,&lt;br /&gt;
                                                                           io:Investigation_of_Trumps_Role_US_Capital_Attack .&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;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Handling_Graded_Documents&lt;br /&gt;
io:Investigation_of_Trumps_Handling_Graded_Documents rdf:type owl:NamedIndividual .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Role_US_Capital_Attack&lt;br /&gt;
io:Investigation_of_Trumps_Role_US_Capital_Attack rdf:type owl:NamedIndividual .&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;
                        &amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt;&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 11)==&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1a0lpmpjngXY2zsKRFcRWeXwVFMM5NO_O?usp=sharing&lt;br /&gt;
&lt;br /&gt;
==Training Graph Embeddings (Lab 12)==&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2335</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2335"/>
		<updated>2023-04-28T16:45:38Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added proposed solution for lab 11&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&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;
#################################################################&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&lt;br /&gt;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &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;
== OWL-DL (Lab 10)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#specialProsecutor&lt;br /&gt;
io:specialProsecutor rdf:type owl:ObjectProperty ;&lt;br /&gt;
                     rdfs:subPropertyOf io:leading .&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; rdf:type owl:DatatypeProperty ;&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;
#################################################################&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://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#SpecialCounselInvestigation&lt;br /&gt;
io:SpecialCounselInvestigation rdf:type owl:Class ;&lt;br /&gt;
                               owl:equivalentClass [ rdf:type owl:Restriction ;&lt;br /&gt;
                                                     owl:onProperty [ owl:inverseOf io:specialProsecutor&lt;br /&gt;
                                                                    ] ;&lt;br /&gt;
                                                     owl:someValuesFrom owl:Thing&lt;br /&gt;
                                                   ] ;&lt;br /&gt;
                               rdfs:subClassOf io:Investigation .&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:Investigator ;&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/Jack_Smith_(politician)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                      io:specialProsecutor io:Investigation_of_Trumps_Handling_Graded_Documents ,&lt;br /&gt;
                                                                           io:Investigation_of_Trumps_Role_US_Capital_Attack .&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;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Handling_Graded_Documents&lt;br /&gt;
io:Investigation_of_Trumps_Handling_Graded_Documents rdf:type owl:NamedIndividual .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Role_US_Capital_Attack&lt;br /&gt;
io:Investigation_of_Trumps_Role_US_Capital_Attack rdf:type owl:NamedIndividual .&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;
                        &amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt;&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 11)==&lt;br /&gt;
&lt;br /&gt;
https://colab.research.google.com/drive/1a0lpmpjngXY2zsKRFcRWeXwVFMM5NO_O?usp=sharing&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2331</id>
		<title>Lab: Web APIs and JSON-LD</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2331"/>
		<updated>2023-04-27T09:48:33Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) Web APIs (RESTful web services) with JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, parse them programmatically, where possible link the resources to established DBpedia ones and finally create a RDFLib graph with the data.&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ Reading and writing with JSON - stackabuse.com]&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples Examples]&lt;br /&gt;
* [https://realpython.com/python-requests/ Requests - realpython.com]&lt;br /&gt;
* [https://json-ld.org/ JSON for Linking Data]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Imports:&#039;&#039;&#039;&lt;br /&gt;
* import json&lt;br /&gt;
* import rdflib&lt;br /&gt;
* import requests&lt;br /&gt;
* import spotlight&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
=== Task 1 ===&lt;br /&gt;
Write a small program that queries the Open Notify Astros API (link below) for the people currently in space. Create a graph from the response connecting each astronaut to the craft they are currently on, for instance using http://example.com/onCraft as a property. Also as the space station is not too big, it is safe to assume that two people who spent time on it at the same time know each other, so add this to the graph.&lt;br /&gt;
&lt;br /&gt;
* Astros API url: http://api.open-notify.org/astros.json&lt;br /&gt;
* Documentation: http://open-notify.org/Open-Notify-API/People-In-Space/&lt;br /&gt;
* Requests Quickstart: https://docs.python-requests.org/en/latest/user/quickstart/&lt;br /&gt;
&lt;br /&gt;
The response from the API follows the format&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;message&amp;quot;: &amp;quot;success&amp;quot;,&lt;br /&gt;
    &amp;quot;number&amp;quot;: 7,&lt;br /&gt;
    &amp;quot;people&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Sergey Ryzhikov&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Kate Rubins&amp;quot;&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;
We only need to think about whats inside the list of the &amp;quot;people&amp;quot;-value.&lt;br /&gt;
To create the graph you can iteratively extract the values of craft and name and add them. As none of the names or craft is a valid URI, they can be crated using the example-namespace.&lt;br /&gt;
&lt;br /&gt;
=== Task 2 ===&lt;br /&gt;
Serialise the graph to JSON-LD, set the context of the JSON-LD object to represent the properties for knows and onCraft.&lt;br /&gt;
&lt;br /&gt;
To do this you need to pip install the json-ld portion of rdflib if you have not already:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install rdflib-jsonld&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== If you have more time ==&lt;br /&gt;
DBpedia Spotlight is a tool for automatically annotating mentions of DBpedia resources in text, providing a solution for linking unstructured information sources to the Linked Open Data cloud through DBpedia.&lt;br /&gt;
&lt;br /&gt;
Build upon the program using the DBpedia Spotlight API (example code below) to use a DBpedia-resource in your graph if one is available. You can add some simple error-handling for cases where no DBpedia resource is found - use an example-entity in stead. Keep in mind that some resources may represent other people with the same name, so try to change the types-parameter so you only get astronauts in return, the confidence-parameter might also help you with this.&lt;br /&gt;
&lt;br /&gt;
The response from DBpedia Spotlight is a list of dictionaries, where each dictionary contains the URI of the resource, its types and some other metadata we will not use now. Set the type of the resouce to the types listed in the response.&lt;br /&gt;
&lt;br /&gt;
=== Example code for DBpedia Spotlight query ===&lt;br /&gt;
First pip install &amp;lt;b&amp;gt;pyspotlight&amp;lt;/b&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import spotlight&lt;br /&gt;
# Note that althoug we import spotlight in python, we need to pip install pyspotlight to get the correct package&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
annotations = spotlight.annotate(SERVER, &amp;quot;str_to_be_annotated&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2330</id>
		<title>Lab: Web APIs and JSON-LD</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2330"/>
		<updated>2023-04-27T09:46:47Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Moved imports into useful materials&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) Web APIs (RESTful web services) with JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, parse them programmatically, where possible link the resources to established DBpedia ones and finally create a RDFLib graph with the data.&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ Reading and writing with JSON - stackabuse.com]&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples Examples]&lt;br /&gt;
* [https://realpython.com/python-requests/ Requests - realpython.com]&lt;br /&gt;
* [https://json-ld.org/ JSON for Linking Data]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Imports:&#039;&#039;&#039;&lt;br /&gt;
* import json&lt;br /&gt;
* import rdflib&lt;br /&gt;
* import requests&lt;br /&gt;
* import spotlight&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
=== Task 1 ===&lt;br /&gt;
Write a small program that queries the Open Notify Astros API (link below) for the people currently in space. Create a graph from the response connecting each astronaut to the craft they are currently on, for instance using http://example.com/onCraft as a property. Also as the space station is not too big, it is safe to assume that two people who spent time on it at the same time know each other, so add this to the graph.&lt;br /&gt;
&lt;br /&gt;
* Astros API url: http://api.open-notify.org/astros.json&lt;br /&gt;
* Documentation: http://open-notify.org/Open-Notify-API/People-In-Space/&lt;br /&gt;
* Requests Quickstart: https://docs.python-requests.org/en/latest/user/quickstart/&lt;br /&gt;
&lt;br /&gt;
The response from the API follows the format&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;message&amp;quot;: &amp;quot;success&amp;quot;,&lt;br /&gt;
    &amp;quot;number&amp;quot;: 7,&lt;br /&gt;
    &amp;quot;people&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Sergey Ryzhikov&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Kate Rubins&amp;quot;&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;
We only need to think about whats inside the list of the &amp;quot;people&amp;quot;-value.&lt;br /&gt;
To create the graph you can iteratively extract the values of craft and name and add them. As none of the names or craft is a valid URI, they can be crated using the example-namespace.&lt;br /&gt;
&lt;br /&gt;
=== Task 2 ===&lt;br /&gt;
Serialise the graph to JSON-LD, set the context of the JSON-LD object to represent the properties for knows and onCraft.&lt;br /&gt;
&lt;br /&gt;
To do this you need to pip install the json-ld portion of rdflib if you have not already:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install rdflib-jsonld&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== If you have more time ===&lt;br /&gt;
DBpedia Spotlight is a tool for automatically annotating mentions of DBpedia resources in text, providing a solution for linking unstructured information sources to the Linked Open Data cloud through DBpedia.&lt;br /&gt;
&lt;br /&gt;
Build upon the program using the DBpedia Spotlight API (example code below) to use a DBpedia-resource in your graph if one is available. You can add some simple error-handling for cases where no DBpedia resource is found - use an example-entity in stead. Keep in mind that some resources may represent other people with the same name, so try to change the types-parameter so you only get astronauts in return, the confidence-parameter might also help you with this.&lt;br /&gt;
&lt;br /&gt;
The response from DBpedia Spotlight is a list of dictionaries, where each dictionary contains the URI of the resource, its types and some other metadata we will not use now. Set the type of the resouce to the types listed in the response.&lt;br /&gt;
&lt;br /&gt;
==== Example code for DBpedia Spotlight query ====&lt;br /&gt;
First pip install &amp;lt;b&amp;gt;pyspotlight&amp;lt;/b&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import spotlight&lt;br /&gt;
# Note that althoug we import spotlight in python, we need to pip install pyspotlight to get the correct package&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
annotations = spotlight.annotate(SERVER, &amp;quot;str_to_be_annotated&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2329</id>
		<title>Lab: Web APIs and JSON-LD</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_Web_APIs_and_JSON-LD&amp;diff=2329"/>
		<updated>2023-04-27T09:44:50Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Moved useful materials up&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
==Topics== &lt;br /&gt;
Programming regular (non-semantic) Web APIs (RESTful web services) with JSON-LD.&lt;br /&gt;
&lt;br /&gt;
We will use Web APIs to retrieve regular JSON data, parse them programmatically, where possible link the resources to established DBpedia ones and finally create a RDFLib graph with the data.&lt;br /&gt;
&lt;br /&gt;
==Imports==&lt;br /&gt;
* import json&lt;br /&gt;
* import rdflib&lt;br /&gt;
* import requests&lt;br /&gt;
* import spotlight&lt;br /&gt;
&lt;br /&gt;
==Useful Reading==&lt;br /&gt;
* [https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ Reading and writing with JSON - stackabuse.com]&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples Examples]&lt;br /&gt;
* [https://realpython.com/python-requests/ Requests - realpython.com]&lt;br /&gt;
* [https://json-ld.org/ JSON for Linking Data]&lt;br /&gt;
* [https://www.dbpedia-spotlight.org/api Spotlight Documentation]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
=== Task 1 ===&lt;br /&gt;
Write a small program that queries the Open Notify Astros API (link below) for the people currently in space. Create a graph from the response connecting each astronaut to the craft they are currently on, for instance using http://example.com/onCraft as a property. Also as the space station is not too big, it is safe to assume that two people who spent time on it at the same time know each other, so add this to the graph.&lt;br /&gt;
&lt;br /&gt;
* Astros API url: http://api.open-notify.org/astros.json&lt;br /&gt;
* Documentation: http://open-notify.org/Open-Notify-API/People-In-Space/&lt;br /&gt;
* Requests Quickstart: https://docs.python-requests.org/en/latest/user/quickstart/&lt;br /&gt;
&lt;br /&gt;
The response from the API follows the format&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
    &amp;quot;message&amp;quot;: &amp;quot;success&amp;quot;,&lt;br /&gt;
    &amp;quot;number&amp;quot;: 7,&lt;br /&gt;
    &amp;quot;people&amp;quot;: [&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Sergey Ryzhikov&amp;quot;&lt;br /&gt;
        },&lt;br /&gt;
        {&lt;br /&gt;
            &amp;quot;craft&amp;quot;: &amp;quot;ISS&amp;quot;,&lt;br /&gt;
            &amp;quot;name&amp;quot;: &amp;quot;Kate Rubins&amp;quot;&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;
We only need to think about whats inside the list of the &amp;quot;people&amp;quot;-value.&lt;br /&gt;
To create the graph you can iteratively extract the values of craft and name and add them. As none of the names or craft is a valid URI, they can be crated using the example-namespace.&lt;br /&gt;
&lt;br /&gt;
=== Task 2 ===&lt;br /&gt;
Serialise the graph to JSON-LD, set the context of the JSON-LD object to represent the properties for knows and onCraft.&lt;br /&gt;
&lt;br /&gt;
To do this you need to pip install the json-ld portion of rdflib if you have not already:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
pip install rdflib-jsonld&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== If you have more time ===&lt;br /&gt;
DBpedia Spotlight is a tool for automatically annotating mentions of DBpedia resources in text, providing a solution for linking unstructured information sources to the Linked Open Data cloud through DBpedia.&lt;br /&gt;
&lt;br /&gt;
Build upon the program using the DBpedia Spotlight API (example code below) to use a DBpedia-resource in your graph if one is available. You can add some simple error-handling for cases where no DBpedia resource is found - use an example-entity in stead. Keep in mind that some resources may represent other people with the same name, so try to change the types-parameter so you only get astronauts in return, the confidence-parameter might also help you with this.&lt;br /&gt;
&lt;br /&gt;
The response from DBpedia Spotlight is a list of dictionaries, where each dictionary contains the URI of the resource, its types and some other metadata we will not use now. Set the type of the resouce to the types listed in the response.&lt;br /&gt;
&lt;br /&gt;
==== Example code for DBpedia Spotlight query ====&lt;br /&gt;
First pip install &amp;lt;b&amp;gt;pyspotlight&amp;lt;/b&amp;gt;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
import spotlight&lt;br /&gt;
# Note that althoug we import spotlight in python, we need to pip install pyspotlight to get the correct package&lt;br /&gt;
&lt;br /&gt;
SERVER = &amp;quot;https://api.dbpedia-spotlight.org/en/annotate&amp;quot;&lt;br /&gt;
annotations = spotlight.annotate(SERVER, &amp;quot;str_to_be_annotated&amp;quot;)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2323</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=2323"/>
		<updated>2023-04-18T19:15:14Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Code to get started */&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 KnolwedgeGraph 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2322</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=2322"/>
		<updated>2023-04-18T19:08:17Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Tasks */&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 KnolwedgeGraph 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 bellow 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2320</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=2320"/>
		<updated>2023-04-18T18:48:02Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful readings */&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 KnolwedgeGraph 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 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 bellow 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2319</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=2319"/>
		<updated>2023-04-18T14:53:43Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Tasks */ added a tip to test entities and relations&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;
&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 KnolwedgeGraph 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 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 bellow 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2318</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=2318"/>
		<updated>2023-04-18T13:36:16Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Code to get started */&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;
&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 KnolwedgeGraph 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;.&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 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 bellow 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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2316</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=2316"/>
		<updated>2023-04-18T13:35:28Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Code to get started */&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;
&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 KnolwedgeGraph 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;.&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 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 bellow is prepared in the following link: https://colab.research.google.com/drive/1gS2D1XYSviAmhkS8moJIpY0N8ltJFM3C?authuser=1#scrollTo=oZcIgRVKe__2&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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_Using_Graph_Embeddings&amp;diff=2315</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=2315"/>
		<updated>2023-04-18T13:33:42Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Code to get started */&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;
&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 KnolwedgeGraph 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;.&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 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. Therefore, Google Colab can be a useful tool. The code bellow is prepared in the following link: https://colab.research.google.com/drive/1gS2D1XYSviAmhkS8moJIpY0N8ltJFM3C?authuser=1#scrollTo=oZcIgRVKe__2&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>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2299</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2299"/>
		<updated>2023-04-17T12:11:52Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* OWL-DL (Lab 10) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&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;
#################################################################&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&lt;br /&gt;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &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;
== OWL-DL (Lab 10)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;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;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#specialProsecutor&lt;br /&gt;
io:specialProsecutor rdf:type owl:ObjectProperty ;&lt;br /&gt;
                     rdfs:subPropertyOf io:leading .&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; rdf:type owl:DatatypeProperty ;&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;
#################################################################&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://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#SpecialCounselInvestigation&lt;br /&gt;
io:SpecialCounselInvestigation rdf:type owl:Class ;&lt;br /&gt;
                               owl:equivalentClass [ rdf:type owl:Restriction ;&lt;br /&gt;
                                                     owl:onProperty [ owl:inverseOf io:specialProsecutor&lt;br /&gt;
                                                                    ] ;&lt;br /&gt;
                                                     owl:someValuesFrom owl:Thing&lt;br /&gt;
                                                   ] ;&lt;br /&gt;
                               rdfs:subClassOf io:Investigation .&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:Investigator ;&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/Jack_Smith_(politician)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                      io:specialProsecutor io:Investigation_of_Trumps_Handling_Graded_Documents ,&lt;br /&gt;
                                                                           io:Investigation_of_Trumps_Role_US_Capital_Attack .&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;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Handling_Graded_Documents&lt;br /&gt;
io:Investigation_of_Trumps_Handling_Graded_Documents rdf:type owl:NamedIndividual .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Role_US_Capital_Attack&lt;br /&gt;
io:Investigation_of_Trumps_Role_US_Capital_Attack rdf:type owl:NamedIndividual .&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;
                        &amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt;&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2298</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2298"/>
		<updated>2023-04-17T12:06:54Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed Solution for Lab 10 (OWL-DL)&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&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;
#################################################################&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&lt;br /&gt;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &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;
== OWL-DL (Lab 10)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#specialProsecutor&lt;br /&gt;
io:specialProsecutor rdf:type owl:ObjectProperty ;&lt;br /&gt;
                     rdfs:subPropertyOf io:leading .&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; rdf:type owl:DatatypeProperty ;&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;
#################################################################&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://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#SpecialCounselInvestigation&lt;br /&gt;
io:SpecialCounselInvestigation rdf:type owl:Class ;&lt;br /&gt;
                               owl:equivalentClass [ rdf:type owl:Restriction ;&lt;br /&gt;
                                                     owl:onProperty [ owl:inverseOf io:specialProsecutor&lt;br /&gt;
                                                                    ] ;&lt;br /&gt;
                                                     owl:someValuesFrom owl:Thing&lt;br /&gt;
                                                   ] ;&lt;br /&gt;
                               rdfs:subClassOf io:Investigation .&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:Investigator ;&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/Jack_Smith_(politician)&lt;br /&gt;
&amp;lt;http://dbpedia.org/resource/Jack_Smith_(politician)&amp;gt; rdf:type owl:NamedIndividual ;&lt;br /&gt;
                                                      io:specialProsecutor io:Investigation_of_Trumps_Handling_Graded_Documents ,&lt;br /&gt;
                                                                           io:Investigation_of_Trumps_Role_US_Capital_Attack .&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;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &amp;quot;Mueller Investigation&amp;quot; .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Handling_Graded_Documents&lt;br /&gt;
io:Investigation_of_Trumps_Handling_Graded_Documents rdf:type owl:NamedIndividual .&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Role_US_Capital_Attack&lt;br /&gt;
io:Investigation_of_Trumps_Role_US_Capital_Attack rdf:type owl:NamedIndividual .&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2291</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2291"/>
		<updated>2023-04-13T14:04:55Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* OWL 2 (Lab 9) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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://purl.org/dc/elements/1.1/title&lt;br /&gt;
&amp;lt;http://purl.org/dc/elements/1.1/title&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;
#################################################################&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&lt;br /&gt;
                                                                        &amp;lt;http://purl.org/dc/elements/1.1/title&amp;gt; &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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2282</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2282"/>
		<updated>2023-04-10T19:22:20Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Removed some details from Lab 9&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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;
                       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;
                  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;
                   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;
                                                                                 io:Investigation ;&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2278</id>
		<title>Lab: OWL-DL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2278"/>
		<updated>2023-04-10T18:42:41Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* OWL ontology editing in Protégé.&lt;br /&gt;
* Manchester-OWL syntax&lt;br /&gt;
* HermiT reasoning.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
* [https://www.w3.org/TR/owl2-primer/ OWL2 Primer] (from S08): &#039;&#039;Show Manchester Syntax&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Protégé:&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab 9 presentation introducing Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09 and same as previous week) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
== Classes and methods ==&lt;br /&gt;
&#039;&#039;&#039;RDF:&#039;&#039;&#039;&lt;br /&gt;
* type&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;RDFS:&#039;&#039;&#039;&lt;br /&gt;
* subClassOf, subPropertyOf, domain, range&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Basic OWL:&#039;&#039;&#039;&lt;br /&gt;
* sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf&lt;br /&gt;
* ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Complex OWL:&#039;&#039;&#039;&lt;br /&gt;
* oneOf, unionOf, intersectionOf. complementOf&lt;br /&gt;
* Restriction, onProperty&lt;br /&gt;
* someValuesFrom, allValuesFrom, hasValue&lt;br /&gt;
* cardinality, minCardinality, maxCardinality&lt;br /&gt;
* qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Continue extending the InvestigationOntology from the previous exercise. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology contains &lt;br /&gt;
* a property for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation and&lt;br /&gt;
* a subproperty for stating that a person is &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
Create instances for Robert Mueller and for the Mueller Investigation. Assert that Robert Mueller is leading the Mueller Investigation, but not that he is involved in it.&lt;br /&gt;
&lt;br /&gt;
Go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039;. Afterwards, check that Robert Mueller is now also leading the Mueller Investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology also contains &lt;br /&gt;
* classes for representing investigators and investigation leaders&lt;br /&gt;
&lt;br /&gt;
Add an axiom to the investigation leader class to make sure that every investigator that is leading and investigation is an investigation leader. If you have asserted that Robert Mueller is an investigation leader, remove the assertion. Re-run the HermiT reasoner, and check that Robert Mueller is now an investigation leader,&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
TBD.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2277</id>
		<title>Lab: OWL-DL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2277"/>
		<updated>2023-04-10T18:41:47Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Added &amp;quot;classes and methods&amp;quot; section&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* OWL ontology editing in Protégé.&lt;br /&gt;
* Manchester-OWL syntax&lt;br /&gt;
* HermiT reasoning.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
* [https://www.w3.org/TR/owl2-primer/ OWL2 Primer] (from S08): &#039;&#039;Show Manchester Syntax&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Protégé:&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab 9 presentation introducing Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09 and same as previous week) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
== Classes and methods ==&lt;br /&gt;
&#039;&#039;&#039;RDF:&#039;&#039;&#039;&lt;br /&gt;
* type&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;RDFS:&#039;&#039;&#039;&lt;br /&gt;
* subClassOf, subPropertyOf, domain, range&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Basic OWL:&#039;&#039;&#039;&lt;br /&gt;
* sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf&lt;br /&gt;
* ReflexiveProperty, IrreflexiveProperty, SymmetricProperty, AsymmetricProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Complex OWL:&#039;&#039;&#039;&lt;br /&gt;
* oneOf, unionOf, intersectionOf. complementOf&lt;br /&gt;
* Restriction, onProperty&lt;br /&gt;
* someValuesFrom, allValuesFrom, hasValue&lt;br /&gt;
* cardinality, minCardinality, maxCardinality&lt;br /&gt;
* qualifiedCardinality, minQualifiedCardinality, maxQualifiedCardinality, onClass&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Continue extending the InvestigationOntology from the previous exercise. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology contains &lt;br /&gt;
* a property for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation and&lt;br /&gt;
* a subproperty for stating that a person is &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
Create instances for Robert Mueller and for the Mueller Investigation. Assert that Robert Mueller is leading the Mueller Investigation, but not that he is involved in it.&lt;br /&gt;
&lt;br /&gt;
Go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039;. Afterwards, check that Robert Mueller is now also leading the Mueller Investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology also contains &lt;br /&gt;
* classes for representing investigators and investigation leaders&lt;br /&gt;
&lt;br /&gt;
Add an axiom to the investigation leader class to make sure that every investigator that is leading and investigation is an investigation leader. If you have asserted that Robert Mueller is an investigation leader, remove the assertion. Re-run the HermiT reasoner, and check that Robert Mueller is now an investigation leader,&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
TBD.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2276</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2276"/>
		<updated>2023-04-09T16:12:23Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed solution for Lab 9 - OWL 2&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 9)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: This is an OWL Protégé file&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight&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#hasLeader&lt;br /&gt;
io:hasLeader rdf:type owl:ObjectProperty ;&lt;br /&gt;
             rdfs:subPropertyOf io:involved ;&lt;br /&gt;
             owl:inverseOf io:leading .&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#involved&lt;br /&gt;
io:involved rdf:type owl:ObjectProperty ;&lt;br /&gt;
            owl:inverseOf io:involvedIn ;&lt;br /&gt;
            rdfs:domain io:Investigation ;&lt;br /&gt;
            rdfs:range foaf:Person .&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;
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#teamMembers&lt;br /&gt;
io:teamMembers rdf:type owl:ObjectProperty ;&lt;br /&gt;
               rdfs:subPropertyOf io:involved ;&lt;br /&gt;
               rdfs:domain 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;
                 io:involvedIn &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&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;
                  io:indictedIn &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&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;
                io:indictedIn &amp;lt;http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)&amp;gt; ;&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;
                                                                        io:hasLeader dbr:Robert_Mueller ;&lt;br /&gt;
                                                                        io:involved dbr:Donald_Trump ,&lt;br /&gt;
                                                                                    dbr:Michael_Flynn ,&lt;br /&gt;
                                                                                    dbr:Paul_Manafort ,&lt;br /&gt;
                                                                                    dbr:Roger_Stone ;&lt;br /&gt;
                                                                        io:teamMembers dbr:Elizabeth_Prelogar ,&lt;br /&gt;
                                                                                       dbr:Robert_Mueller ;&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2275</id>
		<title>Lab: OWL 2</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2275"/>
		<updated>2023-03-31T08:12:21Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful materials */ Updated FOAF link&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Basic OWL ontology editing in Protégé.&lt;br /&gt;
* WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/installation/ Installation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/getting-started/ Getting Started]&lt;br /&gt;
** An online version, [https://protege.stanford.edu/products.php#web-protege Webprotégé], is also available, but we recommend that you download the Desktop version and run it locally.&lt;br /&gt;
* [https://www.youtube.com/playlist?list=PLea0WJq13cnAfCC0azrCyquCN_tPelJN1 Youtube Playlist with quick tutorials of Protégé, particularly video 1 - 5]&lt;br /&gt;
* [https://www.w3.org/TR/owl-ref/ OWL Documentation] (from S08)&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab presentation of Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/0.1/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Follow the [https://protegeproject.github.io/protege/installation/ Protégé 5 Installation instructions] to download and install Protégé Desktop.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Go through the [https://protegeproject.github.io/protege/getting-started/ Protégé 5 Getting Started advice] to learn the basics of Protégé Desktop. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create a new InvestigationOntology that can be used to represent the Mueller Investigation, as well as other public investigations. Choose a prefix (for example &#039;&#039;io:&#039;&#039;) path for the ontology, and save the empty ontology to a file.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Start adding classes and properties to your ontology. Use the experience from earlier exercises. For example, the ontology can include these top-level classes:&lt;br /&gt;
* Investigation&lt;br /&gt;
* Person&lt;br /&gt;
Subclasses of Person can be&lt;br /&gt;
* Investigator&lt;br /&gt;
* InvestigatedPerson&lt;br /&gt;
A subclass of Investigator can be InvestigationLeader.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Connect your classes to at least one class from a well-known ontology, for example foaf:Person. There are three ways you can do this do this: &lt;br /&gt;
# use foaf:Person instead of &amp;quot;your own&amp;quot; Person class;&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class an rdfs:subClassOf foaf:Person; or&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class owl:equivalentClass to foaf:Person.&lt;br /&gt;
Alternative 2 is most common but all are ok.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Hint 1:&#039;&#039; You must first create &#039;&#039;foaf:Person&#039;&#039; as a class in your ontology.&lt;br /&gt;
&#039;&#039;Hint 2:&#039;&#039; Use the &#039;&#039;Ontology Prefixes&#039;&#039; sub-tab in the &#039;&#039;Active ontology&#039;&#039; tab to define a new prefix.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create or reuse data properties for &lt;br /&gt;
* investigation title and description;&lt;br /&gt;
* person names; and&lt;br /&gt;
* investigation start and end times.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Hint:&#039;&#039; To reuse a property from another vocabulary, you need to create it as a property in your ontology.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task,&#039;&#039;&#039; Define the proper domains and ranges of your data properties. Should some of them be marked as &#039;&#039;Functional&#039;&#039;?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Along the way, keep saving the ontology to a file, and use [http://vowl.visualdataweb.org/webvowl.html WebVOWL] to visualise it (either &#039;&#039;Run WebVOWL&#039;&#039; or &#039;&#039;Old WebVOWL version&#039;&#039;). Keep improving the ontology until it looks the way you think it should.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Also along the way, go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039; to check that your ontology is consistent.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; When you change the ontology and the reasoner is running, you must use &#039;&#039;Reasoner -&amp;gt; Synchronize&#039;&#039; to reason over the changes.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
* Create or import object properties for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation.&lt;br /&gt;
* Create subproperties of &#039;&#039;involved in&#039;&#039; for stating that a person can be &#039;&#039;indicted in&#039;&#039;, &#039;&#039;investigating&#039;&#039;, or &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Define the proper domains and ranges of your object properties. Should some of them have particular &#039;&#039;Characteristics&#039;&#039;?&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Stop the reasoner, and add individuals to represent that:&lt;br /&gt;
* Robert Mueller lead the Mueller Investigation.&lt;br /&gt;
* Paul Manafort was indicted.&lt;br /&gt;
* Elizabeth Prelogar was an investigator.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Start the reasoner again. Has any axioms/triples been added to the ontology?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Can you do a change that makes your ontology inconsistent? (Save often, so you always have a consistent version to revert to :-))&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
You can add a lot more classes (types) and relations (object properties) to your ontology. For example:&lt;br /&gt;
* InvestigationTeam, which has all the Investigators as members&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2274</id>
		<title>Lab: OWL-DL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2274"/>
		<updated>2023-03-30T11:46:12Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* OWL ontology editing in Protégé.&lt;br /&gt;
* Manchester-OWL syntax&lt;br /&gt;
* HermiT reasoning.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
* [https://www.w3.org/TR/owl2-primer/ OWL2 Primer] (from S08): &#039;&#039;Show Manchester Syntax&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Protégé:&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab 9 presentation introducing Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09 and same as previous week) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Continue extending the InvestigationOntology from the previous exercise. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology contains &lt;br /&gt;
* a property for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation and&lt;br /&gt;
* a subproperty for stating that a person is &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
Create instances for Robert Mueller and for the Mueller Investigation. Assert that Robert Mueller is leading the Mueller Investigation, but not that he is involved in it.&lt;br /&gt;
&lt;br /&gt;
Go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039;. Afterwards, check that Robert Mueller is now also leading the Mueller Investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology also contains &lt;br /&gt;
* classes for representing investigators and investigation leaders&lt;br /&gt;
&lt;br /&gt;
Add an axiom to the investigation leader class to make sure that every investigator that is leading and investigation is an investigation leader. If you have asserted that Robert Mueller is an investigation leader, remove the assertion. Re-run the HermiT reasoner, and check that Robert Mueller is now an investigation leader,&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
TBD.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2273</id>
		<title>Lab: OWL-DL</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL-DL&amp;diff=2273"/>
		<updated>2023-03-29T14:35:39Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful materials */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* OWL ontology editing in Protégé.&lt;br /&gt;
* Manchester-OWL syntax&lt;br /&gt;
* HermiT reasoning.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
* [https://www.w3.org/TR/owl2-primer/ OWL2 Primer] (from S08): &#039;&#039;Show Manchester Syntax&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Protégé:&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab presentation of Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09 and same as previous week) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
Continue extending the InvestigationOntology from the previous exercise. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology contains &lt;br /&gt;
* a property for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation and&lt;br /&gt;
* a subproperty for stating that a person is &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
Create instances for Robert Mueller and for the Mueller Investigation. Assert that Robert Mueller is leading the Mueller Investigation, but not that he is involved in it.&lt;br /&gt;
&lt;br /&gt;
Go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039;. Afterwards, check that Robert Mueller is now also leading the Mueller Investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Make sure that your ontology also contains &lt;br /&gt;
* classes for representing investigators and investigation leaders&lt;br /&gt;
&lt;br /&gt;
Add an axiom to the investigation leader class to make sure that every investigator that is leading and investigation is an investigation leader. If you have asserted that Robert Mueller is an investigation leader, remove the assertion. Re-run the HermiT reasoner, and check that Robert Mueller is now an investigation leader,&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
TBD.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2272</id>
		<title>Lab: OWL 2</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2272"/>
		<updated>2023-03-29T14:34:59Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful materials */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Basic OWL ontology editing in Protégé.&lt;br /&gt;
* WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/installation/ Installation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/getting-started/ Getting Started]&lt;br /&gt;
** An online version, [https://protege.stanford.edu/products.php#web-protege Webprotégé], is also available, but we recommend that you download the Desktop version and run it locally.&lt;br /&gt;
* [https://www.youtube.com/playlist?list=PLea0WJq13cnAfCC0azrCyquCN_tPelJN1 Youtube Playlist with quick tutorials of Protégé, particularly video 1 - 5]&lt;br /&gt;
* [https://www.w3.org/TR/owl-ref/ OWL Documentation] (from S08)&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab presentation of Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Follow the [https://protegeproject.github.io/protege/installation/ Protégé 5 Installation instructions] to download and install Protégé Desktop.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Go through the [https://protegeproject.github.io/protege/getting-started/ Protégé 5 Getting Started advice] to learn the basics of Protégé Desktop. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create a new InvestigationOntology that can be used to represent the Mueller Investigation, as well as other public investigations. Choose a prefix (for example &#039;&#039;io:&#039;&#039;) path for the ontology, and save the empty ontology to a file.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Start adding classes and properties to your ontology. Use the experience from earlier exercises. For example, the ontology can include these top-level classes:&lt;br /&gt;
* Investigation&lt;br /&gt;
* Person&lt;br /&gt;
Subclasses of Person can be&lt;br /&gt;
* Investigator&lt;br /&gt;
* InvestigatedPerson&lt;br /&gt;
A subclass of Investigator can be InvestigationLeader.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Connect your classes to at least one class from a well-known ontology, for example foaf:Person. There are three ways you can do this do this: &lt;br /&gt;
# use foaf:Person instead of &amp;quot;your own&amp;quot; Person class;&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class an rdfs:subClassOf foaf:Person; or&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class owl:equivalentClass to foaf:Person.&lt;br /&gt;
Alternative 2 is most common but all are ok.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Hint 1:&#039;&#039; You must first create &#039;&#039;foaf:Person&#039;&#039; as a class in your ontology.&lt;br /&gt;
&#039;&#039;Hint 2:&#039;&#039; Use the &#039;&#039;Ontology Prefixes&#039;&#039; sub-tab in the &#039;&#039;Active ontology&#039;&#039; tab to define a new prefix.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create or reuse data properties for &lt;br /&gt;
* investigation title and description;&lt;br /&gt;
* person names; and&lt;br /&gt;
* investigation start and end times.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Hint:&#039;&#039; To reuse a property from another vocabulary, you need to create it as a property in your ontology.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task,&#039;&#039;&#039; Define the proper domains and ranges of your data properties. Should some of them be marked as &#039;&#039;Functional&#039;&#039;?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Along the way, keep saving the ontology to a file, and use [http://vowl.visualdataweb.org/webvowl.html WebVOWL] to visualise it (either &#039;&#039;Run WebVOWL&#039;&#039; or &#039;&#039;Old WebVOWL version&#039;&#039;). Keep improving the ontology until it looks the way you think it should.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Also along the way, go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039; to check that your ontology is consistent.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; When you change the ontology and the reasoner is running, you must use &#039;&#039;Reasoner -&amp;gt; Synchronize&#039;&#039; to reason over the changes.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
* Create or import object properties for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation.&lt;br /&gt;
* Create subproperties of &#039;&#039;involved in&#039;&#039; for stating that a person can be &#039;&#039;indicted in&#039;&#039;, &#039;&#039;investigating&#039;&#039;, or &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Define the proper domains and ranges of your object properties. Should some of them have particular &#039;&#039;Characteristics&#039;&#039;?&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Stop the reasoner, and add individuals to represent that:&lt;br /&gt;
* Robert Mueller lead the Mueller Investigation.&lt;br /&gt;
* Paul Manafort was indicted.&lt;br /&gt;
* Elizabeth Prelogar was an investigator.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Start the reasoner again. Has any axioms/triples been added to the ontology?&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Can you do a change that makes your ontology inconsistent? (Save often, so you always have a consistent version to revert to :-))&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
You can add a lot more classes (types) and relations (object properties) to your ontology. For example:&lt;br /&gt;
* InvestigationTeam, which has all the Investigators as members&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2271</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2271"/>
		<updated>2023-03-29T12:30:25Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed solution for Lab 8 OWL 1&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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 8)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2256</id>
		<title>Lab: OWL 2</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2256"/>
		<updated>2023-03-27T13:57:38Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful materials */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Basic OWL ontology editing in Protégé.&lt;br /&gt;
* WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/installation/ Installation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/getting-started/ Getting Started]&lt;br /&gt;
** An online version, [https://protege.stanford.edu/products.php#web-protege Webprotégé], is also available, but we recommend that you download the Desktop version and run it locally.&lt;br /&gt;
* [https://www.youtube.com/playlist?list=PLea0WJq13cnAfCC0azrCyquCN_tPelJN1 Youtube Playlist with quick tutorials of Protégé, particularly video 1 - 5]&lt;br /&gt;
* [https://www.w3.org/TR/owl-ref/ OWL Documentation] (from S08)&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab presentation with tips for Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Follow the [https://protegeproject.github.io/protege/installation/ Protégé 5 Installation instructions] to download and install Protégé Desktop.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Go through the [https://protegeproject.github.io/protege/getting-started/ Protégé 5 Getting Started advice] to learn the basics of Protégé Desktop. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create a new InvestigationOntology that can be used to represent the Mueller Investigation, as well as other public investigations. Choose a prefix (for example &#039;&#039;io:&#039;&#039;) path for the ontology, and save the empty ontology to a file.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Start adding classes and properties to your ontology. Use the experience from earlier exercises. For example, the ontology can include these top-level classes:&lt;br /&gt;
* Investigation&lt;br /&gt;
* Person&lt;br /&gt;
Subclasses of Person can be&lt;br /&gt;
* Investigator&lt;br /&gt;
* InvestigatedPerson&lt;br /&gt;
A subclass of Investigator can be InvestigationLeader.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Connect your classes to at least one class from a well-known ontology, for example foaf:Person. There are three ways you can do this do this: &lt;br /&gt;
# use foaf:Person instead of &amp;quot;your own&amp;quot; Person class;&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class an rdfs:subClassOf foaf:Person; or&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class owl:equivalentClass to foaf:Person.&lt;br /&gt;
Alternative 2 is most common but all are ok.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create or import data properties for &lt;br /&gt;
* investigation title and description;&lt;br /&gt;
* person names; and&lt;br /&gt;
* investigation start and end times.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
* Create or import object properties for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation.&lt;br /&gt;
* Create subproperties of &#039;&#039;involved in&#039;&#039; for stating that a person can be &#039;&#039;indicted in&#039;&#039;, &#039;&#039;investigating&#039;&#039;, or &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Along the way, keep saving the ontology to a file, and use [http://vowl.visualdataweb.org/webvowl.html WebVOWL] to visualise it (either &#039;&#039;Run WebVOWL&#039;&#039; or &#039;&#039;Old WebVOWL version&#039;&#039;). Keep improving the ontology until it looks the way you think it should.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Also along the way, go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039; to check that your ontology is consistent.&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
You can add a lot more classes (types) and relations (object properties) to your ontology. For example:&lt;br /&gt;
* InvestigationTeam, which has all the Investigators as members&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2255</id>
		<title>Lab: OWL 2</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2255"/>
		<updated>2023-03-27T11:55:29Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful materials */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Basic OWL ontology editing in Protégé.&lt;br /&gt;
* WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/installation/ Installation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/getting-started/ Getting Started]&lt;br /&gt;
** An online version, [https://protege.stanford.edu/products.php#web-protege Webprotégé], is also available, but we recommend that you download the Desktop version and run it locally.&lt;br /&gt;
* [https://www.w3.org/TR/owl-ref/ OWL Documentation] (from S08)&lt;br /&gt;
* [https://docs.google.com/presentation/d/17iS--yTuKzccP2k7Nqu0TnFJH2XJczhgufJ69rFrsfM Lab presentation with tips for Protégé]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Follow the [https://protegeproject.github.io/protege/installation/ Protégé 5 Installation instructions] to download and install Protégé Desktop.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Go through the [https://protegeproject.github.io/protege/getting-started/ Protégé 5 Getting Started advice] to learn the basics of Protégé Desktop. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create a new InvestigationOntology that can be used to represent the Mueller Investigation, as well as other public investigations. Choose a prefix (for example &#039;&#039;io:&#039;&#039;) path for the ontology, and save the empty ontology to a file.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Start adding classes and properties to your ontology. Use the experience from earlier exercises. For example, the ontology can include these top-level classes:&lt;br /&gt;
* Investigation&lt;br /&gt;
* Person&lt;br /&gt;
Subclasses of Person can be&lt;br /&gt;
* Investigator&lt;br /&gt;
* InvestigatedPerson&lt;br /&gt;
A subclass of Investigator can be InvestigationLeader.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Connect your classes to at least one class from a well-known ontology, for example foaf:Person. There are three ways you can do this do this: &lt;br /&gt;
# use foaf:Person instead of &amp;quot;your own&amp;quot; Person class;&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class an rdfs:subClassOf foaf:Person; or&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class owl:equivalentClass to foaf:Person.&lt;br /&gt;
Alternative 2 is most common but all are ok.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create or import data properties for &lt;br /&gt;
* investigation title and description;&lt;br /&gt;
* person names; and&lt;br /&gt;
* investigation start and end times.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
* Create or import object properties for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation.&lt;br /&gt;
* Create subproperties of &#039;&#039;involved in&#039;&#039; for stating that a person can be &#039;&#039;indicted in&#039;&#039;, &#039;&#039;investigating&#039;&#039;, or &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Along the way, keep saving the ontology to a file, and use [http://vowl.visualdataweb.org/webvowl.html WebVOWL] to visualise it (either &#039;&#039;Run WebVOWL&#039;&#039; or &#039;&#039;Old WebVOWL version&#039;&#039;). Keep improving the ontology until it looks the way you think it should.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Also along the way, go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039; to check that your ontology is consistent.&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
You can add a lot more classes (types) and relations (object properties) to your ontology. For example:&lt;br /&gt;
* InvestigationTeam, which has all the Investigators as members&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2248</id>
		<title>Lab: OWL 2</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_2&amp;diff=2248"/>
		<updated>2023-03-25T17:30:06Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Tasks */ changed url&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Basic OWL ontology editing in Protégé.&lt;br /&gt;
* WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://protegeproject.github.io/protege/ Protégé 5 Documentation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/installation/ Installation]&lt;br /&gt;
** [https://protegeproject.github.io/protege/getting-started/ Getting Started]&lt;br /&gt;
** An online version, [https://protege.stanford.edu/products.php#web-protege Webprotégé], is also available, but we recommend that you download the Desktop version and run it locally.&lt;br /&gt;
* [https://www.w3.org/TR/owl-ref/ OWL Documentation] (from S08)&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms (from S09) - &#039;&#039;this is for reference: you will not need them all :-)&#039;&#039;:&lt;br /&gt;
* [http://xmlns.com/foaf/spec/ Friend of a Friend (FOAF)] (if necessary follow the link to the 2004 version)&lt;br /&gt;
* [http://motools.sourceforge.net/event/event.html Event Ontology (event)]&lt;br /&gt;
* [http://www.w3.org/TR/owl-time/ Time ontology in OWL (time, OWL-time)]&lt;br /&gt;
* [https://www.w3.org/2003/01/geo/ geo: World Geodetic Standard (WGS) 84]&lt;br /&gt;
* [http://dublincore.org/ Dublin Core (DC)]&lt;br /&gt;
* [http://www.w3.org/2004/02/skos/ SKOS - Simple Knowledge Organization System Home Page]&lt;br /&gt;
* [http://rdfs.org/sioc/spec/ Semantic Interlinked Online Communities (SIOC)]&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Follow the [https://protegeproject.github.io/protege/installation/ Protégé 5 Installation instructions] to download and install Protégé Desktop.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Go through the [https://protegeproject.github.io/protege/getting-started/ Protégé 5 Getting Started advice] to learn the basics of Protégé Desktop. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create a new InvestigationOntology that can be used to represent the Mueller Investigation, as well as other public investigations. Choose a prefix (for example &#039;&#039;io:&#039;&#039;) path for the ontology, and save the empty ontology to a file.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
Start adding classes and properties to your ontology. Use the experience from earlier exercises. For example, the ontology can include these top-level classes:&lt;br /&gt;
* Investigation&lt;br /&gt;
* Person&lt;br /&gt;
Subclasses of Person can be&lt;br /&gt;
* Investigator&lt;br /&gt;
* InvestigatedPerson&lt;br /&gt;
A subclass of Investigator can be InvestigationLeader.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Connect your classes to at least one class from a well-known ontology, for example foaf:Person. There are three ways you can do this do this: &lt;br /&gt;
# use foaf:Person instead of &amp;quot;your own&amp;quot; Person class;&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class an rdfs:subClassOf foaf:Person; or&lt;br /&gt;
# make &amp;quot;your own&amp;quot; Person class owl:equivalentClass to foaf:Person.&lt;br /&gt;
Alternative 2 is most common but all are ok.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Create or import data properties for &lt;br /&gt;
* investigation title and description;&lt;br /&gt;
* person names; and&lt;br /&gt;
* investigation start and end times.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; &lt;br /&gt;
* Create or import object properties for stating that a person is &#039;&#039;involved in&#039;&#039; an investigation.&lt;br /&gt;
* Create subproperties of &#039;&#039;involved in&#039;&#039; for stating that a person can be &#039;&#039;indicted in&#039;&#039;, &#039;&#039;investigating&#039;&#039;, or &#039;&#039;leading&#039;&#039; an investigation.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Along the way, keep saving the ontology to a file, and use [http://vowl.visualdataweb.org/webvowl.html WebVOWL] to visualise it (either &#039;&#039;Run WebVOWL&#039;&#039; or &#039;&#039;Old WebVOWL version&#039;&#039;). Keep improving the ontology until it looks the way you think it should.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039; Also along the way, go to the &#039;&#039;Reasoner&#039;&#039; menu and choose the &#039;&#039;HermiT&#039;&#039; reasoner. Use &#039;&#039;Reasoner -&amp;gt; Start reasoner&#039;&#039; to check that your ontology is consistent.&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
You can add a lot more classes (types) and relations (object properties) to your ontology. For example:&lt;br /&gt;
* InvestigationTeam, which has all the Investigators as members&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2242</id>
		<title>Lab Solutions</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab_Solutions&amp;diff=2242"/>
		<updated>2023-03-21T14:00:44Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: Proposed solution for Lab 7 RDFS&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page will be updated with Python examples related to the labs as the course progresses.&lt;br /&gt;
&lt;br /&gt;
=Examples from the lectures=&lt;br /&gt;
&lt;br /&gt;
==Lecture 1: Introduction to KGs==&lt;br /&gt;
Turtle example:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example.org/&amp;gt; .&lt;br /&gt;
ex:Roger_Stone&lt;br /&gt;
    ex:name &amp;quot;Roger Stone&amp;quot; ;&lt;br /&gt;
    ex:occupation ex:lobbyist ;&lt;br /&gt;
    ex:significant_person ex:Donald_Trump .&lt;br /&gt;
ex:Donald_Trump&lt;br /&gt;
    ex:name &amp;quot;Donald Trump&amp;quot; .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Lecture 2: RDF==&lt;br /&gt;
Blank nodes for anonymity, or when we have not decided on a URI:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Python&amp;quot;&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)  # this is why the line &#039;@prefix ex: &amp;lt;http://example.org/&amp;gt; .&#039;&lt;br /&gt;
                  # and the &#039;ex.&#039; prefix are used when we print out Turtle later&lt;br /&gt;
&lt;br /&gt;
robertMueller = BNode()&lt;br /&gt;
g.add((robertMueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((robertMueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((robertMueller, EX.position_held, Literal(&#039;Director of the Federal Bureau of Investigation&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Blank nodes used to group related properties:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
# This is a task in Exercise 2&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Literals:&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Robert_Mueller, RDF.type, EX.Human))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;Robert Mueller&#039;, lang=&#039;en&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, FOAF.name, Literal(&#039;رابرت مولر&#039;, lang=&#039;fa&#039;)))&lt;br /&gt;
g.add((EX.Robert_Mueller, DC.description, Literal(&#039;sixth director of the FBI&#039;, datatype=XSD.string)))&lt;br /&gt;
g.add((EX.Robert_Mueller, EX.start_time, Literal(2001, datatype=XSD.integer)))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Alternative container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
muellerReportArchives = BNode()&lt;br /&gt;
g.add((muellerReportArchives, RDF.type, RDF.Alt))&lt;br /&gt;
&lt;br /&gt;
archive1 = &#039;https://archive.org/details/MuellerReportVolume1Searchable/&#039; \&lt;br /&gt;
                    &#039;Mueller%20Report%20Volume%201%20Searchable/&#039;&lt;br /&gt;
archive2 = &#039;https://edition.cnn.com/2019/04/18/politics/full-mueller-report-pdf/index.html&#039;&lt;br /&gt;
archive3 = &#039;https://www.politico.com/story/2019/04/18/mueller-report-pdf-download-text-file-1280891&#039;&lt;br /&gt;
&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive1, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive2, datatype=XSD.anyURI)))&lt;br /&gt;
g.add((muellerReportArchives, RDFS.member, Literal(archive3, datatype=XSD.anyURI)))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Mueller_Report, RDF.type, FOAF.Document))&lt;br /&gt;
g.add((EX.Mueller_Report, DC.contributor, EX.Robert_Mueller))&lt;br /&gt;
g.add((EX.Mueller_Report, SCHEMA.archivedAt, muellerReportArchives))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequence container (open):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF.type, RDF.Seq))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._1, EX.IvanaTrump))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._2, EX.MarlaMaples))&lt;br /&gt;
g.add((donaldTrumpSpouses, RDF._3, EX.MelaniaTrump))&lt;br /&gt;
&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Collection (closed list):&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
from rdflib import Graph, Namespace, Literal, BNode, RDF, RDFS, DC, FOAF, XSD&lt;br /&gt;
&lt;br /&gt;
EX = Namespace(&#039;http://example.org/&#039;)&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.bind(&#039;ex&#039;, EX)&lt;br /&gt;
&lt;br /&gt;
donaldTrumpSpouses = BNode()&lt;br /&gt;
Collection(g, donaldTrumpSpouses, [&lt;br /&gt;
    EX.IvanaTrump, EX.MarlaMaples, EX.MelaniaTrump&lt;br /&gt;
])&lt;br /&gt;
g.add((EX.Donald_Trump, SCHEMA.spouse, donaldTrumpSpouses))&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
g.serialize(destination=&#039;s02_Donald_Trump_spouses_list.ttl&#039;, format=&#039;turtle&#039;)&lt;br /&gt;
&lt;br /&gt;
print(g.serialize(format=&#039;turtle&#039;))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Example lab solutions=&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;
g = Graph()&lt;br /&gt;
&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;
&lt;br /&gt;
#The Mueller Investigation was lead by Robert Mueller.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))&lt;br /&gt;
&lt;br /&gt;
#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))&lt;br /&gt;
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))&lt;br /&gt;
&lt;br /&gt;
# --- Paul Manafort ---&lt;br /&gt;
#Paul Manafort was business partner of Rick Gates.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))&lt;br /&gt;
# He was campaign chairman for Trump&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))&lt;br /&gt;
&lt;br /&gt;
# He was charged with money laundering, tax evasion, and foreign lobbying.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))&lt;br /&gt;
&lt;br /&gt;
# He was convicted for bank and tax fraud.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))&lt;br /&gt;
&lt;br /&gt;
# He pleaded guilty to conspiracy.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
# He was sentenced to prison.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))&lt;br /&gt;
&lt;br /&gt;
# --- Rick Gates ---&lt;br /&gt;
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.&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;
g.add((ex.Rick_Gates, 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.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))&lt;br /&gt;
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
&lt;br /&gt;
#Use the serialize method to write out the model in different formats on screen&lt;br /&gt;
print(g.serialize(format=&amp;quot;ttl&amp;quot;))&lt;br /&gt;
# g.serialize(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #or 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;
# 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(graph):&lt;br /&gt;
    data = {&amp;quot;rdf&amp;quot;:graph, &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 fil:&lt;br /&gt;
        shutil.copyfileobj(response.raw, fil)&lt;br /&gt;
&lt;br /&gt;
graph = g.serialize(format=&amp;quot;ttl&amp;quot;)&lt;br /&gt;
graphToImage(graph)&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;
&lt;br /&gt;
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode&lt;br /&gt;
from rdflib.collection import Collection&lt;br /&gt;
&lt;br /&gt;
g = Graph()&lt;br /&gt;
g.parse(&amp;quot;lab1.ttl&amp;quot;, format=&amp;quot;ttl&amp;quot;) #Retrives the triples from lab 1&lt;br /&gt;
&lt;br /&gt;
ex = Namespace(&#039;http://example.org/&#039;)&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.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))&lt;br /&gt;
&lt;br /&gt;
# --- Michael Flynn ---&lt;br /&gt;
#Michael Flynn was adviser to Trump.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
#He pleaded guilty to lying to the FBI.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))&lt;br /&gt;
# He negotiated a plea agreement.&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain)) &lt;br /&gt;
&lt;br /&gt;
#How can you modify your knowledge graph to account for the different lying?&lt;br /&gt;
#Remove these to not have duplicates&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;
# serialize_Graph() #Don&#039;t need this to run until after adding the triples above to the ttl file&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SPARQL Programming (Lab 4)==&lt;br /&gt;
&#039;&#039;&#039;NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.&#039;&#039;&#039;&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. Instead you have to use a nested SELECT query like below, where you use FILTER instead of HAVING. Donald Trump has no pardons, so I have instead chosen Bill Clinton (which has 13 pardons) 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 queries are yet to be implemented in RDFLib, but they are attempting to implement it: https://github.com/RDFLib/rdflib/pull/2221 (Issue and proposed solution raised) &amp;amp; https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 (Solution committed to RDFLib). 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;
namespace = &amp;quot;kb&amp;quot; #Default namespace&lt;br /&gt;
sparql = SPARQLWrapper(&amp;quot;http://localhost:9999/blazegraph/namespace/&amp;quot;+ namespace + &amp;quot;/sparql&amp;quot;) #Replace localhost:9999 with your URL&lt;br /&gt;
&lt;br /&gt;
# The current dates are URIs, we would want to change them to Literals with datatype &amp;quot;date&amp;quot; for task 1 &amp;amp; 2&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;
&lt;br /&gt;
    DELETE {&lt;br /&gt;
        ?s ns1:cp_date ?cp;&lt;br /&gt;
            ns1:investigation_end ?end;&lt;br /&gt;
            ns1:investigation_start ?start.&lt;br /&gt;
    }&lt;br /&gt;
    INSERT{&lt;br /&gt;
        ?s ns1:cp_date ?cpDate;&lt;br /&gt;
            ns1:investigation_end ?endDate;&lt;br /&gt;
            ns1:investigation_start ?startDate.&lt;br /&gt;
    }&lt;br /&gt;
    WHERE{&lt;br /&gt;
        ?s ns1:cp_date ?cp . #Date conviction was recieved&lt;br /&gt;
        BIND (replace(str(?cp), str(ns1:), &amp;quot;&amp;quot;)  AS ?cpRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_end ?end . #Investigation End&lt;br /&gt;
        BIND (replace(str(?end), str(ns1:), &amp;quot;&amp;quot;)  AS ?endRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)&lt;br /&gt;
        &lt;br /&gt;
        ?s ns1:investigation_start ?start . #Investigation Start&lt;br /&gt;
        BIND (replace(str(?start), str(ns1:), &amp;quot;&amp;quot;)  AS ?startRemoved)&lt;br /&gt;
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.query()&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.serialize())&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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?person .&lt;br /&gt;
}&amp;quot;&amp;quot;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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;
sparql.setQuery(update_str)&lt;br /&gt;
sparql.setMethod(POST)&lt;br /&gt;
sparql.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:person ?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;
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;
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;
==CSV To RDF (Lab 5)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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. 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;
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 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;
                # Removing the period as some presidents won&#039;t be found with it&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;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==SHACL (Lab 6)==&lt;br /&gt;
&amp;lt;syntaxhighlight&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 examples from the lab&lt;br /&gt;
data_graph.parse(&amp;quot;data_graph.ttl&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change &amp;quot;exactly one name&amp;quot; to have exactly two, and see the output &lt;br /&gt;
shape_graph = &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;
&lt;br /&gt;
ex:LabTasks_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:MoreTime_Shape rdf:type sh:NodeShape;&lt;br /&gt;
    sh:targetClass ex:Indictment;&lt;br /&gt;
    &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: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 made in the tasks&lt;br /&gt;
shacl_graph.parse(data=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 ?errorBlankNode.&lt;br /&gt;
    ?errorBlankNode sh:resultMessage ?message.    &lt;br /&gt;
&lt;br /&gt;
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)&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 ?errorBlankNode .&lt;br /&gt;
    ?errorBlankNode 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(f&amp;quot;COUNT: {row.num_messages} | MESSAGE: {row.message}&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RDFS (Lab 7)==&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
import owlrl&lt;br /&gt;
from rdflib import Graph, RDF, Namespace, FOAF, RDFS&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;
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;
    owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)&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 is a person under investigation and&lt;br /&gt;
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing 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(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, g.query(&#039;ASK {ex:MoneyLaundering rdf:type ex:Offense}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a ex:PersonUnderInvestigation:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
print(&#039;Is Money Laundering a ex:Offense:&#039;, 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(&#039;Is Rick Gates a foaf:Person:&#039;, g.query(&#039;ASK {ex:Rick_Gates rdf:type foaf:Person}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Rick Gates a foaf:Person:&#039;, 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;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, g.query(&#039;ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}&#039;, initNs=NS).askAnswer)&lt;br /&gt;
flush()&lt;br /&gt;
print(&#039;Is Paul Manafort charged with Tax Evasion:&#039;, 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;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
	<entry>
		<id>http://info216.wiki.uib.no/index.php?title=Lab:_OWL_1&amp;diff=2230</id>
		<title>Lab: OWL 1</title>
		<link rel="alternate" type="text/html" href="http://info216.wiki.uib.no/index.php?title=Lab:_OWL_1&amp;diff=2230"/>
		<updated>2023-03-20T14:53:40Z</updated>

		<summary type="html">&lt;p&gt;Rbo027: /* Useful materials */  Changed old lecture notes with the new one&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Topics==&lt;br /&gt;
* Basic OWL ontology programming with RDFlib and owlrl.&lt;br /&gt;
* RDFS is relevant too.&lt;br /&gt;
* WebVOWL visualisation.&lt;br /&gt;
&lt;br /&gt;
==Useful materials==&lt;br /&gt;
Readings:&lt;br /&gt;
* [https://wiki.app.uib.no/info216/index.php?title=File:S08-OWL.pdf Lecture Notes]&lt;br /&gt;
* [https://wiki.uib.no/info216/index.php/Python_Examples#RDFS_Plus_.2F_OWL_inference_with_RDFLib Example page]&lt;br /&gt;
* [https://www.w3.org/TR/owl-ref/ OWL Documentation] &lt;br /&gt;
* [https://docs.google.com/presentation/d/1N8nN53I2-4Erp-SPoU0rI9yWjyfWaBKgwcRjr7R7c7w/ OWL 1 - Lab Presentation]&lt;br /&gt;
&lt;br /&gt;
Vocabularies and terms:&lt;br /&gt;
* OWL (sameAs, equivalentClass, equivalentProperty, differentFrom, disjointWith, inverseOf)&lt;br /&gt;
* OWL (SymmetricProperty, AsymmetricProperty, ReflexiveProperty, IrreflexiveProperty, TransitiveProperty, FunctionalProperty, InverseFunctionalProperty, AllDifferent)&lt;br /&gt;
&lt;br /&gt;
==Tasks==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039;&lt;br /&gt;
&#039;&#039;Write OWL triples that corresponds to the following text.&#039;&#039; Try to continue your example from labs 1 and 2, or extend the triples at the bottom of this page. OWL terms can be imported from rdflib in the same way as RDF and RDFS terms.&lt;br /&gt;
&lt;br /&gt;
* Donald Trump and Robert Mueller are two different persons.&lt;br /&gt;
* Actually, all the names mentioned in connection with the Muelle investigation refer to different people.&lt;br /&gt;
* All these people are &#039;&#039;foaf:Person&#039;&#039;s as well as &#039;&#039;schema:Person&#039;&#039;s (they are http://xmlns.com/foaf/0.1/Person and http://schema.org/Person).&lt;br /&gt;
* Tax evation is a kind of bank and tax fraud.&lt;br /&gt;
* The Donald Trump involved in the Mueller investigation is &#039;&#039;dbpedia:Donald_Trump&#039;&#039; and not &#039;&#039;dbpedia:Donald_Trump_Jr.&#039;&#039; .&lt;br /&gt;
** &#039;&#039;Tip:&#039;&#039; rdflib&#039;s Turtle parser does not like URLs with punctuation marks written &amp;quot;prefix style&amp;quot; (&#039;&#039;dbpedia:Donald_Trump_Jr.&#039;&#039;), but it will accept the full URL written in angle brackets (&#039;&#039;&amp;lt;http://dbpedia.org/resource/Donald_Trump_Jr.&amp;gt;&#039;&#039;)&lt;br /&gt;
* Congress, FBI and the Mueller investigation are &#039;&#039;foaf:Organization&#039;&#039;s.&lt;br /&gt;
* Nothing can be both a person and an organization. &lt;br /&gt;
* Leading an organization is a way of being involved in an organization.&lt;br /&gt;
* Being a campaign manager or an advisor for is a way of supporting someone.&lt;br /&gt;
* Donald Trump is a politician and a Republican. &lt;br /&gt;
* A  Republican politician is both a politician and a Republican.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.Paul_Manafort, ex.hasBusinessPartner, ex.Rick_Gates))&lt;br /&gt;
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))&lt;br /&gt;
g.add((ex.Rick_Gates_Lying, ex.wasLyingTo, ex.FBI))&lt;br /&gt;
g.add((ex.Donald_Trump, ex.presidentOf, ex.USA))&lt;br /&gt;
g.add((ex.USA, ex.hasPresident, ex.Donald_Trump))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt; &lt;br /&gt;
&lt;br /&gt;
Look through the predicates (properties) above and add new triples for each one that describes them as any of the following: a reflexive, irreflexive, symmetric, asymmetric, transitive, functional, or an inverse functional property.&lt;br /&gt;
e.g&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
g.add((ex.wasLyingTo, RDF.type, OWL.IrreflexiveProperty))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039;&lt;br /&gt;
Serialize the ontology and look at the results. Create an owlrl closure as below to infer additional triples and serialize it again. Can you spot the many inferences?&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
DeductiveClosure(OWLRL_Semantics).expand(graph)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039;&lt;br /&gt;
Finally write the ontology to a XML file, and visualise it using http://vowl.visualdataweb.org/webvowl.html. The purpose of WebVOWL is to visualise classes and their properties, so the individuals may not show. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Tip:&#039;&#039; When you save OWL files as XML, the extension &#039;&#039;.owl-xml&#039;&#039; can be used.&lt;br /&gt;
&lt;br /&gt;
Most likely, your ontology is still quite disconnected. Add &#039;&#039;rdfs:subClassOf&#039;&#039;, &#039;&#039;rdfs:domain&#039;&#039;, and &#039;&#039;rdfs:range&#039;&#039; triples to turn it into a more connected graph that represents the domain. Calculate owlrl closures to see the effects of your triples as you add them.&lt;br /&gt;
&lt;br /&gt;
===Triples you can use in the first task===&lt;br /&gt;
&amp;lt;syntaxhighlight&amp;gt;&lt;br /&gt;
@prefix ex: &amp;lt;http://example/org#&amp;gt; .&lt;br /&gt;
&lt;br /&gt;
ex:Mueller_Investigation ex:involved ex:George_Papadopoulos,&lt;br /&gt;
        ex:Michael_Cohen,&lt;br /&gt;
        ex:Michael_Flynn,&lt;br /&gt;
        ex:Paul_Manafort,&lt;br /&gt;
        ex:Rick_Gates,&lt;br /&gt;
        ex:Roger_Stone ;&lt;br /&gt;
    ex:leadBy ex:Robert_Mueller .&lt;br /&gt;
&lt;br /&gt;
ex:Michael_Cohen ex:attorneyFor ex:Donald_Trump ;&lt;br /&gt;
    ex:pleadedGuilty ex:Michael_Cohens_Lying .&lt;br /&gt;
&lt;br /&gt;
ex:Michael_Cohens_Lying a ex:Lying ;&lt;br /&gt;
    ex:wasLyingAbout ex:Trump_RealEstateDeal ;&lt;br /&gt;
    ex:wasLyingTo ex:Congress .&lt;br /&gt;
&lt;br /&gt;
ex:Michael_Flynn ex:adviserTo ex:Donald_Trump ;&lt;br /&gt;
    ex:negotiatedAgreement ex:PleaAgreement ;&lt;br /&gt;
    ex:pleadedGuilty ex:Michael_Flynns_Lying .&lt;br /&gt;
&lt;br /&gt;
ex:Michael_Flynns_Lying a ex:Lying ;&lt;br /&gt;
    ex:wasLyingTo ex:FBI .&lt;br /&gt;
&lt;br /&gt;
ex:Paul_Manafort ex:campaignManager ex:Donald_Trump ;&lt;br /&gt;
    ex:chargedWith ex:ForeignLobbying,&lt;br /&gt;
        ex:MoneyLaundering,&lt;br /&gt;
        ex:TaxEvasion ;&lt;br /&gt;
    ex:convictedFor ex:BankAndTaxFraud ;&lt;br /&gt;
    ex:hasBusinessPartner ex:Rick_Gates ;&lt;br /&gt;
    ex:negotiatedAgreement ex:PleaAgreement ;&lt;br /&gt;
    ex:pleadedGuilty ex:Conspiracy ;&lt;br /&gt;
    ex:sentencedTo ex:Prison .&lt;br /&gt;
&lt;br /&gt;
ex:Rick_Gates_Lying a ex:Lying ;&lt;br /&gt;
    ex:wasLyingTo ex:FBI .&lt;br /&gt;
&lt;br /&gt;
ex:Rick_Gates ex:chargedWith ex:ForeignLobbying,&lt;br /&gt;
        ex:MoneyLaundering,&lt;br /&gt;
        ex:TaxEvasion ;&lt;br /&gt;
    ex:pleadedGuilty ex:Conspiracy,&lt;br /&gt;
        ex:Rick_Gates_Lying .&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==If you have more time==&lt;br /&gt;
&#039;&#039;&#039;Task.&#039;&#039;&#039;&lt;br /&gt;
Inspect your ontology with [https://webprotege.stanford.edu/ Webprotégé]. &lt;br /&gt;
* Register as a new user and log in. &lt;br /&gt;
* &#039;&#039;Create a new project&#039;&#039; and use &#039;&#039;Create from existing sources&#039;&#039; to upload your OWL/XML file. &lt;br /&gt;
* Explore how to edit and extend your ontology using Protégé.&lt;br /&gt;
&lt;br /&gt;
You can also [https://protege.stanford.edu/products.php download Protégé] for free and run it on your local machine. The stand-alone version is even more powerful with lots of plug-ins.&lt;/div&gt;</summary>
		<author><name>Rbo027</name></author>
	</entry>
</feed>