sparql_example_queries.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from rdflib import Graph, Namespace, RDF
  2. from rdflib.plugins.sparql import prepareQuery
  3. resource = "./python-odml/doc/example_rdfs/example_data/2010-04-16-ab_cutoff_300_contrast_20%.ttl"
  4. g = Graph()
  5. g.parse(resource, format='turtle')
  6. # select d.* from dataset d, stimulus s where s.contrast = '20%'
  7. q1 = prepareQuery("""SELECT *
  8. WHERE {
  9. ?d rdf:type odml:Document .
  10. ?d odml:hasSection ?s .
  11. ?s rdf:type odml:Section .
  12. ?s odml:hasName "Stimulus" .
  13. ?s odml:hasProperty ?p .
  14. ?p odml:hasName "Contrast" .
  15. ?p odml:hasValue ?v .
  16. ?p odml:hasUnit "%" .
  17. ?v rdf:type rdf:Bag .
  18. ?v rdf:li "20.0" .
  19. }""", initNs={"odml": Namespace("https://g-node.org/projects/odml-rdf#"),
  20. "rdf": RDF})
  21. g = Graph()
  22. g.parse(resource, format='turtle')
  23. # select d.* from dataset d, stimulus s, cell c where s.contrast = '20%' and c.celltype='P-unit'
  24. q2 = prepareQuery("""SELECT *
  25. WHERE {
  26. ?d rdf:type odml:Document .
  27. ?d odml:hasSection ?s .
  28. ?s rdf:type odml:Section .
  29. ?s odml:hasName "Stimulus" .
  30. ?s odml:hasProperty ?p .
  31. ?p odml:hasName "Contrast" .
  32. ?p odml:hasValue ?v .
  33. ?p odml:hasUnit "%" .
  34. ?v rdf:type rdf:Bag .
  35. ?v rdf:li "20.0" .
  36. ?d odml:hasSection ?s1 .
  37. ?s1 odml:hasName "Cell" .
  38. ?s1 odml:hasProperty ?p1 .
  39. ?p1 odml:hasName "CellType" .
  40. ?p1 odml:hasValue ?v1 .
  41. ?v1 rdf:li "P-unit" .
  42. }""", initNs={"odml": Namespace("https://g-node.org/projects/odml-rdf#"),
  43. "rdf": RDF})
  44. # select d.* from dataset d, CellProperties s, EOD Frequency c where c.unit = 'Hz'
  45. g = Graph()
  46. g.parse(resource, format='turtle')
  47. q3 = prepareQuery("""SELECT *
  48. WHERE {
  49. ?d rdf:type odml:Document .
  50. ?d odml:hasSection ?s .
  51. ?s rdf:type odml:CellProperties .
  52. ?s odml:hasProperty ?p .
  53. ?p odml:hasName "EOD Frequency" .
  54. ?p odml:hasValue ?v .
  55. ?p odml:hasUnit "Hz" .
  56. ?v rdf:type rdf:Bag .
  57. ?v rdf:li ?value .
  58. }""", initNs={"odml": Namespace("https://g-node.org/projects/odml-rdf#"),
  59. "rdf": RDF})
  60. print("q1")
  61. for row in g.query(q1):
  62. print("Doc: {0}, Sec: {1}, \n"
  63. "Prop: {2}, Bag: {3}".format(row.d, row.s, row.p, row.v))
  64. print("q2")
  65. for row in g.query(q2):
  66. print("Doc: {0}, Sec: {1}, \n"
  67. "Prop: {2}, Bag: {3}".format(row.d, row.s, row.p, row.v))
  68. print("Doc: {0}, Sec: {1}, \n"
  69. "Prop: {2}, Bag: {3}".format(row.d, row.s1, row.p1, row.v1))
  70. print("q3")
  71. for row in g.query(q3):
  72. print("Doc: {0}, Sec: {1}, \n"
  73. "Prop: {2}, Bag: {3} \n"
  74. "Value: {4}".format(row.d, row.s, row.p, row.v, row.value))