comparison dml-cla/python/rdf_wrapper.py @ 0:718306e29690 tip

commiting public release
author Daniel Wolff
date Tue, 09 Feb 2016 21:05:06 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:718306e29690
1 # Part of DML (Digital Music Laboratory)
2 # Copyright 2014-2015 Steven Hargreaves
3
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
18 #!/usr/bin/env python
19 # -*- coding: utf-8 -*-
20 __author__="hargreavess"
21
22 import ConfigParser
23 import logging
24 import sys
25 import os
26 import time
27 import shutil
28 import argparse
29 from os import walk
30 import rdflib
31 from rdflib import Graph, Namespace, BNode, Literal, RDF, RDFS
32 from RDFClosure import DeductiveClosure, OWLRL_Semantics
33 import transforms.keyTonicHistogram
34 import transforms.tuningFrequencyStatistics
35 import transforms.semitoneHistogram
36 import math
37
38 cla = Namespace("http://dml.org/cla#")
39
40 def print_status(msg):
41 sys.stderr.write(msg+'\n')
42
43 def main():
44
45 # get config
46 # print_status("Reading configuration...")
47 # config = ConfigParser.ConfigParser()
48 # config.read('dml-analyser.cfg')
49
50 # parse dmlcla ontolgy and input graph
51 input_graph = Graph()
52 # print_status("Reading DML CLA ontology...")
53 # input_graph.parse(config.get('Ontology', 'dmlclaOntology_URI'), format="n3")
54 # print_status("Reading input triples...")
55 input_graph.parse(sys.stdin, format="n3")
56 # print_status("------")
57 # input_graph.serialize(destination=sys.stderr,format='n3')
58 # print_status("------")
59 # print_status("Forward chaining OWL entailments...")
60 # DeductiveClosure(OWLRL_Semantics).expand(input_graph)
61
62 # initialise output rdf graph
63 # bnode = BNode()
64 # print_status("Building output graph...")
65 output_graph = Graph()
66 output_graph.bind("dmlcla",cla)
67
68 for comp in input_graph.subjects(cla.function,None):
69 func= input_graph.value(comp, cla.function)
70 inp = input_graph.value(comp, cla.input)
71 print_status("Got computation %s: %s(%s)" % (comp,func,inp))
72 fn = eval(func)
73 output = fn(inp.value)
74 print_status("Result is %s" % output)
75 output_graph.set((comp,cla.output,Literal(output)))
76 # comps = input_graph.query(
77 # """prefix cla: <http://dml.org/cla#>
78 # SELECT ?comp ?function ?input
79 # WHERE {
80 # ?comp cla:function ?function .
81 # ?comp cla:input ?input
82 # }""")
83
84 # for row in comps:
85 # print_status("Got computation %s: %s(%s)" % (row.comp,row.function,row.input))
86 # fn = eval(row.function)
87 # output = fn(row.input)
88 # print_state("Result is %s" % output)
89
90
91 # # Determine which transforms are to be applied, and
92 # # the associated input files
93 # transforms = find_transforms_in_n3(input_graph)
94
95 # # Apply the transform(s) to each file and create
96 # # rdf results graph
97 # execute_transforms(transforms, output_graph)
98
99 # # Write output rdf to stdout
100 # print_status("Writing output triples...")
101 output_graph.serialize(destination=sys.stdout,format='n3')
102
103 # # Loop through all transforms, process the corresponding
104 # # input files appropriately and add the (RDF) result to output_graph
105 # def execute_transforms(transforms, output_graph):
106
107 # transform_iter = transforms.iterkeys()
108 # key_histogram = []
109
110 # for (transform, transform_type) in transforms:
111
112 # input_f_files = transforms.get((transform, transform_type))
113
114 # # Add additional clauses to this if statement
115 # # for each transform type
116 # if transform_type == rdflib.term.URIRef(u'http://dml.org/dml/cla#CollectionLevelKeyTonic'):
117
118 # transforms.keyTonicHistogram.run(transform,input_f_files, output_graph)
119
120 # elif transform_type == rdflib.term.URIRef(u'http://dml.org/dml/cla#CollectionLevelTuningFrequencyStatistics'):
121
122 # transforms.tuningFrequencyStatistics.run(transform,input_f_files, output_graph)
123
124 # elif transform_type == rdflib.term.URIRef(u'http://dml.org/dml/cla#CollectionLevelSemitone'):
125 # transforms.semitoneHistogram.run(transform, input_f_files, output_graph)
126
127
128 # # Find all transforms, and their associated input files,
129 # # from rdf_graph
130 # def find_transforms_in_n3(rdf_graph):
131
132 # q1 = rdf_graph.query(
133 # """prefix dml: <http://dml.org/dml/cla#>
134 # SELECT ?comp ?function
135 # WHERE {
136 # ?comp a dml:Computation .
137 # ?comp dml:function ?function .
138 # }""")
139
140 # for row in q1:
141
142 # inputs = rdf_graph.query(
143 # """prefix dml: <http://dml.org/dml/cla#>
144 # SELECT ?input
145 # WHERE {
146 # ?comp dml:input ?input .
147 # }""")
148
149 # computations = dict()
150
151 # for row in qres:
152
153 # comp = row.comp
154 # input = row.input
155 # transform_type = row.transform_type
156
157 # if transforms.has_key((transform_bnode, transform_type)):
158
159 # transform_key = transforms.get((transform_bnode, transform_type))
160 # transform_key.append(dml_input)
161
162 # else:
163
164 # transforms[(transform_bnode, transform_type)] = [dml_input]
165
166 # return transforms
167
168 # # Determine the mapping between feature file URIs and
169 # # their source audio file URIs
170 # def map_audio_to_feature_files():
171
172 # # Loop through audio files
173 # lines = [line.strip() for line in args.audio_files]
174
175 # for audio_file in lines:
176
177 # print "sonic-annotator -T " + args.transforms + " --rdf-basedir " + args.basedir + " <" + audio_file + ">"
178
179 # audio_to_feature_file_dict = dict()
180
181 # for (dirpath, dirnames, filenames) in walk(args.basedir):
182 # for file in filenames:
183
184 # print "found file: " + file
185
186 # if file.endswith(".n3"):
187
188 # print "found n3 file: " + file
189
190 # # open and parse n3 file
191 # rdf_graph = Graph()
192 # rdf_graph.parse(os.path.join(dirpath, file), format="n3")
193
194 # # find subject in ?subject a mo:AudioFile
195 # qres = rdf_graph.query(
196 # """SELECT ?audio_file
197 # WHERE {
198 # ?audio_file a mo:AudioFile .
199 # }""")
200
201 # print len(qres)
202
203 # for row in qres:
204
205 # print("audio file URI is %s" % row.audio_file.n3())
206 # print("feature file URI is %s" % os.path.join(os.getcwd(), dirpath, file))
207 # audio_to_feature_file_dict[row.audio_file.n3()] = os.path.join(os.getcwd(), dirpath, file)
208
209 # # add full file URI, subject to dict
210
211 # print audio_to_feature_file_dict
212
213 if __name__ == "__main__":
214
215 # parser = argparse.ArgumentParser()
216
217 # # parser.add_argument("-T", "--transforms", help="the URI of an n3 (RDF) file describing one or more transforms, and the files to which they should be applied")
218 # parser.add_argument("-b", "--basedir", help="the URI of the base output directory")
219
220 # args = parser.parse_args()
221
222 main()
223