0
|
1 #!/usr/bin/env python
|
|
2 # change to accumulating all configuration for config.json based on the default from the clone
|
|
3 import argparse
|
|
4 import datetime
|
|
5 import hashlib
|
|
6 import json
|
|
7 import logging
|
|
8 import os
|
|
9 import shutil
|
|
10 import subprocess
|
|
11 import tempfile
|
|
12 import xml.etree.ElementTree as ET
|
|
13 from collections import defaultdict
|
|
14
|
|
15 logging.basicConfig(level=logging.INFO)
|
|
16 log = logging.getLogger("jbrowse")
|
|
17 TODAY = datetime.datetime.now().strftime("%Y-%m-%d")
|
|
18 GALAXY_INFRASTRUCTURE_URL = None
|
|
19 mapped_chars = {
|
|
20 ">": "__gt__",
|
|
21 "<": "__lt__",
|
|
22 "'": "__sq__",
|
|
23 '"': "__dq__",
|
|
24 "[": "__ob__",
|
|
25 "]": "__cb__",
|
|
26 "{": "__oc__",
|
|
27 "}": "__cc__",
|
|
28 "@": "__at__",
|
|
29 "#": "__pd__",
|
|
30 "": "__cn__",
|
|
31 }
|
|
32
|
|
33
|
|
34 def etree_to_dict(t):
|
|
35 if t is None:
|
|
36 return {}
|
|
37
|
|
38 d = {t.tag: {} if t.attrib else None}
|
|
39 children = list(t)
|
|
40 if children:
|
|
41 dd = defaultdict(list)
|
|
42 for dc in map(etree_to_dict, children):
|
|
43 for k, v in dc.items():
|
|
44 dd[k].append(v)
|
|
45 d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}}
|
|
46 if t.attrib:
|
|
47 d[t.tag].update(("@" + k, v) for k, v in t.attrib.items())
|
|
48 if t.text:
|
|
49 text = t.text.strip()
|
|
50 if children or t.attrib:
|
|
51 if text:
|
|
52 d[t.tag]["#text"] = text
|
|
53 else:
|
|
54 d[t.tag] = text
|
|
55 return d
|
|
56
|
|
57
|
|
58 INSTALLED_TO = os.path.dirname(os.path.realpath(__file__))
|
|
59
|
|
60
|
|
61 def metadata_from_node(node):
|
|
62 metadata = {}
|
|
63 try:
|
|
64 if len(node.findall("dataset")) != 1:
|
|
65 # exit early
|
|
66 return metadata
|
|
67 except Exception:
|
|
68 return {}
|
|
69
|
|
70 for (key, value) in node.findall("dataset")[0].attrib.items():
|
|
71 metadata["dataset_%s" % key] = value
|
|
72
|
|
73 for (key, value) in node.findall("history")[0].attrib.items():
|
|
74 metadata["history_%s" % key] = value
|
|
75
|
|
76 for (key, value) in node.findall("metadata")[0].attrib.items():
|
|
77 metadata["metadata_%s" % key] = value
|
|
78
|
|
79 for (key, value) in node.findall("tool")[0].attrib.items():
|
|
80 metadata["tool_%s" % key] = value
|
|
81
|
|
82 # Additional Mappings applied:
|
|
83 metadata[
|
|
84 "dataset_edam_format"
|
|
85 ] = '<a target="_blank" href="http://edamontology.org/{0}">{1}</a>'.format(
|
|
86 metadata["dataset_edam_format"], metadata["dataset_file_ext"]
|
|
87 )
|
|
88 metadata["history_user_email"] = '<a href="mailto:{0}">{0}</a>'.format(
|
|
89 metadata["history_user_email"]
|
|
90 )
|
|
91 metadata["hist_name"] = metadata["history_display_name"]
|
|
92 metadata[
|
|
93 "history_display_name"
|
|
94 ] = '<a target="_blank" href="{galaxy}/history/view/{encoded_hist_id}">{hist_name}</a>'.format(
|
|
95 galaxy=GALAXY_INFRASTRUCTURE_URL,
|
|
96 encoded_hist_id=metadata["history_id"],
|
|
97 hist_name=metadata["history_display_name"],
|
|
98 )
|
|
99 metadata[
|
|
100 "tool_tool"
|
|
101 ] = '<a target="_blank" href="{galaxy}/datasets/{encoded_id}/show_params">{tool_id}</a>'.format(
|
|
102 galaxy=GALAXY_INFRASTRUCTURE_URL,
|
|
103 encoded_id=metadata["dataset_id"],
|
|
104 tool_id=metadata["tool_tool_id"],
|
|
105 # tool_version=metadata['tool_tool_version'],
|
|
106 )
|
|
107 return metadata
|
|
108
|
|
109
|
|
110 class JbrowseConnector(object):
|
10
|
111 def __init__(self, outdir, genomes):
|
0
|
112 self.debug = False
|
6
|
113 self.usejson = True
|
0
|
114 self.giURL = GALAXY_INFRASTRUCTURE_URL
|
|
115 self.outdir = outdir
|
|
116 os.makedirs(self.outdir, exist_ok=True)
|
|
117 self.genome_paths = genomes
|
|
118 self.trackIdlist = []
|
|
119 self.tracksToAdd = []
|
6
|
120 self.config_json = {}
|
10
|
121 self.config_json_file = os.path.join(outdir, "config.json")
|
|
122 self.clone_jbrowse(destination=self.outdir)
|
0
|
123
|
|
124 def subprocess_check_call(self, command, output=None):
|
|
125 if output:
|
|
126 if self.debug:
|
|
127 log.debug("cd %s && %s > %s", self.outdir, " ".join(command), output)
|
|
128 subprocess.check_call(command, cwd=self.outdir, stdout=output)
|
|
129 else:
|
|
130 log.debug("cd %s && %s", self.outdir, " ".join(command))
|
|
131 subprocess.check_call(command, cwd=self.outdir)
|
|
132
|
|
133 def subprocess_popen(self, command):
|
|
134 if self.debug:
|
10
|
135 log.debug(command)
|
0
|
136 p = subprocess.Popen(
|
|
137 command,
|
10
|
138 cwd=self.outdir,
|
0
|
139 shell=True,
|
|
140 stdin=subprocess.PIPE,
|
|
141 stdout=subprocess.PIPE,
|
|
142 stderr=subprocess.PIPE,
|
|
143 )
|
|
144 output, err = p.communicate()
|
|
145 retcode = p.returncode
|
|
146 if retcode != 0:
|
10
|
147 log.error(command)
|
0
|
148 log.error(output)
|
|
149 log.error(err)
|
|
150 raise RuntimeError("Command failed with exit code %s" % (retcode))
|
|
151
|
|
152 def subprocess_check_output(self, command):
|
|
153 if self.debug:
|
10
|
154 log.debug(" ".join(command))
|
0
|
155 return subprocess.check_output(command, cwd=self.outdir)
|
|
156
|
|
157 def symlink_or_copy(self, src, dest):
|
|
158 if "GALAXY_JBROWSE_SYMLINKS" in os.environ and bool(
|
|
159 os.environ["GALAXY_JBROWSE_SYMLINKS"]
|
|
160 ):
|
|
161 cmd = ["ln", "-s", src, dest]
|
|
162 else:
|
|
163 cmd = ["cp", src, dest]
|
|
164
|
|
165 return self.subprocess_check_call(cmd)
|
|
166
|
|
167 def process_genomes(self):
|
|
168 assemblies = []
|
|
169 for i, genome_node in enumerate(self.genome_paths):
|
6
|
170 if self.debug:
|
|
171 log.info("genome_node=%s" % str(genome_node))
|
9
|
172 genome_name = genome_node["meta"]["dataset_dname"].strip().split()[0]
|
5
|
173 fapath = genome_node["path"]
|
7
|
174 faname = genome_name + ".fa.gz"
|
10
|
175 fadest = os.path.join(self.outdir, faname)
|
|
176 # fadest = os.path.realpath(os.path.join(self.outdir, faname))
|
|
177 cmd = "bgzip -i -c %s -I %s.gzi > %s && samtools faidx %s" % (
|
7
|
178 fapath,
|
|
179 fadest,
|
10
|
180 fadest,
|
|
181 fadest,
|
7
|
182 )
|
10
|
183 if self.debug:
|
|
184 log.info("### cmd = %s" % cmd)
|
7
|
185 self.subprocess_popen(cmd)
|
|
186 adapter = {
|
|
187 "type": "BgzipFastaAdapter",
|
|
188 "fastaLocation": {
|
6
|
189 "uri": faname,
|
7
|
190 },
|
|
191 "faiLocation": {
|
|
192 "uri": faname + ".fai",
|
|
193 },
|
|
194 "gziLocation": {
|
|
195 "uri": faname + ".gzi",
|
|
196 },
|
|
197 }
|
0
|
198 trackDict = {
|
|
199 "name": genome_name,
|
|
200 "sequence": {
|
|
201 "type": "ReferenceSequenceTrack",
|
|
202 "trackId": genome_name,
|
6
|
203 "adapter": adapter,
|
0
|
204 },
|
6
|
205 "rendering": {"type": "DivSequenceRenderer"},
|
0
|
206 }
|
|
207 assemblies.append(trackDict)
|
|
208 self.genome_name = genome_name
|
6
|
209 if self.usejson:
|
|
210 self.config_json["assemblies"] = assemblies
|
|
211 else:
|
7
|
212 cmd = [
|
|
213 "jbrowse",
|
|
214 "add-assembly",
|
|
215 faname,
|
|
216 "-t",
|
|
217 "bgzipFasta",
|
|
218 "-n",
|
|
219 genome_name,
|
|
220 "--load",
|
|
221 "inPlace",
|
|
222 "--faiLocation",
|
|
223 faname + ".fai",
|
|
224 "--gziLocation",
|
|
225 faname + ".gzi",
|
|
226 "--target",
|
|
227 self.outdir,
|
|
228 ]
|
6
|
229 self.subprocess_check_call(cmd)
|
0
|
230
|
|
231 def add_default_view(self):
|
|
232 cmd = [
|
|
233 "jbrowse",
|
|
234 "set-default-session",
|
|
235 "-s",
|
|
236 self.config_json_file,
|
|
237 "-t",
|
|
238 ",".join(self.trackIdlist),
|
|
239 "-n",
|
6
|
240 "JBrowse2 in Galaxy",
|
0
|
241 "--target",
|
6
|
242 self.config_json_file,
|
|
243 "-v",
|
|
244 " LinearGenomeView",
|
|
245 ]
|
7
|
246 if self.debug:
|
6
|
247 log.info("### calling set-default-session with cmd=%s" % " ".join(cmd))
|
0
|
248 self.subprocess_check_call(cmd)
|
|
249
|
|
250 def write_config(self):
|
|
251 with open(self.config_json_file, "w") as fp:
|
|
252 json.dump(self.config_json, fp)
|
|
253
|
|
254 def add_hic(self, data, trackData):
|
|
255 """
|
|
256 HiC adapter.
|
|
257 https://github.com/aidenlab/hic-format/blob/master/HiCFormatV9.md
|
|
258 for testing locally, these work:
|
|
259 HiC data is from https://s3.amazonaws.com/igv.broadinstitute.org/data/hic/intra_nofrag_30.hic
|
|
260 using hg19 reference track as a
|
|
261 'BgzipFastaAdapter'
|
|
262 fastaLocation:
|
|
263 uri: 'https://s3.amazonaws.com/jbrowse.org/genomes/GRCh38/fasta/GRCh38.fa.gz',
|
|
264 faiLocation:
|
|
265 uri: 'https://s3.amazonaws.com/jbrowse.org/genomes/GRCh38/fasta/GRCh38.fa.gz.fai',
|
|
266 gziLocation:
|
|
267 uri: 'https://s3.amazonaws.com/jbrowse.org/genomes/GRCh38/fasta/GRCh38.fa.gz.gzi',
|
|
268 Cool will not be likely to be a good fit - see discussion at https://github.com/GMOD/jbrowse-components/issues/2438
|
|
269 """
|
|
270 log.info("#### trackData=%s" % trackData)
|
|
271 tId = trackData["label"]
|
5
|
272 dsId = trackData["metadata"]["dataset_id"]
|
0
|
273 url = "%s/api/datasets/%s/display?to_ext=hic " % (
|
|
274 self.giURL,
|
5
|
275 dsId,
|
0
|
276 )
|
5
|
277 hname = trackData["name"]
|
10
|
278 dest = os.path.join(self.outdir, hname)
|
7
|
279 url = hname
|
|
280 cmd = ["cp", data, dest]
|
|
281 self.subprocess_check_call(cmd)
|
|
282 floc = {
|
|
283 "uri": hname,
|
|
284 }
|
0
|
285 trackDict = {
|
|
286 "type": "HicTrack",
|
|
287 "trackId": tId,
|
5
|
288 "name": hname,
|
0
|
289 "assemblyNames": [self.genome_name],
|
|
290 "adapter": {
|
|
291 "type": "HicAdapter",
|
6
|
292 "hicLocation": floc,
|
0
|
293 },
|
|
294 }
|
6
|
295 if self.usejson:
|
|
296 self.tracksToAdd.append(trackDict)
|
|
297 self.trackIdlist.append(tId)
|
|
298 else:
|
|
299 cmd = [
|
|
300 "jbrowse",
|
|
301 "add-track",
|
|
302 url,
|
|
303 "-t",
|
|
304 "HicTrack",
|
|
305 "-a",
|
|
306 self.genome_name,
|
|
307 "-n",
|
|
308 hname,
|
|
309 "--load",
|
|
310 "inPlace",
|
|
311 "--target",
|
|
312 self.outdir,
|
|
313 ]
|
|
314 self.subprocess_check_call(cmd)
|
0
|
315
|
|
316 def add_maf(self, data, trackData):
|
|
317 """
|
|
318 from https://github.com/cmdcolin/maf2bed
|
|
319 Note: Both formats start with a MAF as input, and note that your MAF file should contain the species name and chromosome name
|
|
320 e.g. hg38.chr1 in the sequence identifiers.
|
|
321 need the reference id - eg hg18, for maf2bed.pl as the first parameter
|
|
322 """
|
|
323 mafPlugin = {
|
|
324 "plugins": [
|
|
325 {
|
|
326 "name": "MafViewer",
|
|
327 "url": "https://unpkg.com/jbrowse-plugin-mafviewer/dist/jbrowse-plugin-mafviewer.umd.production.min.js",
|
|
328 }
|
|
329 ]
|
|
330 }
|
|
331 tId = trackData["label"]
|
|
332 fname = "%s.bed" % tId
|
10
|
333 dest = "%s/%s" % (self.outdir, fname)
|
0
|
334 # self.symlink_or_copy(data, dest)
|
|
335 # Process MAF to bed-like. Need build to munge chromosomes
|
|
336 gname = self.genome_name
|
|
337 cmd = [
|
|
338 "bash",
|
|
339 os.path.join(INSTALLED_TO, "convertMAF.sh"),
|
|
340 data,
|
|
341 gname,
|
|
342 INSTALLED_TO,
|
|
343 dest,
|
|
344 ]
|
|
345 self.subprocess_check_call(cmd)
|
|
346 if True or self.debug:
|
|
347 log.info("### convertMAF.sh called as %s" % " ".join(cmd))
|
|
348 # Construct samples list
|
|
349 # We could get this from galaxy metadata, not sure how easily.
|
|
350 ps = subprocess.Popen(["grep", "^s [^ ]*", "-o", data], stdout=subprocess.PIPE)
|
|
351 output = subprocess.check_output(("sort", "-u"), stdin=ps.stdout)
|
|
352 ps.wait()
|
|
353 outp = output.decode("ascii")
|
|
354 soutp = outp.split("\n")
|
|
355 samp = [x.split("s ")[1] for x in soutp if x.startswith("s ")]
|
|
356 samples = [x.split(".")[0] for x in samp]
|
|
357 if self.debug:
|
|
358 log.info("### got samples = %s " % (samples))
|
|
359 trackDict = {
|
|
360 "type": "MafTrack",
|
|
361 "trackId": tId,
|
|
362 "name": trackData["name"],
|
|
363 "adapter": {
|
|
364 "type": "MafTabixAdapter",
|
|
365 "samples": samples,
|
6
|
366 "bedGzLocation": {
|
|
367 "uri": fname + ".sorted.bed.gz",
|
|
368 },
|
0
|
369 "index": {
|
6
|
370 "location": {
|
|
371 "uri": fname + ".sorted.bed.gz.tbi",
|
|
372 },
|
0
|
373 },
|
|
374 },
|
|
375 "assemblyNames": [self.genome_name],
|
|
376 }
|
|
377 self.tracksToAdd.append(trackDict)
|
|
378 self.trackIdlist.append(tId)
|
|
379 if self.config_json.get("plugins", None):
|
|
380 self.config_json["plugins"].append(mafPlugin[0])
|
|
381 else:
|
|
382 self.config_json.update(mafPlugin)
|
|
383
|
|
384 def _blastxml_to_gff3(self, xml, min_gap=10):
|
|
385 gff3_unrebased = tempfile.NamedTemporaryFile(delete=False)
|
|
386 cmd = [
|
|
387 "python",
|
|
388 os.path.join(INSTALLED_TO, "blastxml_to_gapped_gff3.py"),
|
|
389 "--trim",
|
|
390 "--trim_end",
|
|
391 "--include_seq",
|
|
392 "--min_gap",
|
|
393 str(min_gap),
|
|
394 xml,
|
|
395 ]
|
|
396 subprocess.check_call(cmd, cwd=self.outdir, stdout=gff3_unrebased)
|
|
397 gff3_unrebased.close()
|
|
398 return gff3_unrebased.name
|
|
399
|
|
400 def add_blastxml(self, data, trackData, blastOpts, **kwargs):
|
|
401 gff3 = self._blastxml_to_gff3(data, min_gap=blastOpts["min_gap"])
|
|
402
|
|
403 if "parent" in blastOpts and blastOpts["parent"] != "None":
|
|
404 gff3_rebased = tempfile.NamedTemporaryFile(delete=False)
|
|
405 cmd = ["python", os.path.join(INSTALLED_TO, "gff3_rebase.py")]
|
|
406 if blastOpts.get("protein", "false") == "true":
|
|
407 cmd.append("--protein2dna")
|
|
408 cmd.extend([os.path.realpath(blastOpts["parent"]), gff3])
|
|
409 subprocess.check_call(cmd, cwd=self.outdir, stdout=gff3_rebased)
|
|
410 gff3_rebased.close()
|
|
411
|
|
412 # Replace original gff3 file
|
|
413 shutil.copy(gff3_rebased.name, gff3)
|
|
414 os.unlink(gff3_rebased.name)
|
|
415 url = "%s.gff3" % trackData["label"]
|
10
|
416 dest = "%s/%s" % (self.outdir, url)
|
0
|
417 self._sort_gff(gff3, dest)
|
|
418 url = url + ".gz"
|
|
419 tId = trackData["label"]
|
|
420 trackDict = {
|
|
421 "type": "FeatureTrack",
|
|
422 "trackId": tId,
|
|
423 "name": trackData["name"],
|
|
424 "assemblyNames": [self.genome_name],
|
|
425 "adapter": {
|
|
426 "type": "Gff3TabixAdapter",
|
6
|
427 "gffGzLocation": {
|
|
428 "uri": url,
|
|
429 },
|
0
|
430 "index": {
|
6
|
431 "location": {
|
|
432 "uri": url + ".tbi",
|
|
433 }
|
0
|
434 },
|
|
435 },
|
|
436 "displays": [
|
|
437 {
|
|
438 "type": "LinearBasicDisplay",
|
|
439 "displayId": "%s-LinearBasicDisplay" % tId,
|
|
440 },
|
|
441 {"type": "LinearArcDisplay", "displayId": "%s-LinearArcDisplay" % tId},
|
|
442 ],
|
|
443 }
|
6
|
444 if self.usejson:
|
|
445 self.tracksToAdd.append(trackDict)
|
|
446 self.trackIdlist.append(tId)
|
|
447 else:
|
|
448 cmd = [
|
|
449 "jbrowse",
|
|
450 "add-track",
|
|
451 url,
|
|
452 "-t",
|
|
453 "FeatureTrack",
|
|
454 "-a",
|
|
455 self.genome_name,
|
|
456 "--indexFile",
|
|
457 url + ".tbi",
|
|
458 "-n",
|
|
459 trackData["name"],
|
|
460 "--load",
|
|
461 "inPlace",
|
|
462 "--target",
|
|
463 self.outdir,
|
|
464 ]
|
|
465 self.subprocess_check_call(cmd)
|
0
|
466 os.unlink(gff3)
|
|
467
|
|
468 def add_bigwig(self, data, trackData):
|
6
|
469 url = "%s.bw" % trackData["name"]
|
10
|
470 dest = os.path.join(self.outdir, url)
|
7
|
471 cmd = ["cp", data, dest]
|
|
472 self.subprocess_check_call(cmd)
|
|
473 bwloc = {"uri": url}
|
0
|
474 tId = trackData["label"]
|
|
475 trackDict = {
|
|
476 "type": "QuantitativeTrack",
|
|
477 "trackId": tId,
|
6
|
478 "name": url,
|
0
|
479 "assemblyNames": [
|
|
480 self.genome_name,
|
|
481 ],
|
|
482 "adapter": {
|
|
483 "type": "BigWigAdapter",
|
6
|
484 "bigWigLocation": bwloc,
|
0
|
485 },
|
|
486 "displays": [
|
|
487 {
|
|
488 "type": "LinearWiggleDisplay",
|
|
489 "displayId": "%s-LinearWiggleDisplay" % tId,
|
|
490 }
|
|
491 ],
|
|
492 }
|
6
|
493 if self.usejson:
|
|
494 self.tracksToAdd.append(trackDict)
|
|
495 self.trackIdlist.append(tId)
|
|
496 else:
|
|
497 cmd = [
|
|
498 "jbrowse",
|
|
499 "add-track",
|
|
500 url,
|
|
501 "-t",
|
|
502 "QuantitativeTrack",
|
|
503 "-a",
|
|
504 self.genome_name,
|
|
505 "-n",
|
|
506 trackData["name"],
|
|
507 "--load",
|
|
508 "inPlace",
|
|
509 "--target",
|
|
510 self.outdir,
|
|
511 ]
|
|
512 self.subprocess_check_call(cmd)
|
0
|
513
|
|
514 def add_bam(self, data, trackData, bamOpts, bam_index=None, **kwargs):
|
|
515 tId = trackData["label"]
|
5
|
516 fname = "%s.bam" % trackData["label"]
|
10
|
517 dest = "%s/%s" % (self.outdir, fname)
|
7
|
518 url = fname
|
|
519 self.subprocess_check_call(["cp", data, dest])
|
|
520 log.info("### copied %s to %s" % (data, dest))
|
|
521 bloc = {"uri": url}
|
0
|
522 if bam_index is not None and os.path.exists(os.path.realpath(bam_index)):
|
|
523 # bai most probably made by galaxy and stored in galaxy dirs, need to copy it to dest
|
|
524 self.subprocess_check_call(
|
|
525 ["cp", os.path.realpath(bam_index), dest + ".bai"]
|
|
526 )
|
|
527 else:
|
|
528 # Can happen in exotic condition
|
|
529 # e.g. if bam imported as symlink with datatype=unsorted.bam, then datatype changed to bam
|
|
530 # => no index generated by galaxy, but there might be one next to the symlink target
|
|
531 # this trick allows to skip the bam sorting made by galaxy if already done outside
|
|
532 if os.path.exists(os.path.realpath(data) + ".bai"):
|
|
533 self.symlink_or_copy(os.path.realpath(data) + ".bai", dest + ".bai")
|
|
534 else:
|
|
535 log.warn("Could not find a bam index (.bai file) for %s", data)
|
|
536 trackDict = {
|
|
537 "type": "AlignmentsTrack",
|
|
538 "trackId": tId,
|
|
539 "name": trackData["name"],
|
|
540 "assemblyNames": [self.genome_name],
|
|
541 "adapter": {
|
|
542 "type": "BamAdapter",
|
6
|
543 "bamLocation": bloc,
|
0
|
544 "index": {
|
6
|
545 "location": {
|
|
546 "uri": fname + ".bai",
|
|
547 }
|
0
|
548 },
|
|
549 },
|
|
550 }
|
6
|
551 if self.usejson:
|
|
552 self.tracksToAdd.append(trackDict)
|
|
553 self.trackIdlist.append(tId)
|
|
554 else:
|
|
555 cmd = [
|
|
556 "jbrowse",
|
|
557 "add-track",
|
|
558 fname,
|
|
559 "-t",
|
|
560 "AlignmentsTrack",
|
|
561 "-l",
|
|
562 "inPlace",
|
|
563 "-a",
|
|
564 self.genome_name,
|
|
565 "--indexFile",
|
|
566 fname + ".bai",
|
|
567 "-n",
|
|
568 trackData["name"],
|
|
569 "--target",
|
|
570 self.outdir,
|
|
571 ]
|
|
572 self.subprocess_check_call(cmd)
|
0
|
573
|
|
574 def add_vcf(self, data, trackData):
|
|
575 tId = trackData["label"]
|
|
576 url = "%s/api/datasets/%s/display" % (
|
|
577 self.giURL,
|
|
578 trackData["metadata"]["dataset_id"],
|
|
579 )
|
|
580 url = "%s.vcf.gz" % tId
|
10
|
581 dest = "%s/%s" % (self.outdir, url)
|
0
|
582 cmd = "bgzip -c %s > %s" % (data, dest)
|
|
583 self.subprocess_popen(cmd)
|
|
584 cmd = ["tabix", "-p", "vcf", dest]
|
|
585 self.subprocess_check_call(cmd)
|
|
586 trackDict = {
|
|
587 "type": "VariantTrack",
|
|
588 "trackId": tId,
|
|
589 "name": trackData["name"],
|
|
590 "assemblyNames": [self.genome_name],
|
|
591 "adapter": {
|
|
592 "type": "VcfTabixAdapter",
|
6
|
593 "vcfGzLocation": {
|
|
594 "uri": url,
|
|
595 },
|
0
|
596 "index": {
|
6
|
597 "location": {
|
|
598 "uri": url + ".tbi",
|
|
599 }
|
0
|
600 },
|
|
601 },
|
|
602 "displays": [
|
|
603 {
|
|
604 "type": "LinearVariantDisplay",
|
|
605 "displayId": "%s-LinearVariantDisplay" % tId,
|
|
606 },
|
|
607 {
|
|
608 "type": "ChordVariantDisplay",
|
|
609 "displayId": "%s-ChordVariantDisplay" % tId,
|
|
610 },
|
|
611 {
|
|
612 "type": "LinearPairedArcDisplay",
|
|
613 "displayId": "%s-LinearPairedArcDisplay" % tId,
|
|
614 },
|
|
615 ],
|
|
616 }
|
6
|
617 if self.usejson:
|
|
618 self.tracksToAdd.append(trackDict)
|
|
619 self.trackIdlist.append(tId)
|
|
620 else:
|
|
621 cmd = [
|
|
622 "jbrowse",
|
|
623 "add-track",
|
|
624 url,
|
|
625 "-t",
|
|
626 "VariantTrack",
|
|
627 "-a",
|
|
628 self.genome_name,
|
|
629 "--indexFile",
|
|
630 url + ".tbi",
|
|
631 "-n",
|
|
632 trackData["name"],
|
|
633 "--load",
|
|
634 "inPlace",
|
|
635 "--target",
|
|
636 self.outdir,
|
|
637 ]
|
|
638 self.subprocess_check_call(cmd)
|
0
|
639
|
|
640 def _sort_gff(self, data, dest):
|
|
641 # Only index if not already done
|
|
642 if not os.path.exists(dest + ".gz"):
|
|
643 cmd = "jbrowse sort-gff %s | bgzip -c > %s.gz" % (
|
|
644 data,
|
|
645 dest,
|
|
646 ) # "gff3sort.pl --precise '%s' | grep -v \"^$\" > '%s'"
|
|
647 self.subprocess_popen(cmd)
|
|
648 self.subprocess_check_call(["tabix", "-f", "-p", "gff", dest + ".gz"])
|
|
649
|
|
650 def _sort_bed(self, data, dest):
|
|
651 # Only index if not already done
|
|
652 if not os.path.exists(dest):
|
5
|
653 cmd = "sort -k1,1 -k2,2n %s | bgzip -c > %s" % (data, dest)
|
|
654 self.subprocess_popen(cmd)
|
|
655 cmd = ["tabix", "-f", "-p", "bed", dest]
|
|
656 self.subprocess_check_call(cmd)
|
0
|
657
|
|
658 def add_gff(self, data, ext, trackData):
|
|
659 url = "%s.%s" % (trackData["label"], ext)
|
10
|
660 dest = "%s/%s" % (self.outdir, url)
|
0
|
661 self._sort_gff(data, dest)
|
|
662 url = url + ".gz"
|
|
663 tId = trackData["label"]
|
|
664 trackDict = {
|
|
665 "type": "FeatureTrack",
|
|
666 "trackId": tId,
|
|
667 "name": trackData["name"],
|
|
668 "assemblyNames": [self.genome_name],
|
|
669 "adapter": {
|
|
670 "type": "Gff3TabixAdapter",
|
6
|
671 "gffGzLocation": {
|
|
672 "uri": url,
|
|
673 },
|
0
|
674 "index": {
|
6
|
675 "location": {
|
|
676 "uri": url + ".tbi",
|
|
677 }
|
0
|
678 },
|
|
679 },
|
|
680 "displays": [
|
|
681 {
|
|
682 "type": "LinearBasicDisplay",
|
|
683 "displayId": "%s-LinearBasicDisplay" % tId,
|
|
684 },
|
|
685 {"type": "LinearArcDisplay", "displayId": "%s-LinearArcDisplay" % tId},
|
|
686 ],
|
|
687 }
|
6
|
688 if self.usejson:
|
|
689 self.tracksToAdd.append(trackDict)
|
|
690 self.trackIdlist.append(tId)
|
|
691 else:
|
|
692 cmd = [
|
|
693 "jbrowse",
|
|
694 "add-track",
|
|
695 url,
|
|
696 "-t",
|
|
697 "FeatureTrack",
|
|
698 "-a",
|
|
699 self.genome_name,
|
|
700 "-n",
|
|
701 trackData["name"],
|
|
702 "--load",
|
|
703 "inPlace",
|
|
704 "--target",
|
|
705 self.outdir,
|
|
706 ]
|
|
707 self.subprocess_check_call(cmd)
|
0
|
708
|
|
709 def add_bed(self, data, ext, trackData):
|
|
710 url = "%s.%s" % (trackData["label"], ext)
|
10
|
711 dest = "%s/%s.gz" % (self.outdir, url)
|
0
|
712 self._sort_bed(data, dest)
|
|
713 tId = trackData["label"]
|
2
|
714 url = url + ".gz"
|
0
|
715 trackDict = {
|
|
716 "type": "FeatureTrack",
|
|
717 "trackId": tId,
|
|
718 "name": trackData["name"],
|
|
719 "assemblyNames": [self.genome_name],
|
|
720 "adapter": {
|
2
|
721 "type": "BedTabixAdapter",
|
6
|
722 "bedGzLocation": {
|
|
723 "uri": url,
|
|
724 },
|
2
|
725 "index": {
|
6
|
726 "location": {
|
|
727 "uri": url + ".tbi",
|
|
728 }
|
2
|
729 },
|
0
|
730 },
|
|
731 "displays": [
|
|
732 {
|
|
733 "type": "LinearBasicDisplay",
|
|
734 "displayId": "%s-LinearBasicDisplay" % tId,
|
|
735 },
|
|
736 {"type": "LinearArcDisplay", "displayId": "%s-LinearArcDisplay" % tId},
|
|
737 ],
|
|
738 }
|
6
|
739 if self.usejson:
|
|
740 self.tracksToAdd.append(trackDict)
|
|
741 self.trackIdlist.append(tId)
|
|
742 else:
|
|
743 cmd = [
|
|
744 "jbrowse",
|
|
745 "add-track",
|
|
746 url,
|
|
747 "-t",
|
|
748 "FeatureTrack",
|
|
749 "-a",
|
|
750 self.genome_name,
|
|
751 "--indexFile",
|
|
752 url + ".tbi",
|
|
753 "-n",
|
|
754 trackData["name"],
|
|
755 "--load",
|
|
756 "inPlace",
|
|
757 "--target",
|
|
758 self.outdir,
|
|
759 ]
|
|
760 self.subprocess_check_call(cmd)
|
0
|
761
|
|
762 def process_annotations(self, track):
|
|
763 category = track["category"].replace("__pd__date__pd__", TODAY)
|
|
764 for i, (
|
|
765 dataset_path,
|
|
766 dataset_ext,
|
|
767 track_human_label,
|
|
768 extra_metadata,
|
|
769 ) in enumerate(track["trackfiles"]):
|
|
770 # Unsanitize labels (element_identifiers are always sanitized by Galaxy)
|
|
771 for key, value in mapped_chars.items():
|
|
772 track_human_label = track_human_label.replace(value, key)
|
|
773 outputTrackConfig = {
|
|
774 "category": category,
|
|
775 }
|
|
776 if self.debug:
|
|
777 log.info(
|
|
778 "Processing category = %s, track_human_label = %s",
|
|
779 category,
|
|
780 track_human_label,
|
|
781 )
|
|
782 # We add extra data to hash for the case of REST + SPARQL.
|
|
783 if (
|
|
784 "conf" in track
|
|
785 and "options" in track["conf"]
|
|
786 and "url" in track["conf"]["options"]
|
|
787 ):
|
|
788 rest_url = track["conf"]["options"]["url"]
|
|
789 else:
|
|
790 rest_url = ""
|
|
791
|
|
792 # I chose to use track['category'] instead of 'category' here. This
|
|
793 # is intentional. This way re-running the tool on a different date
|
|
794 # will not generate different hashes and make comparison of outputs
|
|
795 # much simpler.
|
|
796 hashData = [
|
|
797 str(dataset_path),
|
|
798 track_human_label,
|
|
799 track["category"],
|
|
800 rest_url,
|
|
801 ]
|
|
802 hashData = "|".join(hashData).encode("utf-8")
|
|
803 outputTrackConfig["label"] = hashlib.md5(hashData).hexdigest() + "_%s" % i
|
|
804 outputTrackConfig["metadata"] = extra_metadata
|
|
805 outputTrackConfig["name"] = track_human_label
|
|
806
|
|
807 if dataset_ext in ("gff", "gff3"):
|
|
808 self.add_gff(
|
|
809 dataset_path,
|
|
810 dataset_ext,
|
|
811 outputTrackConfig,
|
|
812 )
|
|
813 elif dataset_ext in ("hic",):
|
|
814 self.add_hic(
|
|
815 dataset_path,
|
|
816 outputTrackConfig,
|
|
817 )
|
|
818 elif dataset_ext in ("bed",):
|
|
819 self.add_bed(
|
|
820 dataset_path,
|
|
821 dataset_ext,
|
|
822 outputTrackConfig,
|
|
823 )
|
|
824 elif dataset_ext in ("maf",):
|
|
825 self.add_maf(
|
|
826 dataset_path,
|
|
827 outputTrackConfig,
|
|
828 )
|
|
829 elif dataset_ext == "bigwig":
|
|
830 self.add_bigwig(
|
|
831 dataset_path,
|
|
832 outputTrackConfig,
|
|
833 )
|
|
834 elif dataset_ext == "bam":
|
|
835 real_indexes = track["conf"]["options"]["pileup"]["bam_indices"][
|
|
836 "bam_index"
|
|
837 ]
|
|
838 if not isinstance(real_indexes, list):
|
|
839 # <bam_indices>
|
|
840 # <bam_index>/path/to/a.bam.bai</bam_index>
|
|
841 # </bam_indices>
|
|
842 #
|
|
843 # The above will result in the 'bam_index' key containing a
|
|
844 # string. If there are two or more indices, the container
|
|
845 # becomes a list. Fun!
|
|
846 real_indexes = [real_indexes]
|
|
847
|
|
848 self.add_bam(
|
|
849 dataset_path,
|
|
850 outputTrackConfig,
|
|
851 track["conf"]["options"]["pileup"],
|
|
852 bam_index=real_indexes[i],
|
|
853 )
|
|
854 elif dataset_ext == "blastxml":
|
|
855 self.add_blastxml(
|
|
856 dataset_path, outputTrackConfig, track["conf"]["options"]["blast"]
|
|
857 )
|
|
858 elif dataset_ext == "vcf":
|
|
859 self.add_vcf(dataset_path, outputTrackConfig)
|
|
860 else:
|
|
861 log.warn("Do not know how to handle %s", dataset_ext)
|
|
862
|
10
|
863 def clone_jbrowse(self, destination):
|
0
|
864 """Clone a JBrowse directory into a destination directory."""
|
10
|
865 cmd = ["jbrowse", "create", "-f", os.path.realpath(destination)]
|
0
|
866 self.subprocess_check_call(cmd)
|
|
867 for fn in [
|
|
868 "asset-manifest.json",
|
|
869 "favicon.ico",
|
|
870 "robots.txt",
|
|
871 "umd_plugin.js",
|
|
872 "version.txt",
|
|
873 "test_data",
|
|
874 ]:
|
|
875 cmd = ["rm", "-rf", os.path.join(self.outdir, fn)]
|
|
876 self.subprocess_check_call(cmd)
|
10
|
877 cmd = ["cp", os.path.join(INSTALLED_TO, "servejb2.py"), self.outdir]
|
|
878 self.subprocess_check_call(cmd)
|
|
879
|
|
880 def clone_jbrowse2(self, jbrowse_dir, destination):
|
|
881 """Clone a JBrowse directory into a destination directory."""
|
|
882 cmd = ["cp", "-rv", jbrowse_dir + "/*", self.outdir]
|
|
883 self.subprocess_check_call(cmd)
|
|
884 for fn in [
|
|
885 "asset-manifest.json",
|
|
886 "favicon.ico",
|
|
887 "robots.txt",
|
|
888 "umd_plugin.js",
|
|
889 "version.txt",
|
|
890 "test_data",
|
|
891 ]:
|
|
892 cmd = ["rm", "-rf", os.path.join(self.outdir, fn)]
|
|
893 self.subprocess_check_call(cmd)
|
|
894 cmd = ["cp", os.path.join(INSTALLED_TO, "servejb2.py"), self.outdir]
|
7
|
895 self.subprocess_check_call(cmd)
|
0
|
896
|
|
897
|
|
898 if __name__ == "__main__":
|
|
899 parser = argparse.ArgumentParser(description="", epilog="")
|
10
|
900 parser.add_argument("--xml", help="Track Configuration")
|
|
901 parser.add_argument("--jbrowse", help="Output from 'which jbrowse'")
|
0
|
902 parser.add_argument("--outdir", help="Output directory", default="out")
|
10
|
903 parser.add_argument("--version", "-V", action="version", version="%(prog)s 2.0.1")
|
0
|
904 args = parser.parse_args()
|
|
905
|
10
|
906 tree = ET.parse(args.xml)
|
0
|
907 root = tree.getroot()
|
|
908
|
|
909 # This should be done ASAP
|
|
910 GALAXY_INFRASTRUCTURE_URL = root.find("metadata/galaxyUrl").text
|
|
911 # Sometimes this comes as `localhost` without a protocol
|
|
912 if not GALAXY_INFRASTRUCTURE_URL.startswith("http"):
|
|
913 # so we'll prepend `http://` and hope for the best. Requests *should*
|
|
914 # be GET and not POST so it should redirect OK
|
|
915 GALAXY_INFRASTRUCTURE_URL = "http://" + GALAXY_INFRASTRUCTURE_URL
|
|
916 jc = JbrowseConnector(
|
|
917 outdir=args.outdir,
|
|
918 genomes=[
|
|
919 {
|
|
920 "path": os.path.realpath(x.attrib["path"]),
|
|
921 "meta": metadata_from_node(x.find("metadata")),
|
|
922 }
|
|
923 for x in root.findall("metadata/genomes/genome")
|
|
924 ],
|
|
925 )
|
|
926 jc.process_genomes()
|
|
927
|
|
928 for track in root.findall("tracks/track"):
|
|
929 track_conf = {}
|
|
930 track_conf["trackfiles"] = []
|
|
931
|
|
932 is_multi_bigwig = False
|
|
933 try:
|
|
934 if track.find("options/wiggle/multibigwig") and (
|
|
935 track.find("options/wiggle/multibigwig").text == "True"
|
|
936 ):
|
|
937 is_multi_bigwig = True
|
|
938 multi_bigwig_paths = []
|
|
939 except KeyError:
|
|
940 pass
|
|
941
|
|
942 trackfiles = track.findall("files/trackFile")
|
|
943 if trackfiles:
|
|
944 for x in track.findall("files/trackFile"):
|
|
945 if is_multi_bigwig:
|
|
946 multi_bigwig_paths.append(
|
|
947 (x.attrib["label"], os.path.realpath(x.attrib["path"]))
|
|
948 )
|
|
949 else:
|
|
950 if trackfiles:
|
|
951 metadata = metadata_from_node(x.find("metadata"))
|
|
952 track_conf["dataset_id"] = metadata["dataset_id"]
|
|
953 track_conf["trackfiles"].append(
|
|
954 (
|
|
955 os.path.realpath(x.attrib["path"]),
|
|
956 x.attrib["ext"],
|
|
957 x.attrib["label"],
|
|
958 metadata,
|
|
959 )
|
|
960 )
|
|
961 else:
|
|
962 # For tracks without files (rest, sparql)
|
|
963 track_conf["trackfiles"].append(
|
|
964 (
|
|
965 "", # N/A, no path for rest or sparql
|
|
966 track.attrib["format"],
|
|
967 track.find("options/label").text,
|
|
968 {},
|
|
969 )
|
|
970 )
|
|
971
|
|
972 if is_multi_bigwig:
|
|
973 metadata = metadata_from_node(x.find("metadata"))
|
|
974
|
|
975 track_conf["trackfiles"].append(
|
|
976 (
|
|
977 multi_bigwig_paths, # Passing an array of paths to represent as one track
|
|
978 "bigwig_multiple",
|
|
979 "MultiBigWig", # Giving an hardcoded name for now
|
|
980 {}, # No metadata for multiple bigwig
|
|
981 )
|
|
982 )
|
|
983
|
|
984 track_conf["category"] = track.attrib["cat"]
|
|
985 track_conf["format"] = track.attrib["format"]
|
|
986 try:
|
|
987 # Only pertains to gff3 + blastxml. TODO?
|
|
988 track_conf["style"] = {t.tag: t.text for t in track.find("options/style")}
|
|
989 except TypeError:
|
|
990 track_conf["style"] = {}
|
|
991 pass
|
|
992 track_conf["conf"] = etree_to_dict(track.find("options"))
|
|
993 jc.process_annotations(track_conf)
|
|
994 print("## processed", str(track_conf), "trackIdlist", jc.trackIdlist)
|
|
995 print(
|
|
996 "###done processing, trackIdlist=",
|
|
997 jc.trackIdlist,
|
|
998 "config=",
|
|
999 str(jc.config_json),
|
|
1000 )
|
|
1001 jc.config_json["tracks"] = jc.tracksToAdd
|
6
|
1002 if jc.usejson:
|
|
1003 jc.write_config()
|
0
|
1004 jc.add_default_view()
|