1 """Common submission elements
9 from htsworkflow.util.rdfhelp import \
21 from htsworkflow.util.hashfile import make_md5sum
22 from htsworkflow.submission.fastqname import FastqName
23 from htsworkflow.submission.daf import \
24 MetadataLookupException, \
27 LOGGER = logging.getLogger(__name__)
29 class Submission(object):
30 def __init__(self, name, model, host):
34 self.submissionSet = get_submission_uri(self.name)
35 self.submissionSetNS = RDF.NS(str(self.submissionSet) + '#')
36 self.libraryNS = RDF.NS('{0}/library/'.format(host))
38 self.__view_map = None
40 def scan_submission_dirs(self, result_map):
41 """Examine files in our result directory
43 for lib_id, result_dir in result_map.items():
44 LOGGER.info("Importing %s from %s" % (lib_id, result_dir))
46 self.import_analysis_dir(result_dir, lib_id)
47 except MetadataLookupException, e:
48 LOGGER.error("Skipping %s: %s" % (lib_id, str(e)))
50 def import_analysis_dir(self, analysis_dir, library_id):
51 """Import a submission directories and update our model as needed
53 #attributes = get_filename_attribute_map(paired)
54 libNode = self.libraryNS[library_id + "/"]
56 self._add_library_details_to_model(libNode)
58 submission_files = os.listdir(analysis_dir)
59 for filename in submission_files:
60 pathname = os.path.abspath(os.path.join(analysis_dir, filename))
61 self.construct_file_attributes(analysis_dir, libNode, pathname)
63 def construct_file_attributes(self, analysis_dir, libNode, pathname):
64 """Looking for the best extension
65 The 'best' is the longest match
68 filename (str): the filename whose extention we are about to examine
70 path, filename = os.path.split(pathname)
72 LOGGER.debug("Searching for view")
73 file_type = self.find_best_match(filename)
75 LOGGER.warn("Unrecognized file: {0}".format(pathname))
77 if str(file_type) == str(libraryOntology['ignore']):
80 an_analysis_name = self.make_submission_name(analysis_dir)
81 an_analysis = self.get_submission_node(analysis_dir)
82 an_analysis_uri = str(an_analysis.uri)
83 file_classification = self.model.get_target(file_type,
85 if file_classification is None:
86 errmsg = 'Could not find class for {0}'
87 LOGGER.warning(errmsg.format(str(file_type)))
90 self.model.add_statement(
91 RDF.Statement(self.submissionSetNS[''],
92 submissionOntology['has_submission'],
94 self.model.add_statement(RDF.Statement(an_analysis,
95 submissionOntology['name'],
96 toTypedNode(an_analysis_name)))
97 self.model.add_statement(
98 RDF.Statement(an_analysis,
100 submissionOntology['submission']))
101 self.model.add_statement(RDF.Statement(an_analysis,
102 submissionOntology['library'],
105 LOGGER.debug("Adding statements to {0}".format(str(an_analysis)))
106 # add track specific information
107 self.model.add_statement(
108 RDF.Statement(an_analysis,
109 dafTermOntology['paired'],
110 toTypedNode(self._is_paired(libNode))))
111 self.model.add_statement(
112 RDF.Statement(an_analysis,
113 dafTermOntology['submission'],
116 # add file specific information
117 fileNode = self.make_file_node(pathname, an_analysis)
118 self.add_md5s(filename, fileNode, analysis_dir)
119 self.add_fastq_metadata(filename, fileNode)
120 self.model.add_statement(
121 RDF.Statement(fileNode,
124 LOGGER.debug("Done.")
126 def make_file_node(self, pathname, submissionNode):
127 """Create file node and attach it to its submission.
129 # add file specific information
130 path, filename = os.path.split(pathname)
131 fileNode = RDF.Node(RDF.Uri('file://'+ os.path.abspath(pathname)))
132 self.model.add_statement(
133 RDF.Statement(submissionNode,
134 dafTermOntology['has_file'],
136 self.model.add_statement(
137 RDF.Statement(fileNode,
138 dafTermOntology['filename'],
142 def add_md5s(self, filename, fileNode, analysis_dir):
143 LOGGER.debug("Updating file md5sum")
144 submission_pathname = os.path.join(analysis_dir, filename)
145 md5 = make_md5sum(submission_pathname)
147 errmsg = "Unable to produce md5sum for {0}"
148 LOGGER.warning(errmsg.format(submission_pathname))
150 self.model.add_statement(
151 RDF.Statement(fileNode, dafTermOntology['md5sum'], md5))
153 def add_fastq_metadata(self, filename, fileNode):
154 # How should I detect if this is actually a fastq file?
156 fqname = FastqName(filename=filename)
158 # currently its just ignore it if the fastq name parser fails
161 terms = [('flowcell', libraryOntology['flowcell_id']),
162 ('lib_id', libraryOntology['library_id']),
163 ('lane', libraryOntology['lane_number']),
164 ('read', libraryOntology['read']),
165 ('cycle', libraryOntology['read_length'])]
166 for file_term, model_term in terms:
167 value = fqname.get(file_term)
168 if value is not None:
169 s = RDF.Statement(fileNode, model_term, toTypedNode(value))
172 def _add_library_details_to_model(self, libNode):
173 # attributes that can have multiple values
174 set_attributes = set((libraryOntology['has_lane'],
175 libraryOntology['has_mappings'],
176 dafTermOntology['has_file']))
177 parser = RDF.Parser(name='rdfa')
178 new_statements = parser.parse_as_stream(libNode.uri)
180 for s in new_statements:
181 # always add "collections"
182 if s.predicate in set_attributes:
185 # don't override things we already have in the model
186 targets = list(self.model.get_targets(s.subject, s.predicate))
187 if len(targets) == 0:
193 self._add_lane_details(libNode)
195 def _add_lane_details(self, libNode):
196 """Import lane details
198 query = RDF.Statement(libNode, libraryOntology['has_lane'], None)
200 for lane_stmt in self.model.find_statements(query):
201 lanes.append(lane_stmt.object)
203 parser = RDF.Parser(name='rdfa')
205 LOGGER.debug("Importing %s" % (lane.uri,))
207 parser.parse_into_model(self.model, lane.uri)
208 except RDF.RedlandError, e:
209 LOGGER.error("Error accessing %s" % (lane.uri,))
213 def find_best_match(self, filename):
214 """Search through potential filename matching patterns
216 if self.__view_map is None:
217 self.__view_map = self._get_filename_view_map()
220 for pattern, view in self.__view_map.items():
221 if re.match(pattern, filename):
225 msg = "%s matched multiple views %s" % (
227 [str(x) for x in results])
228 raise ModelException(msg)
229 elif len(results) == 1:
234 def _get_filename_view_map(self):
235 """Query our model for filename patterns
237 return a dictionary of compiled regular expressions to view names
239 filename_query = RDF.Statement(
240 None, dafTermOntology['filename_re'], None)
243 for s in self.model.find_statements(filename_query):
244 view_name = s.subject
245 literal_re = s.object.literal_value['string']
246 LOGGER.debug("Found: %s" % (literal_re,))
248 filename_re = re.compile(literal_re)
250 LOGGER.error("Unable to compile: %s" % (literal_re,))
251 patterns[literal_re] = view_name
254 def make_submission_name(self, analysis_dir):
255 analysis_dir = os.path.normpath(analysis_dir)
256 analysis_dir_name = os.path.split(analysis_dir)[1]
257 if len(analysis_dir_name) == 0:
259 "Submission dir name too short: {0}".format(analysis_dir))
260 return analysis_dir_name
262 def get_submission_node(self, analysis_dir):
263 """Convert a submission directory name to a submission node
265 submission_name = self.make_submission_name(analysis_dir)
266 return self.submissionSetNS[submission_name]
268 def _get_library_attribute(self, libNode, attribute):
269 if not isinstance(attribute, RDF.Node):
270 attribute = libraryOntology[attribute]
272 targets = list(self.model.get_targets(libNode, attribute))
274 return self._format_library_attribute(targets)
278 #targets = self._search_same_as(libNode, attribute)
279 #if targets is not None:
280 # return self._format_library_attribute(targets)
282 # we don't know anything about this attribute
283 self._add_library_details_to_model(libNode)
285 targets = list(self.model.get_targets(libNode, attribute))
287 return self._format_library_attribute(targets)
291 def _format_library_attribute(self, targets):
292 if len(targets) == 0:
294 elif len(targets) == 1:
295 return fromTypedNode(targets[0])
296 elif len(targets) > 1:
297 return [fromTypedNode(t) for t in targets]
299 def _is_paired(self, libNode):
300 """Determine if a library is paired end"""
301 library_type = self._get_library_attribute(libNode, 'library_type')
302 if library_type is None:
303 errmsg = "%s doesn't have a library type"
304 raise ModelException(errmsg % (str(libNode),))
306 single = ['CSHL (lacking last nt)',
307 'Single End (non-multiplexed)',
308 'Small RNA (non-multiplexed)',]
309 paired = ['Barcoded Illumina',
312 'Paired End (non-multiplexed)',]
313 if library_type in single:
315 elif library_type in paired:
318 raise MetadataLookupException(
319 "Unrecognized library type %s for %s" % \
320 (library_type, str(libNode)))
322 def execute_query(self, template, context):
323 """Execute the query, returning the results
325 formatted_query = template.render(context)
326 LOGGER.debug(formatted_query)
327 query = RDF.SPARQLQuery(str(formatted_query))
328 rdfstream = query.execute(self.model)
330 for record in rdfstream:
332 for key, value in record.items():
333 d[key] = fromTypedNode(value)