Lab Solutions: Difference between revisions

From info216
No edit summary
No edit summary
 
(158 intermediate revisions by 8 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''
=[[/info216.wiki.uib.no/Lab: Getting started with VSCode, Python and RDFlib|1 Lab: Getting started with VSCode, Python and RDFlib]] =
<syntaxhighlight>
 
from rdflib import Graph, Namespace
 
ex = Namespace('http://example.org/')


g = Graph()


==Lecture 1: Python, RDFlib, and PyCharm==
g.bind("ex", ex)


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


===Printing the triples of the Graph in a readable way===
# It involved Paul Manafort, Rick Gates, George Papadopoulos, Michael Flynn, Michael Cohen, and Roger Stone.
<syntaxhighlight>
g.add((ex.MuellerInvestigation, ex.involved, ex.PaulManafort))
# The turtle format has the purpose of being more readable for humans.  
g.add((ex.MuellerInvestigation, ex.involved, ex.RickGates))
print(g.serialize(format="turtle").decode())
g.add((ex.MuellerInvestigation, ex.involved, ex.GeorgePapadopoulos))
</syntaxhighlight>
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelFlynn))
g.add((ex.MuellerInvestigation, ex.involved, ex.MichaelCohen))
g.add((ex.MuellerInvestigation, ex.involved, ex.RogerStone))


===Coding Tasks Lab 1===
# Paul Manafort was business partner of Rick Gates
<syntaxhighlight>
g.add((ex.PaulManafort, ex.businessPartner, ex.RickGates))
from rdflib import Graph, Namespace, URIRef, BNode, Literal
from rdflib.namespace import RDF, FOAF, XSD


g = Graph()
# He was campaign chairman for Donald Trump
ex = Namespace("http://example.org/")
g.add((ex.PaulManafort, ex.campaignChairman, ex.DonaldTrump))


g.add((ex.Cade, ex.married, ex.Mary))
# He was charged with money laundering, tax evasion, and foreign lobbying.
g.add((ex.France, ex.capital, ex.Paris))
g.add((ex.PaulManafort, ex.chargedWith, ex.MoneyLaundering))
g.add((ex.Cade, ex.age, Literal("27", datatype=XSD.integer)))
g.add((ex.PaulManafort, ex.chargedWith, ex.TaxEvasion))
g.add((ex.Mary, ex.age, Literal("26", datatype=XSD.integer)))
g.add((ex.PaulManafort, ex.chargedWith, ex.ForeignLobbying))
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>
# He was convicted for bank and tax fraud.
g.add((ex.PaulManafort, ex.convictedOf, ex.BankFraud))
g.add((ex.PaulManafort, ex.convictedOf, ex.TaxFraud))


== Lab 1/2 - Different ways to create an address ==
# He pleaded guilty to conspiracy.
g.add((ex.PaulManafort, ex.pleadGuiltyTo, ex.Conspiracy))


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


from rdflib import Graph, Namespace, URIRef, BNode, Literal
# He negotiated a plea agreement.
from rdflib.namespace import RDF, FOAF, XSD
g.add((ex.PaulManafort, ex.negotiated, ex.PleaAgreement))


g = Graph()
# Rick Gates was charged with money laundering, tax evasion and foreign lobbying.
ex = Namespace("http://example.org/")
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))


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


# Solution 1 -
# Loop through the triples in the model to print out all triples that have pleading guilty as predicate
# Make the entire address into one Literal. However, Generally we want to seperate 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.  
for subject, object in g[ : ex.pleadGuiltyTo :]:
    print(subject, ex.pleadGuiltyTo, object)


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


# Solution 2 -
#Write a method (function) that submits your model for rendering and saves the returned image to file.
# Seperate the different pieces information into their own triples
import requests
import shutil


g.add((ex.Cade_tracey, ex.street, Literal("1516_Henry_Street")))
def graphToImage(graphInput):
g.add((ex.Cade_tracey, ex.city, Literal("Berkeley")))
    data = {"rdf":graphInput, "from":"ttl", "to":"png"}
g.add((ex.Cade_tracey, ex.state, Literal("California")))
    link = "http://www.ldf.fi/service/rdf-grapher"
g.add((ex.Cade_tracey, ex.zipcode, Literal("94709")))
    response = requests.get(link, params = data, stream=True)
g.add((ex.Cade_tracey, ex.country, Literal("USA")))
    # 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)


# Solution 3 - Some parts of the addresses can make more sense to be resources than Literals.
</syntaxhighlight>
# 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.


g.add((ex.Cade_tracey, ex.street, Literal("1516_Henry_Street")))
=2 [[/info216.wiki.uib.no/Lab: SPARQL|Lab: SPARQL queries]] =
g.add((ex.Cade_tracey, ex.city, ex.Berkeley))
<syntaxhighlight>
g.add((ex.Cade_tracey, ex.state, ex.California))
List all triples in your graph.
g.add((ex.Cade_tracey, ex.zipcode, Literal("94709")))
g.add((ex.Cade_tracey, ex.country, ex.USA))


select * where {
?s ?p ?o .
}


# Solution 4
List the first 100 triples in your graph.
# Grouping of the information into an Address. We can Represent the address concept with its own URI OR with a Blank Node.
# One advantage of this is that we can easily remove the entire address, instead of removing each individual part of the address.
# 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.  


# Address URI - CadeAdress
select * where {
?s ?p ?o .
} limit 100


g.add((ex.Cade_Tracey, ex.address, ex.CadeAddress))
Count the number of triples in your graph.
g.add((ex.CadeAddress, RDF.type, ex.Address))
g.add((ex.CadeAddress, ex.street, Literal("1516 Henry Street")))
g.add((ex.CadeAddress, ex.city, ex.Berkeley))
g.add((ex.CadeAddress, ex.state, ex.California))
g.add((ex.CadeAddress, ex.postalCode, Literal("94709")))
g.add((ex.CadeAddress, ex.country, ex.USA))


# OR
select (count(?s)as ?tripleCount) where {
?s ?p ?o .
}


# Blank node for Address.
Count the number of indictments in your graph.
address = BNode()
g.add((ex.Cade_Tracey, ex.address, address))
g.add((address, RDF.type, ex.Address))
g.add((address, ex.street, Literal("1516 Henry Street", datatype=XSD.string)))
g.add((address, ex.city, ex.Berkeley))
g.add((address, ex.state, ex.California))
g.add((address, ex.postalCode, Literal("94709", datatype=XSD.string)))
g.add((address, ex.country, ex.USA))


PREFIX muellerkg: <http://example.org#>
select (Count(?s)as ?numIndictment) where {
?s ?p muellerkg:Indictment .
}


# Solution 5 using existing vocabularies for address
List everyone who pleaded guilty, along with the name of the investigation.


# (in this case https://schema.org/PostalAddress from schema.org).
PREFIX m: <http://example.org#>
# Also using existing ontology for places like California. (like http://dbpedia.org/resource/California from dbpedia.org)
select ?name ?s where {
?s ?p m:guilty-plea;
    m:name ?name.


schema = "https://schema.org/"
List everyone who were convicted, but who had their conviction overturned by which president.
dbp = "https://dpbedia.org/resource/"


g.add((ex.Cade_Tracey, schema.address, ex.CadeAddress))
PREFIX muellerkg: <http://example.org#>
g.add((ex.CadeAddress, RDF.type, schema.PostalAddress))
#List everyone who were convicted, but who had their conviction overturned by which president.
g.add((ex.CadeAddress, schema.streetAddress, Literal("1516 Henry Street")))
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))


</syntaxhighlight>
select ?name ?president  where {
?s ?p muellerkg:conviction;
muellerkg:name ?name;
    muellerkg:overturned true;
    muellerkg:president ?president. 
} limit 100


For each investigation, list the number of indictments made.


== Lab 2 - Collection Example ==
PREFIX muellerkg: <http://example.org#>
select ?investigation (count(?investigation) as ?numIndictments) where {
?s muellerkg:investigation ?investigation .
} group by (?investigation)


<syntaxhighlight>
For each investigation with multiple indictments, list the number of indictments made.
from rdflib import Graph, Namespace
from rdflib.collection import Collection


PREFIX muellerkg: <http://example.org#>
select ?investigation (count(?investigation) as ?numIndictments) where {
?s muellerkg:investigation ?investigation.
} group by (?investigation)
having (?numIndictments > 1)


# Sometimes we want to add many objects or subjects for the same predicate at once.
For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first.
# In these cases we can use Collection() to save some time.
# In this case I want to add all countries that Emma has visited at once.


b = BNode()
PREFIX muellerkg: <http://example.org#>
g.add((ex.Emma, ex.visit, b))
select ?investigation (count(?investigation) as ?numIndictments) where {
Collection(g, b,
?s muellerkg:investigation ?investigation.
    [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])
} group by (?investigation)
having (?numIndictments > 1)
order by desc(?numIndictments)


# OR
For each president, list the numbers of convictions and of pardons made after conviction.


g.add((ex.Emma, ex.visit, ex.EmmaVisits))
PREFIX muellerkg: <http://example.org#>
Collection(g, ex.EmmaVisits,
SELECT ?president (COUNT(?conviction) AS ?numConvictions) (COUNT(?pardon) AS ?numPardoned)  
     [ex.Portugal, ex.Italy, ex.France, ex.Germany, ex.Denmark, ex.Sweden])
WHERE {
    ?indictment muellerkg:president ?president ;
                muellerkg:outcome muellerkg:conviction .
    BIND(?indictment AS ?conviction)
     OPTIONAL {
        ?indictment muellerkg:pardoned true .
        BIND(?indictment AS ?pardon)
    }
}
GROUP BY ?president


</syntaxhighlight>
</syntaxhighlight>


== Lab 3/4 - SPARQL queries from the lecture ==
== 3 [[/info216.wiki.uib.no/Lab: SPARQL Programming|Lab: SPARQL programming]] ==
<syntaxhighlight>
<syntaxhighlight>
SELECT DISTINCT ?p WHERE {
 
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 .
     ?s ?p ?o .
}
}
</syntaxhighlight>
""", initNs=NS)


<syntaxhighlight>
print(list(task1))
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>


SELECT DISTINCT ?t WHERE {
# Print out a sorted list of all the presidents represented in your graph.
     ?s rdf:type ?t .
task2 = g.query("""
SELECT DISTINCT ?president WHERE{
     ?s :president ?president .
}
}
</syntaxhighlight>
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 = {}


<syntaxhighlight>
task3 = g.query("""
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT ?president ?person WHERE{
CONSTRUCT {
     ?s :president ?president;
    ?s owl:sameAs ?o2 .
      :name ?person;
} WHERE {
      :outcome :indictment.
     ?s owl:sameAs ?o .
    FILTER(REGEX(STR(?o), "^http://www\\.", "s"))
    BIND(URI(REPLACE(STR(?o), "^http://www\\.", "http://", "s")) AS ?o2)
}
}
</syntaxhighlight>
""", initNs=NS)
 
for president, person in task3:
    if president not in task3_dic:
        task3_dic[president] = [person]
    else:
        task3_dic[president].append(person)


==Lab 3/4 - SPARQL - Select all contents of lists (rdfllib.Collection)==
print(task3_dic)
<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.
# Use an ASK query to investigate whether Donald Trump has pardoned more than 5 people.


PREFIX ex:   <http://example.org/>
task4 = g.query("""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    ASK{
        SELECT ?count WHERE{{
          SELECT (COUNT(?s) as ?count) WHERE{
            ?s :pardoned :true;
                  :president :Bill_Clinton  .
                }}
        FILTER (?count > 5)
        }
    }
""", initNs=NS)


SELECT ?visit
print(task4.askAnswer)
WHERE {
  ex:Emma ex:visit/rdf:rest*/rdf:first ?visit
}
</syntaxhighlight>




== Lab 4/6 - 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"])
 
# 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()


# SELECT all interests of Cade
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#>


== Lab 4/6 - 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)
}"""
 
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 = []


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


== Lecture 5: RDFS inference with RDFLib ==
print(names)


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.
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.


[https://owl-rl.readthedocs.io/en/latest/owlrl.html OWL-RL documentation.]
sparql.setQuery("""
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX ns1: <http://example.org#>


Example program to get started:
    SELECT (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{
<syntaxhighlight>
        ?s  ns1:indictment_days ?days;
import rdflib.plugins.sparql.update
            ns1:outcome ns1:indictment.
import owlrl.RDFSClosure
   
    BIND (replace(str(?days), str(ns1:), "")  AS ?daysR)
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)
}
""")


g = rdflib.Graph()
sparql.setReturnFormat(JSON)
results = sparql.query().convert()


ex = rdflib.Namespace('http://example.org#')
for result in results["results"]["bindings"]:
g.bind('', ex)
    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"]}')


g.update("""
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.
PREFIX ex: <http://example.org#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
INSERT DATA {
    ex:Socrates rdf:type ex:Man .
    ex:Man rdfs:subClassOf ex:Mortal .
}""")


# The next three lines add inferred triples to g.
sparql.setQuery("""
rdfs = owlrl.RDFSClosure.RDFS_Semantics(g, False, False, False)
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
rdfs.closure()
    PREFIX ns1: <http://example.org#>
rdfs.flush_stored_triples()


b = g.query("""
    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{
PREFIX ex: <http://example.org#>
    ?s  ns1:indictment_days ?days;
ASK {
        ns1:outcome ns1:indictment;
     ex:Socrates rdf:type ex:Mortal .
        ns1:investigation ?investigation.
}  
   
     BIND (replace(str(?days), str(ns1:), "")  AS ?daysR)
    BIND (STRDT(STR(?daysR), xsd:float) AS ?daysRemoved)
    }
    GROUP BY ?investigation
""")
""")
print('Result: ' + bool(b))
 
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"]}')
 
</syntaxhighlight>
</syntaxhighlight>


== Lecture 6: RDFS Plus / OWL inference with RDFLib ==  
== Lab 4 JSON-LD==
Part 1<syntaxhighlight lang="json-ld">
{
  "@context": {
      "@base": "http://example.org/",
      "edges": "http://example.org/triple",
      "start": "http://example.org/source",
      "rel": "http://exaxmple.org/predicate",
      "end": "http://example.org/object",
      "Person" : "http://example.org/Person",
      "birthday" : {
          "@id" : "http://example.org/birthday",
          "@type" : "xsd:date"
      },
      "nameEng" : {
          "@id" : "http://example.org/en/name",
          "@language" : "en"
      },
      "nameFr" : {
          "@id" : "http://example.org/fr/name",
          "@language" : "fr"
      },
      "nameCh" : {
          "@id" : "http://example.org/ch/name",
          "@language" : "ch"
      },
      "age" : {
          "@id" : "http://example.org/age",
          "@type" : "xsd:int"
      },
      "likes" : "http://example.org/games/likes",
      "haircolor" : "http://example.org/games/haircolor"
  },
  "@graph": [
      {
          "@id": "people/Jeremy",
          "@type": "Person",
          "birthday" : "1987.1.1",
          "nameEng" : "Jeremy",
          "age" : 26
      },
      {
          "@id": "people/Tom",
          "@type": "Person"
      },
      {
          "@id": "people/Ju",
          "@type": "Person",
          "birthday" : "2001.1.1",
          "nameCh" : "Ju",
          "age" : 22,
          "likes" : "bastketball"
      },
      {
          "@id": "people/Louis",
          "@type": "Person",
          "birthday" : "1978.1.1",
          "haircolor" : "Black",
          "nameFr" : "Louis",
          "age" : 45
      },
      {"edges" : [
      {
          "start" : "people/Jeremy",
          "rel" : "knows",
          "end" : "people/Tom"
      },
      {
          "start" : "people/Tom",
          "rel" : "knows",
          "end" : "people/Louis"
      },
      {
          "start" : "people/Louis",
          "rel" : "teaches",
          "end" : "people/Ju"
      },
      {
          "start" : "people/Ju",
          "rel" : "plays",
          "end" : "people/Jeremy"
      },
      {
          "start" : "people/Ju",
          "rel" : "plays",
          "end" : "people/Tom"
      }
      ]}
  ]
}
</syntaxhighlight>Part 2-3<syntaxhighlight lang="python">
import rdflib


You can use the OWL-RL package again as for Lecture 5.
CN_BASE = 'http://api.conceptnet.io/c/en/'


Instead of:
g = rdflib.Graph()
<syntaxhighlight>
g.parse(CN_BASE+'indictment', format='json-ld')
# 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_OWL_RLSemantics(g, False, False, False)
owl.closure()
owl.flush_stored_triples()
</syntaxhighlight>


Example updates and queries:
# To download JSON object:
<syntaxhighlight>
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 {
import json
    ex:Socrates ex:hasWife ex:Xanthippe .
import requests
    ex:hasHusband owl:inverseOf ex:hasWife .
}
</syntaxhighlight>


<syntaxhighlight>
json_obj = requests.get(CN_BASE+'indictment').json()
ASK {
  ex:Xanthippe ex:hasHusband ex:Socrates .
}
</syntaxhighlight>


<syntaxhighlight>
# To change the @context:
ASK {
  ex:Socrates ^ex:hasHusband ex:Xanthippe .
}
</syntaxhighlight>


<syntaxhighlight>
context = {
INSERT DATA {
    "@base": "http://ex.org/",
    ex:hasWife rdfs:subPropertyOf ex:hasSpouse .
    "edges": "http://ex.org/triple/",
    ex:hasSpouse rdf:type owl:SymmetricProperty .  
    "start": "http://ex.org/s/",
    "rel": "http://ex.org/p/",
    "end": "http://ex.org/o/",
    "label": "http://ex.org/label"
}
}
</syntaxhighlight>
json_obj['@context'] = context
json_str = json.dumps(json_obj)
 
g = rdflib.Graph()
g.parse(data=json_str, format='json-ld')


<syntaxhighlight>
# To extract triples (here with labels):
ASK {
  ex:Socrates ex:hasSpouse ex:Xanthippe .
}
</syntaxhighlight>


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


# Construct a new graph:


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


print(r.graph.serialize(format='ttl'))
</syntaxhighlight>


== Lab 6 SHACL ==
<syntaxhighlight lang="turtle">
Every person under investigation has exactly one name.
ex:PersonShape
  a sh:NodeShape;
  sh:targetClass ex:PersonUnderInvestigation;
  sh:property [
  sh:path foaf:name;
  sh:maxCount 1;
  sh:minCount 1
].


<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 object of a charged with property must be a URI.
ex:PersonShape
  a sh:NodeShape;
  sh:targetClass ex:PersonUnderInvestigation;
  sh:property [
    sh:path ex:chargedWith;
    sh:nodeKind sh:URI
  ].
The object of a charged with property must be an offense.
ex:PersonShape
  a sh:NodeShape;
  sh:targetClass ex:PersonUnderInvestigation;
  sh:property [
    sh:path ex:chargedWith;
    sh:class ex:Offense
  ].
 
All person names must be language-tagged (hint: rdf:langString is a datatype!).
ex:PersonShape
  a sh:NodeShape;
  sh:targetClass ex:PersonUnderInvestigation;
  sh:property [
    sh:path foaf:name;
    sh:datatype rdf:langString
  ].
</syntaxhighlight>

Latest revision as of 09:09, 17 March 2025

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

1 Lab: Getting started with VSCode, Python and RDFlib

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)

2 Lab: SPARQL queries

List all triples in your graph.

select * where { 
	?s ?p ?o .
} 

List the first 100 triples in your graph.

select * where { 
	?s ?p ?o .
} limit 100 

Count the number of triples in your graph.

select (count(?s)as ?tripleCount) where { 
	?s ?p ?o .
} 

Count the number of indictments in your graph.

PREFIX muellerkg: <http://example.org#>
select (Count(?s)as ?numIndictment) where { 
	?s ?p muellerkg:Indictment .
} 

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

PREFIX m: <http://example.org#>
select ?name ?s where { 
	?s ?p m:guilty-plea;
    	m:name ?name.
}  

List everyone who were convicted, but who had their conviction overturned by which president.

PREFIX muellerkg: <http://example.org#>
#List everyone who were convicted, but who had their conviction overturned by which president.

select ?name ?president   where { 
	?s ?p muellerkg:conviction;
		muellerkg:name ?name;
    	muellerkg:overturned true;
     	muellerkg:president ?president.  	
} limit 100 

For each investigation, list the number of indictments made.

PREFIX muellerkg: <http://example.org#>
select ?investigation (count(?investigation) as ?numIndictments) where { 
	?s muellerkg:investigation ?investigation .
} group by (?investigation)

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

PREFIX muellerkg: <http://example.org#>
select ?investigation (count(?investigation) as ?numIndictments) where { 
	?s muellerkg:investigation ?investigation.
} group by (?investigation)
having (?numIndictments > 1)

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

PREFIX muellerkg: <http://example.org#>
select ?investigation (count(?investigation) as ?numIndictments) where { 
	?s muellerkg:investigation ?investigation.
} group by (?investigation)
having (?numIndictments > 1)
order by desc(?numIndictments)

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

PREFIX muellerkg: <http://example.org#>
SELECT ?president (COUNT(?conviction) AS ?numConvictions) (COUNT(?pardon) AS ?numPardoned) 
WHERE { 
    ?indictment muellerkg:president ?president ;
                muellerkg:outcome muellerkg:conviction .
    BIND(?indictment AS ?conviction)
    OPTIONAL {
        ?indictment muellerkg:pardoned true .
        BIND(?indictment AS ?pardon)
    }
} 
GROUP BY ?president

3 Lab: SPARQL programming

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.

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)


# 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"]}')

Lab 4 JSON-LD

Part 1

{
  "@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"
      }
      ]}
  ]
}

Part 2-3

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'))

Lab 6 SHACL

Every person under investigation has exactly one name.
ex:PersonShape 
   a sh:NodeShape;
   sh:targetClass ex:PersonUnderInvestigation;
   sh:property [
   sh:path foaf:name;
   sh:maxCount 1;
   sh:minCount 1
].

The object of a charged with property must be a URI.
ex:PersonShape 
   a sh:NodeShape;
   sh:targetClass ex:PersonUnderInvestigation;
   sh:property [
     sh:path ex:chargedWith;
     sh:nodeKind sh:URI
   ].
 
 The object of a charged with property must be an offense.
 ex:PersonShape 
   a sh:NodeShape;
   sh:targetClass ex:PersonUnderInvestigation;
   sh:property [
     sh:path ex:chargedWith;
     sh:class ex:Offense
   ].
   
 All person names must be language-tagged (hint: rdf:langString is a datatype!).
 ex:PersonShape 
   a sh:NodeShape;
   sh:targetClass ex:PersonUnderInvestigation;
   sh:property [
     sh:path foaf:name;
     sh:datatype rdf:langString
   ].