77a1b68e4db763ab83eb50135f9613e8264ce973
[htsworkflow.git] / htsworkflow / submission / submission.py
1 """Common submission elements
2 """
3 import logging
4 import os
5 import re
6
7 import RDF
8
9 from htsworkflow.util.rdfhelp import \
10      blankOrUri, \
11      dafTermOntology, \
12      dump_model, \
13      get_model, \
14      libraryOntology, \
15      owlNS, \
16      rdfNS, \
17      submissionLog, \
18      submissionOntology, \
19      toTypedNode, \
20      fromTypedNode
21 from htsworkflow.util.hashfile import make_md5sum
22 from htsworkflow.submission.fastqname import FastqName
23 from htsworkflow.submission.daf import \
24      MetadataLookupException, \
25      ModelException, \
26      get_submission_uri
27
28 LOGGER = logging.getLogger(__name__)
29
30 class Submission(object):
31     def __init__(self, name, model, host):
32         self.name = name
33         self.model = model
34
35         self.submissionSet = get_submission_uri(self.name)
36         self.submissionSetNS = RDF.NS(str(self.submissionSet) + '#')
37         self.libraryNS = RDF.NS('{0}/library/'.format(host))
38
39         self.__view_map = None
40
41     def scan_submission_dirs(self, result_map):
42         """Examine files in our result directory
43         """
44         for lib_id, result_dir in result_map.items():
45             LOGGER.info("Importing %s from %s" % (lib_id, result_dir))
46             try:
47                 self.import_analysis_dir(result_dir, lib_id)
48             except MetadataLookupException, e:
49                 LOGGER.error("Skipping %s: %s" % (lib_id, str(e)))
50
51     def import_analysis_dir(self, analysis_dir, library_id):
52         """Import a submission directories and update our model as needed
53         """
54         #attributes = get_filename_attribute_map(paired)
55         libNode = self.libraryNS[library_id + "/"]
56
57         self._add_library_details_to_model(libNode)
58
59         submission_files = os.listdir(analysis_dir)
60         for filename in submission_files:
61             pathname = os.path.abspath(os.path.join(analysis_dir, filename))
62             self.construct_file_attributes(analysis_dir, libNode, pathname)
63
64     def construct_file_attributes(self, analysis_dir, libNode, pathname):
65         """Looking for the best extension
66         The 'best' is the longest match
67
68         :Args:
69         filename (str): the filename whose extention we are about to examine
70         """
71         path, filename = os.path.split(pathname)
72
73         LOGGER.debug("Searching for view")
74         file_type = self.find_best_match(filename)
75         if file_type is None:
76             LOGGER.warn("Unrecognized file: {0}".format(pathname))
77             return None
78         if str(file_type) == str(libraryOntology['ignore']):
79             return None
80
81         an_analysis_name = self.make_submission_name(analysis_dir)
82         an_analysis = self.get_submission_node(analysis_dir)
83         an_analysis_uri = str(an_analysis.uri)
84         file_classification = self.model.get_target(file_type,
85                                                     rdfNS['type'])
86         if file_classification is None:
87             errmsg = 'Could not find class for {0}'
88             LOGGER.warning(errmsg.format(str(file_type)))
89             return
90
91         self.model.add_statement(
92             RDF.Statement(self.submissionSetNS[''],
93                           submissionOntology['has_submission'],
94                           an_analysis))
95         self.model.add_statement(RDF.Statement(an_analysis,
96                                                submissionOntology['name'],
97                                                toTypedNode(an_analysis_name)))
98         self.model.add_statement(
99             RDF.Statement(an_analysis,
100                           rdfNS['type'],
101                           submissionOntology['submission']))
102         self.model.add_statement(RDF.Statement(an_analysis,
103                                                submissionOntology['library'],
104                                                libNode))
105
106         LOGGER.debug("Adding statements to {0}".format(str(an_analysis)))
107         # add track specific information
108         self.model.add_statement(
109             RDF.Statement(an_analysis,
110                           dafTermOntology['paired'],
111                           toTypedNode(self._is_paired(libNode))))
112         self.model.add_statement(
113             RDF.Statement(an_analysis,
114                           dafTermOntology['submission'],
115                           an_analysis))
116
117         # add file specific information
118         fileNode = self.make_file_node(pathname, an_analysis)
119         self.add_md5s(filename, fileNode, analysis_dir)
120         self.add_fastq_metadata(filename, fileNode)
121         self.model.add_statement(
122             RDF.Statement(fileNode,
123                           rdfNS['type'],
124                           file_type))
125         LOGGER.debug("Done.")
126
127     def make_file_node(self, pathname, submissionNode):
128         """Create file node and attach it to its submission.
129         """
130         # add file specific information
131         path, filename = os.path.split(pathname)
132         fileNode = RDF.Node(RDF.Uri('file://'+ os.path.abspath(pathname)))
133         self.model.add_statement(
134             RDF.Statement(submissionNode,
135                           dafTermOntology['has_file'],
136                           fileNode))
137         self.model.add_statement(
138             RDF.Statement(fileNode,
139                           dafTermOntology['filename'],
140                           filename))
141         return fileNode
142
143     def add_md5s(self, filename, fileNode, analysis_dir):
144         LOGGER.debug("Updating file md5sum")
145         submission_pathname = os.path.join(analysis_dir, filename)
146         md5 = make_md5sum(submission_pathname)
147         if md5 is None:
148             errmsg = "Unable to produce md5sum for {0}"
149             LOGGER.warning(errmsg.format(submission_pathname))
150         else:
151             self.model.add_statement(
152                 RDF.Statement(fileNode, dafTermOntology['md5sum'], md5))
153
154     def add_fastq_metadata(self, filename, fileNode):
155         # How should I detect if this is actually a fastq file?
156         try:
157             fqname = FastqName(filename=filename)
158         except ValueError:
159             # currently its just ignore it if the fastq name parser fails
160             return
161         
162         terms = [('flowcell', libraryOntology['flowcell_id']),
163                  ('lib_id', libraryOntology['library_id']),
164                  ('lane', libraryOntology['lane_number']),
165                  ('read', libraryOntology['read']),
166                  ('cycle', libraryOntology['read_length'])]
167         for file_term, model_term in terms:
168             value = fqname.get(file_term)
169             if value is not None:
170                 s = RDF.Statement(fileNode, model_term, toTypedNode(value))
171                 self.model.append(s)
172
173     def _add_library_details_to_model(self, libNode):
174         # attributes that can have multiple values
175         set_attributes = set((libraryOntology['has_lane'],
176                               libraryOntology['has_mappings'],
177                               dafTermOntology['has_file']))
178         parser = RDF.Parser(name='rdfa')
179         new_statements = parser.parse_as_stream(libNode.uri)
180         toadd = []
181         for s in new_statements:
182             # always add "collections"
183             if s.predicate in set_attributes:
184                 toadd.append(s)
185                 continue
186             # don't override things we already have in the model
187             targets = list(self.model.get_targets(s.subject, s.predicate))
188             if len(targets) == 0:
189                 toadd.append(s)
190
191         for s in toadd:
192             self.model.append(s)
193
194         self._add_lane_details(libNode)
195
196     def _add_lane_details(self, libNode):
197         """Import lane details
198         """
199         query = RDF.Statement(libNode, libraryOntology['has_lane'], None)
200         lanes = []
201         for lane_stmt in self.model.find_statements(query):
202             lanes.append(lane_stmt.object)
203
204         parser = RDF.Parser(name='rdfa')
205         for lane in lanes:
206             LOGGER.debug("Importing %s" % (lane.uri,))
207             try:
208                 parser.parse_into_model(self.model, lane.uri)
209             except RDF.RedlandError, e:
210                 LOGGER.error("Error accessing %s" % (lane.uri,))
211                 raise e
212
213
214     def find_best_match(self, filename):
215         """Search through potential filename matching patterns
216         """
217         if self.__view_map is None:
218             self.__view_map = self._get_filename_view_map()
219
220         results = []
221         for pattern, view in self.__view_map.items():
222             if re.match(pattern, filename):
223                 results.append(view)
224
225         if len(results) > 1:
226             msg = "%s matched multiple views %s" % (
227                 filename,
228                 [str(x) for x in results])
229             raise ModelException(msg)
230         elif len(results) == 1:
231             return results[0]
232         else:
233             return None
234
235     def _get_filename_view_map(self):
236         """Query our model for filename patterns
237
238         return a dictionary of compiled regular expressions to view names
239         """
240         filename_query = RDF.Statement(
241             None, dafTermOntology['filename_re'], None)
242
243         patterns = {}
244         for s in self.model.find_statements(filename_query):
245             view_name = s.subject
246             literal_re = s.object.literal_value['string']
247             LOGGER.debug("Found: %s" % (literal_re,))
248             try:
249                 filename_re = re.compile(literal_re)
250             except re.error, e:
251                 LOGGER.error("Unable to compile: %s" % (literal_re,))
252             patterns[literal_re] = view_name
253         return patterns
254
255     def make_submission_name(self, analysis_dir):
256         analysis_dir = os.path.normpath(analysis_dir)
257         analysis_dir_name = os.path.split(analysis_dir)[1]
258         if len(analysis_dir_name) == 0:
259             raise RuntimeError(
260                 "Submission dir name too short: {0}".format(analysis_dir))
261         return analysis_dir_name
262
263     def get_submission_node(self, analysis_dir):
264         """Convert a submission directory name to a submission node
265         """
266         submission_name = self.make_submission_name(analysis_dir)
267         return self.submissionSetNS[submission_name]
268
269     def _get_library_attribute(self, libNode, attribute):
270         if not isinstance(attribute, RDF.Node):
271             attribute = libraryOntology[attribute]
272
273         targets = list(self.model.get_targets(libNode, attribute))
274         if len(targets) > 0:
275             return self._format_library_attribute(targets)
276         else:
277             return None
278
279         #targets = self._search_same_as(libNode, attribute)
280         #if targets is not None:
281         #    return self._format_library_attribute(targets)
282
283         # we don't know anything about this attribute
284         self._add_library_details_to_model(libNode)
285
286         targets = list(self.model.get_targets(libNode, attribute))
287         if len(targets) > 0:
288             return self._format_library_attribute(targets)
289
290         return None
291
292     def _format_library_attribute(self, targets):
293         if len(targets) == 0:
294             return None
295         elif len(targets) == 1:
296             return fromTypedNode(targets[0])
297         elif len(targets) > 1:
298             return [fromTypedNode(t) for t in targets]
299
300     def _is_paired(self, libNode):
301         """Determine if a library is paired end"""
302         library_type = self._get_library_attribute(libNode, 'library_type')
303         if library_type is None:
304             errmsg = "%s doesn't have a library type"
305             raise ModelException(errmsg % (str(libNode),))
306
307         single = ['CSHL (lacking last nt)',
308                   'Single End (non-multiplexed)',
309                   'Small RNA (non-multiplexed)',]
310         paired = ['Barcoded Illumina',
311                   'Multiplexing',
312                   'Nextera',
313                   'Paired End (non-multiplexed)',]
314         if library_type in single:
315             return False
316         elif library_type in paired:
317             return True
318         else:
319             raise MetadataLookupException(
320                 "Unrecognized library type %s for %s" % \
321                 (library_type, str(libNode)))
322
323     def execute_query(self, template, context):
324         """Execute the query, returning the results
325         """
326         formatted_query = template.render(context)
327         LOGGER.debug(formatted_query)
328         query = RDF.SPARQLQuery(str(formatted_query))
329         rdfstream = query.execute(self.model)
330         results = []
331         for record in rdfstream:
332             d = {}
333             for key, value in record.items():
334                 d[key] = fromTypedNode(value)
335             results.append(d)
336         return results