isabl-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
isabl_cli/data.py ADDED
@@ -0,0 +1,1240 @@
1
+ """Data import logic."""
2
+
3
+ from collections import defaultdict
4
+ from datetime import datetime
5
+ from getpass import getuser
6
+ from glob import glob
7
+ from os.path import basename
8
+ from os.path import dirname
9
+ from os.path import getsize
10
+ from os.path import isdir
11
+ from os.path import join
12
+ import os
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+
17
+ from slugify import slugify
18
+ import click
19
+ import yaml
20
+
21
+ from isabl_cli import api
22
+ from isabl_cli import exceptions
23
+ from isabl_cli import options
24
+ from isabl_cli import utils
25
+ from isabl_cli.settings import import_from_string
26
+ from isabl_cli.settings import system_settings
27
+
28
+
29
+ def raw_data_inspector(path):
30
+ """Determine if a path is a supported raw data file."""
31
+ for i, j in [
32
+ # sequencing
33
+ (r"\.bam$", "BAM"),
34
+ (r"\.cram$", "CRAM"),
35
+ # imaging
36
+ (r"\.png$", "PNG"),
37
+ (r"\.jp(e)?g$", "JPEG"),
38
+ (r"\.tiff$", "TIFF"),
39
+ (r"\.dicom$", "DICOM"),
40
+ # text
41
+ (r"\.tsv(\.gz)?$", "TSV"),
42
+ (r"\.csv(\.gz)?$", "CSV"),
43
+ (r"\.txt(\.gz)?$", "TXT"),
44
+ # other
45
+ (r"\.pdf$", "PDF"),
46
+ (r"\.html$", "HTML"),
47
+ (r"\.md5$", "MD5"),
48
+ (r"\.y[a]?ml$", "YAML"),
49
+ ] + system_settings.EXTRA_RAW_DATA_FORMATS:
50
+ if re.search(i, path):
51
+ return j
52
+
53
+ for i in [1, 2]:
54
+ for pattern, fq_type in (
55
+ (r"(([_.]R{0}[_.].+)|([_.]R{0}\.)|(_{0}\.))f(ast)?q(\.gz)?$", "R"),
56
+ (r"(([_.]I{0}[_.].+)|([_.]I{0}\.))f(ast)?q(\.gz)?$", "I"),
57
+ ):
58
+ if re.search(pattern.format(i), path):
59
+ return f"FASTQ_{fq_type}{i}"
60
+
61
+ if re.search(r"\.f(ast)?q(\.gz)?$", path):
62
+ raise click.UsageError(f"cant determine fastq type from: {path}")
63
+
64
+ return None
65
+
66
+
67
+ def update_experiment_bam_file(experiment, assembly_name, analysis_pk, bam_url):
68
+ """
69
+ Update default bam for a experiment given the assembly.
70
+
71
+ Arguments:
72
+ experiment (dict): experiment dict.
73
+ assembly_name (str): assembly name.
74
+ analysis_pk (int): analysis primary key.
75
+ bam_url (str): bam url.
76
+
77
+ Returns:
78
+ dict: patched experiment instance
79
+ """
80
+ utils.check_admin()
81
+ pk = experiment["pk"]
82
+ bam_files = experiment["bam_files"]
83
+
84
+ if bam_files.get(assembly_name, None): # pragma: no cover
85
+ raise click.UsageError(f"Experiment {pk} already has {assembly_name} bam")
86
+
87
+ bam_files[assembly_name] = {"url": bam_url, "analysis": analysis_pk}
88
+ return api.patch_instance("experiments", pk, bam_files=bam_files)
89
+
90
+
91
+ def symlink_experiment_to_projects(experiment):
92
+ """Create symlink from experiment directory and projects directories."""
93
+ for i in experiment["projects"]:
94
+ if not i["storage_url"]: # pragma: no cover
95
+ i = update_storage_url("projects", i["pk"])
96
+
97
+ experiments_dir = join(i["storage_url"], "experiments")
98
+ experiment_dir = join(experiments_dir, experiment["system_id"])
99
+ utils.makedirs(experiments_dir)
100
+ utils.force_symlink(experiment["storage_url"], experiment_dir)
101
+
102
+
103
+ def symlink_analysis_to_targets(analysis):
104
+ """Create symlink from experiment directory and projects directories."""
105
+ if analysis["status"] != "SUCCEEDED":
106
+ return
107
+
108
+ src = analysis["storage_url"]
109
+ dst = "__".join(
110
+ [
111
+ analysis["application"]["name"].lower().replace(" ", "_"),
112
+ analysis["application"]["version"].lower().replace(" ", "_"),
113
+ str(analysis["pk"]),
114
+ ]
115
+ )
116
+
117
+ for i in analysis["targets"]:
118
+ if not i["storage_url"]: # pragma: no cover
119
+ i = update_storage_url("experiments", i["pk"])
120
+
121
+ analyses_dir = join(i["storage_url"], "analyses")
122
+ utils.makedirs(analyses_dir)
123
+ utils.force_symlink(src, join(analyses_dir, dst))
124
+
125
+ if analysis["project_level_analysis"]:
126
+ i = analysis["project_level_analysis"]
127
+ if not i["storage_url"]:
128
+ i = update_storage_url("projects", i["pk"])
129
+
130
+ analyses_dir = join(i["storage_url"], "analyses")
131
+ utils.makedirs(analyses_dir)
132
+ utils.force_symlink(src, join(analyses_dir, dst))
133
+
134
+
135
+ def trigger_analyses_merge(analysis):
136
+ """Submit project level analyses merge if neccessary."""
137
+ if analysis["status"] not in {"SUCCEEDED", "FAILED"}:
138
+ return
139
+
140
+ try:
141
+ application = import_from_string(analysis["application"]["application_class"])()
142
+ except ImportError:
143
+ return
144
+
145
+ def _echo_action(instance, application, pending):
146
+ click.secho(
147
+ ("Skipping " if pending else "Submitting ")
148
+ + ("individual " if "species" in instance else "project ")
149
+ + f"merge for {instance} and application {application}",
150
+ fg="yellow" if pending else "green",
151
+ )
152
+
153
+ if application.has_project_auto_merge:
154
+ projects = {j["pk"]: j for i in analysis["targets"] for j in i["projects"]}
155
+
156
+ for i in projects.values():
157
+ pending = api.get_instances_count(
158
+ endpoint="analyses",
159
+ status__in="STARTED,SUBMITTED",
160
+ application=analysis["application"]["pk"],
161
+ projects=i["pk"],
162
+ )
163
+
164
+ _echo_action(i, analysis.application, pending)
165
+
166
+ if not pending:
167
+ application.submit_merge_analysis(i)
168
+
169
+ if application.has_individual_auto_merge:
170
+ individuals = {
171
+ i.sample.individual.pk: i.sample.individual for i in analysis["targets"]
172
+ }
173
+
174
+ for i in individuals.values():
175
+ pending = api.get_instances_count(
176
+ endpoint="analyses",
177
+ status__in="STARTED,SUBMITTED",
178
+ application=analysis["application"]["pk"],
179
+ targets__sample__individual__pk=i.pk,
180
+ )
181
+
182
+ _echo_action(i, analysis.application, pending)
183
+
184
+ if not pending:
185
+ application.submit_merge_analysis(i)
186
+
187
+
188
+ def trash_analysis_storage(analysis):
189
+ """Move analysis `storage_url` to a trash directory."""
190
+ if analysis["status"] == "SUCCEEDED":
191
+ raise click.UsageError("You can't wipe a succeeded analysis")
192
+
193
+ if isdir(analysis["storage_url"]):
194
+ trash_dir = system_settings.MAKE_STORAGE_DIRECTORY(
195
+ root=system_settings.BASE_STORAGE_DIRECTORY,
196
+ base=join(".analyses_trash", getuser()),
197
+ identifier=analysis["pk"],
198
+ use_hash=True,
199
+ )
200
+
201
+ slug = f'primary_key_{analysis["pk"]}__date_'
202
+ slug += datetime.now(system_settings.TIME_ZONE).isoformat()
203
+ dst = join(trash_dir, slug)
204
+ click.echo(f"\ntrashing: {analysis['storage_url']} -> {dst}\n")
205
+ subprocess.check_call(["mv", analysis["storage_url"], dst])
206
+
207
+
208
+ def _make_storage_directory(root, base, identifier, use_hash=False):
209
+ """
210
+ Get and create path to a data directory.
211
+
212
+ The path is set to:
213
+
214
+ <root>/<base>/<identifier>
215
+
216
+ If `use_hash`, identifier must be integer and path is build using the
217
+ four last digits of the identifier. Say identifiers is 12345, then path is:
218
+
219
+ <root>/<base>/23/45/12345
220
+
221
+ Arguments:
222
+ base (str): instance's API base.
223
+ identifier (str): instance's primary key.
224
+ root (str): root directory.
225
+ use_hash (bool): hash integer identifier for directories.
226
+
227
+ Returns:
228
+ str: path to instance's data directory.
229
+ """
230
+ if not root: # pragma: no cover
231
+ raise click.UsageError("Base storage root directory is required.")
232
+
233
+ if use_hash:
234
+ if not str(identifier).isdigit(): # pragma: no cover
235
+ raise click.UsageError("`use_hash` only supported for integers.")
236
+
237
+ hash_1 = f"{identifier:04d}"[-4:-2]
238
+ hash_2 = f"{identifier:04d}"[-2:]
239
+ path = join(base, hash_1, hash_2)
240
+ else:
241
+ path = join(base)
242
+
243
+ storage_directory = join(root, path, str(identifier))
244
+ original_umask = os.umask(0)
245
+ utils.makedirs(storage_directory)
246
+ os.umask(original_umask)
247
+ return storage_directory
248
+
249
+
250
+ def get_storage_url(endpoint, identifier, use_hash=False):
251
+ """Make storage directory and return patched instance."""
252
+ return system_settings.MAKE_STORAGE_DIRECTORY(
253
+ root=system_settings.BASE_STORAGE_DIRECTORY,
254
+ base=endpoint,
255
+ identifier=identifier,
256
+ use_hash=use_hash,
257
+ )
258
+
259
+
260
+ def update_storage_url(endpoint, identifier, use_hash=False, **data):
261
+ """Make storage directory and return patched instance."""
262
+ data["storage_url"] = get_storage_url(endpoint, identifier, use_hash)
263
+ return api.patch_instance(endpoint, identifier, **data)
264
+
265
+
266
+ class BaseImporter:
267
+ @staticmethod
268
+ def echo_src_dst(msg, src, dst):
269
+ """Print a src to dst msg."""
270
+ click.echo(f"\n{msg}:\n\t{src}\n\t{click.style('->', fg='green')} {dst}")
271
+
272
+ @staticmethod
273
+ def symlink(src, dst):
274
+ """Create symlink from `src` to `dst`."""
275
+ utils.force_symlink(os.path.realpath(src), dst)
276
+
277
+ @staticmethod
278
+ def move(src, dst):
279
+ """Rename `src` to `dst`."""
280
+ os.rename(os.path.realpath(src), dst)
281
+
282
+ @staticmethod
283
+ def copy(src, dst):
284
+ """Copy files from `src` to `dst`."""
285
+ shutil.copy(src, dst)
286
+
287
+
288
+ class LocalReferenceDataImporter(BaseImporter):
289
+
290
+ """An import engine for assemblies' reference_data."""
291
+
292
+ @classmethod
293
+ def import_data(
294
+ cls,
295
+ identifier,
296
+ data_src,
297
+ data_id,
298
+ symlink,
299
+ description,
300
+ sub_dir=None,
301
+ model="assemblies",
302
+ ):
303
+ """
304
+ Register reference resources for a given assembly.
305
+
306
+ Arguments:
307
+ identifier (str): name of assembly or technique.
308
+ model (str): either `techniques` or `assemblies`.
309
+ data_src (str): path to reference data.
310
+ data_id (str): identifier that will be used for reference data.
311
+ symlink (str): symlink instead of move.
312
+ description (str): reference data description.
313
+ sub_dir (str): target sub dir for the resource, default is data_id.
314
+
315
+ Returns:
316
+ dict: updated assembly instance as retrieved from API.
317
+ """
318
+ utils.check_admin()
319
+ data_id = slugify(data_id, separator="_")
320
+ click.echo(f'`data_id` set to: {click.style(data_id, fg="green")}')
321
+ instance = api.get_instance(model, identifier)
322
+
323
+ if data_id in instance["reference_data"]:
324
+ raise click.UsageError(
325
+ f"{instance['name']} has already reference data registered with id "
326
+ f'"{data_id}":\n\n\t{instance["reference_data"][data_id]}'
327
+ )
328
+
329
+ if not instance["storage_url"]:
330
+ instance = update_storage_url(model, instance["name"])
331
+
332
+ data_dir = join(instance["storage_url"], sub_dir or data_id)
333
+ data_dst = join(data_dir, basename(data_src))
334
+ utils.makedirs(data_dir)
335
+
336
+ if symlink:
337
+ cls.echo_src_dst("Linking", data_src, data_dst)
338
+ cls.symlink(data_src, data_dst)
339
+ else:
340
+ cls.echo_src_dst("Moving", data_src, data_dst)
341
+ cls.move(data_src, data_dst)
342
+
343
+ click.secho(f'\nSuccess! patching {instance["name"]}...', fg="green")
344
+ instance["reference_data"][data_id] = {}
345
+ instance["reference_data"][data_id]["url"] = data_dst
346
+ instance["reference_data"][data_id]["description"] = description
347
+ return api.patch_instance(
348
+ endpoint=model,
349
+ instance_id=instance["pk"],
350
+ storage_usage=utils.get_tree_size(instance["storage_url"]),
351
+ reference_data=instance["reference_data"],
352
+ )
353
+
354
+ @classmethod
355
+ def as_cli_command(cls):
356
+ """Get reference data importer as click command line interface."""
357
+ # build isabl_cli command and return it
358
+ @click.command(name="import-reference-data")
359
+ @click.option(
360
+ "--identifier",
361
+ help="name of technique or assembly, see --model",
362
+ required=True,
363
+ )
364
+ @click.option(
365
+ "--model",
366
+ help="default model is assemblies",
367
+ type=click.Choice(["assemblies", "techniques"]),
368
+ default="assemblies",
369
+ )
370
+ @click.option("--description", help="reference data description")
371
+ @click.option("--data-id", help="data identifier (will be slugified)")
372
+ @click.option("--sub-dir", help="target resource sub dir, default is data-id")
373
+ @options.REFERENCE_DATA_SOURCE
374
+ @options.SYMLINK
375
+ def cmd(identifier, model, data_id, symlink, description, data_src, sub_dir):
376
+ """
377
+ Register reference data for assemblies (default) or techniques.
378
+
379
+ If you want to import a Reference Genome please refer to the
380
+ import-reference-genome command. Incoming data (files or directories) will
381
+ moved unless `--symlink` is provided.
382
+ """
383
+ cls().import_data(
384
+ data_id=data_id,
385
+ data_src=data_src,
386
+ description=description,
387
+ identifier=identifier,
388
+ model=model,
389
+ sub_dir=sub_dir,
390
+ symlink=symlink,
391
+ )
392
+
393
+ return cmd
394
+
395
+
396
+ class LocalReferenceGenomeImporter:
397
+
398
+ """An import engine for an assembly reference genome."""
399
+
400
+ @classmethod
401
+ def as_cli_command(cls):
402
+ """Get reference data importer as click command line interface."""
403
+ # build isabl_cli command and return it
404
+ @click.command(name="import-reference-genome")
405
+ @click.option("--assembly", help="name of genome assembly")
406
+ @click.option(
407
+ "--genome-path",
408
+ show_default=True,
409
+ type=click.Path(resolve_path=True, exists=True, readable=True),
410
+ help="path to reference genome (.fq, .fasta, .fasta.gz)",
411
+ )
412
+ @click.option(
413
+ "--dont-index",
414
+ is_flag=True,
415
+ show_default=True,
416
+ help="Do not attempt to generate indexes, I'll do it myself",
417
+ )
418
+ @options.SYMLINK
419
+ def cmd(assembly, symlink, genome_path, dont_index):
420
+ """
421
+ Register an assembly reference genome.
422
+
423
+ By default, an attempt to create indexes will be perfomed.
424
+ """
425
+ assembly = LocalReferenceDataImporter.import_data(
426
+ data_id="genome_fasta",
427
+ symlink=symlink,
428
+ data_src=genome_path,
429
+ identifier=assembly,
430
+ model="assemblies",
431
+ description="Reference Genome Fasta File.",
432
+ )
433
+
434
+ genome_fasta = assembly["reference_data"]["genome_fasta"]["url"]
435
+ genome_dir = dirname(genome_fasta)
436
+ commands = [
437
+ ["bwa", "index", genome_fasta],
438
+ ["samtools", "faidx", genome_fasta],
439
+ [
440
+ "samtools",
441
+ "dict",
442
+ genome_fasta,
443
+ "-a",
444
+ assembly["name"],
445
+ "-s",
446
+ assembly["species"],
447
+ "-o",
448
+ join(genome_fasta + ".dict"),
449
+ ],
450
+ ]
451
+
452
+ for i in commands:
453
+ if dont_index:
454
+ click.secho(
455
+ f"Skipping indexing:\n\n\t{' '.join(i)}", err=True, fg="yellow"
456
+ )
457
+ continue
458
+
459
+ try: # pragma: no cover
460
+ subprocess.check_call(i)
461
+ except (
462
+ FileNotFoundError,
463
+ subprocess.CalledProcessError,
464
+ ): # pragma: no cover
465
+ click.secho(
466
+ f"INDEX FAILED, MUST BE FIXED:\n\n\t{' '.join(i)}",
467
+ err=True,
468
+ fg="red",
469
+ )
470
+
471
+ indexes = {
472
+ "bwa index": ["amb", "ann", "bwt", "pac", "sa"],
473
+ "samtools faidx": ["fai"],
474
+ "samtools dict": ["dict"],
475
+ }
476
+
477
+ for i, indexes in indexes.items():
478
+ for j in indexes:
479
+ assembly["reference_data"][f"genome_fasta_{j}"] = {
480
+ "url": join(genome_fasta + f".{j}"),
481
+ "description": f"Index generated by: {i}",
482
+ }
483
+
484
+ for i in glob(genome_fasta.split(".", 1)[0] + "*"):
485
+ dst = join(genome_dir, assembly["name"] + "." + i.split(".", 1)[-1])
486
+ if i != dst:
487
+ utils.force_symlink(i, dst)
488
+
489
+ api.patch_instance(
490
+ endpoint="assemblies",
491
+ instance_id=assembly["pk"],
492
+ storage_usage=utils.get_tree_size(assembly["storage_url"]),
493
+ reference_data=assembly["reference_data"],
494
+ )
495
+
496
+ return cmd
497
+
498
+
499
+ class LocalBedImporter(BaseImporter):
500
+
501
+ """An import engine for Technique BED files."""
502
+
503
+ @staticmethod
504
+ def process_bedfile(path):
505
+ """Sort, tabix and gzip a bedfile."""
506
+ command = ["sort", "-k1,1V", "-k2,2n", path]
507
+ sorted_bed = subprocess.check_output(command)
508
+
509
+ with open(path, "+w") as f:
510
+ f.write(sorted_bed.decode("utf-8"))
511
+
512
+ subprocess.check_call(["bgzip", path])
513
+ subprocess.check_call(["tabix", "-p", "bed", path + ".gz"])
514
+
515
+ with open(path, "+w") as f: # write uncompressed file again
516
+ f.write(sorted_bed.decode("utf-8"))
517
+
518
+ @classmethod
519
+ def import_bedfiles(
520
+ cls, technique, targets_path, baits_path, assembly, species, description=None
521
+ ):
522
+ """
523
+ Register input_bed_path in technique's storage dir and update `data`.
524
+
525
+ Arguments:
526
+ technique (str): technique slug.
527
+ targets_path (str): path to targets bedfile.
528
+ baits_path (str): path to baits bedfile.
529
+ assembly (str): name of reference genome for bedfile.
530
+ species (str): name of genome species.
531
+ description (str): a description of the BED files.
532
+
533
+ Returns:
534
+ dict: updated technique instance as retrieved from API.
535
+ """
536
+ utils.check_admin()
537
+ technique = api.get_instance("techniques", technique)
538
+ targets_key = f"{assembly}_targets_bedfile"
539
+ baits_key = f"{assembly}_baits_bedfile"
540
+
541
+ if targets_key in technique["reference_data"]:
542
+ raise click.UsageError(
543
+ f"Technique '{technique['slug']}' "
544
+ f"has registered BED files for '{assembly}':\n"
545
+ f'\n\t{technique["reference_data"][targets_key]}'
546
+ f'\n\t{technique["reference_data"][baits_key]}'
547
+ )
548
+
549
+ if not technique["storage_url"]:
550
+ technique = update_storage_url("techniques", technique["pk"])
551
+
552
+ api.create_instance("assemblies", name=assembly, species=species)
553
+ beds_dir = join(technique["storage_url"], "bed_files", assembly)
554
+ base_name = slugify(f'{technique["slug"]}.{assembly}')
555
+ targets_dst = join(beds_dir, f"{base_name}.targets.bed")
556
+ baits_dst = join(beds_dir, f"{base_name}.baits.bed")
557
+ utils.makedirs(beds_dir)
558
+
559
+ for src, dst in [(targets_path, targets_dst), (baits_path, baits_dst)]:
560
+ cls.echo_src_dst("Copying", src, dst)
561
+ shutil.copy(src, dst)
562
+ click.secho(f"\nProcessing {basename(dst)}...", fg="blue")
563
+ cls.process_bedfile(dst)
564
+
565
+ click.secho(f'\nSuccess! patching {technique["slug"]}...', fg="green")
566
+
567
+ for i, j in [(targets_key, targets_dst), (baits_key, baits_dst)]:
568
+ technique["reference_data"][i] = {
569
+ "url": j + ".gz",
570
+ "description": description,
571
+ }
572
+
573
+ return api.patch_instance(
574
+ endpoint="techniques",
575
+ instance_id=technique["pk"],
576
+ storage_usage=utils.get_tree_size(technique["storage_url"]),
577
+ reference_data=technique["reference_data"],
578
+ )
579
+
580
+ @classmethod
581
+ def as_cli_command(cls):
582
+ """Get bed importer as click command line interface."""
583
+ # build isabl_cli command and return it
584
+ @click.command(name="import-bedfiles")
585
+ @options.TECHNIQUE_IDENTIFIER
586
+ @options.TARGETS_PATH
587
+ @options.BAITS_PATH
588
+ @click.option("--assembly", help="name of reference genome", required=True)
589
+ @click.option("--species", help="name of species", required=True)
590
+ @click.option("--description", help="BED files description")
591
+ def cmd(technique, assembly, targets_path, baits_path, description, species):
592
+ """
593
+ Register targets and baits BED files in a technique's data directory.
594
+
595
+ Incoming BED files will be compressed and tabixed. Both gzipped and
596
+ uncompressed versions are kept. Instance's storage_url, storage_usage,
597
+ and reference_data fields are updated.
598
+ """
599
+ cls().import_bedfiles(
600
+ technique=technique,
601
+ targets_path=targets_path,
602
+ baits_path=baits_path,
603
+ assembly=assembly,
604
+ species=species,
605
+ description=description,
606
+ )
607
+
608
+ return cmd
609
+
610
+
611
+ class LocalDataImporter(BaseImporter):
612
+
613
+ """
614
+ A Data import engine for experiments.
615
+
616
+ Attributes:
617
+ RAW_DATA_INSPECTORS (list): list of functions which argument is a path and
618
+ are tasked to return the data type of supported formats.
619
+ """
620
+
621
+ RAW_DATA_INSPECTORS = [raw_data_inspector]
622
+
623
+ def annotate_file_data(
624
+ self, experiment, file_data, file_type, src, dst
625
+ ): # pylint: disable=no-self-use,unused-argument
626
+ """Overwrite this method to provide custom file_data annotations."""
627
+ return file_data
628
+
629
+ def import_data(
630
+ self,
631
+ directories,
632
+ symlink=False,
633
+ commit=False,
634
+ key=lambda x: x["system_id"],
635
+ files_data=None,
636
+ dtypes=None,
637
+ iexact=False,
638
+ ignore_ownership=False,
639
+ copy=False,
640
+ **filters,
641
+ ):
642
+ """
643
+ Import raw data for multiple experiments.
644
+
645
+ Experiments's `storage_url`, `storage_usage`, `raw_data` are
646
+ updated.
647
+
648
+ Arguments:
649
+ directories (list): list of directories to be recursively explored.
650
+ copy (bool): if True files are copied intead of moved.
651
+ symlink (bool): if True symlink instead of moving.
652
+ commit (bool): if True perform import operation.
653
+ key (function): given a experiment dict returns id to match.
654
+ filters (dict): key value pairs to use as API query params.
655
+ dtypes (list): data types that should be matched (e.g. BAM, PNG. etc.).
656
+ iexact (bool): case insensitive match of identifiers.
657
+ ignore_ownership (bool): raise error if files not owned by admin user.
658
+ files_data (dict): keys are files basenames and values are
659
+ dicts with extra annotations such as PL, LB, or any other,
660
+ see also annotate_file_data.
661
+
662
+ Raises:
663
+ click.UsageError: if `key` returns the same identifier for multiple
664
+ experiments. If a experiment matches both fastq and bam files.
665
+ if cant determine read 1 or read 2 from matched fastq files.
666
+
667
+ Returns:
668
+ tuple: list of experiments for which data has been matched and a
669
+ summary of the operation.
670
+ """
671
+ utils.check_admin()
672
+ files_data = files_data or {}
673
+ experiments_matched = []
674
+ cache = defaultdict(dict)
675
+ patterns = []
676
+ identifiers = {}
677
+ dtypes = set(dtypes or [])
678
+
679
+ # validate files_data
680
+ for i, j in files_data.items():
681
+ if not isinstance(j, dict): # pragma: no cover
682
+ raise click.UsageError(f"Invalid file data, expected dict {i}: {j}")
683
+
684
+ # get experiments and load cache dictionary
685
+ for i in api.get_instances("experiments", verbose=True, **filters):
686
+ index = f"primary_key_{i['pk']}"
687
+ using_id = f"{i['system_id']} (Skipped, identifier is NULL)"
688
+
689
+ try:
690
+ identifier = key(i)
691
+ except Exception as error: # pylint: disable=broad-except
692
+ raise click.UsageError(f"Failed to retieve id using {key}: {error}")
693
+
694
+ if identifier in identifiers: # duplicated identifiers not valid
695
+ raise click.UsageError(
696
+ f"Can't use same identifier for {i['system_id']} "
697
+ f"and {identifiers[identifier]}: {identifier}"
698
+ )
699
+
700
+ if i["raw_data"] or i["bam_files"]:
701
+ using_id = f"{i['system_id']} (Skipped, experiment has raw data)"
702
+ elif identifier:
703
+ identifiers[identifier] = i["system_id"]
704
+ patterns.append(self.get_regex_pattern(index, identifier, iexact))
705
+ using_id = f"{i['system_id']} (using {identifier})"
706
+
707
+ cache[index]["using_id"] = using_id
708
+ cache[index]["instance"] = i
709
+ cache[index]["files"] = []
710
+
711
+ # forgive me gods of complexity
712
+ overlaps = []
713
+ for i in identifiers:
714
+ for j in identifiers:
715
+ if i != j and (i in j or j in i):
716
+ overlaps.append((i, j))
717
+
718
+ if overlaps:
719
+ raise click.UsageError(
720
+ "Overlapping identifiers are not allowed, use a more specific field "
721
+ "or further filter your experiments:\n\n"
722
+ + f"\n\n".join(
723
+ f" {identifiers[i]}\t{click.style(i, fg='red')}\n"
724
+ + f" {identifiers[j]}\t{click.style(j, fg='red')}"
725
+ for i, j in overlaps
726
+ ).expandtabs(20)
727
+ )
728
+
729
+ if patterns:
730
+ # see http://stackoverflow.com/questions/8888567 for pattern
731
+ pattern = re.compile("|".join(patterns))
732
+ data_storage_dir = system_settings.BASE_STORAGE_DIRECTORY
733
+ label = f"Exploring directories..."
734
+
735
+ # explore dirs
736
+ for directory in set(directories):
737
+ with click.progressbar(
738
+ os.walk(directory, followlinks=True), label=label
739
+ ) as bar:
740
+ for root, _, files in bar:
741
+ if not root.startswith(data_storage_dir):
742
+ for i in files:
743
+ if len(patterns) > 800: # pragma: no cover
744
+ click.echo(
745
+ f"\nMatching {i} against "
746
+ f"{len(patterns)} experiments..."
747
+ )
748
+
749
+ path = join(root, i)
750
+ match = self.match_path(path, pattern)
751
+
752
+ if match and (not dtypes or match["dtype"] in dtypes):
753
+ cache[match.pop("index")]["files"].append(match)
754
+
755
+ # check ownership if needed
756
+ if not ignore_ownership and not symlink and not copy:
757
+ self.check_ownership(cache)
758
+
759
+ # check files are readable
760
+ self.check_are_readable(cache)
761
+
762
+ # process files if needed
763
+ label = "Processing..."
764
+ bar = sorted(cache.values(), key=lambda x: x["instance"]["pk"])
765
+ with click.progressbar(bar, label=label) as bar:
766
+ for i in bar:
767
+ if commit and i["files"]:
768
+ experiments_matched.append(
769
+ self.import_files(
770
+ instance=i["instance"],
771
+ files=i["files"],
772
+ symlink=symlink,
773
+ copy=copy,
774
+ files_data=files_data,
775
+ )
776
+ )
777
+ elif i["files"]: # pragma: no cover
778
+ experiments_matched.append(i["instance"])
779
+
780
+ return experiments_matched, self.get_summary(cache)
781
+
782
+ @staticmethod
783
+ def check_ownership(cache):
784
+ """Make sure files matched are owned by current user."""
785
+ label = "Checking ownership, ignore with --ignore-ownership..."
786
+ bar = sorted(cache.values(), key=lambda x: x["instance"]["pk"])
787
+ owner_mismatch = []
788
+
789
+ with click.progressbar(bar, label=label) as bar:
790
+ for i in bar:
791
+ for j in i["files"]:
792
+ try:
793
+ utils.assert_same_owner(j["path"])
794
+ except AssertionError:
795
+ owner_mismatch.append(j["path"])
796
+
797
+ if owner_mismatch:
798
+ raise click.UsageError(
799
+ click.style(
800
+ "The following files are not owned by current user "
801
+ "(consider using --ignore-ownership):\n\t",
802
+ fg="red",
803
+ )
804
+ + "\n\t".join(owner_mismatch)
805
+ )
806
+
807
+ @staticmethod
808
+ def check_are_readable(cache):
809
+ """Make sure files matched can be accessed and read."""
810
+ label = "Checking files are readable..."
811
+ bar = sorted(cache.values(), key=lambda x: x["instance"]["pk"])
812
+ unreadable_files = []
813
+
814
+ with click.progressbar(bar, label=label) as bar:
815
+ for i in bar:
816
+ for j in i["files"]:
817
+ try:
818
+ assert os.access(j["path"], os.R_OK)
819
+ except AssertionError:
820
+ unreadable_files.append(j["path"])
821
+
822
+ if unreadable_files:
823
+ raise click.UsageError(
824
+ click.style(
825
+ "The following files are not readable by current user:\n\t",
826
+ fg="red",
827
+ )
828
+ + "\n\t".join(unreadable_files)
829
+ )
830
+
831
+ def match_path(self, path, pattern):
832
+ """Match `path` with `pattern` and update cache if fastq or bam."""
833
+ try:
834
+ # first match ids in path
835
+ matches = pattern.finditer(path)
836
+ index = next(matches).lastgroup
837
+ assert index is not None # happens when pattern is empty
838
+
839
+ # determine if valid data type
840
+ dtypes = [i(path) for i in self.RAW_DATA_INSPECTORS]
841
+ dtypes = set(i for i in dtypes if i)
842
+ assert dtypes # happens if no data type matched
843
+
844
+ # raise error if multiple data types matched
845
+ if len(dtypes) != 1:
846
+ raise exceptions.ImplementationError( # pragma: no cover
847
+ f"Conflicting data types ({dtypes}) were "
848
+ f"identified by inspectors: {self.RAW_DATA_INSPECTORS} "
849
+ )
850
+
851
+ return dict(index=index, path=path, dtype=dtypes.pop())
852
+ except (StopIteration, AssertionError): # pragma: no cover
853
+ return None
854
+
855
+ def import_files(self, instance, files, files_data, symlink, copy):
856
+ """
857
+ Move/link files into instance's `storage_url` and update database.
858
+
859
+ Arguments:
860
+ instance (dict): experiment instance.
861
+ files (dict): list of files to be imported.
862
+ copy (bool): if True files are copied intead of moved.
863
+ symlink (dict): whether to symlink or move the data.
864
+ files_data (dict): keys are files basenames and values are
865
+ dicts with extra annotations such as PL, LB, or any other.
866
+
867
+ Raises:
868
+ click.UsageError: if multiple data formats are found.
869
+
870
+ Returns:
871
+ dict: patched experiment instance.
872
+ """
873
+ raw_data = []
874
+ src_dst = []
875
+
876
+ if not instance["storage_url"]:
877
+ instance = update_storage_url(
878
+ endpoint="experiments", identifier=instance["pk"], use_hash=True
879
+ )
880
+
881
+ data_dir = join(instance["storage_url"], "data")
882
+ utils.makedirs(data_dir)
883
+
884
+ for src, file_type in [(i["path"], i["dtype"]) for i in files]:
885
+ file_name = basename(src)
886
+ file_data = files_data.get(file_name, {})
887
+
888
+ # make sure there are no duplicate file names
889
+ if not file_name.startswith(instance["system_id"]):
890
+ file_hash = hex(abs(hash(dirname(src))))[2:]
891
+ file_name = f'{instance["system_id"]}_{file_hash}_{file_name}'
892
+
893
+ # make sure we don't add the same file twice
894
+ if all(i != src for i, _ in src_dst):
895
+ dst = join(data_dir, file_name)
896
+ src_dst.append((src, dst))
897
+ raw_data.append(
898
+ dict(
899
+ hash_value=getsize(src),
900
+ hash_method="os.path.getsize",
901
+ file_url=dst,
902
+ file_type=file_type,
903
+ file_data=self.annotate_file_data(
904
+ experiment=instance,
905
+ file_type=file_type,
906
+ file_data=file_data,
907
+ src=src,
908
+ dst=dst,
909
+ ),
910
+ )
911
+ )
912
+
913
+ for src, dst in src_dst:
914
+ if copy:
915
+ click.secho(f"\nCopying raw data files...", fg="blue")
916
+ self.copy(src, dst)
917
+ elif symlink:
918
+ self.symlink(src, dst)
919
+ else:
920
+ self.move(src, dst)
921
+
922
+ try:
923
+ subprocess.check_call(["chmod", "a-w", dst])
924
+ except subprocess.CalledProcessError:
925
+ pass
926
+
927
+ return api.patch_instance(
928
+ endpoint="experiments",
929
+ instance_id=instance["pk"],
930
+ storage_url=instance["storage_url"],
931
+ storage_usage=utils.get_tree_size(instance["storage_url"]),
932
+ raw_data=sorted(raw_data, key=lambda i: i["file_url"]),
933
+ )
934
+
935
+ @staticmethod
936
+ def get_regex_pattern(group_name, identifier, iexact=False):
937
+ """
938
+ Get regex pattern for `identifier` group as `group_name`.
939
+
940
+ This pattern treats dashes, underscores and dots equally.
941
+
942
+ Arguments:
943
+ group_name (str): regex pattern group name.
944
+ identifier (str): identifier to be matched by regex.
945
+ iexact (bool): use case insensitive match.
946
+
947
+ Returns:
948
+ str: a regex pattern.
949
+ """
950
+ return r"(?P<{}>{}(^|[-_. ])?{}[-_. ])".format(
951
+ group_name,
952
+ r"(?i)" if iexact else "",
953
+ re.sub(r"[-_. ]", r"[-_. ]", identifier),
954
+ )
955
+
956
+ @staticmethod
957
+ def get_summary(cache):
958
+ """Get a summary of the matched, skipped, and missing files."""
959
+ skipped, missing, matched, total_matched, nl = [], [], [], 0, "\n"
960
+
961
+ for i in cache.values():
962
+ if i["instance"]["raw_data"]:
963
+ msg = click.style(f"skipped {i['using_id']}\t", fg="cyan")
964
+ skipped.append(msg)
965
+ elif i["files"]:
966
+ total_matched += len(i["files"])
967
+ matched.append(
968
+ click.style(f"found {i['using_id']}\n\t\t", fg="green")
969
+ + "\n\t\t".join([f"{j['dtype']} - {j['path']}" for j in i["files"]])
970
+ )
971
+ else:
972
+ msg = click.style(f"missing {i['using_id']}\t", fg="red")
973
+ missing.append(msg + "no files matched")
974
+
975
+ return (
976
+ f"{nl.join([nl] + skipped) if skipped else ''}"
977
+ f"{nl.join([nl] + missing) if missing else ''}"
978
+ f"{nl.join([nl] + matched) if matched else ''}"
979
+ f"\n\ntotal samples: {len(cache)}"
980
+ f"\nsamples skipped: {len(skipped)}"
981
+ f"\nsamples missing: {len(missing)}"
982
+ f"\nsamples matched: {len(matched)}"
983
+ f"\ntotal files matched: {total_matched}"
984
+ )
985
+
986
+ @classmethod
987
+ def as_cli_command(cls):
988
+ """Get data importer as a click command line interface."""
989
+ # build isabl_cli command and return it
990
+ @click.command(name="import-data")
991
+ @options.DIRECTORIES
992
+ @options.IDENTIFIER
993
+ @options.FILTERS
994
+ @options.COMMIT
995
+ @options.SYMLINK
996
+ @options.FILES_DATA
997
+ @click.option(
998
+ "--dtypes", help="Limit data types to be imported.", multiple=True
999
+ )
1000
+ @click.option(
1001
+ "--iexact", help="Case insensitive match of identifiers.", is_flag=True
1002
+ )
1003
+ @click.option("--ignore-ownership", help="Don't check ownership.", is_flag=True)
1004
+ @click.option("--copy", help="Copy files instead of moving them.", is_flag=True)
1005
+ def cmd(
1006
+ identifier,
1007
+ commit,
1008
+ filters,
1009
+ directories,
1010
+ symlink,
1011
+ copy,
1012
+ files_data,
1013
+ dtypes,
1014
+ iexact,
1015
+ ignore_ownership,
1016
+ ):
1017
+ """
1018
+ Find and import experiments data from many directories.
1019
+
1020
+ A recursive search will match raw data with database identifiers. Use
1021
+ --dtypes to limit the data types that will be matched at a given import.
1022
+
1023
+ Its possible to provide custom annotation per file (e.g. PL, PU, or
1024
+ LB in the case of fastq data). In order to do so, provide a yaml
1025
+ file using the `--files-data` argument. Such file must look
1026
+ like this, please note that keys are file names, not full paths:
1027
+
1028
+ \b
1029
+ 1.fq:
1030
+ ID: 9
1031
+ LB: Library_id
1032
+ PL: ILLUMINA
1033
+ PM: HiSeq-XTen
1034
+ PU: MICHELLE
1035
+ 2.fq:
1036
+ LB: Library2
1037
+ ...
1038
+ """
1039
+ # function to get nested attributes from dictionary
1040
+ def key(experiment):
1041
+ value, types = experiment, (int, str, type(None))
1042
+ for i in identifier:
1043
+ value = value.get(i)
1044
+ if not isinstance(value, types):
1045
+ raise click.UsageError(
1046
+ f"invalid type for identifier "
1047
+ f'`{".".join(identifier)}`: {type(value)}'
1048
+ )
1049
+ return value
1050
+
1051
+ if files_data:
1052
+ with open(files_data) as f:
1053
+ files_data = yaml.load(f.read(), Loader=yaml.FullLoader)
1054
+ else:
1055
+ files_data = {}
1056
+
1057
+ if symlink and copy:
1058
+ raise click.UsageError(
1059
+ f"Use either --copy or --symlink."
1060
+ ) # pragma: no cover
1061
+
1062
+ if symlink and ignore_ownership:
1063
+ click.secho(
1064
+ "--ignore-ownership isnt used when --symlink.",
1065
+ err=True,
1066
+ fg="yellow",
1067
+ ) # pragma: no cover
1068
+
1069
+ matched, summary = cls().import_data(
1070
+ directories=directories,
1071
+ symlink=symlink,
1072
+ copy=copy,
1073
+ commit=commit,
1074
+ key=key,
1075
+ files_data=files_data,
1076
+ dtypes=dtypes,
1077
+ iexact=iexact,
1078
+ ignore_ownership=ignore_ownership,
1079
+ **filters,
1080
+ )
1081
+
1082
+ click.echo(summary)
1083
+
1084
+ if not commit and matched: # pragma: no cover
1085
+ utils.echo_add_commit_message()
1086
+
1087
+ return cmd
1088
+
1089
+
1090
+ class LocalYamlDataImporter(LocalDataImporter):
1091
+ def import_data_from_yaml(
1092
+ self,
1093
+ symlink=False,
1094
+ copy=False,
1095
+ commit=False,
1096
+ files_data=None,
1097
+ ignore_ownership=False,
1098
+ **filters,
1099
+ ):
1100
+ """Import data from local YAML file."""
1101
+ utils.check_admin()
1102
+ experiments_matched = []
1103
+ files_to_import = []
1104
+
1105
+ # retrieve the experiment
1106
+ experiments = api.get_instances("experiments", verbose=True, **filters)
1107
+ assert (
1108
+ len(experiments) == 1
1109
+ ), f"{len(experiments)} experiments retrieved when expected only 1"
1110
+ experiment = experiments[0]
1111
+
1112
+ assert (
1113
+ experiment["raw_data"] is None and len(experiment["bam_files"]) == 0
1114
+ ), f"Experiment already has data"
1115
+
1116
+ # to reuse import_files method, creating a new dictionary w/o absolute paths
1117
+ modified_files_data = {}
1118
+
1119
+ # get files to import
1120
+ with open(files_data) as file:
1121
+ files_data_yaml = yaml.load(file, Loader=yaml.FullLoader)
1122
+
1123
+ for file_to_be_imported in files_data_yaml.keys():
1124
+ # verify files listed in yaml actually exist
1125
+ assert os.path.exists(
1126
+ file_to_be_imported
1127
+ ), f"File {file_to_be_imported} does not exist"
1128
+
1129
+ # check file ownership, if applicable
1130
+ if not ignore_ownership and not symlink:
1131
+ utils.assert_same_owner(file_to_be_imported)
1132
+
1133
+ # determine if valid data type
1134
+ dtypes = [i(file_to_be_imported) for i in self.RAW_DATA_INSPECTORS]
1135
+ dtypes = set(i for i in dtypes if i)
1136
+ assert len(dtypes) == 1 # happens if no data type matched
1137
+ files_to_import.append(
1138
+ {"path": file_to_be_imported, "dtype": dtypes.pop()}
1139
+ )
1140
+
1141
+ modified_files_data[basename(file_to_be_imported)] = files_data_yaml[
1142
+ file_to_be_imported
1143
+ ]
1144
+
1145
+ # import experiment if commit is set to true and there are files to import
1146
+ if commit and files_to_import:
1147
+ experiments_matched.append(
1148
+ self.import_files(
1149
+ instance=experiment,
1150
+ files=files_to_import,
1151
+ symlink=symlink,
1152
+ copy=copy,
1153
+ files_data=modified_files_data,
1154
+ )
1155
+ )
1156
+ else:
1157
+ experiments_matched = [experiment]
1158
+
1159
+ return self.get_summary(
1160
+ files_to_import, experiment, commit, experiments_matched
1161
+ )
1162
+
1163
+ @staticmethod
1164
+ def get_summary(files, experiment, commit, matched):
1165
+ """Return summary of the import operation."""
1166
+ summary = (
1167
+ f"\n\nFor experiment '{experiment.system_id}' "
1168
+ f"linked to sample '{experiment.sample.identifier}', "
1169
+ f"{click.style('IMPORTED ' if commit else 'WOULD HAVE IMPORTED ', fg='cyan', bold=True)}"
1170
+ )
1171
+ summary += f"the following {len(files)} files:"
1172
+
1173
+ for file in files:
1174
+ summary += f"\n\t {click.style('->', fg='yellow', bold=True)} {file}"
1175
+
1176
+ if not commit and matched: # pragma: no cover
1177
+ summary += click.style(
1178
+ "\n\nAdd --commit to proceed.\n", fg="green", blink=True
1179
+ )
1180
+
1181
+ return summary
1182
+
1183
+ @classmethod
1184
+ def as_cli_command(cls):
1185
+ """Get data importer as a click command line interface."""
1186
+ # build isabl_cli command and return it
1187
+ @click.command(name="import-data-from-yaml")
1188
+ @options.FILTERS
1189
+ @options.COMMIT
1190
+ @options.SYMLINK
1191
+ @options.FILES_DATA
1192
+ @click.option("--ignore-ownership", help="Don't check ownership.", is_flag=True)
1193
+ @click.option("--copy", help="Copy files instead of moving them.", is_flag=True)
1194
+ def cmd(commit, filters, symlink, copy, files_data, ignore_ownership):
1195
+ """
1196
+ Import data into an experiment by specifying a path to a files_data yaml file.
1197
+
1198
+ The files_data yaml file must contain absolute file paths.
1199
+
1200
+ files_data.yaml structure:
1201
+
1202
+ The top level key needs to be an absolute path to a file,
1203
+ while the values can be whatever data is relevant to the person importing.
1204
+
1205
+ \b
1206
+ \b
1207
+ Example of files_data yaml structure:
1208
+ \b
1209
+ absolute/path/to/file/file_name_1.some_extension <-- top level key
1210
+ key_1: value_1 <-- top level value
1211
+ key_2: value_2 <-- top level value
1212
+ absolute/path/to/file/file_name_2.some_extension <-- top level key
1213
+ key_1: value_1 <-- top level value
1214
+ key_2: value_2 <-- top level value
1215
+ ...
1216
+ """
1217
+ # verify yaml file exits
1218
+ assert os.path.exists(
1219
+ files_data
1220
+ ), f"The following files_data yaml path '{files_data}' does not exist."
1221
+
1222
+ if symlink and ignore_ownership: # pragma: no cover
1223
+ click.secho(
1224
+ "--ignore-ownership isnt used when --symlink.",
1225
+ err=True,
1226
+ fg="yellow",
1227
+ )
1228
+
1229
+ summary = cls().import_data_from_yaml(
1230
+ symlink=symlink,
1231
+ copy=copy,
1232
+ commit=commit,
1233
+ files_data=files_data,
1234
+ ignore_ownership=ignore_ownership,
1235
+ **filters,
1236
+ )
1237
+
1238
+ click.echo(summary)
1239
+
1240
+ return cmd