Lab Solutions: Difference between revisions

From info216
No edit summary
(Added proposed solution for Lab 9 - SHACL)
 
(103 intermediate revisions by 7 users not shown)
Line 1: Line 1:
This page will be updated with Python examples related to the lectures and labs. We will add more examples after each lab has ended. The first examples will use Python's RDFlib. We will introduce other relevant libraries later.
Here we will present suggested solutions after each lab. ''The page will be updated as the course progresses''


=Getting started (Lab 1)=


==Lecture 1: Python, RDFlib, and PyCharm==
<syntaxhighlight>
 
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)


===Printing the triples of the Graph in a readable way===
<syntaxhighlight>
# The turtle format has the purpose of being more readable for humans.
print(g.serialize(format="turtle").decode())
</syntaxhighlight>
</syntaxhighlight>


===Coding Tasks Lab 1===
=RDF programming with RDFlib (Lab 2)=
 
<syntaxhighlight>
<syntaxhighlight>
from rdflib import Graph, Namespace, URIRef, BNode, Literal
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef
from rdflib.namespace import RDF, FOAF, XSD
from rdflib.collection import Collection


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


g.add((ex.Cade, ex.married, ex.Mary))
g.bind("ex", ex)
g.add((ex.France, ex.capital, ex.Paris))
g.bind("foaf", FOAF)
g.add((ex.Cade, ex.age, Literal("27", datatype=XSD.integer)))
g.add((ex.Mary, ex.age, Literal("26", datatype=XSD.integer)))
g.add((ex.Mary, ex.interest, ex.Hiking))
g.add((ex.Mary, ex.interest, ex.Chocolate))
g.add((ex.Mary, ex.interest, ex.Biology))
g.add((ex.Mary, RDF.type, ex.Student))
g.add((ex.Paris, RDF.type, ex.City))
g.add((ex.Paris, ex.locatedIn, ex.France))
g.add((ex.Cade, ex.characteristic, ex.Kind))
g.add((ex.Mary, ex.characteristic, ex.Kind))
g.add((ex.Mary, RDF.type, FOAF.Person))
g.add((ex.Cade, RDF.type, FOAF.Person))


</syntaxhighlight>
# --- 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))


==Lecture 2: RDF programming==
# 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))


===Different ways to create an address===
# --- 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))


<syntaxhighlight>
# --- 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))


from rdflib import Graph, Namespace, URIRef, BNode, Literal
# --- Michael Cohen ---
from rdflib.namespace import RDF, FOAF, XSD
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))


g = Graph()
print(g.serialize(format="ttl"))
ex = Namespace("http://example.org/")


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


# How to represent the address of Cade Tracey. From probably the worst solution to the best.
#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).
'''


# Solution 1 -
#Read (parse) the Turtle file back into a Python program, and check that the new triples are there
# Make the entire address into one Literal. However, Generally we want to separate each part of an address into their own triples. This is useful for instance if we want to find only the streets where people live.  
def serialize_Graph():
    newGraph = Graph()
    newGraph.parse("lab2.ttl")
    print(newGraph.serialize())


g.add((ex.Cade_Tracey, ex.livesIn, Literal("1516_Henry_Street, Berkeley, California 94709, USA")))
#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()


# Solution 2 -  
def create_Tree(model, nodes):
# Seperate the different pieces information into their own triples
    #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


g.add((ex.Cade_tracey, ex.street, Literal("1516_Henry_Street")))
def print_Tree(tree, root, indent=0):
g.add((ex.Cade_tracey, ex.city, Literal("Berkeley")))
    #Print the tree depth-first.
g.add((ex.Cade_tracey, ex.state, Literal("California")))
    print(str(root))
g.add((ex.Cade_tracey, ex.zipcode, Literal("94709")))
    for s, p, o in tree:
g.add((ex.Cade_tracey, ex.country, Literal("USA")))
        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)
</syntaxhighlight>


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


# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.
===List the first 100 triples===
# Larger concepts like a city or state are typically represented as resources rather than Literals, but this is not necesarilly a requirement in the case that you don't intend to say more about them.
<syntaxhighlight lang="SPARQL">
SELECT ?s ?p ?o
WHERE {?s ?p ?o .}
LIMIT 100
</syntaxhighlight>


g.add((ex.Cade_tracey, ex.street, Literal("1516_Henry_Street")))
===Count the number of triples===
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))
<syntaxhighlight lang="SPARQL">
g.add((ex.Cade_tracey, ex.state, ex.California))
SELECT (COUNT(*) as ?count)
g.add((ex.Cade_tracey, ex.zipcode, Literal("94709")))
WHERE {?s ?p ?o .}
g.add((ex.Cade_tracey, ex.country, ex.USA))
</syntaxhighlight>


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


# Solution 4
SELECT (COUNT(?ind) as ?amount)
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node.  
WHERE {
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address.
  ?s ns1:outcome ?ind;
# Solution 4 or 5 is how I would recommend to make addresses. Here, ex.CadeAddress could also be called something like ex.address1 or so on, if you want to give each address a unique ID.
      ns1:outcome ns1:indictment.
}
</syntaxhighlight>


# Address URI - CadeAdress
===List the names of everyone who pleaded guilty, along with the name of the investigation===
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>


g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))
SELECT ?name ?invname
g.add((ex.CadeAddress, RDF.type, ex.Address))
WHERE {
g.add((ex.CadeAddress, ex.street, Literal("1516 Henry Street")))
  ?s ns1:name ?name;
g.add((ex.CadeAddress, ex.city, ex.Berkeley))
      ns1:investigation ?invname;
g.add((ex.CadeAddress, ex.state, ex.California))
      ns1:outcome ns1:guilty-plea .
g.add((ex.CadeAddress, ex.postalCode, Literal("94709")))
}
g.add((ex.CadeAddress, ex.country, ex.USA))
</syntaxhighlight>


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


# Blank node for Address. 
SELECT ?name ?president
address = BNode()
WHERE {
g.add((ex.Cade_Tracey, ex.address, address))
  ?s ns1:name ?name;
g.add((address, RDF.type, ex.Address))
      ns1:president ?president;
g.add((address, ex.street, Literal("1516 Henry Street", datatype=XSD.string)))
      ns1:outcome ns1:conviction;
g.add((address, ex.city, ex.Berkeley))
      ns1:overturned ns1:true.
g.add((address, ex.state, ex.California))
}
g.add((address, ex.postalCode, Literal("94709", datatype=XSD.string)))
</syntaxhighlight>
g.add((address, ex.country, ex.USA))


===For each investigation, list the number of indictments made===
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>


# Solution 5 using existing vocabularies for address
SELECT ?invs (COUNT(?invs) as ?count)
WHERE {
  ?s ns1:investigation ?invs;
      ns1:outcome ns1:indictment .
}
GROUP BY ?invs
</syntaxhighlight>


# (in this case https://schema.org/PostalAddress from schema.org).
===For each investigation with multiple indictments, list the number of indictments made===
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>


schema = "https://schema.org/"
SELECT ?invs (COUNT(?invs) as ?count)
dbp = "https://dpbedia.org/resource/"
WHERE {
  ?s ns1:investigation ?invs;
      ns1:outcome ns1:indictment .
}
GROUP BY ?invs
HAVING(?count > 1)
</syntaxhighlight>


g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))
===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))
<syntaxhighlight lang="SPARQL">
g.add((ex.CadeAddress, schema.streetAddress, Literal("1516 Henry Street")))
PREFIX ns1: <http://example.org#>
g.add((ex.CadeAddress, schema.addresCity, dbp.Berkeley))
g.add((ex.CadeAddress, schema.addressRegion, dbp.California))
g.add((ex.CadeAddress, schema.postalCode, Literal("94709")))
g.add((ex.CadeAddress, schema.addressCountry, dbp.United_States))


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)
</syntaxhighlight>
</syntaxhighlight>


===Typed Literals===
===For each president, list the numbers of convictions and of pardons made===
<syntaxhighlight>
<syntaxhighlight lang="SPARQL">
from rdflib import Graph, Literal, Namespace
PREFIX ns1: <http://example.org#>
from rdflib.namespace import XSD
g = Graph()
ex = Namespace("http://example.org/")


g.add((ex.Cade, ex.age, Literal(27, datatype=XSD.integer)))
SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as
g.add((ex.Cade, ex.gpa, Literal(3.3, datatype=XSD.float)))
?pardons)
g.add((ex.Cade, FOAF.name, Literal("Cade Tracey", datatype=XSD.string)))
WHERE {
g.add((ex.Cade, ex.birthday, Literal("2006-01-01", datatype=XSD.date)))
  ?s ns1:president ?president;
      ns1:outcome ?outcome ;
      ns1:outcome ns1:conviction.
      OPTIONAL{
        ?s ns1:pardoned ?pardon .
        FILTER (?pardon = ns1:true)
      }
}
GROUP BY ?president
</syntaxhighlight>
</syntaxhighlight>


===Rename mullerkg:name to something like muellerkg:person===
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>


===Writing and reading graphs/files===
DELETE{?s ns1:name ?o}
INSERT{?s ns1:person ?o}
WHERE {?s ns1:name ?o}
</syntaxhighlight>


<syntaxhighlight>
===Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings===
  # Writing the graph to a file on your system. Possible formats = turtle, n3, xml, nt.
g.serialize(destination="triples.txt", format="turtle")


  # Parsing a local file
<syntaxhighlight lang="SPARQL">
parsed_graph = g.parse(location="triples.txt", format="turtle")
PREFIX ns1: <http://example.org#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>


  # Parsing a remote endpoint like Dbpedia
#Persons
dbpedia_graph = g.parse("http://dbpedia.org/resource/Pluto")
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)
}
</syntaxhighlight>
</syntaxhighlight>


===Use INSERT DATA updates to add these triples===


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


<syntaxhighlight>
INSERT DATA {
from rdflib import Graph, Namespace
    ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;
from rdflib.collection import Collection
        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 .}
</syntaxhighlight>
 
===Use DELETE DATA and then INSERT DATA updates to correct that Roger Stone was cleared of all charges===
 
<syntaxhighlight lang="SPARQL">
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.
}


# Sometimes we want to add many objects or subjects for the same predicate at once.
#The task specifically requested DELETE DATA & INSERT DATA, put below is
# In these cases we can use Collection() to save some time.
a more efficient solution
# In this case I want to add all countries that Emma has visited at once.


b = BNode()
DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
g.add((ex.Emma, ex.visit, b))
INSERT{
Collection(g, b,
  ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])
                                  ns1:WitnessTampering,
                                  ns1:FalseStatements.
}
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
</syntaxhighlight>


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


g.add((ex.Emma, ex.visit, ex.EmmaVisits))
<syntaxhighlight lang="SPARQL">
Collection(g, ex.EmmaVisits,
PREFIX ns1: <http://example.org#>
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])


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


==Lecture 3: SPARQL==
===Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone===
 
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>


===SPARQL queries from the lecture===
CONSTRUCT {
<syntaxhighlight>
  ns1:Roger_Stone ?p ?o.
SELECT DISTINCT ?p WHERE {
  ?s ?p2 ns1:Roger_Stone.
    ?s ?p ?o .
}
WHERE {
  ns1:Roger_Stone ?p ?o .
  ?s ?p2 ns1:Roger_Stone
}
}
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight>
===Write a DELETE/INSERT statement to change one of the prefixes in your graph===
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
 
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>
PREFIX dbp: <https://dbpedia.org/page/>


SELECT DISTINCT ?t WHERE {
DELETE {?s ns1:person ?o1}
    ?s rdf:type ?t .
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)
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight>
===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. ===
PREFIX owl: <http://www.w3.org/2002/07/owl#>
 
CONSTRUCT {  
<syntaxhighlight lang="SPARQL">
    ?s owl:sameAs ?o2 .
#Whilst this solution is not exactly what the task asks for, I feel like
} WHERE {
this is more appropiate given the dataset. The following update
    ?s owl:sameAs ?o .
changes the objects that uses the cp_date as predicate from a URI, to a
    FILTER(REGEX(STR(?o), "^http://www\\.", "s"))
literal with date as it's datatype
    BIND(URI(REPLACE(STR(?o), "^http://www\\.", "http://", "s")) AS ?o2)
 
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)
}
}
</syntaxhighlight>
</syntaxhighlight>


===Select all contents of lists (rdfllib.Collection)===
=SPARQL Programming (Lab 5)=
 
<syntaxhighlight>
<syntaxhighlight>


# rdflib.Collection has a different interntal structure so it requires a slightly more advance query. Here I am selecting all places that Emma has visited.
from rdflib import Graph, Namespace, RDF, FOAF
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE


PREFIX ex:  <http://example.org/>
g = Graph()
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
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.


SELECT ?visit
# 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:
WHERE {
task4 = g.query("""
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit
ASK {
  SELECT (COUNT(?s) as ?count) WHERE{
    ?s :pardoned :true;
    :president :Bill_Clinton  .
    }
    HAVING (?count > 5)
}
}
</syntaxhighlight>
""", 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.


==Lecture 4- SPARQL PROGRAMMING==
# 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


===SELECTING data from Blazegraph via Python===
# task5 = g.query("""
<syntaxhighlight>
# DESCRIBE :Donald_Trump
# """, initNs=NS)


from SPARQLWrapper import SPARQLWrapper, JSON
# print(task5.serialize())


# This creates a server connection to the same URL that contains the graphic interface for Blazegraph.
# ----- SPARQLWrapper -----
# You also need to add "sparql" to end of the URL like below.


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


# SELECT all triples in the database.
# 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("""
sparql.setQuery("""
     SELECT DISTINCT ?p WHERE {
     PREFIX ns1: <http://example.org#>
    ?s ?p ?o.
    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)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
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"]:
for result in results["results"]["bindings"]:
     print(result["p"]["value"])
     print(result["s"]["value"])


# SELECT all interests of Cade
# 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("""
sparql.setQuery("""
     PREFIX ex: <http://example.org/>
     PREFIX ns1: <http://example.org#>
     SELECT DISTINCT ?interest WHERE {
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    ex:Cade ex:interest ?interest.
 
     SELECT DISTINCT ?types
    WHERE{
        ?s rdf:type ?types .  
     }
     }
""")
""")
sparql.setReturnFormat(JSON)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results = sparql.query().convert()
rdf_Types = []


for result in results["results"]["bindings"]:
for result in results["results"]["bindings"]:
     print(result["interest"]["value"])
     rdf_Types.append(result["types"]["value"])
</syntaxhighlight>
 
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#>


===Updating data from Blazegraph via Python===
    INSERT{
<syntaxhighlight>
        ?invest rdf:type ns1:Investigation .
from SPARQLWrapper import SPARQLWrapper, POST, DIGEST
    }
    WHERE{
        ?s ns1:investigation ?invest .
}"""


namespace = "kb"
sparqlUpdate.setQuery(update_str)
sparql = SPARQLWrapper("http://localhost:9999/blazegraph/namespace/"+ namespace + "/sparql")
sparqlUpdate.setMethod(POST)
sparqlUpdate.query()


sparql.setMethod(POST)
#To Test
sparql.setQuery("""
sparql.setQuery("""
     PREFIX ex: <http://example.org/>
    prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
     INSERT DATA{
     PREFIX ns1: <http://example.org#>
    ex:Cade ex:interest ex:Mathematics.
 
     ASK{
        ns1:watergate rdf:type ns1:Investigation.
     }
     }
""")
""")


results = sparql.query()
sparql.setReturnFormat(JSON)
print(results.response.read())
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)
}"""


</syntaxhighlight>
sparqlUpdate.setQuery(update_str)
===Retrieving data from Wikidata with SparqlWrapper===
sparqlUpdate.setMethod(POST)
<syntaxhighlight>
sparqlUpdate.query()
from SPARQLWrapper import SPARQLWrapper, JSON


sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
#Same test as above, replace it with e.g. ns1:watergate dc:title "watergate"
# In the query I want to select all the Vitamins in wikidata.


# Print out a sorted list of all the indicted persons represented in your graph.
sparql.setQuery("""
sparql.setQuery("""
     SELECT ?nutrient ?nutrientLabel WHERE
    PREFIX ns1: <http://example.org#>
{
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
  ?nutrient wdt:P279 wd:Q34956.
 
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
     SELECT ?name
}
    WHERE{
    ?s  ns1:name ?name;
            ns1:outcome ns1:indictment.
    }
    ORDER BY ?name
""")
""")


sparql.setReturnFormat(JSON)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results = sparql.query().convert()
names = []


for result in results["results"]["bindings"]:
for result in results["results"]["bindings"]:
     print(result["nutrient"]["value"], "  ", result["nutrientLabel"]["value"])
     names.append(result["name"]["value"])
</syntaxhighlight>


print(names)


== Lecture 5: RDFS==
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.


===RDFS inference with RDFLib===
sparql.setQuery("""
You can use the OWL-RL package to add inference capabilities to RDFLib. Download it [https://github.com/RDFLib/OWL-RL GitHub] and copy the ''owlrl'' subfolder into your project folder next to your Python files.
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX ns1: <http://example.org#>


[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]
    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)
}
""")


Example program to get started:
sparql.setReturnFormat(JSON)
<syntaxhighlight>
results = sparql.query().convert()
import rdflib.plugins.sparql.update
import owlrl.RDFSClosure


g = rdflib.Graph()
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"]}')


ex = rdflib.Namespace('http://example.org#')
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.
g.bind('', ex)


g.update("""
sparql.setQuery("""
PREFIX ex: <http://example.org#>
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX ns1: <http://example.org#>
INSERT DATA {
    ex:Socrates rdf:type ex:Man .
    ex:Man rdfs:subClassOf ex:Mortal .
}""")


# The next three lines add inferred triples to g.
    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min) WHERE{
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)
    ?s  ns1:indictment_days ?days;
rdfs.closure()
        ns1:outcome ns1:indictment;
rdfs.flush_stored_triples()
        ns1:investigation ?investigation.
 
   
b = g.query("""
     BIND (replace(str(?days), str(ns1:), "")  AS ?daysR)
PREFIX ex: <http://example.org#>
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)
ASK {
    }
     ex:Socrates rdf:type ex:Mortal .
    GROUP BY ?investigation
}  
""")
""")
print('Result: ' + bool(b))
</syntaxhighlight>


===Languaged tagged RDFS labels===
sparql.setReturnFormat(JSON)
<syntaxhighlight>
results = sparql.query().convert()
from rdflib import Graph, Namespace, Literal
from rdflib.namespace import RDFS


g = Graph()
for result in results["results"]["bindings"]:
ex = Namespace("http://example.org/")
    print(f'{result["investigation"]["value"]} - min: {result["min"]["value"]}, max: {result["max"]["value"]}, avg: {result["avg"]["value"]}')


g.add((ex.France, RDFS.label, Literal("Frankrike", lang="no")))
</syntaxhighlight>
g.add((ex.France, RDFS.label, Literal("France", lang="en")))
g.add((ex.France, RDFS.label, Literal("Francia", lang="es")))


=Wikidata SPARQL (Lab 6)=
===Use a DESCRIBE query to retrieve some triples about your entity===


<syntaxhighlight lang="SPARQL">
DESCRIBE wd:Q42 LIMIT 100
</syntaxhighlight>
</syntaxhighlight>


== Lecture 6: RDFS Plus / OWL ==
===Use a SELECT query to retrieve the first 100 triples about your entity===
===RDFS Plus / OWL inference with RDFLib===  


You can use the OWL-RL package again as for Lecture 5.
<syntaxhighlight lang="SPARQL">
SELECT * WHERE {
  wd:Q42 ?p ?o .
} LIMIT 100
</syntaxhighlight>


Instead of:
===Write a local SELECT query that embeds a SERVICE query to retrieve the first 100 triples about your entity to your local machine===
<syntaxhighlight>
# The next three lines add inferred triples to g.
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)
rdfs.closure()
rdfs.flush_stored_triples()
</syntaxhighlight>
you can write this to get both RDFS and basic RDFS Plus / OWL inference:
<syntaxhighlight>
# The next three lines add inferred triples to g.
owl = owlrl.CombinedClosure.RDFS_OWLRL_Semantics(g, False, False, False)
owl.closure()
owl.flush_stored_triples()
</syntaxhighlight>


Example updates and queries:
<syntaxhighlight lang="SPARQL">
<syntaxhighlight>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX ex: <http://example.org#>


INSERT DATA {
SELECT * WHERE {
     ex:Socrates ex:hasWife ex:Xanthippe .
     SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
     ex:hasHusband owl:inverseOf ex:hasWife .
        SELECT * WHERE {
            wd:Q42 ?p ?o .
        } LIMIT 100
     }
}
}
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight>
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository===
ASK {
  ex:Xanthippe ex:hasHusband ex:Socrates .
}
</syntaxhighlight>


<syntaxhighlight>
<syntaxhighlight lang="SPARQL">
ASK {
PREFIX wd: <http://www.wikidata.org/entity/>
  ex:Socrates ^ex:hasHusband ex:Xanthippe .
}
</syntaxhighlight>


<syntaxhighlight>
INSERT {
INSERT DATA {
     wd:Q42 ?p ?o .
     ex:hasWife rdfs:subPropertyOf ex:hasSpouse .
} WHERE {
     ex:hasSpouse rdf:type owl:SymmetricProperty .  
     SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
        SELECT * WHERE {
            wd:Q42 ?p ?o .
        } LIMIT 100
    }
}
}
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight>
===Use a FILTER statement to only SELECT primary triples in this sense.===
ASK {
 
  ex:Socrates ex:hasSpouse ex:Xanthippe .
<syntaxhighlight lang="SPARQL">
}
PREFIX wd: <http://www.wikidata.org/entity/>
</syntaxhighlight>


<syntaxhighlight>
SELECT * WHERE {
ASK {
    wd:Q42 ?p ?o .
  ex:Socrates ^ex:hasSpouse ex:Xanthippe .
}
    FILTER (STRSTARTS(STR(?p), STR(wdt:)))
    FILTER (STRSTARTS(STR(?o), STR(wd:)))
} LIMIT 100
</syntaxhighlight>
</syntaxhighlight>


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


===Download from BlazeGraph===
<syntaxhighlight lang="SPARQL">
PREFIX wd: <http://www.wikidata.org/entity/>


<syntaxhighlight>
SELECT ?p ?oLabel WHERE {
"""
    wd:Q42 ?p ?o .
Dumps a database to a local RDF file.
You need to install the SPARQLWrapper package first...
    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>


import datetime
===Edit your query (by relaxing the FILTER expression) so it also returns triples where the object has DATATYPE xsd:string.===
from SPARQLWrapper import SPARQLWrapper, RDFXML


# your namespace, the default is 'kb'
<syntaxhighlight lang="SPARQL">
ns = 'kb'
PREFIX wd: <http://www.wikidata.org/entity/>


# the SPARQL endpoint
SELECT ?p ?oLabel ?o WHERE {
endpoint = 'http://info216.i2s.uib.no/bigdata/namespace/' + ns + '/sparql'
    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>


# - the endpoint just moved, the old one was:
===Relax the FILTER expression again so it also returns triples with these three predicates (rdfs:label, skos:altLabel and schema:description) ===
# endpoint = 'http://i2s.uib.no:8888/bigdata/namespace/' + ns + '/sparql'


# create wrapper
<syntaxhighlight lang="SPARQL">
wrapper = SPARQLWrapper(endpoint)
PREFIX wd: <http://www.wikidata.org/entity/>


# prepare the SPARQL update
SELECT ?p ?oLabel ?o WHERE {
wrapper.setQuery('CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }')
    wd:Q42 ?p ?o .
wrapper.setReturnFormat(RDFXML)
    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>


# execute the SPARQL update and convert the result to an rdflib.Graph
===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" ===
graph = wrapper.query().convert()


# the destination file, with code to make it timestamped
<syntaxhighlight lang="SPARQL">
destfile = 'rdf_dumps/slr-kg4news-' + datetime.datetime.now().strftime('%Y%m%d-%H%M') + '.rdf'
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/>


# serialize the result to file
SELECT * WHERE {
graph.serialize(destination=destfile, format='ttl')
  SERVICE <https://query.wikidata.org/bigdata/namespace/wdq/sparql> {
    SELECT ?p ?oLabel ?o WHERE {
        wd:Q42 ?p ?o .


# report and quit
        FILTER (
print('Wrote %u triples to file %s .' %
          (STRSTARTS(STR(?p), STR(wdt:)) &&
      (len(res), destfile))
          STRSTARTS(STR(?o), STR(wd:)) || DATATYPE(?o) = xsd:string)
</syntaxhighlight>
          ||
          (?p IN (rdfs:label, skos:altLabel, schema:description) &&
          DATATYPE(?o) = rdf:langString && LANG(?o) = "en")
        )


==Semantic Lifting - CSV==
        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }


<syntaxhighlight>
    } LIMIT 100
from rdflib import Graph, Literal, Namespace, URIRef
  }
from rdflib.namespace import RDF, FOAF, RDFS, OWL
}
import pandas as pd
</syntaxhighlight>


g = Graph()
===Change the SELECT query to an INSERT query that adds the Wikidata triples your local repository ===
ex = Namespace("http://example.org/")
g.bind("ex", ex)


# Load the CSV data as a pandas Dataframe.
<syntaxhighlight lang="SPARQL">
csv_data = pd.read_csv("task1.csv")
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/>


# Here I deal with spaces (" ") in the data. I replace them with "_" so that URI's become valid.
INSERT {
csv_data = csv_data.replace(to_replace=" ", value="_", regex=True)
  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 .


# Here I mark all missing/empty data as "unknown". This makes it easy to delete triples containing this later.
        FILTER (
csv_data = csv_data.fillna("unknown")
          (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")
        )


# Loop through the CSV data, and then make RDF triples.
        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
for index, row in csv_data.iterrows():
    # The names of the people act as subjects.
    subject = row['Name']
    # Create triples: e.g. "Cade_Tracey - age - 27"
    g.add((URIRef(ex + subject), URIRef(ex + "age"), Literal(row["Age"])))
    g.add((URIRef(ex + subject), URIRef(ex + "married"), URIRef(ex + row["Spouse"])))
    g.add((URIRef(ex + subject), URIRef(ex + "country"), URIRef(ex + row["Country"])))


     # If We want can add additional RDF/RDFS/OWL information e.g
     } LIMIT 500
    g.add((URIRef(ex + subject), RDF.type, FOAF.Person))
  }
}
</syntaxhighlight>


# I remove triples that I marked as unknown earlier.
==If you have more time ==
g.remove((None, None, URIRef("http://example.org/unknown")))
===You must therefore REPLACE all wdt: prefixes of properties with wd: prefixes and BIND the new URI AS a new variable, for example ?pw. ===


# Clean printing of the graph.
<syntaxhighlight lang="SPARQL">
print(g.serialize(format="turtle").decode())
PREFIX wd: <http://www.wikidata.org/entity/>
</syntaxhighlight>


===CSV file for above example===
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)


<syntaxhighlight>
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
"Name","Age","Spouse","Country"
"Cade Tracey","26","Mary Jackson","US"
} LIMIT 100
"Bob Johnson","21","","Canada"
"Mary Jackson","25","","France"
"Phil Philips","32","Catherine Smith","Japan"
</syntaxhighlight>
</syntaxhighlight>


==Semantic Lifting - XML==
===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>
from rdflib import Graph, Literal, Namespace, URIRef
from rdflib.namespace import RDF, XSD, RDFS
import xml.etree.ElementTree as ET


g = Graph()
<syntaxhighlight lang="SPARQL">
ex = Namespace("http://example.org/TV/")
PREFIX wikibase: <http://wikiba.se/ontology#>
prov = Namespace("http://www.w3.org/ns/prov#")
PREFIX bd: <http://www.bigdata.com/rdf#>
g.bind("ex", ex)
PREFIX wd: <http://www.wikidata.org/entity/>
g.bind("prov", prov)
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/>


tree = ET.parse("tv_shows.xml")
INSERT {
root = tree.getroot()
  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 .


for tv_show in root.findall('tv_show'):
        FILTER (
    show_id = tv_show.attrib["id"]
          STRSTARTS(STR(?p1), STR(wdt:)) &&
    title = tv_show.find("title").text
          STRSTARTS(STR(?o1), STR(wd:)) &&
          STRSTARTS(STR(?p2), STR(wdt:)) &&
          STRSTARTS(STR(?o2), STR(wd:))
        )


    g.add((URIRef(ex + show_id), ex.title, Literal(title, datatype=XSD.string)))
        SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    g.add((URIRef(ex + show_id), RDF.type, ex.TV_Show))


     for actor in tv_show.findall("actor"):
     } LIMIT 500
        first_name = actor.find("firstname").text
  }
        last_name = actor.find("lastname").text
}
        full_name = first_name + "_" + last_name
</syntaxhighlight>
       
        g.add((URIRef(ex + show_id), ex.stars, URIRef(ex + full_name)))
        g.add((URIRef(ex + full_name), ex.starsIn, URIRef(title)))
        g.add((URIRef(ex + full_name), RDF.type, ex.Actor))


print(g.serialize(format="turtle").decode())
=CSV to RDF (Lab 7)=
</syntaxhighlight>


<syntaxhighlight lang="Python">


#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


===XML Data for above example===
SERVER = "https://api.dbpedia-spotlight.org/en/annotate"
<syntaxhighlight>
# Test around with the confidence, and see how many names changes depending on the confidence.
<data>
# 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
    <tv_show id="1050">
CONFIDENCE = 0.83
        <title>The_Sopranos</title>
        <actor>
            <firstname>James</firstname>
            <lastname>Gandolfini</lastname>
        </actor>
    </tv_show>
    <tv_show id="1066">
        <title>Seinfeld</title>
        <actor>
            <firstname>Jerry</firstname>
            <lastname>Seinfeld</lastname>
        </actor>
        <actor>
            <firstname>Julia</firstname>
            <lastname>Louis-dreyfus</lastname>
        </actor>
        <actor>
            <firstname>Jason</firstname>
            <lastname>Alexander</lastname>
        </actor>
    </tv_show>
</data>
</syntaxhighlight>


==Semantic Lifting - HTML==
# This function uses DBpedia Spotlight, which was not a part of the CSV lab this year. 
<syntaxhighlight>
def annotate_entity(entity, filters={'types': 'DBpedia:Person'}):
from bs4 import BeautifulSoup as bs, NavigableString
annotations = []
from rdflib import Graph, URIRef, Namespace
try:
from rdflib.namespace import RDF
annotations = annotate(address=SERVER, text=entity, confidence=CONFIDENCE, filters=filters)
except SpotlightException as e:
print(e)
return annotations


g = Graph()
g = Graph()
Line 583: Line 1,097:
g.bind("ex", ex)
g.bind("ex", ex)


html = open("tv_shows.html").read()
#Pandas' read_csv function to load russia-investigation.csv
html = bs(html, features="html.parser")
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)


shows = html.find_all('li', attrs={'class': 'show'})
return value
for show in shows:
    title = show.find("h3").text
    actors = show.find('ul', attrs={'class': 'actor_list'})
    for actor in actors:
        if isinstance(actor, NavigableString):
            continue
        else:
            actor = actor.text.replace(" ", "_")
            g.add((URIRef(ex + title), ex.stars, URIRef(ex + actor)))
            g.add((URIRef(ex + actor), RDF.type, ex.Actor))


    g.add((URIRef(ex + title), RDF.type, ex.TV_Show))
#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")


print(g.serialize(format="turtle").decode())
</syntaxhighlight>
</syntaxhighlight>


===HTML code for the example above===
=JSON-LD (Lab 8)=
<syntaxhighlight>
== Task 1) Basic JSON-LD ==
<!DOCTYPE html>
 
<html>
<syntaxhighlight lang="JSON-LD">
<head>
 
    <meta charset="utf-8">
{
    <title></title>
    "@context": {
</head>
        "@base": "http://example.org/",
<body>
        "edges": "http://example.org/triple",
    <div class="tv_shows">
        "start": "http://example.org/source",
         <ul>
        "rel": "http://exaxmple.org/predicate",
             <li class="show">
        "end": "http://example.org/object",
                <h3>The_Sopranos</h3>
        "Person" : "http://example.org/Person",
                <div class="irrelevant_data"></div>
        "birthday" : {
                <ul class="actor_list">
            "@id" : "http://example.org/birthday",
                    <li>James Gandolfini</li>
            "@type" : "xsd:date"
                </ul>
        },
             </li>
        "nameEng" : {
             <li class="show">
            "@id" : "http://example.org/en/name",
                <h3>Seinfeld</h3>
            "@language" : "en"
                <div class="irrelevant_data"></div>
         },
                <ul class="actor_list">
        "nameFr" : {
                    <li >Jerry Seinfeld</li>
            "@id" : "http://example.org/fr/name",
                    <li>Jason Alexander</li>
             "@language" : "fr"
                    <li>Julia Louis-Dreyfus</li>
        },
                </ul>
        "nameCh" : {
             </li>
            "@id" : "http://example.org/ch/name",
         </ul>
            "@language" : "ch"
    </div>
        },
</body>
        "age" : {
</html>
            "@id" : "http://example.org/age",
</syntaxhighlight>
            "@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"
        }
        ]}
    ]
}


==WEB API Calls (In this case JSON)==
<syntaxhighlight>
import requests
import json
import pprint


# Retrieve JSON data from API service URL. Then load it with the json library as a json object.
url = "http://api.geonames.org/postalCodeLookupJSON?postalcode=46020&#country=ES&username=demo"
data = requests.get(url).content.decode("utf-8")
data = json.loads(data)
pprint.pprint(data)
</syntaxhighlight>
</syntaxhighlight>


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


==JSON-LD==
<syntaxhighlight lang="Python">


<syntaxhighlight>
import rdflib
import rdflib
CN_BASE = 'http://api.conceptnet.io/c/en/'


g = rdflib.Graph()
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()


example = """
# To change the @context:
{
 
  "@context": {
context = {
    "name": "http://xmlns.com/foaf/0.1/name",
    "@base": "http://ex.org/",
    "homepage": {
    "edges": "http://ex.org/triple/",
      "@id": "http://xmlns.com/foaf/0.1/homepage",
    "start": "http://ex.org/s/",
      "@type": "@id"
    "rel": "http://ex.org/p/",
    }
    "end": "http://ex.org/o/",
  },
    "label": "http://ex.org/label"
  "@id": "http://me.markus-lanthaler.com/",
  "name": "Markus Lanthaler",
  "homepage": "http://www.markus-lanthaler.com/"
}
}
"""
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):


# json-ld parsing automatically deals with @contexts
r = g.query("""
g.parse(data=example, format='json-ld')
        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())


# serialisation does expansion by default
# Construct a new graph:
for line in g.serialize(format='json-ld').decode().splitlines():
    print(line)


# by supplying a context object, serialisation can do compaction
r = g.query("""
context = {
        CONSTRUCT {
    "foaf": "http://xmlns.com/foaf/0.1/"
            ?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 .
}
}
for line in g.serialize(format='json-ld', context=context).decode().splitlines():
        """, initNs={'cn': CN_BASE})
    print(line)
 
print(r.graph.serialize(format='ttl'))
 
</syntaxhighlight>
</syntaxhighlight>


=SHACL (Lab 9)=
<syntaxhighlight lang="Python">
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;
    ];


<div class="credits" style="text-align: right; direction: ltr; margin-left: 1em;">''INFO216, UiB, 2017-2020. All code examples are [https://creativecommons.org/choose/zero/ CC0].'' </div>
    # 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 ;
    ] ;


==OWL - Complex Classes and Restrictions==
    # No URI-s can contain hyphens ('-').
<syntaxhighlight>
    sh:property [
import owlrl
        sh:path ex:outcome ;
from rdflib import Graph, Literal, Namespace, BNode
        sh:nodeKind sh:IRI ;
from rdflib.namespace import RDF, OWL, RDFS
        sh:pattern "^[^-]*$" ;
from rdflib.collection import Collection
    ] ;
 
    # 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'
)


g = Graph()
# prints out the validation result
ex = Namespace("http://example.org/")
boolean_value, results_graph, results_text = results
g.bind("ex", ex)
g.bind("owl", OWL)


# a Season is either Autumn, Winter, Spring, Summer
# print(boolean_value)
seasons = BNode()
print(results_graph.serialize(format='ttl'))
Collection(g, seasons, [ex.Winter, ex.Autumn, ex.Spring, ex.Summer])
# print(results_text)
g.add((ex.Season, OWL.oneOf, seasons))


# A Parent is a Father or Mother
#Write a SPARQL query to print out each distinct sh:resultMessage in the results_graph
b = BNode()
distinct_messages = """
Collection(g, b, [ex.Father, ex.Mother])
PREFIX sh: <http://www.w3.org/ns/shacl#>
g.add((ex.Parent, OWL.unionOf, b))


# A Woman is a person who has the "female" gender
SELECT DISTINCT ?message WHERE {
br = BNode()
    [] sh:result / sh:resultMessage ?message .
g.add((br, RDF.type, OWL.Restriction))
}
g.add((br, OWL.onProperty, ex.gender))
"""
g.add((br, OWL.hasValue, ex.Female))
messages = results_graph.query(distinct_messages)
bi = BNode()
for row in messages:
Collection(g, bi, [ex.Person, br])
    print(row.message)
g.add((ex.Woman, OWL.intersectionOf, bi))


# A vegetarian is a Person who only eats vegetarian food
#each sh:resultMessage in the results_graph once, along with the number of times that message has been repeated in the results
br = BNode()
count_messages = """
g.add((br, RDF.type, OWL.Restriction))
PREFIX sh: <http://www.w3.org/ns/shacl#>
g.add((br, OWL.onProperty, ex.eats))
g.add((br, OWL.allValuesFrom, ex.VeganFood))
bi = BNode()
Collection(g, bi, [ex.Person, br])
g.add((ex.Vegetarian, OWL.intersectionOf, bi))


# A vegetarian is a Person who can not eat meat.
SELECT ?message (COUNT(?node) AS ?num_messages) WHERE {
br = BNode()
    [] sh:result ?result .
g.add((br, RDF.type, OWL.Restriction))
    ?result sh:resultMessage ?message ;
g.add((br, OWL.onProperty, ex.eats))
            sh:focusNode ?node .
g.add((br, OWL.QualifiedCardinality, Literal(0)))
}
g.add((br, OWL.onClass, ex.Meat))
GROUP BY ?message
bi = BNode()
ORDER BY DESC(?count) ?message
Collection(g, bi, [ex.Person, br])
"""
g.add((ex.Vegetarian, OWL.intersectionOf, bi))


# A Worried Parent is a parent who has at least one sick child
messages = results_graph.query(count_messages)
br = BNode()
for row in messages:
g.add((br, RDF.type, OWL.Restriction))
    print("COUNT    MESSAGE")
g.add((br, OWL.onProperty, ex.hasChild))
    print(row.num_messages, "      ", row.message)
g.add((br, OWL.QualifiedMinCardinality, Literal(1)))
g.add((br, OWL.onClass, ex.Sick))
bi = BNode()
Collection(g, bi, [ex.Parent, br])
g.add((ex.WorriedParent, OWL.intersectionOf, bi))


# using the restriction above, If we now write...:
g.add((ex.Bob, RDF.type, ex.Parent))
g.add((ex.Bob, ex.hasChild, ex.John))
g.add((ex.John, RDF.type, ex.Sick))
# ...we can infer with owl reasoning that Bob is a worried Parent even though we didn't specify it ourselves because Bob fullfills the restriction and Parent requirements.


</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 15:51, 22 March 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 = ns1: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)