Lab Solutions: Difference between revisions

From info216
m (Minor headline fix)
 
(21 intermediate revisions by 4 users not shown)
Line 1: Line 1:
Here we will present suggested solutions after each lab. ''The page will be updated as the course progresses''
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]] =
=Getting started (Lab 1)=
 
<syntaxhighlight>
<syntaxhighlight>


Line 87: Line 85:
</syntaxhighlight>
</syntaxhighlight>


=RDF programming with RDFlib (Lab 2)=
=2 [[/info216.wiki.uib.no/Lab: SPARQL|Lab: SPARQL queries]] =
<syntaxhighlight>
List all triples in your graph.
 
select * where {
?s ?p ?o .
}
 
List the first 100 triples in your graph.


<syntaxhighlight>
select * where {
from rdflib import Graph, Namespace, Literal, BNode, XSD, FOAF, RDF, URIRef
?s ?p ?o .
from rdflib.collection import Collection
} limit 100


g = Graph()
Count the number of triples in your graph.


# Getting the graph created in the first lab
select (count(?s)as ?tripleCount) where {
g.parse("lab1.ttl", format="ttl")
?s ?p ?o .
}


ex = Namespace("http://example.org/")
Count the number of indictments in your graph.


g.bind("ex", ex)
PREFIX muellerkg: <http://example.org#>
g.bind("foaf", FOAF)
select (Count(?s)as ?numIndictment) where {
?s ?p muellerkg:Indictment .
}


# --- Michael Cohen ---
List everyone who pleaded guilty, along with the name of the investigation.
# 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 ---
PREFIX m: <http://example.org#>
# Michael Flynn was adviser to Donald Trump.
select ?name ?s where {
g.add((ex.MichaelFlynn, ex.adviserTo, ex.DonaldTrump))
?s ?p m:guilty-plea;
# He pleaded guilty for lying to the FBI.
    m:name ?name.
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.
List everyone who were convicted, but who had their conviction overturned by which president.
# 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 ---
PREFIX muellerkg: <http://example.org#>
FlynnLying = BNode()
#List everyone who were convicted, but who had their conviction overturned by which president.
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 ---
select ?name ?president  where {
GatesLying = BNode()
?s ?p muellerkg:conviction;
Crimes = BNode()
muellerkg:name ?name;
Charged = BNode()
    muellerkg:overturned true;
Collection(g, Crimes, [ex.LyingToFBI, ex.Conspiracy])
    muellerkg:president ?president.
Collection(g, Charged, [ex.ForeignLobbying, ex.MoneyLaundering, ex.TaxEvasion])
} limit 100
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 ---
For each investigation, list the number of indictments made.
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"))
PREFIX muellerkg: <http://example.org#>
select ?investigation (count(?investigation) as ?numIndictments) where {
?s muellerkg:investigation ?investigation .
} group by (?investigation)


#Save (serialize) your graph to a Turtle file.
For each investigation with multiple indictments, list the number of indictments made.
# g.serialize("lab2.ttl", format="ttl")


#Add a few triples to the Turtle file with more information about Donald Trump.
PREFIX muellerkg: <http://example.org#>
'''
select ?investigation (count(?investigation) as ?numIndictments) where {
ex:Donald_Trump ex:address [ ex:city ex:Palm_Beach ;
?s muellerkg:investigation ?investigation.
            ex:country ex:United_States ;
} group by (?investigation)
            ex:postalCode 33480 ;
having (?numIndictments > 1)
            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
For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first.
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
PREFIX muellerkg: <http://example.org#>
# serialize_Graph()  
select ?investigation (count(?investigation) as ?numIndictments) where {
?s muellerkg:investigation ?investigation.
} group by (?investigation)
having (?numIndictments > 1)
order by desc(?numIndictments)


#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
For each president, list the numbers of convictions and of pardons made after conviction.
visited_nodes = set()


def create_Tree(model, nodes):
PREFIX muellerkg: <http://example.org#>
    #Traverse the model breadth-first to create the tree.
SELECT ?president (COUNT(?conviction) AS ?numConvictions) (COUNT(?pardon) AS ?numPardoned)  
    global visited_nodes
WHERE {
    tree = Graph()
     ?indictment muellerkg:president ?president ;
    children = set()
                muellerkg:outcome muellerkg:conviction .
    visited_nodes |= set(nodes)
    BIND(?indictment AS ?conviction)
     for s, p, o in model:
    OPTIONAL {
        if s in nodes and o not in visited_nodes:
         ?indictment muellerkg:pardoned true .
            tree.add((s, p, o))
        BIND(?indictment AS ?pardon)
            visited_nodes.add(o)
     }
            children.add(o)
}
         if o in nodes and s not in visited_nodes:
GROUP BY ?president
            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)
</syntaxhighlight>
</syntaxhighlight>


=SPARQL (Lab 3-4)=
== 3 [[/info216.wiki.uib.no/Lab: SPARQL Programming|Lab: SPARQL programming]] ==
===List all triples===
<syntaxhighlight>
<syntaxhighlight lang="SPARQL">
 
SELECT ?s ?p ?o
from rdflib import Graph, Namespace, RDF, FOAF
WHERE {?s ?p ?o .}
from SPARQLWrapper import SPARQLWrapper, JSON, POST, GET, TURTLE
</syntaxhighlight>


===List the first 100 triples===
g = Graph()
<syntaxhighlight lang="SPARQL">
g.parse("Russia_investigation_kg.ttl")
SELECT ?s ?p ?o
WHERE {?s ?p ?o .}
LIMIT 100
</syntaxhighlight>


===Count the number of triples===
# ----- RDFLIB -----
<syntaxhighlight lang="SPARQL">
ex = Namespace('http://example.org#')
SELECT (COUNT(*) as ?count)
WHERE {?s ?p ?o .}
</syntaxhighlight>


===Count the number of indictments===
NS = {
<syntaxhighlight lang="SPARQL">
    '': ex,
PREFIX ns1: <http://example.org#>
    'rdf': RDF,
    'foaf': FOAF,
}


SELECT (COUNT(?ind) as ?amount)
# Print out a list of all the predicates used in your graph.
WHERE {
task1 = g.query("""
  ?s ns1:outcome ?ind;
SELECT DISTINCT ?p WHERE{
      ns1:outcome ns1:indictment.
    ?s ?p ?o .
}
}
</syntaxhighlight>
""", initNs=NS)


===List the names of everyone who pleaded guilty, along with the name of the investigation===
print(list(task1))
<syntaxhighlight lang="SPARQL">
PREFIX ns1: <http://example.org#>


SELECT ?name ?invname
# Print out a sorted list of all the presidents represented in your graph.
WHERE {
task2 = g.query("""
  ?s ns1:name ?name;
SELECT DISTINCT ?president WHERE{
      ns1:investigation ?invname;
    ?s :president ?president .
      ns1:outcome ns1:guilty-plea .
}
}
</syntaxhighlight>
ORDER BY ?president
""", initNs=NS)
 
print(list(task2))


===List the names of everyone who were convicted, but who had their conviction overturned by which president===
# 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.
<syntaxhighlight lang="SPARQL">
task3_dic = {}
PREFIX ns1: <http://example.org#>


SELECT ?name ?president
task3 = g.query("""
WHERE {
SELECT ?president ?person WHERE{
  ?s ns1:name ?name;
    ?s :president ?president;
      ns1:president ?president;
      :name ?person;
      ns1:outcome ns1:conviction;
      :outcome :indictment.
      ns1:overturned ns1:true.
}
}
</syntaxhighlight>
""", 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"])


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


SELECT ?invs (COUNT(?invs) as ?count)
# Update the graph to that every resource that is an object in a muellerkg:investigation triple has the rdf:type muellerkg:Investigation.
WHERE {
update_str = """
  ?s ns1:investigation ?invs;
    PREFIX ns1: <http://example.org#>
      ns1:outcome ns1:indictment .
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
}
GROUP BY ?invs
</syntaxhighlight>


===For each investigation with multiple indictments, list the number of indictments made===
    INSERT{
<syntaxhighlight lang="SPARQL">
        ?invest rdf:type ns1:Investigation .
PREFIX ns1: <http://example.org#>
    }
    WHERE{
        ?s ns1:investigation ?invest .
}"""


SELECT ?invs (COUNT(?invs) as ?count)
sparqlUpdate.setQuery(update_str)
WHERE {
sparqlUpdate.setMethod(POST)
  ?s ns1:investigation ?invs;
sparqlUpdate.query()
      ns1:outcome ns1:indictment .
}
GROUP BY ?invs
HAVING(?count > 1)
</syntaxhighlight>


===For each investigation with multiple indictments, list the number of indictments made, sorted with the most indictments first===
#To Test
<syntaxhighlight lang="SPARQL">
sparql.setQuery("""
PREFIX ns1: <http://example.org#>
    prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX ns1: <http://example.org#>


SELECT ?invs (COUNT(?invs) as ?count)
    ASK{
WHERE {
        ns1:watergate rdf:type ns1:Investigation.
  ?s ns1:investigation ?invs;
    }
      ns1:outcome ns1:indictment .
""")
}
GROUP BY ?invs
HAVING(?count > 1)
ORDER BY DESC(?count)
</syntaxhighlight>


===For each president, list the numbers of convictions and of pardons made===
sparql.setReturnFormat(JSON)
<syntaxhighlight lang="SPARQL">
results = sparql.query().convert()
PREFIX ns1: <http://example.org#>
print(results['boolean'])


SELECT ?president (COUNT(?outcome) as ?conviction) (COUNT(?pardon) as
# Update the graph to that every resource that is an object in a muellerkg:person triple has the rdf:type muellerkg:IndictedPerson.
?pardons)
update_str = """
WHERE {
    PREFIX ns1: <http://example.org#>
  ?s ns1:president ?president;
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
      ns1:outcome ?outcome ;
      ns1:outcome ns1:conviction.
      OPTIONAL{
        ?s ns1:pardoned ?pardon .
        FILTER (?pardon = ns1:true)
      }
}
GROUP BY ?president
</syntaxhighlight>


===Rename mullerkg:name to something like muellerkg:person===
    INSERT{
        ?person rdf:type ns1:IndictedPerson .
    }
    WHERE{
        ?s ns1:name ?person .
}"""


<syntaxhighlight lang="SPARQL">
sparqlUpdate.setQuery(update_str)
PREFIX ns1: <http://example.org#>
sparqlUpdate.setMethod(POST)
sparqlUpdate.query()


DELETE{?s ns1:name ?o}
#To test, run the query in the above task, replacing the ask query with e.g. ns1:Deborah_Gore_Dean rdf:type ns1:IndictedPerson
INSERT{?s ns1:person ?o}
WHERE {?s ns1:name ?o}
</syntaxhighlight>


===Update the graph so all the investigated person and president nodes become the subjects in foaf:name triples with the corresponding strings===
# 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/>


<syntaxhighlight lang="SPARQL">
    INSERT{
PREFIX ns1: <http://example.org#>
        ?invest dc:title ?investString.
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    }
    WHERE{
        ?s ns1:investigation ?invest .
        BIND (replace(str(?invest), str(ns1:), "")  AS ?investString)
}"""


#Persons
sparqlUpdate.setQuery(update_str)
INSERT {?person foaf:name ?name}
sparqlUpdate.setMethod(POST)
WHERE {
sparqlUpdate.query()
      ?investigation ns1:person ?person .
      BIND(REPLACE(STR(?person), STR(ns1:), "") AS ?name)
}


#Presidents
#Same test as above, replace it with e.g. ns1:watergate dc:title "watergate"
INSERT {?president foaf:name ?name}
WHERE {
      ?investigation ns1:president ?president .
      BIND(REPLACE(STR(?president), STR(ns1:), "") AS ?name)
}
</syntaxhighlight>


===Use INSERT DATA updates to add these triples===
# 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/>


<syntaxhighlight lang="SPARQL">
    SELECT ?name
PREFIX ns1: <http://example.org#>
    WHERE{
    ?s  ns1:name ?name;
            ns1:outcome ns1:indictment.
    }
    ORDER BY ?name
""")


INSERT DATA {
sparql.setReturnFormat(JSON)
    ns1:George_Papadopoulos ns1:adviserTo ns1:Donald_Trump;
results = sparql.query().convert()
        ns1:pleadGuiltyTo ns1:LyingToFBI;
        ns1:sentencedTo ns1:Prison.


    ns1:Roger_Stone a ns1:Republican;
names = []
        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
for result in results["results"]["bindings"]:
SELECT ?p ?o
    names.append(result["name"]["value"])
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===
print(names)


<syntaxhighlight lang="SPARQL">
# Print out the minimum, average and maximum indictment days for all the indictments in the graph.
PREFIX ns1: <http://example.org#>


DELETE DATA {
sparql.setQuery("""
      ns1:Roger_Stone ns1:clearedOf ns1:AllCharges .
    prefix xsd: <http://www.w3.org/2001/XMLSchema#>
}
    PREFIX ns1: <http://example.org#>


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


#The task specifically requested DELETE DATA & INSERT DATA, put below is
sparql.setReturnFormat(JSON)
a more efficient solution
results = sparql.query().convert()


DELETE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
for result in results["results"]["bindings"]:
INSERT{
    print(f'The longest an investigation lasted was: {result["max"]["value"]}')
  ns1:Roger_Stone ns1:indictedFor ns1:ObstructionOfJustice,
    print(f'The shortest an investigation lasted was: {result["min"]["value"]}')
                                  ns1:WitnessTampering,
    print(f'The average investigation lasted: {result["avg"]["value"]}')
                                  ns1:FalseStatements.
}
WHERE{ns1:Roger_Stone ns1:clearedOf ns1:AllCharges.}
</syntaxhighlight>


===Use a DESCRIBE query to show the updated information about Roger Stone===
# Print out the minimum, average and maximum indictment days for all the indictments in the graph per investigation.


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


DESCRIBE ?o
    SELECT ?investigation (AVG(?daysRemoved) as ?avg) (MAX(?daysRemoved) as ?max) (MIN(?daysRemoved) as ?min)  WHERE{
WHERE {ns1:Roger_Stone ns1:indictedFor ?o .}
    ?s  ns1:indictment_days ?days;
</syntaxhighlight>
        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
""")


===Use a CONSTRUCT query to create a new RDF group with triples only about Roger Stone===
sparql.setReturnFormat(JSON)
results = sparql.query().convert()


<syntaxhighlight lang="SPARQL">
for result in results["results"]["bindings"]:
PREFIX ns1: <http://example.org#>
    print(f'{result["investigation"]["value"]} - min: {result["min"]["value"]}, max: {result["max"]["value"]}, avg: {result["avg"]["value"]}')


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


===Write a DELETE/INSERT statement to change one of the prefixes in your graph===
== 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


<syntaxhighlight lang="SPARQL">
CN_BASE = 'http://api.conceptnet.io/c/en/'
PREFIX ns1: <http://example.org#>
PREFIX dbp: <https://dbpedia.org/page/>


DELETE {?s ns1:person ?o1}
g = rdflib.Graph()
INSERT {?s ns1:person ?o2}
g.parse(CN_BASE+'indictment', format='json-ld')
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
# To download JSON object:
predicate. It changes it's prefix of ns1 (which is the
"shortcut/shorthand" for example.org) to the prefix dbp (dbpedia.org)
</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. ===
import json
import requests


<syntaxhighlight lang="SPARQL">
json_obj = requests.get(CN_BASE+'indictment').json()
#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#>
# To change the @context:
PREFIX ns1: <http://example.org#>


DELETE {?s ns1:cp_date ?o}
context = {
INSERT{?s ns1:cp_date ?o3}
    "@base": "http://ex.org/",
WHERE{
    "edges": "http://ex.org/triple/",
  ?s ns1:cp_date ?o .
    "start": "http://ex.org/s/",
  BIND (replace(str(?o), str(ns1:), "")  AS ?o2)
    "rel": "http://ex.org/p/",
  BIND (STRDT(STR(?o2), xsd:date) AS ?o3)
    "end": "http://ex.org/o/",
    "label": "http://ex.org/label"
}
}
json_obj['@context'] = context
json_str = json.dumps(json_obj)


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


PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
# To extract triples (here with labels):
PREFIX ns1: <http://example.org#>


SELECT ?s ?o
r = g.query("""
WHERE{
        SELECT ?s ?sLabel ?p ?o ?oLabel WHERE {
  ?s ns1:cp_date ?o.
            ?edge
  FILTER(datatype(?o) = xsd:date)
                <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())


#To change it to an integer, use the following code, and to change it
# Construct a new graph:
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}
r = g.query("""
INSERT{?s ns1:cp_date ?o2}
        CONSTRUCT {
WHERE{
            ?s ?p ?o .
  ?s ns1:cp_date ?o .
            ?s <http://ex.org/label> ?sLabel .
  BIND (STRDT(STR(?o), xsd:integer) AS ?o2)
            ?o <http://ex.org/label> ?oLabel .
        } WHERE {
            ?edge <http://ex.org/s/> ?s ;
                  <http://ex.org/p/> ?p ;
                  <http://ex.org/o/> ?o .
            ?s <http://ex.org/label> ?sLabel .
            ?o <http://ex.org/label> ?oLabel .
}
}
        """, initNs={'cn': CN_BASE})


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

Latest revision as of 09:55, 10 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'))