Lab Solutions: Difference between revisions

From info216
No edit summary
 
(18 intermediate revisions by 3 users not shown)
Line 1: Line 1:
''Here we will present suggested solutions after each lab.''
Here we will present suggested solutions after each lab. ''The page will be updated as the course progresses''


<!--
=Getting started (Lab 1)=
==Getting started (Lab 1)==


<syntaxhighlight>
<syntaxhighlight>


from rdflib import Graph, Namespace
from rdflib import Graph, Namespace
ex = Namespace('http://example.org/')


g = Graph()
g = Graph()


ex = Namespace('http://example.org/')
g.bind("ex", ex)


g.bind("ex", ex)
# The Mueller Investigation was lead by Robert Mueller
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))


#The Mueller Investigation was lead by Robert Mueller.
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.
g.add((ex.Mueller_Investigation, ex.leadBy, ex.Robert_Muller))
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))


#It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, and Roger Stone.
# Paul Manafort was business partner of Rick Gates
g.add((ex.Mueller_Investigation, ex.involved, ex.Paul_Manafort))
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))
g.add((ex.Mueller_Investigation, ex.involved, ex.Rick_Gates))
g.add((ex.Mueller_Investigation, ex.involved, ex.George_Papadopoulos))
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Flynn))
g.add((ex.Mueller_Investigation, ex.involved, ex.Michael_Cohen))
g.add((ex.Mueller_Investigation, ex.involved, ex.Roger_Stone))


# --- Paul Manafort ---
# He was campaign chairman for Donald Trump
#Paul Manafort was business partner of Rick Gates.
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))
g.add((ex.Paul_Manafort, ex.businessManager, ex.Rick_Gates))
# He was campaign chairman for Trump
g.add((ex.Paul_Manafort, ex.campaignChairman, ex.Donald_Trump))


# He was charged with money laundering, tax evasion, and foreign lobbying.
# He was charged with money laundering, tax evasion, and foreign lobbying.
g.add((ex.Paul_Manafort, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.Paul_Manafort, ex.chargedWith, ex.TaxEvasion))
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))
g.add((ex.Paul_Manafort, ex.chargedWith, ex.ForeignLobbying))
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))


# He was convicted for bank and tax fraud.
# He was convicted for bank and tax fraud.
g.add((ex.Paul_Manafort, ex.convictedFor, ex.BankFraud))
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxFraud))
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))


# He pleaded guilty to conspiracy.
# He pleaded guilty to conspiracy.
g.add((ex.Paul_Manafort, ex.pleadGuiltyTo, ex.Conspiracy))
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))
 
# He was sentenced to prison.
# He was sentenced to prison.
g.add((ex.Paul_Manafort, ex.sentencedTo, ex.Prison))
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))
 
# He negotiated a plea agreement.
# He negotiated a plea agreement.
g.add((ex.Paul_Manafort, ex.negoiated, ex.PleaBargain))
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))


# --- Rick Gates ---
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.
#Rick Gates was charged with money laundering, tax evasion and foreign lobbying.
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))
g.add((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))
g.add((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))


#He pleaded guilty to conspiracy and lying to FBI.
# He pleaded guilty to conspiracy and lying to FBI.
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))


#Use the serialize method to write out the model in different formats on screen
# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)
print(g.serialize(format="ttl"))
print(g.serialize(format="ttl")) # To screen
# g.serialize("lab1.ttl", format="ttl") #or to file
#g.serialize("lab1.ttl", format="ttl") # To file


#Loop through the triples in the model to print out all triples that have pleading guilty as predicate
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate
for subject, object in g[ : ex.pleadGuiltyTo : ]:
for subject, object in g[ : ex.pleadGuiltyTo :]:
     print(subject, ex.pleadGuiltyTo, object)
     print(subject, ex.pleadGuiltyTo, object)
# --- IF you have more time tasks ---


# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week  
# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week  
Line 71: Line 73:
import shutil
import shutil


def graphToImage(graph):
def graphToImage(graphInput):
     data = {"rdf":graph, "from":"ttl", "to":"png"}
     data = {"rdf":graphInput, "from":"ttl", "to":"png"}
     link = "http://www.ldf.fi/service/rdf-grapher"
     link = "http://www.ldf.fi/service/rdf-grapher"
     response = requests.get(link, params = data, stream=True)
     response = requests.get(link, params = data, stream=True)
     # print(response.content)
     # print(response.content)
     print(response.raw)
     print(response.raw)
     with open("lab1.png", "wb") as fil:
     with open("lab1.png", "wb") as file:
         shutil.copyfileobj(response.raw, fil)
         shutil.copyfileobj(response.raw, file)


graph = g.serialize(format="ttl")
graph = g.serialize(format="ttl")
graphToImage(graph)
graphToImage(graph)
</syntaxhighlight>
</syntaxhighlight>


==RDF programming with RDFlib (Lab 2)==
=RDF programming with RDFlib (Lab 2)=


<syntaxhighlight>
<syntaxhighlight>
 
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef
from rdflib import Graph, URIRef, Namespace, Literal, XSD, BNode
from rdflib.collection import Collection
from rdflib.collection import Collection


g = Graph()
g = Graph()
g.parse("lab1.ttl", format="ttl") #Retrives the triples from lab 1


ex = Namespace('http://example.org/')
# Getting the graph created in the first lab
g.parse("lab1.ttl", format="ttl")
 
ex = Namespace("http://example.org/")
 
g.bind("ex", ex)
g.bind("foaf", FOAF)


# --- Michael Cohen ---
# --- Michael Cohen ---
#Michael Cohen was Donald Trump's attorney.
# Michael Cohen was Donald Trump's attorney.
g.add((ex.Michael_Cohen, ex.attorneyTo, ex.Donald_Trump))
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))
#He pleaded guilty to lying to the FBI.
# He pleaded guilty for lying to Congress.
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))


# --- Michael Flynn ---
# --- Michael Flynn ---
#Michael Flynn was adviser to Trump.
# Michael Flynn was adviser to Donald Trump.
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))
#He pleaded guilty to lying to the FBI.
# He pleaded guilty for lying to the FBI.
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))
# He negotiated a plea agreement.
# He negotiated a plea agreement.
g.add((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))  
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))


#How can you modify your knowledge graph to account for the different lying?
# Change your graph so it represents instances of lying as blank nodes.
#Remove these to not have duplicates
# Remove the triples that will be duplicated
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))  
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI))  
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))
Line 180: Line 187:
     print(newGraph.serialize())
     print(newGraph.serialize())


# serialize_Graph() #Don't need this to run until after adding the triples above to the ttl file
#Don't need this to run until after adding the triples above to the ttl file
# serialize_Graph()


#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
#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
Line 217: Line 225:
tree = create_Tree(g, [ex.Donald_Trump])
tree = create_Tree(g, [ex.Donald_Trump])
print_Tree(tree, ex.Donald_Trump)
print_Tree(tree, ex.Donald_Trump)
</syntaxhighlight>
</syntaxhighlight>


==SPARQL (Lab 3)==
=SPARQL (Lab 3-4)=
===List all triples===
===List all triples===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
SELECT ?s ?p ?o
SELECT ?s ?p ?o
WHERE {?s ?p ?o .}  
WHERE {?s ?p ?o .}
</syntaxhighlight>
</syntaxhighlight>


Line 230: Line 237:
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
SELECT ?s ?p ?o
SELECT ?s ?p ?o
WHERE {?s ?p ?o .}  
WHERE {?s ?p ?o .}
LIMIT 100  
LIMIT 100
</syntaxhighlight>
</syntaxhighlight>


Line 237: Line 244:
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
SELECT (COUNT(*) as ?count)
SELECT (COUNT(*) as ?count)
WHERE {?s ?p ?o .}  
WHERE {?s ?p ?o .}
</syntaxhighlight>
</syntaxhighlight>


===Count the number of indictments===
===Count the number of indictments===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT (COUNT(?ind) as ?amount)  
SELECT (COUNT(?ind) as ?amount)
WHERE {
WHERE {
  ?s ns1:outcome ?ind;
  ?s ns1:outcome ?ind;
    ns1:outcome ns1:indictment.
      ns1:outcome ns1:indictment.
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 253: Line 260:
===List the names of everyone who pleaded guilty, along with the name of the investigation===
===List the names of everyone who pleaded guilty, along with the name of the investigation===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?name ?invname  
SELECT ?name ?invname
WHERE {
WHERE {
  ?s ns1:name ?name;
  ?s ns1:name ?name;
    ns1:investigation ?invname;
      ns1:investigation ?invname;
    ns1:outcome ns1:guilty-plea .
      ns1:outcome ns1:guilty-plea .
}  
}
</syntaxhighlight>
</syntaxhighlight>


===List the names of everyone who were convicted, but who had their conviction overturned by which president===
===List the names of everyone who were convicted, but who had their conviction overturned by which president===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?name ?president
SELECT ?name ?president
WHERE {
WHERE {
  ?s ns1:name ?name;
  ?s ns1:name ?name;
    ns1:president ?president;
      ns1:president ?president;
    ns1:outcome ns1:conviction;
      ns1:outcome ns1:conviction;
    ns1:overturned ns1:true.
      ns1:overturned ns1:true.
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 278: Line 285:
===For each investigation, list the number of indictments made===
===For each investigation, list the number of indictments made===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?invs (COUNT(?invs) as ?count)
SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
WHERE {
  ?s ns1:investigation ?invs;
  ?s ns1:investigation ?invs;
    ns1:outcome ns1:indictment .
      ns1:outcome ns1:indictment .
}  
}
GROUP BY ?invs
GROUP BY ?invs
</syntaxhighlight>
</syntaxhighlight>
Line 290: Line 297:
===For each investigation with multiple indictments, list the number of indictments made===
===For each investigation with multiple indictments, list the number of indictments made===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?invs (COUNT(?invs) as ?count)
SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
WHERE {
  ?s ns1:investigation ?invs;
  ?s ns1:investigation ?invs;
    ns1:outcome ns1:indictment .
      ns1:outcome ns1:indictment .
}  
}
GROUP BY ?invs
GROUP BY ?invs
HAVING(?count > 1)
HAVING(?count > 1)
Line 303: Line 310:
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?invs (COUNT(?invs) as ?count)
SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
WHERE {
  ?s ns1:investigation ?invs;
  ?s ns1:investigation ?invs;
    ns1:outcome ns1:indictment .
      ns1:outcome ns1:indictment .
}  
}
GROUP BY ?invs
GROUP BY ?invs
HAVING(?count > 1)
HAVING(?count > 1)
Line 317: Line 324:
===For each president, list the numbers of convictions and of pardons made===
===For each president, list the numbers of convictions and of pardons made===
<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as ?pardons)
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as
?pardons)
WHERE {
WHERE {
  ?s ns1:president ?president;
  ?s ns1:president ?president;
    ns1:outcome ?outcome ;
      ns1:outcome ?outcome ;
    ns1:outcome ns1:conviction.
      ns1:outcome ns1:conviction.
    OPTIONAL{
      OPTIONAL{
        ?s ns1:pardoned ?pardon .
        ?s ns1:pardoned ?pardon .
        FILTER (?pardon = ns1:true)
        FILTER (?pardon = true)
    }
      }
}
}
GROUP BY ?president
GROUP BY ?president
Line 335: Line 343:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


DELETE{?s ns1:name ?o}
DELETE{?s ns1:name ?o}
Line 345: Line 353:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>


Line 351: Line 359:
INSERT {?person foaf:name ?name}
INSERT {?person foaf:name ?name}
WHERE {
WHERE {
    ?investigation ns1:person ?person .
      ?investigation ns1:person ?person .
    BIND(REPLACE(STR(?person), STR(ns1:), "") AS ?name)
      BIND(REPLACE(STR(?person), STR(ns1:), "") AS ?name)
}
}


Line 358: Line 366:
INSERT {?president foaf:name ?name}
INSERT {?president foaf:name ?name}
WHERE {
WHERE {
    ?investigation ns1:president ?president .
      ?investigation ns1:president ?president .
    BIND(REPLACE(STR(?president), STR(ns1:), "") AS ?name)
      BIND(REPLACE(STR(?president), STR(ns1:), "") AS ?name)
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 366: Line 374:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


INSERT DATA {
INSERT DATA {
    ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;
    ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;
        ns1:pleadGuiltyTo ns1:LyingToFBI;
        ns1:pleadGuiltyTo ns1:LyingToFBI;
        ns1:sentencedTo ns1:Prison.
        ns1:sentencedTo ns1:Prison.
       
 
    ns1:Roger_Stone a ns1:Republican;
    ns1:Roger_Stone a ns1:Republican;
        ns1:adviserTo ns1:Donald_Trump;
        ns1:adviserTo ns1:Donald_Trump;
        ns1:officialTo ns1:Trump_Campaign;
        ns1:officialTo ns1:Trump_Campaign;
        ns1:interactedWith ns1:Wikileaks;
        ns1:interactedWith ns1:Wikileaks;
        ns1:providedTestimony ns1:House_Intelligence_Committee;
        ns1:providedTestimony ns1:House_Intelligence_Committee;
        ns1:clearedOf ns1:AllCharges.
        ns1:clearedOf ns1:AllCharges.
}
}


#To test if added
#To test if added
SELECT ?p ?o
SELECT ?p ?o
WHERE {ns1:Roger_Stone ?p ?o .}  
WHERE {ns1:Roger_Stone ?p ?o .}
</syntaxhighlight>
</syntaxhighlight>


Line 389: Line 397:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


DELETE DATA {
DELETE DATA {
    ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .
}
}


INSERT DATA {
INSERT DATA {
    ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
                                    ns1:WitnessTampering,  
                                      ns1:WitnessTampering,
                                    ns1:FalseStatements.
                                      ns1:FalseStatements.
}
}


#The task specifically requested DELETE DATA & INSERT DATA, put below is a more efficient solution
#The task specifically requested DELETE DATA & INSERT DATA, put below is
a more efficient solution


DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
INSERT{
INSERT{
  ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
  ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
                                  ns1:WitnessTampering,
                                  ns1:WitnessTampering,
                                  ns1:FalseStatements.
                                  ns1:FalseStatements.
}
}
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
Line 415: Line 424:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


DESCRIBE ?o
DESCRIBE ?o
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}  
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}
</syntaxhighlight>
</syntaxhighlight>


Line 424: Line 433:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


CONSTRUCT {
CONSTRUCT {
  ns1:Roger_Stone ?p ?o.
  ns1:Roger_Stone ?p ?o.
  ?s ?p2 ns1:Roger_Stone.
  ?s ?p2 ns1:Roger_Stone.
}
}
WHERE {
WHERE {
  ns1:Roger_Stone ?p ?o .
  ns1:Roger_Stone ?p ?o .
  ?s ?p2 ns1:Roger_Stone
  ?s ?p2 ns1:Roger_Stone
}  
}
</syntaxhighlight>
</syntaxhighlight>


Line 439: Line 448:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>
PREFIX dbp: <https://dbpedia.org/page/>
PREFIX dbp: <https://dbpedia.org/page/>


DELETE {?s ns1:person ?o1}  
DELETE {?s ns1:person ?o1}
INSERT {?s ns1:person ?o2}  
INSERT {?s ns1:person ?o2}
WHERE{
WHERE{
  ?s ns1:person ?o1 .
  ?s ns1:person ?o1 .
  BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)
  BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)
}
}


#This update changes the object in triples with ns1:person as the predicate. It changes it's prefix of ns1 (which is the "shortcut/shorthand" for example.org) to the prefix dbp (dbpedia.org)  
#This update changes the object in triples with ns1:person as the
predicate. It changes it's prefix of ns1 (which is the
"shortcut/shorthand" for example.org) to the prefix dbp (dbpedia.org)
</syntaxhighlight>
</syntaxhighlight>


Line 455: Line 466:


<syntaxhighlight lang="SPARQL">
<syntaxhighlight lang="SPARQL">
#Whilst this solution is not exactly what the task asks for, I feel like this is more appropiate given the dataset. The following update
#Whilst this solution is not exactly what the task asks for, I feel like
changes the objects that uses the cp_date as predicate from a URI, to a literal with date as it's datatype  
this is more appropiate given the dataset. The following update
changes the objects that uses the cp_date as predicate from a URI, to a
literal with date as it's datatype


PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>  
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


DELETE {?s ns1:cp_date ?o}
DELETE {?s ns1:cp_date ?o}
INSERT{?s ns1:cp_date ?o3}
INSERT{?s ns1:cp_date ?o3}
WHERE{
WHERE{
  ?s ns1:cp_date ?o .
  ?s ns1:cp_date ?o .
  BIND (replace(str(?o), str(ns1:), "")  AS ?o2)
  BIND (replace(str(?o), str(ns1:), "")  AS ?o2)
  BIND (STRDT(STR(?o2), xsd:date) AS ?o3)
  BIND (STRDT(STR(?o2), xsd:date) AS ?o3)
}
}


#To test:
#To test:


PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>  
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


SELECT ?s ?o  
SELECT ?s ?o
WHERE{
WHERE{
  ?s ns1:cp_date ?o.
  ?s ns1:cp_date ?o.
  FILTER(datatype(?o) = xsd:date)
  FILTER(datatype(?o) = xsd:date)
}
}


#To change it to an integer, use the following code, and to change it back to date, swap "xsd:integer" to "xsd:date"  
#To change it to an integer, use the following code, and to change it
back to date, swap "xsd:integer" to "xsd:date"


PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>  
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ns1: <http://example.org#>  
PREFIX ns1: <http://example.org#>


DELETE {?s ns1:cp_date ?o}
DELETE {?s ns1:cp_date ?o}
INSERT{?s ns1:cp_date ?o2}
INSERT{?s ns1:cp_date ?o2}
WHERE{
WHERE{
  ?s ns1:cp_date ?o .
  ?s ns1:cp_date ?o .
  BIND (STRDT(STR(?o), xsd:integer) AS ?o2)
  BIND (STRDT(STR(?o), xsd:integer) AS ?o2)
}
}


</syntaxhighlight>
</syntaxhighlight>


==SPARQL Programming (Lab 4)==
=SPARQL Programming (Lab 5)=
'''NOTE: These tasks were performed on the old dataset, with the new dataset, some of these answers would be different.'''
 
<syntaxhighlight>
<syntaxhighlight>


Line 566: Line 580:
print(task4.askAnswer)
print(task4.askAnswer)


# 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.  
# 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 with 13 to check if the query works.  


task4 = g.query("""
task4 = g.query("""
Line 584: Line 600:
# Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.
# Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.


# 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) & 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
# By all accounts, it seems DESCRIBE querires 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 rasied
# https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 <--- Solution commited to RDFLib
# This solution does not work. However, this proposed solution should work if DESCRIBE is implemented in RDFLib


# task5 = g.query("""  
# task5 = g.query("""  
Line 594: Line 613:
# ----- SPARQLWrapper -----
# ----- SPARQLWrapper -----


namespace = "kb" #Default namespace
SERVER = 'http://localhost:7200' #Might need to replace this
sparql = SPARQLWrapper("http://localhost:9999/blazegraph/namespace/"+ namespace + "/sparql") #Replace localhost:9999 with your URL
REPOSITORY = 'Labs' #Replace with your repository name


# The current dates are URIs, we would want to change them to Literals with datatype "date" for task 1 & 2
# Query Endpoint
update_str = """
sparql = SPARQLWrapper(f'{SERVER}/repositories/{REPOSITORY}')  
    PREFIX ns1: <http://example.org#>
# Update Endpoint
 
sparqlUpdate = SPARQLWrapper(f'{SERVER}/repositories/{REPOSITORY}/statements')
    DELETE {
        ?s ns1:cp_date ?cp;
            ns1:investigation_end ?end;
            ns1:investigation_start ?start.
    }
    INSERT{
        ?s ns1:cp_date ?cpDate;
            ns1:investigation_end ?endDate;
            ns1:investigation_start ?startDate.
    }
    WHERE{
        ?s ns1:cp_date ?cp . #Date conviction was recieved
        BIND (replace(str(?cp), str(ns1:), "")  AS ?cpRemoved)
        BIND (STRDT(STR(?cpRemoved), xsd:date) AS ?cpDate)
       
        ?s ns1:investigation_end ?end . #Investigation End
        BIND (replace(str(?end), str(ns1:), "")  AS ?endRemoved)
        BIND (STRDT(STR(?endRemoved), xsd:date) AS ?endDate)
       
        ?s ns1:investigation_start ?start . #Investigation Start
        BIND (replace(str(?start), str(ns1:), "")  AS ?startRemoved)
        BIND (STRDT(STR(?startRemoved), xsd:date) AS ?startDate)
}"""
 
sparql.setQuery(update_str)
sparql.setMethod(POST)
sparql.query()


# Ask whether there was an ongoing indictment on the date 1990-01-01.
# Ask whether there was an ongoing indictment on the date 1990-01-01.
Line 674: Line 666:
results = sparql.query().convert()
results = sparql.query().convert()


print(results.serialize())
print(results)


# Print out a list of all the types used in your graph.
# Print out a list of all the types used in your graph.
Line 709: Line 701:
}"""
}"""


sparql.setQuery(update_str)
sparqlUpdate.setQuery(update_str)
sparql.setMethod(POST)
sparqlUpdate.setMethod(POST)
sparql.query()
sparqlUpdate.query()


#To Test
#To Test
Line 736: Line 728:
     }
     }
     WHERE{
     WHERE{
         ?s ns1:person ?person .
         ?s ns1:name ?person .
}"""
}"""


sparql.setQuery(update_str)
sparqlUpdate.setQuery(update_str)
sparql.setMethod(POST)
sparqlUpdate.setMethod(POST)
sparql.query()
sparqlUpdate.query()


#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson
#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson
Line 759: Line 751:
}"""
}"""


sparql.setQuery(update_str)
sparqlUpdate.setQuery(update_str)
sparql.setMethod(POST)
sparqlUpdate.setMethod(POST)
sparql.query()
sparqlUpdate.query()


#Same test as above, replace it with e.g. ns1:watergate dc:title "watergate"
#Same test as above, replace it with e.g. ns1:watergate dc:title "watergate"
Line 772: Line 764:
     SELECT ?name
     SELECT ?name
     WHERE{
     WHERE{
     ?s  ns1:person ?name;
     ?s  ns1:name ?name;
        ns1:outcome ns1:indictment.
            ns1:outcome ns1:indictment.
     }
     }
     ORDER BY ?name
     ORDER BY ?name
Line 789: Line 781:


# Print out the minimum, average and maximum indictment days for all the indictments in the graph.
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.
sparql.setQuery("""
sparql.setQuery("""
     prefix xsd: <http://www.w3.org/2001/XMLSchema#>
     prefix xsd: <http://www.w3.org/2001/XMLSchema#>
Line 811: Line 804:


# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.
sparql.setQuery("""
sparql.setQuery("""
     prefix xsd: <http://www.w3.org/2001/XMLSchema#>
     prefix xsd: <http://www.w3.org/2001/XMLSchema#>
Line 834: Line 828:
</syntaxhighlight>
</syntaxhighlight>


==CSV To RDF (Lab 5)==
=Wikidata SPARQL (Lab 6)=
<syntaxhighlight>
===Use a DESCRIBE query to retrieve some triples about your entity===
 
<syntaxhighlight lang="SPARQL">
DESCRIBE wd:Q42 LIMIT 100
</syntaxhighlight>
 
===Use a SELECT query to retrieve the first 100 triples about your entity===
 
<syntaxhighlight lang="SPARQL">
SELECT * WHERE {
  wd:Q42 ?p ?o .
} LIMIT 100
</syntaxhighlight>
 
===Write a local SELECT query that embeds a SERVICE query to retrieve the first 100 triples about your entity to your local machine===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
SELECT * WHERE {
    SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
        SELECT * WHERE {
            wd:Q42 ?p ?o .
        } LIMIT 100
    }
}
</syntaxhighlight>
 
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
INSERT {
    wd:Q42 ?p ?o .
} WHERE {
    SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
        SELECT * WHERE {
            wd:Q42 ?p ?o .
        } LIMIT 100
    }
}
</syntaxhighlight>
 
===Use a FILTER statement to only SELECT primary triples in this sense.===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
SELECT * WHERE {
    wd:Q42 ?p ?o .
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
} LIMIT 100
</syntaxhighlight>
 
===Use Wikidata's in-built SERVICE wikibase:label to get labels for all the object resources===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
SELECT ?p ?oLabel WHERE {
    wd:Q42 ?p ?o .
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} LIMIT 100
</syntaxhighlight>
 
===Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE xsd:string.===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
SELECT ?p ?oLabel ?o WHERE {
    wd:Q42 ?p ?o .
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (
      STRSTARTS(STR(?o), STR(wd:)) ||  # comment out this whole line to see only string literals!
      DATATYPE(?o) = xsd:string
    )
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} LIMIT 100
</syntaxhighlight>
 
===Relax the FILTER expression again so it also returns triples with these three predicates (rdfs:label, skos:altLabel and schema:description) ===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
SELECT ?p ?oLabel ?o WHERE {
    wd:Q42 ?p ?o .
    FILTER (
      (STRSTARTS(STR(?p), STR(wdt:)) &&  # comment out these three lines to see only fingerprint literals!
      STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
      ||
      (?p IN (rdfs:label, skos:altLabel, schema:description) &&
      DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
    )
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} LIMIT 100
</syntaxhighlight>
 
===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 "en" ===
 
<syntaxhighlight lang="SPARQL">
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX schema: <http://schema.org/>
 
SELECT * WHERE {
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p ?oLabel ?o WHERE {
        wd:Q42 ?p ?o .
 
        FILTER (
          (STRSTARTS(STR(?p), STR(wdt:)) &&
          STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
          ||
          (?p IN (rdfs:label, skos:altLabel, schema:description) &&
          DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
        )
 
        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
    } LIMIT 100
  }
}
</syntaxhighlight>
 
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository ===
 
<syntaxhighlight lang="SPARQL">
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX schema: <http://schema.org/>
 
INSERT {
  wd:Q42 ?p ?o .
  ?o rdfs:label ?oLabel .
} WHERE {
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p ?oLabel ?o WHERE {
        wd:Q42 ?p ?o .
 
        FILTER (
          (STRSTARTS(STR(?p), STR(wdt:)) &&
          STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
          ||
          (?p IN (rdfs:label, skos:altLabel, schema:description) &&
          DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
        )
 
        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
    } LIMIT 500
  }
}
</syntaxhighlight>
 
==If you have more time ==
===You must therefore REPLACE all wdt: prefixes of properties with wd: prefixes and BIND the new URI AS a new variable, for example ?pw. ===
 
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>
 
SELECT ?pwLabel ?oLabel WHERE {
    wd:Q42 ?p ?o .
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
    BIND (IRI(REPLACE(STR(?p), STR(wdt:), STR(wd:))) AS ?pw)
 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} LIMIT 100
</syntaxhighlight>
 
===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 "one step out", i.e., triples where the subjects are objects of triples involving your reference entity. ===
 
<syntaxhighlight lang="SPARQL">
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX schema: <http://schema.org/>
 
INSERT {
  wd:Q42 ?p1 ?o1 .
  ?o1 rdfs:label ?o1Label .
  ?o1 ?p2 ?o2 .
  ?o2 rdfs:label ?o2Label .
} WHERE {
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p1 ?o1Label ?o1 ?p2 ?o2Label ?o2 WHERE {
        wd:Q42 ?p1 ?o1 .
        ?o1 ?p2 ?o2 .
 
        FILTER (
          STRSTARTS(STR(?p1), STR(wdt:)) &&
          STRSTARTS(STR(?o1), STR(wd:)) &&
          STRSTARTS(STR(?p2), STR(wdt:)) &&
          STRSTARTS(STR(?o2), STR(wd:))
        )
 
        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
    } LIMIT 500
  }
}
</syntaxhighlight>
 
=CSV to RDF (Lab 7)=
 
<syntaxhighlight lang="Python">


#Imports
#Imports
Line 845: Line 1,080:


SERVER = "https://api.dbpedia-spotlight.org/en/annotate"
SERVER = "https://api.dbpedia-spotlight.org/en/annotate"
# 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
# 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
CONFIDENCE = 0.83  
CONFIDENCE = 0.83  


# This function uses DBpedia Spotlight, which was not a part of the CSV lab this year. 
def annotate_entity(entity, filters={'types': 'DBpedia:Person'}):
def annotate_entity(entity, filters={'types': 'DBpedia:Person'}):
annotations = []
annotations = []
Line 865: Line 1,102:
df = df.replace(nan, None)
df = df.replace(nan, None)


#Function that prepares the values to be added to the graph as a URI or Literal
#Function that prepares the values to be added to the graph as a URI (ex infront) or Literal
def prepareValue(row):
def prepareValue(row):
if row == None: #none type
if row == None: #none type
Line 902: Line 1,139:
#Spotlight Search
#Spotlight Search
name = annotate_entity(str(row['name']))
name = annotate_entity(str(row['name']))
                # Removing the period as some presidents won't be found with it
president = annotate_entity(str(row['president']).replace(".", ""))
president = annotate_entity(str(row['president']).replace(".", ""))
Line 934: Line 1,170:
csv_to_rdf(df)
csv_to_rdf(df)
print(g.serialize())
print(g.serialize())
g.serialize("lab7.ttl", format="ttl")
</syntaxhighlight>
=JSON-LD (Lab 8)=
== Task 1) Basic JSON-LD ==
<syntaxhighlight lang="JSON-LD">
{
    "@context": {
        "@base": "http://example.org/",
        "edges": "http://example.org/triple",
        "start": "http://example.org/source",
        "rel": "http://exaxmple.org/predicate",
        "end": "http://example.org/object",
        "Person" : "http://example.org/Person",
        "birthday" : {
            "@id" : "http://example.org/birthday",
            "@type" : "xsd:date"
        },
        "nameEng" : {
            "@id" : "http://example.org/en/name",
            "@language" : "en"
        },
        "nameFr" : {
            "@id" : "http://example.org/fr/name",
            "@language" : "fr"
        },
        "nameCh" : {
            "@id" : "http://example.org/ch/name",
            "@language" : "ch"
        },
        "age" : {
            "@id" : "http://example.org/age",
            "@type" : "xsd:int"
        },
        "likes" : "http://example.org/games/likes",
        "haircolor" : "http://example.org/games/haircolor"
    },
    "@graph": [
        {
            "@id": "people/Jeremy",
            "@type": "Person",
            "birthday" : "1987.1.1",
            "nameEng" : "Jeremy",
            "age" : 26
        },
        {
            "@id": "people/Tom",
            "@type": "Person"
        },
        {
            "@id": "people/Ju",
            "@type": "Person",
            "birthday" : "2001.1.1",
            "nameCh" : "Ju",
            "age" : 22,
            "likes" : "bastketball"
        },
        {
            "@id": "people/Louis",
            "@type": "Person",
            "birthday" : "1978.1.1",
            "haircolor" : "Black",
            "nameFr" : "Louis",
            "age" : 45
        },
        {"edges" : [
        {
            "start" : "people/Jeremy",
            "rel" : "knows",
            "end" : "people/Tom"
        },
        {
            "start" : "people/Tom",
            "rel" : "knows",
            "end" : "people/Louis"
        },
        {
            "start" : "people/Louis",
            "rel" : "teaches",
            "end" : "people/Ju"
        },
        {
            "start" : "people/Ju",
            "rel" : "plays",
            "end" : "people/Jeremy"
        },
        {
            "start" : "people/Ju",
            "rel" : "plays",
            "end" : "people/Tom"
        }
        ]}
    ]
}
</syntaxhighlight>
== Task 2 & 3) Retrieving JSON-LD from ConceptNet / Programming JSON-LD in Python ==
<syntaxhighlight lang="Python">
import rdflib
CN_BASE = 'http://api.conceptnet.io/c/en/'
g = rdflib.Graph()
g.parse(CN_BASE+'indictment', format='json-ld')
# To download JSON object:
import json
import requests
json_obj = requests.get(CN_BASE+'indictment').json()
# To change the @context:
context = {
    "@base": "http://ex.org/",
    "edges": "http://ex.org/triple/",
    "start": "http://ex.org/s/",
    "rel": "http://ex.org/p/",
    "end": "http://ex.org/o/",
    "label": "http://ex.org/label"
}
json_obj['@context'] = context
json_str = json.dumps(json_obj)
g = rdflib.Graph()
g.parse(data=json_str, format='json-ld')
# To extract triples (here with labels):
r = g.query("""
        SELECT ?s ?sLabel ?p ?o ?oLabel WHERE {
            ?edge
                <http://ex.org/s/> ?s ;
                <http://ex.org/p/> ?p ;
                <http://ex.org/o/> ?o .
            ?s <http://ex.org/label> ?sLabel .
            ?o <http://ex.org/label> ?oLabel .
}
        """, initNs={'cn': CN_BASE})
print(r.serialize(format='txt').decode())
# Construct a new graph:
r = g.query("""
        CONSTRUCT {
            ?s ?p ?o .
            ?s <http://ex.org/label> ?sLabel .
            ?o <http://ex.org/label> ?oLabel .
        } WHERE {
            ?edge <http://ex.org/s/> ?s ;
                  <http://ex.org/p/> ?p ;
                  <http://ex.org/o/> ?o .
            ?s <http://ex.org/label> ?sLabel .
            ?o <http://ex.org/label> ?oLabel .
}
        """, initNs={'cn': CN_BASE})
print(r.graph.serialize(format='ttl'))


</syntaxhighlight>
</syntaxhighlight>


==SHACL (Lab 6)==
=SHACL (Lab 9)=
<syntaxhighlight>
 
<syntaxhighlight lang="Python">


from pyshacl import validate
from pyshacl import validate
Line 944: Line 1,347:


data_graph = Graph()
data_graph = Graph()
# parses the Turtle examples from the lab
# parses the Turtle example from the task
data_graph.parse("data_graph.ttl")
data_graph.parse("data_graph.ttl")


# Remember to test you need to change the rules so they conflict with the data graph (or vice versa). For example, change "exactly one name" to have exactly two, and see the output
prefixes = """
shape_graph = """
@prefix ex: <http://example.org/> .
@prefix ex: <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
Line 954: Line 1,356:
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
"""


ex:LabTasks_Shape
shape_graph = """
ex:PUI_Shape
     a sh:NodeShape ;
     a sh:NodeShape ;
     sh:targetClass ex:PersonUnderInvestigation ;
     sh:targetClass ex:PersonUnderInvestigation ;
Line 971: Line 1,375:


# --- If you have more time tasks ---
# --- If you have more time tasks ---
ex:MoreTime_Shape rdf:type sh:NodeShape;
ex:User_Shape rdf:type sh:NodeShape;
     sh:targetClass ex:Indictment;
     sh:targetClass ex:Indictment;
   
     # The only allowed values for ex:american are true, false or unknown.
     # The only allowed values for ex:american are true, false or unknown.
     sh:property [
     sh:property [
         sh:path ex:american;
         sh:path ex:american;
         sh:pattern "(true|false|unknown)" ;
         sh:pattern "(true|false|unknown)" ;
     ] ;
     ];
      
      
     # The value of a property that counts days must be an integer.
     # The value of a property that counts days must be an integer.
Line 984: Line 1,387:
         sh:path ex:indictment_days;
         sh:path ex:indictment_days;
         sh:datatype xsd:integer;
         sh:datatype xsd:integer;
     ] ;   
     ];   
     sh:property [
     sh:property [
         sh:path ex:investigation_days;
         sh:path ex:investigation_days;
         sh:datatype xsd:integer;
         sh:datatype xsd:integer;
     ] ;
     ];
      
      
     # The value of a property that indicates a start date must be xsd:date.
     # The value of a property that indicates a start date must be xsd:date.
Line 994: Line 1,397:
         sh:path ex:investigation_start;
         sh:path ex:investigation_start;
         sh:datatype xsd:date;
         sh:datatype xsd:date;
     ] ;
     ];


     # The value of a property that indicates an end date must be xsd:date or unknown (tip: you can use sh:or (...) ).
     # The value of a property that indicates an end date must be xsd:date or unknown (tip: you can use sh:or (...) ).
Line 1,002: Line 1,405:
         [ sh:datatype xsd:date ]
         [ sh:datatype xsd:date ]
         [ sh:hasValue "unknown" ]
         [ sh:hasValue "unknown" ]
     )] ;
     )];
      
      
     # Every indictment must have exactly one FOAF name for the investigated person.
     # Every indictment must have exactly one FOAF name for the investigated person.
Line 1,009: Line 1,412:
         sh:minCount 1;
         sh:minCount 1;
         sh:maxCount 1;
         sh:maxCount 1;
     ] ;
     ];
      
      
     # Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.
     # Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.
Line 1,030: Line 1,433:
     sh:property [
     sh:property [
         sh:path ex:president ;
         sh:path ex:president ;
        sh:minCount 1 ;
         sh:class ex:President ;
         sh:class ex:President ;
         sh:nodeKind sh:IRI ;
         sh:nodeKind sh:IRI ;
Line 1,036: Line 1,440:


shacl_graph = Graph()
shacl_graph = Graph()
# parses the contents of a shape_graph made in the tasks
# parses the contents of a shape_graph you made in the previous task
shacl_graph.parse(data=shape_graph)
shacl_graph.parse(data=prefixes+shape_graph)


# uses pySHACL's validate method to apply the shape_graph constraints to the data_graph
# uses pySHACL's validate method to apply the shape_graph constraints to the data_graph
Line 1,058: Line 1,462:


SELECT DISTINCT ?message WHERE {
SELECT DISTINCT ?message WHERE {
     [] sh:result ?errorBlankNode.
     [] sh:result / sh:resultMessage ?message .
    ?errorBlankNode sh:resultMessage ?message.   
 
    # Alternativ and cleaner solution, look at https://www.w3.org/TR/sparql11-query/#pp-language (9.1 Property Path Syntax)
    # [] sh:result / sh:resultMessage ?message .
}
}
"""
"""
Line 1,074: Line 1,474:


SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {
SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {
     [] sh:result ?errorBlankNode .
     [] sh:result ?result .
     ?errorBlankNode sh:resultMessage ?message ;
     ?result sh:resultMessage ?message ;
                    sh:focusNode ?node .
            sh:focusNode ?node .
}
}
GROUP BY ?message
GROUP BY ?message
Line 1,084: Line 1,484:
messages = results_graph.query(count_messages)
messages = results_graph.query(count_messages)
for row in messages:
for row in messages:
     print(f"COUNT: {row.num_messages} | MESSAGE: {row.message}")
     print("COUNT   MESSAGE")
    print(row.num_messages, "      ", row.message)
 


</syntaxhighlight>
</syntaxhighlight>


==RDFS (Lab 7)==
=RDFS (Lab 10)=
<syntaxhighlight>
 
<syntaxhighlight lang="Python">


import owlrl
import owlrl
from rdflib import Graph, RDF, Namespace, FOAF, RDFS
from rdflib import Graph, RDF, Namespace, Literal, XSD, FOAF, RDFS
from rdflib.collection import Collection


g = Graph()
g = Graph()
Line 1,099: Line 1,503:
g.bind("ex", ex)
g.bind("ex", ex)
g.bind("foaf", FOAF)
g.bind("foaf", FOAF)


NS = {
NS = {
Line 1,109: Line 1,514:
#Write a small function that computes the RDFS closure on your graph.
#Write a small function that computes the RDFS closure on your graph.
def flush():
def flush():
     owlrl.DeductiveClosure(owlrl.RDFS_Semantics).expand(g)
     engine = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)
    engine.closure()
    engine.flush_stored_triples()


#Rick Gates was charged with money laundering and tax evasion.
#Rick Gates was charged with money laundering and tax evasion.
Line 1,116: Line 1,523:


#When one thing that is charged with another thing,
#When one thing that is charged with another thing,
g.add((ex.chargedWith, RDFS.domain, ex.PersonUnderInvestigation))  #the first thing is a person under investigation and
g.add((ex.chargedWith, RDFS.domain, ex.PersonUnderInvestigation))  #the first thing (subject) is a person under investigation and
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing is an offense.
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing (object) is an offense.


#Write a SPARQL query that checks the RDF type(s) of Rick Gates and money laundering in your RDF graph.
#Write a SPARQL query that checks the RDF type(s) of Rick Gates and money laundering in your RDF graph.
print('Is Rick Gates a ex:PersonUnderInvestigation:', g.query('ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}', initNs=NS).askAnswer)
print(g.query('ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}', initNs=NS).askAnswer)
print('Is Money Laundering a ex:Offense:', g.query('ASK {ex:MoneyLaundering rdf:type ex:Offense}', initNs=NS).askAnswer)
print(g.query('ASK {ex:MoneyLaundering rdf:type ex:Offense}', initNs=NS).askAnswer)
flush()
flush()
print('Is Rick Gates a ex:PersonUnderInvestigation:', g.query('ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}', initNs=NS).askAnswer)
print(g.query('ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}', initNs=NS).askAnswer)
print('Is Money Laundering a ex:Offense:', g.query('ASK {ex:MoneyLaundering rdf:type ex:Offense}', initNs=NS).askAnswer)
print(g.query('ASK {ex:MoneyLaundering rdf:type ex:Offense}', initNs=NS).askAnswer)


#A person under investigation is a FOAF person
#A person under investigation is a FOAF person
g.add((ex.PersonUnderInvestigation, RDFS.subClassOf, FOAF.Person))
g.add((ex.PersonUnderInvestigation, RDFS.subClassOf, FOAF.Person))
print('Is Rick Gates a foaf:Person:', g.query('ASK {ex:Rick_Gates rdf:type foaf:Person}', initNs=NS).askAnswer)
print(g.query('ASK {ex:Rick_Gates rdf:type foaf:Person}', initNs=NS).askAnswer)
flush()
flush()
print('Is Rick Gates a foaf:Person:', g.query('ASK {ex:Rick_Gates rdf:type foaf:Person}', initNs=NS).askAnswer)
print(g.query('ASK {ex:Rick_Gates rdf:type foaf:Person}', initNs=NS).askAnswer)


#Paul Manafort was convicted for tax evasion.
#Paul Manafort was convicted for tax evasion.
Line 1,136: Line 1,543:
#the first thing is also charged with the second thing
#the first thing is also charged with the second thing
g.add((ex.convictedFor, RDFS.subPropertyOf, ex.chargedWith))  
g.add((ex.convictedFor, RDFS.subPropertyOf, ex.chargedWith))  
print('Is Paul Manafort charged with Tax Evasion:', g.query('ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}', initNs=NS).askAnswer)
flush()
flush()
print('Is Paul Manafort charged with Tax Evasion:', g.query('ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}', initNs=NS).askAnswer)
print(g.query('ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}', initNs=NS).askAnswer)


print(g.serialize())
print(g.serialize())
Line 1,144: Line 1,550:
</syntaxhighlight>
</syntaxhighlight>


==OWL 1 (Lab 8)==
=OWL 1 (Lab 11)=
<syntaxhighlight>
<syntaxhighlight lang="Python">


from rdflib import Graph, RDFS, Namespace, RDF, FOAF, BNode, OWL, URIRef, Literal, XSD
from rdflib import Graph, RDFS, Namespace, RDF, FOAF, BNode, OWL, URIRef, Literal, XSD
Line 1,242: Line 1,648:
</syntaxhighlight>
</syntaxhighlight>


== OWL 2 (Lab 9)==
=OWL 2 (Lab 12)=
'''NOTE: This is an OWL Protégé file'''
<syntaxhighlight lang="Python">
 
<syntaxhighlight>


@prefix : <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
@prefix : <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
Line 1,301: Line 1,705:
                                               rdfs:domain io:Investigation ;
                                               rdfs:domain io:Investigation ;
                                               rdfs:range xsd:string .
                                               rdfs:range xsd:string .
###  http://purl.org/dc/elements/1.1/title
<http://purl.org/dc/elements/1.1/title> rdf:type owl:DatatypeProperty ;
                                        rdfs:domain io:Investigation ;
                                        rdfs:range xsd:string .




Line 1,329: Line 1,727:




#################################################################
###  http://xmlns.com/foaf/0.1/title
#    Classes
foaf:title rdf:type owl:DatatypeProperty ;
#################################################################
          rdfs:domain io:Investigation ;
 
          rdfs:range xsd:string .
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigatedPerson
io:InvestigatedPerson rdf:type owl:Class ;
                      rdfs:subClassOf io:Person ;
                      owl:disjointWith io:Investigator .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation
io:Investigation rdf:type owl:Class .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigationLeader
io:InvestigationLeader rdf:type owl:Class ;
                      rdfs:subClassOf io:Investigator .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigator
io:Investigator rdf:type owl:Class ;
                rdfs:subClassOf io:Person .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Person
io:Person rdf:type owl:Class ;
          rdfs:subClassOf foaf:Person .
 
 
###  http://xmlns.com/foaf/0.1/Person
foaf:Person rdf:type owl:Class .
 
 
#################################################################
#    Individuals
#################################################################
 
###  http://dbpedia.org/resource/Donald_Trump
dbr:Donald_Trump rdf:type owl:NamedIndividual ;
                foaf:name "Donald Trump" .
 
 
###  http://dbpedia.org/resource/Elizabeth_Prelogar
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ;
                      foaf:name "Elizabeth Prelogar" .
 
 
###  http://dbpedia.org/resource/Michael_Flynn
dbr:Michael_Flynn rdf:type owl:NamedIndividual ;
                  foaf:name "Michael Flynn" .
 
 
###  http://dbpedia.org/resource/Paul_Manafort
dbr:Paul_Manafort rdf:type owl:NamedIndividual ;
                  foaf:name "Paul Manafort" .
 
 
###  http://dbpedia.org/resource/Robert_Mueller
dbr:Robert_Mueller rdf:type owl:NamedIndividual ;
                  foaf:name "Robert Mueller" .
 
 
###  http://dbpedia.org/resource/Roger_Stone
dbr:Roger_Stone rdf:type owl:NamedIndividual ;
                foaf:name "Roger Stone" .
 
 
###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)
<http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)> rdf:type owl:NamedIndividual ,
                                                                                io:Investigation ;
                                                                        <http://purl.org/dc/elements/1.1/title> "Mueller Investigation" .
 
 
#################################################################
#    General axioms
#################################################################
 
[ rdf:type owl:AllDifferent ;
  owl:distinctMembers ( dbr:Donald_Trump
                        dbr:Elizabeth_Prelogar
                        dbr:Michael_Flynn
                        dbr:Paul_Manafort
                        dbr:Robert_Mueller
                        dbr:Roger_Stone
                      )
] .
 
 
###  Generated by the OWL API (version 4.5.25.2023-02-15T19:15:49Z) https://github.com/owlcs/owlapi
 
</syntaxhighlight>
 
== OWL-DL (Lab 10)==
'''NOTE: This is an OWL Protégé file.'''
 
<syntaxhighlight>
@prefix : <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
@prefix dc: <http://purl.org/dc/terms#> .
@prefix io: <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
@prefix dbr: <http://dbpedia.org/resource/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix prov: <http://www.w3.org/ns/prov#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@base <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
 
<http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology> rdf:type owl:Ontology .
 
#################################################################
#    Object Properties
#################################################################
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#indictedIn
io:indictedIn rdf:type owl:ObjectProperty ;
              rdfs:subPropertyOf io:involvedIn ;
              rdfs:domain io:InvestigatedPerson ;
              rdfs:range io:Investigation .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#investigating
io:investigating rdf:type owl:ObjectProperty ;
                rdfs:subPropertyOf io:involvedIn ;
                rdfs:domain io:Investigator ;
                rdfs:range io:Investigation .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#involvedIn
io:involvedIn rdf:type owl:ObjectProperty ;
              rdfs:domain foaf:Person ;
              rdfs:range io:Investigation .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#leading
io:leading rdf:type owl:ObjectProperty ;
          rdfs:subPropertyOf io:investigating ;
          rdfs:domain io:InvestigationLeader ;
          rdfs:range io:Investigation .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#specialProsecutor
io:specialProsecutor rdf:type owl:ObjectProperty ;
                    rdfs:subPropertyOf io:leading .
 
 
#################################################################
#    Data properties
#################################################################
 
###  http://purl.org/dc/elements/1.1/description
<http://purl.org/dc/elements/1.1/description> rdf:type owl:DatatypeProperty ;
                                              rdfs:domain io:Investigation ;
                                              rdfs:range xsd:string .
 
 
###  http://purl.org/dc/elements/1.1/title
<http://purl.org/dc/elements/1.1/title> rdf:type owl:DatatypeProperty ;
                                        rdfs:range xsd:string .
 
 
###  http://www.w3.org/ns/prov#endedAtTime
prov:endedAtTime rdf:type owl:DatatypeProperty ,
                          owl:FunctionalProperty ;
                rdfs:domain io:Investigation ;
                rdfs:range xsd:dateTime .
 
 
###  http://www.w3.org/ns/prov#startedAtTime
prov:startedAtTime rdf:type owl:DatatypeProperty ,
                            owl:FunctionalProperty ;
                  rdfs:domain io:Investigation ;
                  rdfs:range xsd:dateTime .
 
 
###  http://xmlns.com/foaf/0.1/name
foaf:name rdf:type owl:DatatypeProperty ;
          rdfs:domain foaf:Person ;
          rdfs:range xsd:string .




Line 1,538: Line 1,760:
io:Person rdf:type owl:Class ;
io:Person rdf:type owl:Class ;
           rdfs:subClassOf foaf:Person .
           rdfs:subClassOf foaf:Person .
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#SpecialCounselInvestigation
io:SpecialCounselInvestigation rdf:type owl:Class ;
                              owl:equivalentClass [ rdf:type owl:Restriction ;
                                                    owl:onProperty [ owl:inverseOf io:specialProsecutor
                                                                    ] ;
                                                    owl:someValuesFrom owl:Thing
                                                  ] ;
                              rdfs:subClassOf io:Investigation .




Line 1,564: Line 1,776:


###  http://dbpedia.org/resource/Elizabeth_Prelogar
###  http://dbpedia.org/resource/Elizabeth_Prelogar
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ,
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ;
                                io:Investigator ;
                       io:investigating <http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)> ;
                       io:investigating <http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)> ;
                       foaf:name "Elizabeth Prelogar" .
                       foaf:name "Elizabeth Prelogar" .
Line 1,590: Line 1,801:
dbr:Roger_Stone rdf:type owl:NamedIndividual ;
dbr:Roger_Stone rdf:type owl:NamedIndividual ;
                 foaf:name "Roger Stone" .
                 foaf:name "Roger Stone" .
###  http://dbpedia.org/resource/Jack_Smith_(politician)
<http://dbpedia.org/resource/Jack_Smith_(politician)> rdf:type owl:NamedIndividual ;
                                                      io:specialProsecutor io:Investigation_of_Trumps_Handling_Graded_Documents ,
                                                                          io:Investigation_of_Trumps_Role_US_Capital_Attack .




###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)
###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)
<http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)> rdf:type owl:NamedIndividual ;
<http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)> rdf:type owl:NamedIndividual ;
                                                                         <http://purl.org/dc/elements/1.1/title> "Mueller Investigation" .
                                                                         foaf:title "Mueller Investigation" .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Handling_Graded_Documents
io:Investigation_of_Trumps_Handling_Graded_Documents rdf:type owl:NamedIndividual .
 
 
###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation_of_Trumps_Role_US_Capital_Attack
io:Investigation_of_Trumps_Role_US_Capital_Attack rdf:type owl:NamedIndividual .




Line 1,622: Line 1,819:
                         dbr:Robert_Mueller
                         dbr:Robert_Mueller
                         dbr:Roger_Stone
                         dbr:Roger_Stone
                        <http://dbpedia.org/resource/Jack_Smith_(politician)>
                       )
                       )
] .
] .
Line 1,631: Line 1,827:
</syntaxhighlight>
</syntaxhighlight>


==Using Graph Embeddings (Lab 11)==
=Using Graph Embeddings (Lab 13)=


https://colab.research.google.com/drive/1a0lpmpjngXY2zsKRFcRWeXwVFMM5NO_O?usp=sharing
https://colab.research.google.com/drive/1WkRJUeUBVF5yVv7o0pOKfsd4pqG6369k


==Training Graph Embeddings (Lab 12)==
=Training Graph Embeddings (Lab 14)=


https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q
https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q
==Web APIs and JSON-LD (Lab 13)==
<syntaxhighlight>
import requests
from rdflib import FOAF, Namespace, Literal, RDF, Graph
r = requests.get('http://api.open-notify.org/astros.json').json()
g = Graph()
ex = Namespace('http://example.org/')
g.bind("ex", ex)
NS = {
    "ex": ex,
    "foaf":FOAF
}
#Write a small program that queries the Open Notify Astros API
for item in r['people']:
    craft = item['craft'].replace(" ","_")
    person = item['name'].replace(" ","_")
    g.add((ex[person], ex.onCraft, ex[craft]))
    g.add((ex[person], RDF.type, FOAF.Person))
    g.add((ex[person], FOAF.name, Literal(item['name'])))
    g.add((ex[craft], FOAF.name, Literal(item['craft'])))
res = g.query("""
    CONSTRUCT {?person1 foaf:knows ?person2}
    WHERE {
        ?person1 ex:onCraft ?craft .
        ?person2 ex:onCraft ?craft .
        }
""", initNs=NS)
for triplet in res:
    # (we don't need to add that they know themselves)
    if (triplet[0] != triplet[2]):
        g.add((triplet))
#Serialise the graph to JSON-LD   
print(g.serialize(format="json-ld"))
#DBpedia Spotlight was worked on Lab 5 (CSV to RDF).
</syntaxhighlight>
-->

Latest revision as of 09:40, 20 May 2024

Here we will present suggested solutions after each lab. The page will be updated as the course progresses

Getting started (Lab 1)

from rdflib import Graph, Namespace

ex = Namespace('http://example.org/')

g = Graph()

g.bind("ex", ex)

# The Mueller Investigation was lead by Robert Mueller
g.add((ex.MuellerInvestigation, ex.leadBy, ex.RobertMueller))

# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))

# Paul Manafort was business partner of Rick Gates
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))

# He was campaign chairman for Donald Trump
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))

# He was charged with money laundering, tax evasion, and foreign lobbying.
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))

# He was convicted for bank and tax fraud.
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))

# He pleaded guilty to conspiracy.
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))

# He was sentenced to prison.
g.add((ex.PaulManafort, ex.sentencedTo, ex.Prison))

# He negotiated a plea agreement.
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))

# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.
g.add((ex.RickGates, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.RickGates, ex.chargedWith, ex.TaxEvasion))
g.add((ex.RickGates, ex.chargedWith, ex.ForeignLobbying))

# He pleaded guilty to conspiracy and lying to FBI.
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.Conspiracy))
g.add((ex.RickGates, ex.pleadGuiltyTo, ex.LyingToFBI))

# Use the serialize method of rdflib.Graph to write out the model in different formats (on screen or to file)
print(g.serialize(format="ttl")) # To screen
#g.serialize("lab1.ttl", format="ttl") # To file

# Loop through the triples in the model to print out all triples that have pleading guilty as predicate
for subject, object in g[ : ex.pleadGuiltyTo :]:
    print(subject, ex.pleadGuiltyTo, object)

# --- IF you have more time tasks ---

# Michael Cohen, Michael Flynn and the lying is part of lab 2 and therefore the answer is not provided this week 

#Write a method (function) that submits your model for rendering and saves the returned image to file.
import requests
import shutil

def graphToImage(graphInput):
    data = {"rdf":graphInput, "from":"ttl", "to":"png"}
    link = "http://www.ldf.fi/service/rdf-grapher"
    response = requests.get(link, params = data, stream=True)
    # print(response.content)
    print(response.raw)
    with open("lab1.png", "wb") as file:
        shutil.copyfileobj(response.raw, file)

graph = g.serialize(format="ttl")
graphToImage(graph)

RDF programming with RDFlib (Lab 2)

from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef
from rdflib.collection import Collection

g = Graph()

# Getting the graph created in the first lab
g.parse("lab1.ttl", format="ttl")

ex = Namespace("http://example.org/")

g.bind("ex", ex)
g.bind("foaf", FOAF)

# --- Michael Cohen ---
# Michael Cohen was Donald Trump's attorney.
g.add((ex.MichaelCohen, ex.attorneyTo, ex.DonaldTrump))
# He pleaded guilty for lying to Congress.
g.add((ex.MichaelCohen, ex.pleadGuiltyTo, ex.LyingToCongress))

# --- Michael Flynn ---
# Michael Flynn was adviser to Donald Trump.
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))
# He pleaded guilty for lying to the FBI.
g.add((ex.MichaelFlynn, ex.pleadGuiltyTo, ex.LyingToFBI))
# He negotiated a plea agreement.
g.add((ex.MichaelFlynn, ex.negotiated, ex.PleaAgreement))

# Change your graph so it represents instances of lying as blank nodes.
# Remove the triples that will be duplicated
g.remove((ex.Michael_Flynn, ex.pleadGuiltyTo, ex.LyingToFBI)) 
g.remove((ex.Michael_Flynn, ex.negoiated, ex.PleaBargain))
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.LyingToFBI))
g.remove((ex.Rick_Gates, ex.pleadGuiltyTo, ex.Conspiracy))
g.remove((ex.Rick_Gates, ex.chargedWith, ex.ForeignLobbying))
g.remove((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))
g.remove((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))
g.remove((ex.Michael_Cohen, ex.pleadGuiltyTo, ex.LyingToCongress))

# --- Michael Flynn ---
FlynnLying = BNode() 
g.add((FlynnLying, ex.crime, ex.LyingToFBI))
g.add((FlynnLying, ex.pleadGulityOn, Literal("2017-12-1", datatype=XSD.date)))
g.add((FlynnLying, ex.liedAbout, Literal("His communications with a former Russian ambassador during the presidential transition", datatype=XSD.string)))
g.add((FlynnLying, ex.pleaBargain, Literal("true", datatype=XSD.boolean)))
g.add((ex.Michael_Flynn, ex.pleadGuiltyTo, FlynnLying))

# --- Rick Gates ---
GatesLying = BNode()
Crimes = BNode()
Charged = BNode()
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])
g.add((GatesLying, ex.crime, Crimes))
g.add((GatesLying, ex.chargedWith, Charged))
g.add((GatesLying, ex.pleadGulityOn, Literal("2018-02-23", datatype=XSD.date)))
g.add((GatesLying, ex.pleaBargain, Literal("true", datatype=XSD.boolean)))
g.add((ex.Rick_Gates, ex.pleadGuiltyTo, GatesLying))

# --- Michael Cohen ---
CohenLying = BNode()
g.add((CohenLying, ex.crime, ex.LyingToCongress))
g.add((CohenLying, ex.liedAbout, ex.TrumpRealEstateDeal))
g.add((CohenLying, ex.prosecutorsAlleged, Literal("In an August 2017 letter Cohen sent to congressional committees investigating Russian election interference, he falsely stated that the project ended in January 2016", datatype=XSD.string)))
g.add((CohenLying, ex.mullerInvestigationAlleged, Literal("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", datatype=XSD.string)))
g.add((CohenLying, ex.pleadGulityOn, Literal("2018-11-29", datatype=XSD.date)))
g.add((CohenLying, ex.pleaBargain, Literal("true", datatype=XSD.boolean)))
g.add((ex.Michael_Cohen, ex.pleadGuiltyTo, CohenLying))

print(g.serialize(format="ttl"))

#Save (serialize) your graph to a Turtle file.
# g.serialize("lab2.ttl", format="ttl")

#Add a few triples to the Turtle file with more information about Donald Trump.
'''
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;
            ex:country ex:United_States ;
            ex:postalCode 33480 ;
            ex:residence ex:Mar_a_Lago ;
            ex:state ex:Florida ;
            ex:streetName "1100 S Ocean Blvd"^^xsd:string ] ;
    ex:previousAddress [ ex:city ex:Washington_DC ;
            ex:country ex:United_States ;
            ex:phoneNumber "1 202 456 1414"^^xsd:integer ;
            ex:postalCode "20500"^^xsd:integer ;
            ex:residence ex:The_White_House ;
            ex:streetName "1600 Pennsylvania Ave."^^xsd:string ];
    ex:marriedTo ex:Melania_Trump;
    ex:fatherTo (ex:Ivanka_Trump ex:Donald_Trump_Jr ex: ex:Tiffany_Trump ex:Eric_Trump ex:Barron_Trump).
'''

#Read (parse) the Turtle file back into a Python program, and check that the new triples are there
def serialize_Graph():
    newGraph = Graph()
    newGraph.parse("lab2.ttl")
    print(newGraph.serialize())

#Don't need this to run until after adding the triples above to the ttl file
# serialize_Graph() 

#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
visited_nodes = set()

def create_Tree(model, nodes):
    #Traverse the model breadth-first to create the tree.
    global visited_nodes
    tree = Graph()
    children = set()
    visited_nodes |= set(nodes)
    for s, p, o in model:
        if s in nodes and o not in visited_nodes:
            tree.add((s, p, o))
            visited_nodes.add(o)
            children.add(o)
        if o in nodes and s not in visited_nodes:
            invp = URIRef(f'{p}_inv') #_inv represents inverse of
            tree.add((o, invp, s))
            visited_nodes.add(s)
            children.add(s)
    if len(children) > 0:
        children_tree = create_Tree(model, children)
        for triple in children_tree:
            tree.add(triple)
    return tree

def print_Tree(tree, root, indent=0):
    #Print the tree depth-first.
    print(str(root))
    for s, p, o in tree:
        if s==root:
            print('    '*indent + '  ' + str(p), end=' ')
            print_Tree(tree, o, indent+1)
    
tree = create_Tree(g, [ex.Donald_Trump])
print_Tree(tree, ex.Donald_Trump)

SPARQL (Lab 3-4)

List all triples

SELECT ?s ?p ?o
WHERE {?s ?p ?o .}

List the first 100 triples

SELECT ?s ?p ?o
WHERE {?s ?p ?o .}
LIMIT 100

Count the number of triples

SELECT (COUNT(*) as ?count)
WHERE {?s ?p ?o .}

Count the number of indictments

PREFIX ns1: <http://example.org#>

SELECT (COUNT(?ind) as ?amount)
WHERE {
   ?s ns1:outcome ?ind;
      ns1:outcome ns1:indictment.
}

List the names of everyone who pleaded guilty, along with the name of the investigation

PREFIX ns1: <http://example.org#>

SELECT ?name ?invname
WHERE {
   ?s ns1:name ?name;
      ns1:investigation ?invname;
      ns1:outcome ns1:guilty-plea .
}

List the names of everyone who were convicted, but who had their conviction overturned by which president

PREFIX ns1: <http://example.org#>

SELECT ?name ?president
WHERE {
   ?s ns1:name ?name;
      ns1:president ?president;
      ns1:outcome ns1:conviction;
      ns1:overturned ns1:true.
}

For each investigation, list the number of indictments made

PREFIX ns1: <http://example.org#>

SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
   ?s ns1:investigation ?invs;
      ns1:outcome ns1:indictment .
}
GROUP BY ?invs

For each investigation with multiple indictments, list the number of indictments made

PREFIX ns1: <http://example.org#>

SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
   ?s ns1:investigation ?invs;
      ns1:outcome ns1:indictment .
}
GROUP BY ?invs
HAVING(?count > 1)

For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first

PREFIX ns1: <http://example.org#>

SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
   ?s ns1:investigation ?invs;
      ns1:outcome ns1:indictment .
}
GROUP BY ?invs
HAVING(?count > 1)
ORDER BY DESC(?count)

For each president, list the numbers of convictions and of pardons made

PREFIX ns1: <http://example.org#>

SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as
?pardons)
WHERE {
   ?s ns1:president ?president;
      ns1:outcome ?outcome ;
      ns1:outcome ns1:conviction.
      OPTIONAL{
         ?s ns1:pardoned ?pardon .
         FILTER (?pardon = true)
      }
}
GROUP BY ?president

Rename mullerkg:name to something like muellerkg:person

PREFIX ns1: <http://example.org#>

DELETE{?s ns1:name ?o}
INSERT{?s ns1:person ?o}
WHERE {?s ns1:name ?o}

Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings

PREFIX ns1: <http://example.org#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

#Persons
INSERT {?person foaf:name ?name}
WHERE {
      ?investigation ns1:person ?person .
      BIND(REPLACE(STR(?person), STR(ns1:), "") AS ?name)
}

#Presidents
INSERT {?president foaf:name ?name}
WHERE {
      ?investigation ns1:president ?president .
      BIND(REPLACE(STR(?president), STR(ns1:), "") AS ?name)
}

Use INSERT DATA updates to add these triples

PREFIX ns1: <http://example.org#>

INSERT DATA {
     ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;
         ns1:pleadGuiltyTo ns1:LyingToFBI;
         ns1:sentencedTo ns1:Prison.

     ns1:Roger_Stone a ns1:Republican;
         ns1:adviserTo ns1:Donald_Trump;
         ns1:officialTo ns1:Trump_Campaign;
         ns1:interactedWith ns1:Wikileaks;
         ns1:providedTestimony ns1:House_Intelligence_Committee;
         ns1:clearedOf ns1:AllCharges.
}

#To test if added
SELECT ?p ?o
WHERE {ns1:Roger_Stone ?p ?o .}

Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges

PREFIX ns1: <http://example.org#>

DELETE DATA {
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .
}

INSERT DATA {
      ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
                                      ns1:WitnessTampering,
                                      ns1:FalseStatements.
}

#The task specifically requested DELETE DATA & INSERT DATA, put below is
a more efficient solution

DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
INSERT{
   ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
                                   ns1:WitnessTampering,
                                   ns1:FalseStatements.
}
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}

Use a DESCRIBE query to show the updated information about Roger Stone

PREFIX ns1: <http://example.org#>

DESCRIBE ?o
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}

Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone

PREFIX ns1: <http://example.org#>

CONSTRUCT {
   ns1:Roger_Stone ?p ?o.
   ?s ?p2 ns1:Roger_Stone.
}
WHERE {
   ns1:Roger_Stone ?p ?o .
   ?s ?p2 ns1:Roger_Stone
}

Write a DELETE/INSERT statement to change one of the prefixes in your graph

PREFIX ns1: <http://example.org#>
PREFIX dbp: <https://dbpedia.org/page/>

DELETE {?s ns1:person ?o1}
INSERT {?s ns1:person ?o2}
WHERE{
   ?s ns1:person ?o1 .
   BIND (IRI(replace(str(?o1), str(ns1:), str(dbp:)))  AS ?o2)
}

#This update changes the object in triples with ns1:person as the
predicate. It changes it's prefix of ns1 (which is the
"shortcut/shorthand" for example.org) to the prefix dbp (dbpedia.org)

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.

#Whilst this solution is not exactly what the task asks for, I feel like
this is more appropiate given the dataset. The following update
changes the objects that uses the cp_date as predicate from a URI, to a
literal with date as it's datatype

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ns1: <http://example.org#>

DELETE {?s ns1:cp_date ?o}
INSERT{?s ns1:cp_date ?o3}
WHERE{
   ?s ns1:cp_date ?o .
   BIND (replace(str(?o), str(ns1:), "")  AS ?o2)
   BIND (STRDT(STR(?o2), xsd:date) AS ?o3)
}

#To test:

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ns1: <http://example.org#>

SELECT ?s ?o
WHERE{
   ?s ns1:cp_date ?o.
   FILTER(datatype(?o) = xsd:date)
}

#To change it to an integer, use the following code, and to change it
back to date, swap "xsd:integer" to "xsd:date"

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ns1: <http://example.org#>

DELETE {?s ns1:cp_date ?o}
INSERT{?s ns1:cp_date ?o2}
WHERE{
   ?s ns1:cp_date ?o .
   BIND (STRDT(STR(?o), xsd:integer) AS ?o2)
}

SPARQL Programming (Lab 5)

from rdflib import Graph, Namespace, RDF, FOAF
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE

g = Graph()
g.parse("Russia_investigation_kg.ttl")

# ----- RDFLIB -----
ex = Namespace('http://example.org#')

NS = {
    '': ex,
    'rdf': RDF,
    'foaf': FOAF,
}

# Print out a list of all the predicates used in your graph.
task1 = g.query("""
SELECT DISTINCT ?p WHERE{
    ?s ?p ?o .
}
""", initNs=NS)

print(list(task1))

# Print out a sorted list of all the presidents represented in your graph.
task2 = g.query("""
SELECT DISTINCT ?president WHERE{
    ?s :president ?president .
}
ORDER BY ?president
""", initNs=NS)

print(list(task2))

# 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.
task3_dic = {}

task3 = g.query("""
SELECT ?president ?person WHERE{
    ?s :president ?president;
       :name ?person;
       :outcome :indictment.
}
""", initNs=NS)

for president, person in task3:
    if president not in task3_dic:
        task3_dic[president] = [person]
    else:
        task3_dic[president].append(person)

print(task3_dic)

# Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.

# This task is a lot trickier than it needs to be. As far as I'm aware RDFLib has no HAVING support, so a query like this:
task4 = g.query("""
ASK {
  	SELECT (COUNT(?s) as ?count) WHERE{
    	?s :pardoned :true;
   	   :president :Bill_Clinton  .
    }
    HAVING (?count > 5)
}
""", initNs=NS)

print(task4.askAnswer)

# 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 with 13 to check if the query works. 

task4 = g.query("""
    ASK{
        SELECT ?count WHERE{{
  	        SELECT (COUNT(?s) as ?count) WHERE{
    	        ?s :pardoned :true;
                   :president :Bill_Clinton  .
                }}
        FILTER (?count > 5) 
        }
    }
""", initNs=NS)

print(task4.askAnswer)

# Use a DESCRIBE query to create a new graph with information about Donald Trump. Print out the graph in Turtle format.

# By all accounts, it seems DESCRIBE querires 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 rasied
# https://github.com/RDFLib/rdflib/commit/2325b4a81724c1ccee3a131067db4fbf9b4e2629 <--- Solution commited to RDFLib
# This solution does not work. However, this proposed solution should work if DESCRIBE is implemented in RDFLib

# task5 = g.query(""" 
# DESCRIBE :Donald_Trump
# """, initNs=NS)

# print(task5.serialize())

# ----- SPARQLWrapper -----

SERVER = 'http://localhost:7200' #Might need to replace this
REPOSITORY = 'Labs' #Replace with your repository name

# Query Endpoint
sparql = SPARQLWrapper(f'{SERVER}/repositories/{REPOSITORY}') 
# Update Endpoint
sparqlUpdate = SPARQLWrapper(f'{SERVER}/repositories/{REPOSITORY}/statements')

# Ask whether there was an ongoing indictment on the date 1990-01-01.
sparql.setQuery("""
    PREFIX ns1: <http://example.org#>
    ASK {
        SELECT ?end ?start
        WHERE{
            ?s ns1:investigation_end ?end;
               ns1:investigation_start ?start;
               ns1:outcome ns1:indictment.
            FILTER(?start <= "1990-01-01"^^xsd:date && ?end >= "1990-01-01"^^xsd:date) 
	    }
    }
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
print(f"Are there any investigation on the 1990-01-01: {results['boolean']}")

# List ongoing indictments on that date 1990-01-01.
sparql.setQuery("""
    PREFIX ns1: <http://example.org#>
    SELECT ?s
    WHERE{
        ?s ns1:investigation_end ?end;
           ns1:investigation_start ?start;
           ns1:outcome ns1:indictment.
        FILTER(?start <= "1990-01-01"^^xsd:date && ?end >= "1990-01-01"^^xsd:date) 
    }
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

print("The ongoing investigations on the 1990-01-01 are:")
for result in results["results"]["bindings"]:
    print(result["s"]["value"])

# Describe investigation number 100 (muellerkg:investigation_100).
sparql.setQuery("""
    PREFIX ns1: <http://example.org#>
    DESCRIBE ns1:investigation_100
""")

sparql.setReturnFormat(TURTLE)
results = sparql.query().convert()

print(results)

# Print out a list of all the types used in your graph.
sparql.setQuery("""
    PREFIX ns1: <http://example.org#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    SELECT DISTINCT ?types
    WHERE{
        ?s rdf:type ?types . 
    }
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

rdf_Types = []

for result in results["results"]["bindings"]:
    rdf_Types.append(result["types"]["value"])

print(rdf_Types)

# Update the graph to that every resource that is an object in a muellerkg:investigation triple has the rdf:type muellerkg:Investigation.
update_str = """
    PREFIX ns1: <http://example.org#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    INSERT{
        ?invest rdf:type ns1:Investigation .
    }
    WHERE{
        ?s ns1:investigation ?invest .
}"""

sparqlUpdate.setQuery(update_str)
sparqlUpdate.setMethod(POST)
sparqlUpdate.query()

#To Test
sparql.setQuery("""
    prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX ns1: <http://example.org#>

    ASK{
        ns1:watergate rdf:type ns1:Investigation.
    }
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()
print(results['boolean'])

# Update the graph to that every resource that is an object in a muellerkg:person triple has the rdf:type muellerkg:IndictedPerson.
update_str = """
    PREFIX ns1: <http://example.org#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

    INSERT{
        ?person rdf:type ns1:IndictedPerson .
    }
    WHERE{
        ?s ns1:name ?person .
}"""

sparqlUpdate.setQuery(update_str)
sparqlUpdate.setMethod(POST)
sparqlUpdate.query()

#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson

# 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.
update_str = """
    PREFIX ns1: <http://example.org#>
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>

    INSERT{
        ?invest dc:title ?investString.
    }
    WHERE{
        ?s ns1:investigation ?invest .
        BIND (replace(str(?invest), str(ns1:), "")  AS ?investString)
}"""

sparqlUpdate.setQuery(update_str)
sparqlUpdate.setMethod(POST)
sparqlUpdate.query()

#Same test as above, replace it with e.g. ns1:watergate dc:title "watergate"

# Print out a sorted list of all the indicted persons represented in your graph.
sparql.setQuery("""
    PREFIX ns1: <http://example.org#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>

    SELECT ?name
    WHERE{
    ?s  ns1:name ?name;
            ns1:outcome ns1:indictment.
    }
    ORDER BY ?name
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

names = []

for result in results["results"]["bindings"]:
    names.append(result["name"]["value"])

print(names)

# Print out the minimum, average and maximum indictment days for all the indictments in the graph.

sparql.setQuery("""
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX ns1: <http://example.org#>

    SELECT (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{
        ?s  ns1:indictment_days ?days;
            ns1:outcome ns1:indictment.
    
    BIND (replace(str(?days), str(ns1:), "")  AS ?daysR)
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)
}
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
    print(f'The longest an investigation lasted was: {result["max"]["value"]}')
    print(f'The shortest an investigation lasted was: {result["min"]["value"]}')
    print(f'The average investigation lasted: {result["avg"]["value"]}')

# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.

sparql.setQuery("""
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX ns1: <http://example.org#>

    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{
    ?s  ns1:indictment_days ?days;
        ns1:outcome ns1:indictment;
        ns1:investigation ?investigation.
    
    BIND (replace(str(?days), str(ns1:), "")  AS ?daysR)
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)
    }
    GROUP BY ?investigation
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
    print(f'{result["investigation"]["value"]} - min: {result["min"]["value"]}, max: {result["max"]["value"]}, avg: {result["avg"]["value"]}')

Wikidata SPARQL (Lab 6)

Use a DESCRIBE query to retrieve some triples about your entity

DESCRIBE wd:Q42 LIMIT 100

Use a SELECT query to retrieve the first 100 triples about your entity

SELECT * WHERE {
  wd:Q42 ?p ?o .
} LIMIT 100

Write a local SELECT query that embeds a SERVICE query to retrieve the first 100 triples about your entity to your local machine

PREFIX wd: <http://www.wikidata.org/entity/>

SELECT * WHERE {
    SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
        SELECT * WHERE {
            wd:Q42 ?p ?o .
        } LIMIT 100
    }
}

Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository

PREFIX wd: <http://www.wikidata.org/entity/>

INSERT {
    wd:Q42 ?p ?o .
} WHERE {
    SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
        SELECT * WHERE {
            wd:Q42 ?p ?o .
        } LIMIT 100
    }
}

Use a FILTER statement to only SELECT primary triples in this sense.

PREFIX wd: <http://www.wikidata.org/entity/>

SELECT * WHERE {
    wd:Q42 ?p ?o .
 
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
} LIMIT 100

Use Wikidata's in-built SERVICE wikibase:label to get labels for all the object resources

PREFIX wd: <http://www.wikidata.org/entity/>

SELECT ?p ?oLabel WHERE {
    wd:Q42 ?p ?o .
 
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
} LIMIT 100

Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE xsd:string.

PREFIX wd: <http://www.wikidata.org/entity/>

SELECT ?p ?oLabel ?o WHERE {
    wd:Q42 ?p ?o .
 
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (
      STRSTARTS(STR(?o), STR(wd:)) ||  # comment out this whole line to see only string literals!
      DATATYPE(?o) = xsd:string
    )
 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
} LIMIT 100

Relax the FILTER expression again so it also returns triples with these three predicates (rdfs:label, skos:altLabel and schema:description)

PREFIX wd: <http://www.wikidata.org/entity/>

SELECT ?p ?oLabel ?o WHERE {
    wd:Q42 ?p ?o .
 
    FILTER (
      (STRSTARTS(STR(?p), STR(wdt:)) &&  # comment out these three lines to see only fingerprint literals!
       STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
      ||
      (?p IN (rdfs:label, skos:altLabel, schema:description) &&
       DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
    )
 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
} LIMIT 100

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 "en"

PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX schema: <http://schema.org/>

SELECT * WHERE {
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p ?oLabel ?o WHERE {
        wd:Q42 ?p ?o .

        FILTER (
          (STRSTARTS(STR(?p), STR(wdt:)) &&
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
          ||
          (?p IN (rdfs:label, skos:altLabel, schema:description) &&
           DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
        )

        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }

    } LIMIT 100
  }
}

Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository

PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX schema: <http://schema.org/>

INSERT {
  wd:Q42 ?p ?o .
  ?o rdfs:label ?oLabel .
} WHERE {
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p ?oLabel ?o WHERE {
        wd:Q42 ?p ?o .

        FILTER (
          (STRSTARTS(STR(?p), STR(wdt:)) &&
           STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
          ||
          (?p IN (rdfs:label, skos:altLabel, schema:description) &&
           DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
        )

        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }

    } LIMIT 500
  }
}

If you have more time

You must therefore REPLACE all wdt: prefixes of properties with wd: prefixes and BIND the new URI AS a new variable, for example ?pw.

PREFIX wd: <http://www.wikidata.org/entity/>

SELECT ?pwLabel ?oLabel WHERE {
    wd:Q42 ?p ?o .
 
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
 
    BIND (IRI(REPLACE(STR(?p), STR(wdt:), STR(wd:))) AS ?pw)

    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
} LIMIT 100

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 "one step out", i.e., triples where the subjects are objects of triples involving your reference entity.

PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX schema: <http://schema.org/>

INSERT {
  wd:Q42 ?p1 ?o1 .
  ?o1 rdfs:label ?o1Label .
  ?o1 ?p2 ?o2 .
  ?o2 rdfs:label ?o2Label .
} WHERE {
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p1 ?o1Label ?o1 ?p2 ?o2Label ?o2 WHERE {
        wd:Q42 ?p1 ?o1 .
        ?o1 ?p2 ?o2 .

        FILTER (
           STRSTARTS(STR(?p1), STR(wdt:)) &&
           STRSTARTS(STR(?o1), STR(wd:)) &&
           STRSTARTS(STR(?p2), STR(wdt:)) &&
           STRSTARTS(STR(?o2), STR(wd:))
        )

        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }

    } LIMIT 500
  }
}

CSV to RDF (Lab 7)

#Imports
import re
from pandas import *
from numpy import nan
from rdflib import Graph, Namespace, URIRef, Literal, RDF, XSD, FOAF
from spotlight import SpotlightException, annotate

SERVER = "https://api.dbpedia-spotlight.org/en/annotate"
# 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
CONFIDENCE = 0.83 

# This function uses DBpedia Spotlight, which was not a part of the CSV lab this year.  
def annotate_entity(entity, filters={'types': 'DBpedia:Person'}):
	annotations = []
	try:
		annotations = annotate(address=SERVER, text=entity, confidence=CONFIDENCE, filters=filters)
	except SpotlightException as e:
		print(e)
	return annotations

g = Graph()
ex = Namespace("http://example.org/")
g.bind("ex", ex)

#Pandas' read_csv function to load russia-investigation.csv
df = read_csv("russia-investigation.csv")
#Replaces all instances of nan to None type with numpy's nan
df = df.replace(nan, None)

#Function that prepares the values to be added to the graph as a URI (ex infront) or Literal
def prepareValue(row):
	if row == None: #none type
		value = Literal(row)
	elif isinstance(row, str) and re.match(r'\d{4}-\d{2}-\d{2}', row): #date
		value = Literal(row, datatype=XSD.date)
	elif isinstance(row, bool): #boolean value (true / false)
		value = Literal(row, datatype=XSD.boolean)
	elif isinstance(row, int): #integer
		value = Literal(row, datatype=XSD.integer)
	elif isinstance(row, str): #string
		value = URIRef(ex + row.replace('"', '').replace(" ", "_").replace(",","").replace("-", "_"))
	elif isinstance(row, float): #float
		value = Literal(row, datatype=XSD.float)

	return value

#Convert the non-semantic CSV dataset into a semantic RDF 
def csv_to_rdf(df):
	for index, row in df.iterrows():
		id = URIRef(ex + "Investigation_" + str(index))
		investigation = prepareValue(row["investigation"])
		investigation_start = prepareValue(row["investigation-start"])
		investigation_end = prepareValue(row["investigation-end"])
		investigation_days = prepareValue(row["investigation-days"])
		indictment_days = prepareValue(row["indictment-days "])
		cp_date = prepareValue(row["cp-date"])
		cp_days = prepareValue(row["cp-days"])
		overturned = prepareValue(row["overturned"])
		pardoned = prepareValue(row["pardoned"])
		american = prepareValue(row["american"])
		outcome = prepareValue(row["type"])
		name_ex = prepareValue(row["name"])
		president_ex = prepareValue(row["president"])

		#Spotlight Search
		name = annotate_entity(str(row['name']))
		president = annotate_entity(str(row['president']).replace(".", ""))
		
		#Adds the tripples to the graph
		g.add((id, RDF.type, ex.Investigation))
		g.add((id, ex.investigation, investigation))
		g.add((id, ex.investigation_start, investigation_start))
		g.add((id, ex.investigation_end, investigation_end))
		g.add((id, ex.investigation_days, investigation_days))
		g.add((id, ex.indictment_days, indictment_days))
		g.add((id, ex.cp_date, cp_date))
		g.add((id, ex.cp_days, cp_days))
		g.add((id, ex.overturned, overturned))
		g.add((id, ex.pardoned, pardoned))
		g.add((id, ex.american, american))
		g.add((id, ex.outcome, outcome))

		#Spotlight search
		#Name
		try:
			g.add((id, ex.person, URIRef(name[0]["URI"])))
		except:
			g.add((id, ex.person, name_ex))

		#President
		try:
			g.add((id, ex.president, URIRef(president[0]["URI"])))
		except:
			g.add((id, ex.president, president_ex))

csv_to_rdf(df)
print(g.serialize())
g.serialize("lab7.ttl", format="ttl")

JSON-LD (Lab 8)

Task 1) Basic JSON-LD

{
    "@context": {
        "@base": "http://example.org/",
        "edges": "http://example.org/triple",
        "start": "http://example.org/source",
        "rel": "http://exaxmple.org/predicate",
        "end": "http://example.org/object",
        "Person" : "http://example.org/Person",
        "birthday" : {
            "@id" : "http://example.org/birthday",
            "@type" : "xsd:date"
        },
        "nameEng" : {
            "@id" : "http://example.org/en/name",
            "@language" : "en"
        },
        "nameFr" : {
            "@id" : "http://example.org/fr/name",
            "@language" : "fr"
        },
        "nameCh" : {
            "@id" : "http://example.org/ch/name",
            "@language" : "ch"
        },
        "age" : {
            "@id" : "http://example.org/age",
            "@type" : "xsd:int"
        },
        "likes" : "http://example.org/games/likes",
        "haircolor" : "http://example.org/games/haircolor"
    },
    "@graph": [
        {
            "@id": "people/Jeremy",
            "@type": "Person",
            "birthday" : "1987.1.1",
            "nameEng" : "Jeremy",
            "age" : 26
        },
        {
            "@id": "people/Tom",
            "@type": "Person"
        },
        {
            "@id": "people/Ju",
            "@type": "Person",
            "birthday" : "2001.1.1",
            "nameCh" : "Ju",
            "age" : 22,
            "likes" : "bastketball"
        },
        {
            "@id": "people/Louis",
            "@type": "Person",
            "birthday" : "1978.1.1",
            "haircolor" : "Black",
            "nameFr" : "Louis",
            "age" : 45
        },
        {"edges" : [
        {
            "start" : "people/Jeremy",
            "rel" : "knows",
            "end" : "people/Tom"
        },
        {
            "start" : "people/Tom",
            "rel" : "knows",
            "end" : "people/Louis"
        },
        {
            "start" : "people/Louis",
            "rel" : "teaches",
            "end" : "people/Ju"
        },
        {
            "start" : "people/Ju",
            "rel" : "plays",
            "end" : "people/Jeremy"
        },
        {
            "start" : "people/Ju",
            "rel" : "plays",
            "end" : "people/Tom"
        }
        ]}
    ]
}

Task 2 & 3) Retrieving JSON-LD from ConceptNet / Programming JSON-LD in Python

import rdflib

CN_BASE = 'http://api.conceptnet.io/c/en/'

g = rdflib.Graph()
g.parse(CN_BASE+'indictment', format='json-ld')

# To download JSON object:

import json
import requests

json_obj = requests.get(CN_BASE+'indictment').json()

# To change the @context:

context = {
     "@base": "http://ex.org/",
     "edges": "http://ex.org/triple/",
     "start": "http://ex.org/s/",
     "rel": "http://ex.org/p/",
     "end": "http://ex.org/o/",
     "label": "http://ex.org/label"
}
json_obj['@context'] = context
json_str = json.dumps(json_obj)

g = rdflib.Graph()
g.parse(data=json_str, format='json-ld')

# To extract triples (here with labels):

r = g.query("""
         SELECT ?s ?sLabel ?p ?o ?oLabel WHERE {
             ?edge
                 <http://ex.org/s/> ?s ;
                 <http://ex.org/p/> ?p ;
                 <http://ex.org/o/> ?o .
             ?s <http://ex.org/label> ?sLabel .
             ?o <http://ex.org/label> ?oLabel .
}
         """, initNs={'cn': CN_BASE})
print(r.serialize(format='txt').decode())

# Construct a new graph:

r = g.query("""
         CONSTRUCT {
             ?s ?p ?o .
             ?s <http://ex.org/label> ?sLabel .
             ?o <http://ex.org/label> ?oLabel .
         } WHERE {
             ?edge <http://ex.org/s/> ?s ;
                   <http://ex.org/p/> ?p ;
                   <http://ex.org/o/> ?o .
             ?s <http://ex.org/label> ?sLabel .
             ?o <http://ex.org/label> ?oLabel .
}
         """, initNs={'cn': CN_BASE})

print(r.graph.serialize(format='ttl'))

SHACL (Lab 9)

from pyshacl import validate
from rdflib import Graph

data_graph = Graph()
# parses the Turtle example from the task
data_graph.parse("data_graph.ttl")

prefixes = """
@prefix ex: <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
"""

shape_graph = """
ex:PUI_Shape
    a sh:NodeShape ;
    sh:targetClass ex:PersonUnderInvestigation ;
    sh:property [
        sh:path foaf:name ;
        sh:minCount 1 ; #Every person under investigation has exactly one name. 
        sh:maxCount 1 ; #Every person under investigation has exactly one name.
        sh:datatype rdf:langString ; #All person names must be language-tagged
    ] ;
    sh:property [
        sh:path ex:chargedWith ;
        sh:nodeKind sh:IRI ; #The object of a charged with property must be a URI.
        sh:class ex:Offense ; #The object of a charged with property must be an offense.
    ] .

# --- If you have more time tasks ---
ex:User_Shape rdf:type sh:NodeShape;
    sh:targetClass ex:Indictment;
    # The only allowed values for ex:american are true, false or unknown.
    sh:property [
        sh:path ex:american;
        sh:pattern "(true|false|unknown)" ;
    ];
    
    # The value of a property that counts days must be an integer.
    sh:property [
        sh:path ex:indictment_days;
        sh:datatype xsd:integer;
    ];   
    sh:property [
        sh:path ex:investigation_days;
        sh:datatype xsd:integer;
    ];
    
    # The value of a property that indicates a start date must be xsd:date.
    sh:property [
        sh:path ex:investigation_start;
        sh:datatype xsd:date;
    ];

    # The value of a property that indicates an end date must be xsd:date or unknown (tip: you can use sh:or (...) ).
    sh:property [
        sh:path ex:investigation_end;
        sh:or (
         [ sh:datatype xsd:date ]
         [ sh:hasValue "unknown" ]
    )];
    
    # Every indictment must have exactly one FOAF name for the investigated person.
    sh:property [
        sh:path foaf:name;
        sh:minCount 1;
        sh:maxCount 1;
    ];
    
    # Every indictment must have exactly one investigated person property, and that person must have the type ex:PersonUnderInvestigation.
    sh:property [
        sh:path ex:investigatedPerson ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
        sh:class ex:PersonUnderInvestigation ;
        sh:nodeKind sh:IRI ;
    ] ;

    # No URI-s can contain hyphens ('-').
    sh:property [
        sh:path ex:outcome ;
        sh:nodeKind sh:IRI ;
        sh:pattern "^[^-]*$" ;
    ] ;

    # Presidents must be identified with URIs.
    sh:property [
        sh:path ex:president ;
        sh:minCount 1 ;
        sh:class ex:President ;
        sh:nodeKind sh:IRI ;
    ] .
"""

shacl_graph = Graph()
# parses the contents of a shape_graph you made in the previous task
shacl_graph.parse(data=prefixes+shape_graph)

# uses pySHACL's validate method to apply the shape_graph constraints to the data_graph
results = validate(
    data_graph,
    shacl_graph=shacl_graph,
    inference='both'
)

# prints out the validation result
boolean_value, results_graph, results_text = results

# print(boolean_value)
print(results_graph.serialize(format='ttl'))
# print(results_text)

#Write a SPARQL query to print out each distinct sh:resultMessage in the results_graph
distinct_messages = """
PREFIX sh: <http://www.w3.org/ns/shacl#> 

SELECT DISTINCT ?message WHERE {
    [] sh:result / sh:resultMessage ?message .
}
"""
messages = results_graph.query(distinct_messages)
for row in messages:
    print(row.message)

#each sh:resultMessage in the results_graph once, along with the number of times that message has been repeated in the results
count_messages = """
PREFIX sh: <http://www.w3.org/ns/shacl#> 

SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {
    [] sh:result ?result .
    ?result sh:resultMessage ?message ;
            sh:focusNode ?node .
}
GROUP BY ?message
ORDER BY DESC(?count) ?message
"""

messages = results_graph.query(count_messages)
for row in messages:
    print("COUNT    MESSAGE")
    print(row.num_messages, "      ", row.message)

RDFS (Lab 10)

import owlrl
from rdflib import Graph, RDF, Namespace, Literal, XSD, FOAF, RDFS
from rdflib.collection import Collection

g = Graph()
ex = Namespace('http://example.org/')

g.bind("ex", ex)
g.bind("foaf", FOAF)


NS = {
    'ex': ex,
    'rdf': RDF,
    'rdfs': RDFS,
    'foaf': FOAF,
}

#Write a small function that computes the RDFS closure on your graph.
def flush():
    engine = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)
    engine.closure()
    engine.flush_stored_triples()

#Rick Gates was charged with money laundering and tax evasion.
g.add((ex.Rick_Gates, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.Rick_Gates, ex.chargedWith, ex.TaxEvasion))

#When one thing that is charged with another thing,
g.add((ex.chargedWith, RDFS.domain, ex.PersonUnderInvestigation))  #the first thing (subject) is a person under investigation and
g.add((ex.chargedWith, RDFS.range, ex.Offense))  #the second thing (object) is an offense.

#Write a SPARQL query that checks the RDF type(s) of Rick Gates and money laundering in your RDF graph.
print(g.query('ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}', initNs=NS).askAnswer)
print(g.query('ASK {ex:MoneyLaundering rdf:type ex:Offense}', initNs=NS).askAnswer)
flush()
print(g.query('ASK {ex:Rick_Gates rdf:type ex:PersonUnderInvestigation}', initNs=NS).askAnswer)
print(g.query('ASK {ex:MoneyLaundering rdf:type ex:Offense}', initNs=NS).askAnswer)

#A person under investigation is a FOAF person
g.add((ex.PersonUnderInvestigation, RDFS.subClassOf, FOAF.Person))
print(g.query('ASK {ex:Rick_Gates rdf:type foaf:Person}', initNs=NS).askAnswer)
flush()
print(g.query('ASK {ex:Rick_Gates rdf:type foaf:Person}', initNs=NS).askAnswer)

#Paul Manafort was convicted for tax evasion.
g.add((ex.Paul_Manafort, ex.convictedFor, ex.TaxEvasion))
#the first thing is also charged with the second thing
g.add((ex.convictedFor, RDFS.subPropertyOf, ex.chargedWith)) 
flush()
print(g.query('ASK {ex:Paul_Manafort ex:chargedWith ex:TaxEvasion}', initNs=NS).askAnswer)

print(g.serialize())

OWL 1 (Lab 11)

from rdflib import Graph, RDFS, Namespace, RDF, FOAF, BNode, OWL, URIRef, Literal, XSD
from rdflib.collection import Collection
import owlrl

g = Graph()
ex = Namespace('http://example.org/')
schema = Namespace('http://schema.org/')
dbr = Namespace('https://dbpedia.org/page/')

g.bind("ex", ex)
# g.bind("schema", schema)
g.bind("foaf", FOAF)

# Donald Trump and Robert Mueller are two different persons.
g.add((ex.Donald_Trump, OWL.differentFrom, ex.Robert_Mueller))

# Actually, all the names mentioned in connection with the Mueller investigation refer to different people.
b1 = BNode()
b2 = BNode()
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])
g.add((b1, RDF.type, OWL.AllDifferent))
g.add((b1, OWL.distinctMembers, b2))

# All these people are foaf:Persons as well as schema:Persons
g.add((FOAF.Person, OWL.equivalentClass, schema.Person))

# Tax evation is a kind of bank and tax fraud.
g.add((ex.TaxEvation, RDFS.subClassOf, ex.BankFraud))
g.add((ex.TaxEvation, RDFS.subClassOf, ex.TaxFraud))

# The Donald Trump involved in the Mueller investigation is dbpedia:Donald_Trump and not dbpedia:Donald_Trump_Jr.
g.add((ex.Donald_Trump, OWL.sameAs, dbr.Donald_Trump))
g.add((ex.Donald_Trump, OWL.differentFrom, URIRef(dbr + "Donald_Trump_Jr.")))

# Congress, FBI and the Mueller investigation are foaf:Organizations.
g.add((ex.Congress, RDF.type, FOAF.Organization))
g.add((ex.FBI, RDF.type, FOAF.Organization))
g.add((ex.Mueller_Investigation, RDF.type, FOAF.Organization))

# Nothing can be both a person and an organization.
g.add((FOAF.Person, OWL.disjointWith, FOAF.Organization))

# Leading an organization is a way of being involved in an organization.
g.add((ex.leading, RDFS.subPropertyOf, ex.involved))

# Being a campaign manager or an advisor for is a way of supporting someone.
g.add((ex.campaignManagerTo, RDFS.subPropertyOf, ex.supports))
g.add((ex.advisorTo, RDFS.subPropertyOf, ex.supports))

# Donald Trump is a politician and a Republican.
g.add((ex.Donald_Trump, RDF.type, ex.Politician))
g.add((ex.Donald_Trump, RDF.type, ex.Republican))

# A Republican politician is both a politician and a Republican.
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Politician))
g.add((ex.RepublicanPolitician, RDFS.subClassOf, ex.Republican))

#hasBusinessPartner
g.add((ex.Paul_Manafort, ex.hasBusinessPartner, ex.Rick_Gates))
g.add((ex.hasBusinessPartner, RDF.type, OWL.SymmetricProperty))
g.add((ex.hasBusinessPartner, RDF.type, OWL.IrreflexiveProperty))

#adviserTo
g.add((ex.Michael_Flynn, ex.adviserTo, ex.Donald_Trump))
g.add((ex.adviserTo, RDF.type, OWL.IrreflexiveProperty))
# Not necessarily asymmetric as it's not a given that they couldn't be advisors to each other  

#wasLyingTo
g.add((ex.Rick_Gates_Lying, ex.wasLyingTo, ex.FBI))
g.add((ex.wasLyingTo, RDF.type, OWL.IrreflexiveProperty))
# Not asymmetric as the subject and object could lie to each other; also in this context, the FBI can lie to you

#presidentOf
g.add((ex.Donald_Trump, ex.presidentOf, ex.USA))
g.add((ex.presidentOf, RDF.type, OWL.AsymmetricProperty))
g.add((ex.presidentOf, RDF.type, OWL.IrreflexiveProperty))
g.add((ex.presidentOf, RDF.type, OWL.FunctionalProperty)) #can only be president of one country
#not inversefunctionalproperty as Bosnia has 3 presidents https://www.culturalworld.org/do-any-countries-have-more-than-one-president.htm

#hasPresident
g.add((ex.USA, ex.hasPresident, ex.Donald_Trump))
g.add((ex.hasPresident, RDF.type, OWL.AsymmetricProperty))
g.add((ex.hasPresident, RDF.type, OWL.IrreflexiveProperty))
g.add((ex.hasPresident, RDF.type, OWL.InverseFunctionalProperty)) #countries do not share their president with another
#not functionalproperty as a country (Bosnia) can have more than one president

#Closure
owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)

#Serialization
print(g.serialize(format="ttl"))
# g.serialize("lab8.xml", format="xml") #serializes to XML file

OWL 2 (Lab 12)

@prefix : <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
@prefix dc: <http://purl.org/dc/terms#> .
@prefix io: <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .
@prefix dbr: <http://dbpedia.org/resource/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix prov: <http://www.w3.org/ns/prov#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@base <http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#> .

<http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology> rdf:type owl:Ontology .

#################################################################
#    Object Properties
#################################################################

###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#indictedIn
io:indictedIn rdf:type owl:ObjectProperty ;
              rdfs:subPropertyOf io:involvedIn ;
              rdfs:domain io:InvestigatedPerson ;
              rdfs:range io:Investigation .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#investigating
io:investigating rdf:type owl:ObjectProperty ;
                 rdfs:subPropertyOf io:involvedIn ;
                 rdfs:domain io:Investigator ;
                 rdfs:range io:Investigation .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#involvedIn
io:involvedIn rdf:type owl:ObjectProperty ;
              rdfs:domain foaf:Person ;
              rdfs:range io:Investigation .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#leading
io:leading rdf:type owl:ObjectProperty ;
           rdfs:subPropertyOf io:investigating ;
           rdfs:domain io:InvestigationLeader ;
           rdfs:range io:Investigation .


#################################################################
#    Data properties
#################################################################

###  http://purl.org/dc/elements/1.1/description
<http://purl.org/dc/elements/1.1/description> rdf:type owl:DatatypeProperty ;
                                              rdfs:domain io:Investigation ;
                                              rdfs:range xsd:string .


###  http://www.w3.org/ns/prov#endedAtTime
prov:endedAtTime rdf:type owl:DatatypeProperty ,
                          owl:FunctionalProperty ;
                 rdfs:domain io:Investigation ;
                 rdfs:range xsd:dateTime .


###  http://www.w3.org/ns/prov#startedAtTime
prov:startedAtTime rdf:type owl:DatatypeProperty ,
                            owl:FunctionalProperty ;
                   rdfs:domain io:Investigation ;
                   rdfs:range xsd:dateTime .


###  http://xmlns.com/foaf/0.1/name
foaf:name rdf:type owl:DatatypeProperty ;
          rdfs:domain foaf:Person ;
          rdfs:range xsd:string .


###  http://xmlns.com/foaf/0.1/title
foaf:title rdf:type owl:DatatypeProperty ;
           rdfs:domain io:Investigation ;
           rdfs:range xsd:string .


#################################################################
#    Classes
#################################################################

###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigatedPerson
io:InvestigatedPerson rdf:type owl:Class ;
                      rdfs:subClassOf io:Person ;
                      owl:disjointWith io:Investigator .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigation
io:Investigation rdf:type owl:Class .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#InvestigationLeader
io:InvestigationLeader rdf:type owl:Class ;
                       rdfs:subClassOf io:Investigator .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Investigator
io:Investigator rdf:type owl:Class ;
                rdfs:subClassOf io:Person .


###  http://www.semanticweb.org/bruker/ontologies/2023/2/InvestigationOntology#Person
io:Person rdf:type owl:Class ;
          rdfs:subClassOf foaf:Person .


###  http://xmlns.com/foaf/0.1/Person
foaf:Person rdf:type owl:Class .


#################################################################
#    Individuals
#################################################################

###  http://dbpedia.org/resource/Donald_Trump
dbr:Donald_Trump rdf:type owl:NamedIndividual ;
                 foaf:name "Donald Trump" .


###  http://dbpedia.org/resource/Elizabeth_Prelogar
dbr:Elizabeth_Prelogar rdf:type owl:NamedIndividual ;
                       io:investigating <http://dbpedia.org/resource/Special_Counsel_investigation_(20172019)> ;
                       foaf:name "Elizabeth Prelogar" .


###  http://dbpedia.org/resource/Michael_Flynn
dbr:Michael_Flynn rdf:type owl:NamedIndividual ;
                  foaf:name "Michael Flynn" .


###  http://dbpedia.org/resource/Paul_Manafort
dbr:Paul_Manafort rdf:type owl:NamedIndividual ;
                  io:indictedIn <http://dbpedia.org/resource/Special_Counsel_investigation_(20172019)> ;
                  foaf:name "Paul Manafort" .


###  http://dbpedia.org/resource/Robert_Mueller
dbr:Robert_Mueller rdf:type owl:NamedIndividual ;
                   io:leading <http://dbpedia.org/resource/Special_Counsel_investigation_(20172019)> ;
                   foaf:name "Robert Mueller" .


###  http://dbpedia.org/resource/Roger_Stone
dbr:Roger_Stone rdf:type owl:NamedIndividual ;
                foaf:name "Roger Stone" .


###  http://dbpedia.org/resource/Special_Counsel_investigation_(2017–2019)
<http://dbpedia.org/resource/Special_Counsel_investigation_(20172019)> rdf:type owl:NamedIndividual ;
                                                                        foaf:title "Mueller Investigation" .


#################################################################
#    General axioms
#################################################################

[ rdf:type owl:AllDifferent ;
  owl:distinctMembers ( dbr:Donald_Trump
                        dbr:Elizabeth_Prelogar
                        dbr:Michael_Flynn
                        dbr:Paul_Manafort
                        dbr:Robert_Mueller
                        dbr:Roger_Stone
                      )
] .


###  Generated by the OWL API (version 4.5.25.2023-02-15T19:15:49Z) https://github.com/owlcs/owlapi

Using Graph Embeddings (Lab 13)

https://colab.research.google.com/drive/1WkRJUeUBVF5yVv7o0pOKfsd4pqG6369k

Training Graph Embeddings (Lab 14)

https://colab.research.google.com/drive/1jKpzlQ7gYTVzgphJsrK5iuMpFhkrY96q