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/app.py ADDED
@@ -0,0 +1,1926 @@
1
+ """Abstract Application."""
2
+
3
+ # pylint: disable=R0201,C0103,too-many-lines
4
+
5
+ from collections import defaultdict
6
+ from contextlib import redirect_stderr
7
+ from contextlib import redirect_stdout
8
+ from os.path import isdir
9
+ from os.path import isfile
10
+ from os.path import join
11
+ import abc
12
+ import os
13
+ import sys
14
+ import traceback
15
+
16
+ from cached_property import cached_property
17
+ from click import progressbar
18
+ from slugify import slugify
19
+ import analytics
20
+ import click
21
+
22
+ from isabl_cli import api
23
+ from isabl_cli import data
24
+ from isabl_cli import exceptions
25
+ from isabl_cli import utils
26
+ from isabl_cli import options
27
+ from isabl_cli.batch_systems import submit_local
28
+ from isabl_cli.settings import get_application_settings
29
+ from isabl_cli.settings import system_settings
30
+
31
+
32
+ class AbstractApplication: # pylint: disable=too-many-public-methods
33
+
34
+ """An Abstract Isabl application."""
35
+
36
+ # The uniqueness of an application is determined by it's name and version.
37
+ # A good strategy to applications is to ask are results still comparable?
38
+ # An optimization that doesn't change outputs might not require a version change.
39
+ NAME = None
40
+ VERSION = None
41
+
42
+ # Optionally set ASSEMBLY and SPECIES to version as a function of genome build.
43
+ # This is particularly useful for NGS applications as often results are only
44
+ # comparable if data was analyzed against the same version of the genome.
45
+ ASSEMBLY = None
46
+ SPECIES = None
47
+
48
+ # URL (or comma separated URLs) to be stored in the application database object.
49
+ application_url = None
50
+ application_description = ""
51
+
52
+ # Applications can depend on multiple configurations such as paths to executables,
53
+ # references files, compute requirements, etc. These settings are explicitly
54
+ # defined using the application_settings dictionary. Learn more at:
55
+ # https://docs.isabl.io/writing-applications#application-settings
56
+ application_settings = dict()
57
+ application_import_strings = set()
58
+
59
+ # Applications can be launched from the command line. To support this capability
60
+ # you have to tell the application how to link analyses to different experiments.
61
+ # Learn more: https://docs.isabl.io/writing-applications#command-line-configuration
62
+ cli_help = ""
63
+ cli_options = []
64
+ cli_allow_force = True
65
+ cli_allow_restart = True
66
+ cli_allow_local = True
67
+
68
+ # You can provide an specification your application results using this attribute.
69
+ # Each key is a result id and the value is a dictionary with specs of the result.
70
+ # By default, analysis results are protected upon completion (i.e. permissions are
71
+ # set to read only).
72
+ application_results = dict()
73
+
74
+ # Disabling application_protect_results makes an app re-runnable. Meaning that
75
+ # analyses in SUCCEEDED status can be re-run and overwritten.
76
+ application_protect_results = True
77
+
78
+ # Isabl applications can produce auto-merge analyses at a project and individual
79
+ # level. For example, you may want to merge variants whenever new results are
80
+ # available for a given project, or update quality control reports when a new
81
+ # sample is added to an individual. A newly versioned analysis will be created for
82
+ # each type of auto-merge and your role is to take a list of succeeded analysis
83
+ # and implement the merge logic.
84
+ application_project_level_results = dict()
85
+ application_individual_level_results = dict()
86
+
87
+ # application_inputs are analysis-specific settings (settings are the same for all
88
+ # analyses, yet inputs are potentially different for each analysis). Each input set
89
+ # to NotImplemented is considered required and must be resolved at get_dependencies
90
+ application_inputs = dict()
91
+
92
+ dependencies_results = []
93
+
94
+ # It is possible to create applications that are unique at the individual level.
95
+ # A good example of a unique per individual application could be a patient centric
96
+ # report that aggregates results across all samples. Applications that require a
97
+ # unique analysis per individual don't support individual level auto-merge.
98
+ unique_analysis_per_individual = False
99
+
100
+ # Analyses in these status won't be prepared for submission. To re-rerun SUCCEEDED
101
+ # analyses see unique_analysis_per_individual. To re-rerun failed analyses use
102
+ # either --force or --restart.
103
+ skip_status = {
104
+ "FAILED",
105
+ "FINISHED",
106
+ "STARTED",
107
+ "SUBMITTED",
108
+ "SUCCEEDED",
109
+ "REJECTED",
110
+ }
111
+
112
+ # If any of these errors is raised during the command generation process, the
113
+ # submission will continue. Errors or valdation messages are presented at the end.
114
+ skip_exceptions = (
115
+ AssertionError,
116
+ click.UsageError,
117
+ exceptions.MissingRequirementError,
118
+ exceptions.ConfigurationError,
119
+ exceptions.MissingOutputError,
120
+ )
121
+
122
+ # private variables
123
+ _staged_message = "READY FOR SUBMISSION"
124
+
125
+ # private result keys
126
+ _command_script_key = "command_script"
127
+ _command_log_key = "command_log"
128
+ _command_err_key = "command_err"
129
+ _base_results = {
130
+ _command_script_key: {
131
+ "frontend_type": "ansi",
132
+ "description": "Script used to execute the analysis.",
133
+ "verbose_name": "Analysis Script",
134
+ },
135
+ _command_log_key: {
136
+ "frontend_type": "ansi",
137
+ "description": "Analysis standard output.",
138
+ "verbose_name": "Standard Output",
139
+ },
140
+ _command_err_key: {
141
+ "frontend_type": "ansi",
142
+ "description": "Analysis standard error.",
143
+ "verbose_name": "Standard Error",
144
+ },
145
+ }
146
+
147
+ # -----------------------------
148
+ # USER REQUIRED IMPLEMENTATIONS
149
+ # -----------------------------
150
+
151
+ def get_command(self, analysis, inputs, settings): # pylint: disable=W9008
152
+ """
153
+ Must return a shell command for the analysis as a string.
154
+
155
+ Arguments:
156
+ analysis (dict): an analysis object as retrieved from API.
157
+ inputs (dict): as returned by `get_dependencies`.
158
+ settings (dict): applications settings.
159
+
160
+ Returns:
161
+ str: command
162
+ """
163
+ raise NotImplementedError()
164
+
165
+ # ------------------------
166
+ # OPTIONAL IMPLEMENTATIONS
167
+ # ------------------------
168
+
169
+ @abc.abstractmethod
170
+ def get_experiments_from_cli_options(self, **cli_options): # pylint: disable=W9008
171
+ """
172
+ Must return list of target-reference experiment tuples given the parsed options.
173
+
174
+ Arguments:
175
+ cli_options (dict): parsed command line options.
176
+
177
+ Returns:
178
+ list: of (targets, references) tuples.
179
+ """
180
+ raise NotImplementedError()
181
+
182
+ def get_analysis_results(self, analysis): # pylint: disable=W9008,W0613
183
+ """
184
+ Get dictionary of analysis results.
185
+
186
+ This function is run on completion.
187
+
188
+ Arguments:
189
+ analysis (dict): succeeded analysis instance.
190
+
191
+ Returns:
192
+ dict: a jsonable dictionary.
193
+ """
194
+ return {} # pragma: no cover
195
+
196
+ def get_after_completion_status(self, analysis): # pylint: disable=W0613
197
+ """Possible values are FINISHED and IN_PROGRESS."""
198
+ return "FINISHED"
199
+
200
+ def validate_settings(self, settings):
201
+ """
202
+ Validate settings.
203
+
204
+ Make sure application settings are valid by raising an AssertionError if
205
+ something is properly configured.
206
+
207
+ Arguments:
208
+ settings (isabl_cli.settings.ApplicationSettings): an application settings
209
+ object, which is also a Munch-like dictionary.
210
+ """
211
+ return
212
+
213
+ def validate_experiments(self, targets, references): # pylint: disable=W9008
214
+ """
215
+ Raise AssertionError if tuple combination isn't valid.
216
+
217
+ Some of the advantages of metadata-driven applications is that we can prevent
218
+ analyses that don't make sense, for example running a variant calling
219
+ application on imaging data.
220
+
221
+ Arguments:
222
+ targets (list): list of targets dictionaries.
223
+ references (list): list of references dictionaries.
224
+
225
+ Raises:
226
+ AssertionError: if tuple is invalid.
227
+ """
228
+ raise NotImplementedError()
229
+
230
+ def get_dependencies(
231
+ self, targets, references, settings
232
+ ): # pylint: disable=W9008,W0613
233
+ """
234
+ Get dictionary of inputs, this function is run before `get_command`.
235
+
236
+ Arguments:
237
+ targets (list): created analysis instance.
238
+ references (list): created analysis instance.
239
+ settings (object): settings namespace.
240
+
241
+ Returns:
242
+ tuple: (list of analyses dependencies primary keys, inputs dict).
243
+ """
244
+ return [], {}
245
+
246
+ # --------------------------------------
247
+ # PROJECT LEVEL OPTIONAL IMPLEMENTATIONS
248
+ # --------------------------------------
249
+
250
+ def get_project_analysis_results(self, analysis): # pylint: disable=W9008,W0613
251
+ """
252
+ Get dictionary of results for a project level analysis.
253
+
254
+ This function is run on completion.
255
+
256
+ Arguments:
257
+ analysis (dict): succeeded analysis instance.
258
+
259
+ Returns:
260
+ dict: a jsonable dictionary.
261
+ """
262
+ return {} # pragma: no cover
263
+
264
+ @abc.abstractmethod # add __isabstractmethod__ property to method
265
+ def merge_project_analyses(self, analysis, analyses):
266
+ """
267
+ Merge analyses on a project level basis.
268
+
269
+ If implemented, a new project level analyses will be created. This
270
+ function will only be called if no other analysis of the same
271
+ application is currently running or submitted.
272
+
273
+ Arguments:
274
+ analysis (dict): the project level analysis.
275
+ analyses (list): list of succeeded analyses instances.
276
+ """
277
+ raise NotImplementedError("No merging logic available!")
278
+
279
+ def validate_project_analyses(self, project, analyses):
280
+ """Raise AssertionError if project level analysis logic shouldn't happen."""
281
+ return
282
+
283
+ # --------------------------------------
284
+ # INDIVIDUAL LEVEL OPTIONAL IMPLEMENTATIONS
285
+ # --------------------------------------
286
+
287
+ def get_individual_analysis_results(self, analysis): # pylint: disable=W9008,W0613
288
+ """
289
+ Get dictionary of results for a individual level analysis.
290
+
291
+ This function is run on completion.
292
+
293
+ Arguments:
294
+ analysis (dict): succeeded analysis instance.
295
+
296
+ Returns:
297
+ dict: a jsonable dictionary.
298
+ """
299
+ return {} # pragma: no cover
300
+
301
+ @abc.abstractmethod # add __isabstractmethod__ property to method
302
+ def merge_individual_analyses(self, analysis, analyses):
303
+ """
304
+ Merge analyses on a individual level basis.
305
+
306
+ If implemented, a new individual level analyses will be created. This
307
+ function will only be called if no other analysis of the same
308
+ application is currently running or submitted.
309
+
310
+ Arguments:
311
+ analysis (dict): the individual level analysis.
312
+ analyses (list): list of succeeded analyses instances.
313
+ """
314
+ raise NotImplementedError("No merging logic available!")
315
+
316
+ def validate_individual_analyses(self, individual, analyses):
317
+ """Raise AssertionError if individual level analysis logic shouldn't happen."""
318
+ return
319
+
320
+ # --------------------
321
+ # MERGE ANALYSES LOGIC
322
+ # --------------------
323
+
324
+ def submit_merge_analysis(self, instance):
325
+ """
326
+ Directly call merge logic unless SUBMIT_MERGE_ANALYSIS.
327
+
328
+ Use setting SUBMIT_MERGE_ANALYSIS to submit the merge work with custom logic.
329
+
330
+ Arguments:
331
+ instance (obj): a project or individual instance.
332
+ """
333
+ submit_merge = system_settings.SUBMIT_MERGE_ANALYSIS
334
+
335
+ if submit_merge:
336
+ click.secho(
337
+ f"Submitting merge analyses for {instance} "
338
+ f"using: {submit_merge.__module__}.{submit_merge.__name__}"
339
+ )
340
+
341
+ submit_merge(
342
+ instance=instance,
343
+ application=self,
344
+ command=self._get_cli_merge_command(instance),
345
+ )
346
+ elif "species" in instance:
347
+ self.run_individual_merge(instance)
348
+ else:
349
+ self.run_project_merge(instance)
350
+
351
+ def _run_analyses_merge(self, instance, analyses):
352
+ merge_type = "project"
353
+ merge_analyses = self.merge_project_analyses
354
+ validate_analyses = self.validate_project_analyses
355
+ get_analysis = self.get_project_level_auto_merge_analysis
356
+
357
+ if "species" in instance:
358
+ merge_type = "individual"
359
+ merge_analyses = self.merge_individual_analyses
360
+ validate_analyses = self.validate_individual_analyses
361
+ get_analysis = self.get_individual_level_auto_merge_analysis
362
+
363
+ if not analyses or len(analyses) < 2:
364
+ click.secho(
365
+ f"Not enough analyses for {instance} merge, "
366
+ f"at least 2 required but got: {len(analyses)}",
367
+ err=True,
368
+ fg="yellow",
369
+ )
370
+ return
371
+
372
+ try:
373
+ validate_analyses(instance, analyses)
374
+ analysis = get_analysis(instance)
375
+ except AssertionError as error: # pragma: no cover
376
+ click.echo(f"Analysis not created, validation failed: {error}")
377
+ return
378
+
379
+ if analysis.status == "STARTED": # pragma: no cover
380
+ click.secho(f"analysis {analysis} is 'STARTED', exiting...", fg="blue")
381
+ return
382
+
383
+ if not analysis.storage_url:
384
+ self._patch_analysis(analysis)
385
+
386
+ try:
387
+ # raise error if can't write in directory
388
+ with open(self.get_command_script_path(analysis), "w") as f:
389
+ f.write(self._get_cli_merge_command(instance))
390
+ except PermissionError as error: # pragma: no cover
391
+ api.patch_analysis_status(analysis, "FAILED")
392
+ raise error
393
+
394
+ # make sure merge level analyses are group writable
395
+ oldmask = os.umask(0o07)
396
+ stdout_path = self.get_command_log_path(analysis)
397
+ stderr_path = self.get_command_err_path(analysis)
398
+ error = None
399
+ error_msg = ""
400
+
401
+ with open(stdout_path, "w") as out, open(stderr_path, "w") as err:
402
+ with redirect_stdout(out), redirect_stderr(err):
403
+ try:
404
+ # TODO: setting to submitted here temporarily, will fix later
405
+ api.patch_analysis_status(analysis, "SUBMITTED")
406
+ api.patch_analysis_status(analysis, "STARTED")
407
+ merge_analyses(analysis, analyses)
408
+ api.patch_analysis_status(analysis, "SUCCEEDED")
409
+ except Exception as e: # pragma: no cover pylint: disable=W0703
410
+ error_msg = traceback.format_exc()
411
+ click.echo(error_msg, file=sys.stderr)
412
+ click.echo(e, file=sys.stderr)
413
+ api.patch_analysis_status(analysis, "FAILED")
414
+ error = e
415
+ print(error_msg)
416
+
417
+ api.patch_instance("analyses", analysis.pk, data=analysis.data)
418
+ os.umask(oldmask)
419
+ if error is not None:
420
+ raise Exception(
421
+ f"Merge analysis ({analysis}) failed for {instance}. You can "
422
+ f"retry this operation with `isabl merge-{merge_type}-analyses "
423
+ f"--{merge_type} {instance.pk} "
424
+ f"--application {analyses[0].application.pk}`. "
425
+ f"The error traceback, if any, was: {error} {error_msg}"
426
+ )
427
+
428
+ def _get_cli_merge_command(self, instance):
429
+ if "species" in instance:
430
+ return (
431
+ f"isabl merge-individual-analyses --individual {instance['pk']} "
432
+ f"--application {self.primary_key}\n"
433
+ )
434
+
435
+ return (
436
+ f"isabl merge-project-analyses --project {instance['pk']} "
437
+ f"--application {self.primary_key}\n"
438
+ )
439
+
440
+ # ----------------------
441
+ # MERGE BY PROJECT LOGIC
442
+ # ----------------------
443
+
444
+ def run_project_merge(self, project):
445
+ """
446
+ Merge analyses on a project level basis.
447
+
448
+ Arguments:
449
+ project (dict): project instance.
450
+ """
451
+ self._run_analyses_merge(
452
+ project,
453
+ api.get_instances(
454
+ endpoint="analyses",
455
+ application=self.application["pk"],
456
+ projects=project["pk"],
457
+ status="SUCCEEDED",
458
+ ),
459
+ )
460
+
461
+ def get_project_level_auto_merge_analysis(self, project):
462
+ """
463
+ Get or create project level analysis.
464
+
465
+ Arguments:
466
+ project (dict): project instance.
467
+
468
+ Returns:
469
+ dict: analysis instance.
470
+ """
471
+ return api.create_instance(
472
+ endpoint="analyses",
473
+ project_level_analysis=project,
474
+ application=self.project_level_auto_merge_application,
475
+ )
476
+
477
+ # -------------------------
478
+ # MERGE BY INDIVIDUAL LOGIC
479
+ # -------------------------
480
+
481
+ def run_individual_merge(self, individual):
482
+ """
483
+ Merge analyses on a individual level basis.
484
+
485
+ Arguments:
486
+ individual (dict): individual instance.
487
+ """
488
+ assert not self.unique_analysis_per_individual, (
489
+ "Applications that require a unique analysis per individual "
490
+ "don't support individual level auto-merge."
491
+ )
492
+
493
+ self._run_analyses_merge(
494
+ individual,
495
+ api.get_instances(
496
+ endpoint="analyses",
497
+ application=self.application["pk"],
498
+ targets__sample__individual__pk=individual["pk"],
499
+ status="SUCCEEDED",
500
+ ),
501
+ )
502
+
503
+ def get_individual_level_auto_merge_analysis(self, individual):
504
+ """
505
+ Get or create individual level analysis.
506
+
507
+ Arguments:
508
+ individual (dict): individual instance.
509
+
510
+ Returns:
511
+ dict: analysis instance.
512
+ """
513
+ assert not self.unique_analysis_per_individual, (
514
+ "Applications that require a unique analysis per individual "
515
+ "don't support individual level auto-merge."
516
+ )
517
+
518
+ return api.create_instance(
519
+ endpoint="analyses",
520
+ individual_level_analysis=individual,
521
+ application=self.individual_level_auto_merge_application,
522
+ )
523
+
524
+ # ----------
525
+ # PROPERTIES
526
+ # ----------
527
+
528
+ @cached_property
529
+ def client_id(self):
530
+ """Get current client ID."""
531
+ return str(system_settings.client.get("pk", "default_client"))
532
+
533
+ @cached_property
534
+ def primary_key(self):
535
+ """Space separated name, version and assembly."""
536
+ return self.application["pk"]
537
+
538
+ @cached_property
539
+ def settings(self):
540
+ """Return the application settings."""
541
+ reference_data = dict()
542
+ import_strings = set(self.application_import_strings)
543
+ import_strings.add("submit_analyses")
544
+ defaults = self.application_settings.copy()
545
+ defaults["submit_analyses"] = defaults.get("submit_analyses", None)
546
+
547
+ if self.application.assembly:
548
+ reference_data = self.application.assembly.reference_data or {}
549
+
550
+ return get_application_settings(
551
+ defaults=defaults,
552
+ settings=self._settings_for_client,
553
+ reference_data=reference_data,
554
+ import_strings=import_strings,
555
+ )
556
+
557
+ @cached_property
558
+ def application(self):
559
+ """Get application database object."""
560
+ assert all([self.NAME, self.VERSION]), (
561
+ f"NAME must be set: {self.NAME}\n" f"VERSION must be set: {self.VERSION}\n"
562
+ )
563
+
564
+ if any([self.ASSEMBLY, self.SPECIES]):
565
+ assert all([self.ASSEMBLY, self.SPECIES]), (
566
+ f"ASSEMBLY must be set: {self.ASSEMBLY}\n"
567
+ f"SPECIES must be set: {self.SPECIES}\n"
568
+ )
569
+
570
+ application = api.create_instance(
571
+ endpoint="applications",
572
+ name=self.NAME,
573
+ version=self.VERSION,
574
+ assembly=(
575
+ {"name": self.ASSEMBLY, "species": self.SPECIES}
576
+ if self.ASSEMBLY
577
+ else None
578
+ ),
579
+ )
580
+
581
+ if application.settings.get("default_client") is None:
582
+ application.settings["default_client"] = {}
583
+
584
+ return api.patch_instance(
585
+ description=self.application_description,
586
+ endpoint="applications",
587
+ instance_id=application["pk"],
588
+ application_class=f"{self.__module__}.{self.__class__.__name__}",
589
+ results=self._application_results,
590
+ url=self.application_url,
591
+ settings=application.settings,
592
+ )
593
+
594
+ @cached_property
595
+ def individual_level_auto_merge_application(self):
596
+ """Get or create an individual level application database object."""
597
+ assert not hasattr(
598
+ self.merge_individual_analyses, "__isabstractmethod__"
599
+ ), "No logic implemented to merge analyses for an individual..."
600
+
601
+ application = api.create_instance(
602
+ endpoint="applications",
603
+ name=f"{self.NAME} Individual Application",
604
+ version=self.VERSION,
605
+ assembly=self.application["assembly"],
606
+ )
607
+
608
+ return api.patch_instance(
609
+ description=f"{self.NAME} {self.VERSION} Individual Level Application.",
610
+ endpoint="applications",
611
+ instance_id=application["pk"],
612
+ results=self._application_individual_level_results,
613
+ application_class=self.application["application_class"],
614
+ url=self.application_url,
615
+ )
616
+
617
+ @cached_property
618
+ def project_level_auto_merge_application(self):
619
+ """Get or create a project level application database object."""
620
+ assert not hasattr(
621
+ self.merge_project_analyses, "__isabstractmethod__"
622
+ ), "No logic implemented to merge project analyses..."
623
+
624
+ application = api.create_instance(
625
+ endpoint="applications",
626
+ name=f"{self.NAME} Project Application",
627
+ version=self.VERSION,
628
+ assembly=self.application["assembly"],
629
+ )
630
+
631
+ return api.patch_instance(
632
+ description=f"{self.NAME} {self.VERSION} Project Level Application.",
633
+ endpoint="applications",
634
+ instance_id=application["pk"],
635
+ results=self._application_project_level_results,
636
+ application_class=self.application["application_class"],
637
+ url=self.application_url,
638
+ )
639
+
640
+ @cached_property
641
+ def assembly(self):
642
+ """Get assembly database object."""
643
+ return self.application["assembly"]
644
+
645
+ @property
646
+ def has_project_auto_merge(self):
647
+ """Return True if project level auto merge logic is defined."""
648
+ return not hasattr(self.merge_project_analyses, "__isabstractmethod__")
649
+
650
+ @property
651
+ def has_individual_auto_merge(self):
652
+ """Return True if individual level auto merge logic is defined."""
653
+ return not hasattr(self.merge_individual_analyses, "__isabstractmethod__")
654
+
655
+ @property
656
+ def _application_results(self):
657
+ ret = self.application_results
658
+ ret.update(self._base_results)
659
+ return ret
660
+
661
+ @property
662
+ def _application_project_level_results(self):
663
+ ret = self.application_project_level_results
664
+ ret.update(self._base_results)
665
+ return ret
666
+
667
+ @property
668
+ def _application_individual_level_results(self):
669
+ ret = self.application_individual_level_results
670
+ ret.update(self._base_results)
671
+ return ret
672
+
673
+ @property
674
+ def _settings_for_client(self):
675
+ return self.application.settings.get(self.client_id) or {}
676
+
677
+ # ----------------------------
678
+ # COMMAND LINE INTERFACE LOGIC
679
+ # ----------------------------
680
+
681
+ @classmethod
682
+ def as_cli_command(cls):
683
+ """Get application as click command line interface."""
684
+ pipe = cls()
685
+
686
+ commit = click.option(
687
+ "--commit",
688
+ show_default=True,
689
+ is_flag=True,
690
+ help="Submit application analyses.",
691
+ )
692
+
693
+ quiet = click.option(
694
+ "--quiet",
695
+ show_default=True,
696
+ is_flag=True,
697
+ help="Don't print verbose output of the operation.",
698
+ )
699
+
700
+ force = click.option(
701
+ "--force",
702
+ help="Wipe unfinished analyses and start from scratch.",
703
+ is_flag=True,
704
+ )
705
+
706
+ restart = click.option(
707
+ "--restart",
708
+ help="Attempt restarting failed analyses from previous checkpoint.",
709
+ is_flag=True,
710
+ )
711
+
712
+ local = click.option(
713
+ "--local",
714
+ help="Run analyses' head jobs locally, one after the other one.",
715
+ is_flag=True,
716
+ )
717
+
718
+ cli_options = [ # pylint: disable=unused-variable
719
+ (quiet, True),
720
+ (commit, True),
721
+ (force, cls.cli_allow_force),
722
+ (restart, cls.cli_allow_restart),
723
+ (local, cls.cli_allow_local),
724
+ ]
725
+
726
+ def print_url(ctx, _, value):
727
+ """Print the application url url."""
728
+ if value:
729
+ url = pipe.application["url"]
730
+ if url:
731
+ click.secho("\nApplication URL:\n", fg="green")
732
+ click.secho(url)
733
+ else: # pragma: no cover
734
+ click.secho("\nApplication has no url defined.\n")
735
+ ctx.exit()
736
+
737
+ @click.command(name=pipe.get_cli_command_name(), help=pipe.cli_help)
738
+ @click.option(
739
+ "--url",
740
+ help="Show the url or main repo of the app.",
741
+ is_eager=True,
742
+ is_flag=True,
743
+ expose_value=False,
744
+ callback=print_url,
745
+ )
746
+ @utils.apply_decorators(pipe.cli_options + [i for i, j in cli_options if j])
747
+ def command(commit, quiet, **cli_options):
748
+ """Click command to be used in the CLI."""
749
+ force = cli_options.pop("force", False)
750
+ restart = cli_options.pop("restart", False)
751
+ local = cli_options.pop("local", False)
752
+ tuples = []
753
+
754
+ if commit and force:
755
+ raise click.UsageError("--commit not required when using --force")
756
+
757
+ if commit and restart: # pragma: no cover
758
+ raise click.UsageError("--restart not required when using --force")
759
+
760
+ if force and restart:
761
+ raise click.UsageError("cant use --force and --restart together")
762
+
763
+ if not hasattr(
764
+ cls.get_experiments_from_cli_options, "__isabstractmethod__"
765
+ ):
766
+ tuples = pipe.get_experiments_from_cli_options(**cli_options)
767
+ else:
768
+ tuples = cls.get_experiments_from_default_cli_options(cli_options)
769
+
770
+ pipe.run(
771
+ tuples=tuples,
772
+ commit=commit,
773
+ force=force,
774
+ verbose=not quiet,
775
+ restart=restart,
776
+ local=local,
777
+ run_args=cli_options,
778
+ )
779
+
780
+ if not (commit or force or restart):
781
+ utils.echo_add_commit_message()
782
+
783
+ return command
784
+
785
+ def get_cli_command_name(self):
786
+ """Get name for isabl_cli command."""
787
+ return f"{slugify(self.NAME)}-{slugify(self.VERSION, separator='.')}"
788
+
789
+ @classmethod
790
+ def get_experiments_from_default_cli_options(cls, cli_options):
791
+ """Get experiments from default CLI options."""
792
+ tuples = []
793
+ references = []
794
+ supported_cli_options = [
795
+ options.ANALYSES,
796
+ options.NORMAL_TARGETS,
797
+ options.TARGETS,
798
+ options.REFERENCES,
799
+ options.NULLABLE_REFERENCES,
800
+ options.PAIR,
801
+ options.PAIRS,
802
+ options.PAIRS_FROM_FILE,
803
+ ]
804
+
805
+ assert any(i in cls.cli_options for i in supported_cli_options), (
806
+ f"'{cls.__name__}.cli_options' must include at least one of the "
807
+ f"supported default options to get experiments: {supported_cli_options}"
808
+ )
809
+
810
+ if options.PAIR in cls.cli_options:
811
+ tuples += cli_options.get("pair", [])
812
+
813
+ if options.PAIRS in cls.cli_options:
814
+ tuples += cli_options.get("pairs", [])
815
+
816
+ if options.PAIRS_FROM_FILE in cls.cli_options:
817
+ tuples += cli_options.get("pairs_from_file", [])
818
+
819
+ if options.ANALYSES in cls.cli_options:
820
+ for i in cli_options.get("analyses_filters", []):
821
+ tuples.append((i.targets, i.references))
822
+
823
+ if (
824
+ options.REFERENCES in cls.cli_options
825
+ or options.NULLABLE_REFERENCES in cls.cli_options
826
+ ):
827
+ references += cli_options.get("references", [])
828
+
829
+ if any(i in cls.cli_options for i in [options.NORMAL_TARGETS, options.TARGETS]):
830
+ for i in cli_options.get("targets", []):
831
+ tuples.append(([i], references))
832
+
833
+ return tuples
834
+
835
+ # ------------------------
836
+ # ANALYSES EXECUTION LOGIC
837
+ # ------------------------
838
+
839
+ def run(
840
+ self,
841
+ tuples,
842
+ commit,
843
+ force=False,
844
+ restart=False,
845
+ verbose=True,
846
+ run_args=None,
847
+ local=False,
848
+ ):
849
+ """
850
+ Run a list of targets, references tuples.
851
+
852
+ Arguments:
853
+ restart (bool): set settings.restart = True.
854
+ force (bool): if true, analyses are wiped before being submitted.
855
+ local (bool): if true, analyses will be run locally one by one.
856
+ commit (bool): if true, analyses are started (`force` overwrites).
857
+ verbose (bool): whether or not verbose output should be printed.
858
+ tuples (list): list of (targets, references) tuples.
859
+ run_args (dict): dictionary of extra arguments required to run the app.
860
+
861
+ Returns:
862
+ tuple: command_tuples, skipped_tuples, invalid_tuples
863
+ """
864
+ key = f"{self.NAME} {self.VERSION} {self.ASSEMBLY}"
865
+ commit = True if force or restart else commit
866
+ tuples = [tuple(i) for i in tuples] # coerce to tuple
867
+ utils.echo_title(f"Running {len(tuples)} tuples for {key}")
868
+
869
+ if not tuples: # pragma: no cover
870
+ return None
871
+
872
+ # make sure required settings are set before building commands
873
+ for i in self.application_settings:
874
+ getattr(self.settings, i)
875
+
876
+ # set restart attribute
877
+ self.settings.restart = restart
878
+
879
+ # set force attribute
880
+ self.settings.force = force
881
+
882
+ # update run arguments attribute
883
+ self.settings.run_args = api.isablfy(run_args or {})
884
+
885
+ # run extra settings validation
886
+ self.validate_settings(self.settings)
887
+
888
+ # create analyses
889
+ analyses, invalid_tuples = self.get_or_create_analyses(tuples)
890
+
891
+ # make sure outdir is set
892
+ for i in analyses:
893
+ if not i.storage_url: # pragma: no cover
894
+ self._patch_analysis(i)
895
+
896
+ # run analyses
897
+ run_tuples, skipped_tuples, invalid_run_tuples = self.run_analyses(
898
+ analyses=analyses, commit=commit, force=force, restart=restart, local=local
899
+ )
900
+
901
+ invalid_tuples.extend(invalid_run_tuples)
902
+
903
+ if verbose:
904
+ self.echo_run_summary(run_tuples, skipped_tuples, invalid_tuples)
905
+
906
+ if commit:
907
+ click.echo(
908
+ f"RAN {len(run_tuples)} | "
909
+ f"SKIPPED {len(skipped_tuples)} | "
910
+ f"INVALID {len(invalid_tuples)}\n"
911
+ )
912
+
913
+ else:
914
+ click.echo(
915
+ f"STAGED {len(run_tuples)} | "
916
+ f"SKIPPED {len(skipped_tuples)} | "
917
+ f"INVALID {len(invalid_tuples)}\n"
918
+ )
919
+
920
+ num_run_on_commit = len(run_tuples)
921
+ num_succeeded = 0
922
+ num_failed = 0
923
+
924
+ for i in skipped_tuples:
925
+ if i[1] == "SUCCEEDED":
926
+ num_succeeded += 1
927
+ if not self.application_protect_results:
928
+ num_run_on_commit += 1
929
+ else:
930
+ num_failed += 1
931
+
932
+ if not self.application_protect_results:
933
+ if num_run_on_commit == 1:
934
+ click.echo(f"{num_run_on_commit} analysis available to run:")
935
+ else:
936
+ click.echo(f"{num_run_on_commit} analyses available to run:")
937
+
938
+ click.echo(f"\t{len(run_tuples)} STAGED")
939
+ click.echo(f"\t{num_succeeded} SUCCEEDED (Unprotected)")
940
+
941
+ return run_tuples, skipped_tuples, invalid_tuples
942
+
943
+ def run_analyses(self, analyses, commit, force, restart, local):
944
+ """
945
+ Run a list of analyses.
946
+
947
+ Returns:
948
+ list: tuple of
949
+ """
950
+ skipped_tuples = []
951
+ invalid_tuples = []
952
+ command_tuples = []
953
+ submit_analyses = (
954
+ submit_local
955
+ if local
956
+ else (self.settings.submit_analyses or system_settings.SUBMIT_ANALYSES)
957
+ )
958
+
959
+ with progressbar(analyses, label="Building commands...\t\t") as bar:
960
+ for i in bar:
961
+ # if not protect results we need to change the status to staged
962
+ if (
963
+ not self.application_protect_results
964
+ and commit
965
+ and i.status == "SUCCEEDED"
966
+ ):
967
+ api.patch_analysis_status(i, "STAGED")
968
+
969
+ # trash analysis and create outdir again
970
+ elif force and i["status"] not in {"SUCCEEDED", "FINISHED", "REJECTED"}:
971
+ system_settings.TRASH_ANALYSIS_STORAGE(i)
972
+ utils.makedirs(i["storage_url"])
973
+
974
+ # only restart failed analyses
975
+ elif (
976
+ not (restart and i["status"] == "FAILED")
977
+ and i["status"] in self.skip_status
978
+ ):
979
+ skipped_tuples.append((i, i["status"]))
980
+ continue
981
+
982
+ elif restart and i.ran_by != system_settings.api_username:
983
+ invalid_tuples.append(
984
+ (
985
+ i,
986
+ "Can't restart: started by different user. Consider --force",
987
+ )
988
+ )
989
+ continue
990
+
991
+ try:
992
+ inputs = i.pop(
993
+ "application_inputs",
994
+ self._get_dependencies(i.targets, i.references),
995
+ )
996
+
997
+ command = self.get_command(i, inputs, self.settings)
998
+ command_tuples.append((i, command))
999
+ self.write_command_script(i, command)
1000
+ except self.skip_exceptions as error: # pragma: no cover
1001
+ skipped_tuples.append((i, error))
1002
+
1003
+ # track user app usage from cli
1004
+ self.send_analytics(
1005
+ command_tuples=command_tuples,
1006
+ skipped_tuples=skipped_tuples,
1007
+ invalid_tuples=invalid_tuples,
1008
+ commit=commit,
1009
+ force=force,
1010
+ restart=restart,
1011
+ submitter=submit_analyses.__name__,
1012
+ )
1013
+
1014
+ if commit:
1015
+ click.echo(f"Running analyses with {submit_analyses.__name__}...")
1016
+ run_tuples = submit_analyses(self, command_tuples)
1017
+ else:
1018
+ run_tuples = [(i, self._staged_message) for i, _ in command_tuples]
1019
+
1020
+ return run_tuples, skipped_tuples, invalid_tuples
1021
+
1022
+ def send_analytics(
1023
+ self,
1024
+ command_tuples,
1025
+ skipped_tuples,
1026
+ invalid_tuples,
1027
+ commit,
1028
+ force,
1029
+ restart,
1030
+ submitter,
1031
+ ):
1032
+ """Send analytics event of analyses ran from cli."""
1033
+ analyses_tuples = []
1034
+ for i, _ in command_tuples:
1035
+ status = (
1036
+ "FORCED"
1037
+ if force
1038
+ else (
1039
+ "RESTARTED"
1040
+ if restart
1041
+ else "SUBMITTED" if commit else self._staged_message
1042
+ )
1043
+ )
1044
+ analyses_tuples.append((i, status))
1045
+ for i, _ in skipped_tuples + invalid_tuples:
1046
+ analyses_tuples.append((i, "INVALID"))
1047
+
1048
+ analyses = []
1049
+ for i, status in analyses_tuples:
1050
+ analysis = {
1051
+ "analysis": i.pk,
1052
+ "application": {
1053
+ "name": i.application.name,
1054
+ "pk": i.application.pk,
1055
+ "version": i.application.version,
1056
+ },
1057
+ "status": status,
1058
+ }
1059
+ analyses.append(analysis)
1060
+
1061
+ analytics.track(
1062
+ system_settings.api_username,
1063
+ "Ran app",
1064
+ {
1065
+ "analyses": analyses[:200],
1066
+ "total": len(analyses),
1067
+ "submitter": submitter,
1068
+ "valid": len(command_tuples),
1069
+ "invalid": len(skipped_tuples) + len(invalid_tuples),
1070
+ },
1071
+ )
1072
+
1073
+ def get_command_script_path(self, analysis):
1074
+ """Get path to analysis command script."""
1075
+ return join(analysis["storage_url"], "head_job.sh")
1076
+
1077
+ def get_command_log_path(self, analysis):
1078
+ """Get path to analysis log file."""
1079
+ return join(analysis["storage_url"], "head_job.log")
1080
+
1081
+ def get_command_err_path(self, analysis):
1082
+ """Get path to analysis err file."""
1083
+ return join(analysis["storage_url"], "head_job.err")
1084
+
1085
+ def write_command_script(self, analysis, command):
1086
+ """
1087
+ Write analysis command to bash script and get path to it.
1088
+
1089
+ Arguments:
1090
+ analysis (dict): an analysis instance.
1091
+ command (str): command to be run.
1092
+ """
1093
+ # check status, if not run by admin will be marked as succeeded later
1094
+ outdir = analysis["storage_url"]
1095
+ utils.makedirs(outdir)
1096
+ status = self._get_after_completion_status(analysis)
1097
+
1098
+ # build and write command
1099
+ tmpdir = os.getenv("TMP", "/tmp")
1100
+ tmpdir = " && ".join(
1101
+ f"export {i}={tmpdir}" for i in ["TMP", "TMPDIR", "TMP_DIR"]
1102
+ )
1103
+ failed = self.get_patch_status_command(analysis["pk"], "FAILED")
1104
+ started = self.get_patch_status_command(analysis["pk"], "STARTED")
1105
+ finished = self.get_patch_status_command(analysis["pk"], status)
1106
+ command = (
1107
+ f"umask g+wrx && date && cd {outdir} && {tmpdir} && "
1108
+ f"{started} && {command} && {finished} && date"
1109
+ )
1110
+
1111
+ with open(self.get_command_script_path(analysis), "w") as f:
1112
+ f.write(f"{{\n\n {command}\n\n}} || {{\n\n {failed}\n\n}}")
1113
+
1114
+ @staticmethod
1115
+ def get_patch_status_command(key, status):
1116
+ """Return a command to patch the `status` of a given analysis `key`."""
1117
+ return f"isabl patch-status --key {key} --status {status}"
1118
+
1119
+ def _get_after_completion_status(self, analysis):
1120
+ status = self.get_after_completion_status(analysis)
1121
+ assert status in {"IN_PROGRESS", "FINISHED"}, "Status not supported"
1122
+
1123
+ if system_settings.is_admin_user and status == "FINISHED":
1124
+ status = "SUCCEEDED"
1125
+
1126
+ return status
1127
+
1128
+ def _get_dependencies(self, targets, references):
1129
+ missing = []
1130
+ if self.dependencies_results:
1131
+ analyses, inputs = self._get_dependencies_results(targets, references)
1132
+ else:
1133
+ analyses, inputs = self.get_dependencies(targets, references, self.settings)
1134
+
1135
+ for i, j in self.application_inputs.items(): # pragma: no cover
1136
+ if i not in inputs:
1137
+ if j is NotImplemented:
1138
+ missing.append(i)
1139
+ else:
1140
+ inputs[i] = j
1141
+
1142
+ if missing: # pragma: no cover
1143
+ missing = ", ".join(map(str, missing))
1144
+ raise exceptions.ConfigurationError(
1145
+ f"Required inputs missing from `get_dependencies`: {missing}"
1146
+ )
1147
+
1148
+ return analyses, inputs
1149
+
1150
+ def _get_dependencies_results(self, targets, references):
1151
+ """
1152
+ Get dependencies' results from a defined application version.
1153
+
1154
+ It's called when `self.dependencies_results` is an array containing an object:
1155
+ {
1156
+ result (str): Result key `Application.results.result_key`.
1157
+ name (str): Name the result will have in the inputs objects.
1158
+ app (obj): `Application` instance.
1159
+ app_name (str): `Application.name`.
1160
+ app_version (str): `Application.version`. If not defined, use
1161
+ any available. Use `any` if you want to use the latest available.
1162
+ linked (bool): if False, the analysis is not linked as a dependencie of
1163
+ the analysis. As adding new dependencies to an analysis forces isabl
1164
+ to not recognize existing ones (Default: True).
1165
+ }
1166
+ """
1167
+ inputs = {}
1168
+ analyses = []
1169
+ for dependency in self.dependencies_results:
1170
+ result_args = {
1171
+ "result_key": dependency["result"],
1172
+ "targets": targets,
1173
+ "references": references,
1174
+ }
1175
+ # Match app by name, and optionally by version
1176
+ if dependency.get("app_name"):
1177
+ result_args["application_name"] = dependency.get("app_name")
1178
+ if "app_version" in dependency:
1179
+ result_args["application_version"] = dependency.get("app_version")
1180
+ else:
1181
+ # Match app by primary key
1182
+ result_args["application_key"] = dependency.get("app").primary_key
1183
+ result_args["application_name"] = dependency.get("app").NAME
1184
+
1185
+ if "status" in dependency:
1186
+ result_args["status"] = dependency["status"]
1187
+
1188
+ input_name = dependency.get("name")
1189
+ inputs[input_name], key = self.get_result(targets[0], **result_args)
1190
+
1191
+ if not "linked" in dependency or dependency["linked"]:
1192
+ # Avoid linking the analysis as dependency to avoid creating new runs.
1193
+ analyses.append(key)
1194
+
1195
+ return analyses, inputs
1196
+
1197
+ def _get_analysis_results_from_patterns(self, analysis, specification):
1198
+ """Get first matching file, if "pattern" is in result specification."""
1199
+ results = {}
1200
+ for name, result_specification in specification.items():
1201
+ pattern = result_specification.get("pattern")
1202
+ exclude = result_specification.get("exclude")
1203
+ if pattern:
1204
+ results[name] = utils.first_matching_file(
1205
+ analysis.storage_url, pattern, exclude
1206
+ )
1207
+ return results
1208
+
1209
+ def _get_analysis_results(self, analysis, created=False):
1210
+ """Get results dictionary and append head job script, logs and error files."""
1211
+ results = {
1212
+ self._command_log_key: self.get_command_log_path(analysis),
1213
+ self._command_err_key: self.get_command_err_path(analysis),
1214
+ self._command_script_key: self.get_command_script_path(analysis),
1215
+ }
1216
+
1217
+ if created:
1218
+ return results
1219
+
1220
+ if analysis.project_level_analysis:
1221
+ specification = self.application_project_level_results
1222
+ get_results = self.get_project_analysis_results
1223
+ elif analysis.individual_level_analysis and self.has_individual_auto_merge:
1224
+ specification = self.application_individual_level_results
1225
+ get_results = self.get_individual_analysis_results
1226
+ else:
1227
+ specification = self.application_results
1228
+ get_results = self.get_analysis_results
1229
+
1230
+ results.update(
1231
+ self._get_analysis_results_from_patterns(analysis, specification)
1232
+ )
1233
+ results.update(get_results(analysis))
1234
+
1235
+ for i in specification:
1236
+ assert i in results, f"Missing expected result {i} in: {results}"
1237
+
1238
+ return results
1239
+
1240
+ # -----------------
1241
+ # APPLICATION UTILS
1242
+ # -----------------
1243
+
1244
+ @staticmethod
1245
+ def get_result(*args, **kwargs): # pragma: no cover
1246
+ """Get an application result."""
1247
+ return utils.get_result(*args, **kwargs)
1248
+
1249
+ @staticmethod
1250
+ def get_results(*args, **kwargs):
1251
+ """Get application results."""
1252
+ return utils.get_results(*args, **kwargs)
1253
+
1254
+ def patch_application_settings(self, client_id=None, **settings):
1255
+ """Patch application settings if necessary."""
1256
+ assert system_settings.is_admin_user, "Apps can be patched only by admin user."
1257
+ click.echo(f"Patching settings: {self.NAME} {self.VERSION} {self.ASSEMBLY}\n")
1258
+ client_id = str(client_id or self.client_id) # must be a string
1259
+
1260
+ try:
1261
+ assert self.application.settings.get(client_id) == settings
1262
+ click.secho(
1263
+ f"\tNo changes detected, skipping patch.\n", err=True, fg="yellow"
1264
+ )
1265
+ except AssertionError:
1266
+ try:
1267
+ api.patch_instance(
1268
+ "applications",
1269
+ self.primary_key,
1270
+ settings={**self.application.settings, client_id: settings},
1271
+ )
1272
+
1273
+ try:
1274
+ del self.settings # make sure cached settings are re-computed
1275
+ except AttributeError:
1276
+ pass
1277
+
1278
+ try:
1279
+ del self.application # make sure application is refetched
1280
+ except AttributeError:
1281
+ pass
1282
+
1283
+ click.secho("\tSuccessfully patched settings.\n", fg="green")
1284
+ except TypeError as error: # pragma: no cover
1285
+ click.secho(
1286
+ f"\tPatched failed with error: {error}.\n", err=True, fg="red"
1287
+ )
1288
+
1289
+ # create or update project level application
1290
+ if self.has_project_auto_merge:
1291
+ assert self.project_level_auto_merge_application
1292
+ click.secho(
1293
+ "\tSuccessfully updated project level application.\n", fg="magenta"
1294
+ )
1295
+
1296
+ # create or update individual level application
1297
+ if self.has_individual_auto_merge:
1298
+ assert self.individual_level_auto_merge_application
1299
+ click.secho(
1300
+ "\tSuccessfully updated individual level application.\n", fg="magenta"
1301
+ )
1302
+
1303
+ @staticmethod
1304
+ def get_job_name(analysis):
1305
+ """Get job name given an analysis instance."""
1306
+ targets = analysis["targets"]
1307
+ references = analysis["references"]
1308
+ methods = {i["technique"]["method"] for i in targets}
1309
+ projects = {str(j["pk"]) for i in targets for j in i["projects"]}
1310
+
1311
+ if len(targets) > 2 or not targets:
1312
+ targets = f"{len(targets)} samples."
1313
+ else:
1314
+ targets = " ".join([i["system_id"] for i in targets])
1315
+
1316
+ if len(references) > 2 or not references:
1317
+ references = f"{len(references)} samples."
1318
+ else: # pragma: no cover
1319
+ references = " ".join([i["system_id"] for i in references])
1320
+
1321
+ return " | ".join(
1322
+ [
1323
+ f'analysis: {analysis["pk"]}',
1324
+ f"targets: {targets}",
1325
+ f"references: {references}",
1326
+ f'methods: {" ".join(methods)}',
1327
+ f'projects: {" ".join(projects)}',
1328
+ f'rundir: {analysis["storage_url"]}',
1329
+ f'application: {analysis["application"]["pk"]}',
1330
+ ]
1331
+ )
1332
+
1333
+ def echo_run_summary(self, run_tuples, skipped_tuples, invalid_tuples):
1334
+ """
1335
+ Echo errors for error tuples such as `invalid`, `cant_run`.
1336
+
1337
+ Arguments:
1338
+ invalid_tuples (list): of (tuple, error) tuples.
1339
+ run_tuples (list): of (analysis, status) tuples.
1340
+ skipped_tuples (list): of (analysis, skip reason) tuples.
1341
+ """
1342
+ cols = ["IDENTIFIER", "PROJECTS", "TARGETS", "REFERENCES", "MESSAGE"]
1343
+ summary = ["\n", "\t".join(cols)]
1344
+ run_tuples.sort(key=lambda i: str(i[1]))
1345
+ invalid_tuples.sort(key=lambda i: str(i[1]))
1346
+ skipped_tuples.sort(key=lambda i: str(i[1]))
1347
+
1348
+ def _style_msg(msg):
1349
+ msg = str(msg)
1350
+ color = "blue"
1351
+ blink = False
1352
+
1353
+ if isinstance(msg, Exception): # pragma: no cover
1354
+ color = "red"
1355
+ elif msg == "SUCCEEDED":
1356
+ color = "green"
1357
+ elif msg == "FAILED":
1358
+ color = "red"
1359
+ elif msg == "INVALID":
1360
+ color = "yellow"
1361
+ elif msg == "SUBMITTED": # pragma: no cover
1362
+ color = "cyan"
1363
+ elif msg == self._staged_message: # pragma: no cover
1364
+ color = "magenta"
1365
+ blink = True
1366
+
1367
+ if len(msg) > 20: # pragma: no cover
1368
+ msg = msg[:100] + "..."
1369
+
1370
+ return click.style(msg, fg=color, blink=blink)
1371
+
1372
+ def _style_projects(targets):
1373
+ keys = set()
1374
+ for i in targets:
1375
+ for j in i["projects"]: # pragma: no cover
1376
+ keys.add(f"{j['pk']} ({i['technique']['method']})")
1377
+ return f"{', '.join(keys)}" if keys else "0"
1378
+
1379
+ def _style_experiments(experiments):
1380
+ if len(experiments) > 2 or not experiments:
1381
+ return f"{len(experiments)}"
1382
+ return " ".join([i["system_id"] for i in experiments])
1383
+
1384
+ for i, msg in run_tuples + skipped_tuples + invalid_tuples:
1385
+ extra_msg = ""
1386
+
1387
+ if isinstance(i, dict): # if skipped, succeeded or failed
1388
+ identifier = str(i["pk"])
1389
+ targets = i["targets"]
1390
+ references = i["references"]
1391
+ extra_msg = " " + i["storage_url"]
1392
+ else: # if invalid tuples
1393
+ extra_msg = " " + str(msg)
1394
+ msg = identifier = "INVALID"
1395
+ targets = i[0]
1396
+ references = i[1]
1397
+
1398
+ row = {k: "NA" for k in cols}
1399
+ row["IDENTIFIER"] = identifier
1400
+ row["MESSAGE"] = _style_msg(msg) + extra_msg
1401
+ row["PROJECTS"] = _style_projects(targets)
1402
+ row["TARGETS"] = _style_experiments(targets)
1403
+ row["REFERENCES"] = _style_experiments(references)
1404
+ summary.append("\t".join(row[k] for k in cols))
1405
+
1406
+ summary = "\n".join(summary).expandtabs(20) + "\n"
1407
+ click.echo(f"{summary}\n")
1408
+
1409
+ # ------------------
1410
+ # NGS SPECIFIC UTILS
1411
+ # ------------------
1412
+
1413
+ def get_bedfile(self, experiment, bedfile_type="targets"):
1414
+ """Get targets or baits bedfile for experiment."""
1415
+ bedfile_key = f"{self.ASSEMBLY}_{bedfile_type}_bedfile"
1416
+ assert bedfile_type in {"targets", "baits"}, "Unsupported bedfile type."
1417
+ return experiment["technique"]["reference_data"][bedfile_key]["url"]
1418
+
1419
+ def get_bam(self, experiment):
1420
+ """Get experiment bam for application assembly."""
1421
+ try:
1422
+ return experiment["bam_files"][self.ASSEMBLY]["url"]
1423
+ except KeyError:
1424
+ raise exceptions.ValidationError(
1425
+ f"{experiment.system_id} has no registered bam for {self.ASSEMBLY}"
1426
+ )
1427
+
1428
+ def get_bams(self, experiments):
1429
+ """Get bams for multiple experiments."""
1430
+ return [self.get_bam(i) for i in experiments]
1431
+
1432
+ def update_experiment_bam_file(self, experiment, bam_url, analysis_pk):
1433
+ """Update experiment default bam for assembly, ADMIN ONLY."""
1434
+ try:
1435
+ self.get_bam(experiment)
1436
+ return experiment
1437
+ except exceptions.ValidationError:
1438
+ pass
1439
+
1440
+ return data.update_experiment_bam_file(
1441
+ experiment=experiment,
1442
+ assembly_name=self.ASSEMBLY,
1443
+ analysis_pk=analysis_pk,
1444
+ bam_url=bam_url,
1445
+ )
1446
+
1447
+ def validate_bams(self, experiments):
1448
+ """Raise error not all experiments have registered bams."""
1449
+ errors = []
1450
+
1451
+ for i in experiments:
1452
+ try:
1453
+ self.get_bam(i)
1454
+ except exceptions.ValidationError as error:
1455
+ errors.append(error)
1456
+
1457
+ if errors:
1458
+ raise exceptions.ValidationError("\n".join(map(str, errors)))
1459
+
1460
+ def validate_bedfiles(self, experiments, bedfile_type="targets"):
1461
+ """Raise error not all experiments have registered bedfile."""
1462
+ errors = []
1463
+
1464
+ for i in experiments:
1465
+ try:
1466
+ bed = self.get_bedfile(i, bedfile_type=bedfile_type)
1467
+ assert isfile(bed), f"BED file does not exist: {bed}"
1468
+ except (KeyError, AssertionError):
1469
+ errors.append(f'{i["system_id"]} has no registered bedfile')
1470
+
1471
+ if errors:
1472
+ raise exceptions.ValidationError("\n".join(errors))
1473
+
1474
+ # -----------------------
1475
+ # ANALYSES CREATION LOGIC
1476
+ # -----------------------
1477
+
1478
+ def get_or_create_analyses(self, tuples):
1479
+ """
1480
+ Get or create analysis for a application and a list of tuples.
1481
+
1482
+ Arguments:
1483
+ tuples (list): list of (targets, references, analyses) tuples.
1484
+
1485
+ Returns:
1486
+ tuple: list of analyses, invalid tuples [(tuple, error), ...].
1487
+ """
1488
+ # add dependencies and inputs
1489
+ invalid_tuples, valid_tuples, created_analyses = [], [], []
1490
+ unique_individuals = set()
1491
+
1492
+ for i in tuples:
1493
+ try:
1494
+ valid_tuples.append(i + self._get_dependencies(*i))
1495
+
1496
+ if self.unique_analysis_per_individual:
1497
+ individual = self._get_individual_from_tuple(i[0], i[1])
1498
+
1499
+ if individual.pk not in unique_individuals:
1500
+ unique_individuals.add(individual.pk)
1501
+ else: # pragma: no cover
1502
+ raise exceptions.ValidationError(
1503
+ "Another tuple with the same individual has been passed."
1504
+ )
1505
+ except (
1506
+ exceptions.ValidationError,
1507
+ exceptions.ConfigurationError,
1508
+ AssertionError,
1509
+ ) as error: # pragma: no cover
1510
+ invalid_tuples.append((i, exceptions.ValidationError(*error.args)))
1511
+
1512
+ # get existing analyses from valid tuples
1513
+ if self.unique_analysis_per_individual:
1514
+ get_existing_analyses = self.get_individual_level_analyses
1515
+ else:
1516
+ get_existing_analyses = self.get_existing_analyses
1517
+
1518
+ existing_analyses, valid_tuples = get_existing_analyses(valid_tuples)
1519
+
1520
+ if len(valid_tuples) > 1000: # pragma: no cover
1521
+ click.secho(
1522
+ f"Attempting to create {len(valid_tuples)} analyses, "
1523
+ f"this process might take some time...",
1524
+ fg="yellow",
1525
+ )
1526
+
1527
+ # validate existing analyses
1528
+ with click.progressbar(
1529
+ existing_analyses,
1530
+ file=sys.stderr,
1531
+ label=f"Validating tuples of the {len(existing_analyses)} existing analyses...\t\t",
1532
+ ) as bar:
1533
+ for i in bar:
1534
+ try:
1535
+ self.validate_experiments(i["targets"], i["references"])
1536
+ created_analyses.append(i)
1537
+ except (
1538
+ exceptions.ValidationError,
1539
+ AssertionError,
1540
+ ) as error: # pragma: no cover
1541
+ invalid_tuples.append((i, exceptions.ValidationError(*error.args)))
1542
+
1543
+ # create new analyses and validate
1544
+ with click.progressbar(
1545
+ valid_tuples,
1546
+ file=sys.stderr,
1547
+ label=f"Creating analyses for {len(valid_tuples)} tuples...\t\t",
1548
+ ) as bar:
1549
+ for i in bar:
1550
+ try:
1551
+ targets, references, analyses, inputs, individual = i
1552
+ # self.validate_species(targets + references)
1553
+ self.validate_experiments(targets, references)
1554
+ analysis = self._patch_analysis(
1555
+ api.create_instance(
1556
+ endpoint="analyses",
1557
+ application=self.application,
1558
+ targets=targets,
1559
+ references=references,
1560
+ analyses=analyses,
1561
+ individual_level_analysis=individual,
1562
+ )
1563
+ )
1564
+
1565
+ analysis["application_inputs"] = inputs
1566
+ created_analyses.append(analysis)
1567
+ except (exceptions.ValidationError, AssertionError) as error:
1568
+ invalid_tuples.append((i, exceptions.ValidationError(*error.args)))
1569
+
1570
+ return created_analyses, invalid_tuples
1571
+
1572
+ def get_existing_analyses(self, tuples):
1573
+ """
1574
+ Get list of existing analyses for a list of `tuples`.
1575
+
1576
+ Check targets and references for an exact match. Check whether all the
1577
+ requested analyses are in `analysis.analyses`.
1578
+
1579
+ Arguments:
1580
+ tuples (list): (targets, references, analyses, inputs) tuples.
1581
+
1582
+ Returns:
1583
+ tuple: list of existing analyses, list of tuples without analysis
1584
+ """
1585
+ if not tuples: # pragma: no cover
1586
+ return [], []
1587
+
1588
+ click.echo("Checking for existing analyses...", file=sys.stderr)
1589
+ projects = {j["pk"] for i in tuples for j in i[0][0]["projects"]}
1590
+ cache = defaultdict(list)
1591
+ existing, missing = [], []
1592
+ targets_pks = ",".join(str(j.pk) for i in tuples for j in i[0])
1593
+ filters = dict(application=self.application["pk"])
1594
+
1595
+ if projects:
1596
+ filters["projects__pk__in"] = projects
1597
+
1598
+ if targets_pks:
1599
+ filters["targets__pk__in"] = targets_pks
1600
+
1601
+ def get_cache_key(targets, references):
1602
+ return (
1603
+ tuple(sorted(set(i["pk"] for i in targets))),
1604
+ tuple(sorted(set(i["pk"] for i in references))),
1605
+ )
1606
+
1607
+ for i in api.get_instances("analyses", limit=5000, **filters):
1608
+ cache[get_cache_key(i["targets"], i["references"])].append(i)
1609
+
1610
+ for targets, references, analyses, inputs in tuples:
1611
+ expected = set(analyses)
1612
+ found_existing = False
1613
+
1614
+ for i in cache[get_cache_key(targets, references)]:
1615
+ if expected.issubset(set(i["analyses"])):
1616
+ found_existing = True
1617
+ i["application_inputs"] = inputs
1618
+ existing.append(i)
1619
+ break
1620
+
1621
+ if not found_existing:
1622
+ missing.append((targets, references, analyses, inputs, None))
1623
+
1624
+ return existing, missing
1625
+
1626
+ def get_individual_level_analyses(self, tuples):
1627
+ """Get existing individual level analyses."""
1628
+ # add individual to tuples
1629
+ tuples = [i + (self._get_individual_from_tuple(*i[:2]),) for i in tuples]
1630
+ tuples_map = {i[-1].pk: i for i in tuples}
1631
+ existing = {}
1632
+
1633
+ if tuples_map:
1634
+ for i in api.get_analyses(
1635
+ application=self.application.pk,
1636
+ individual_level_analysis__pk__in=",".join(map(str, tuples_map)),
1637
+ ):
1638
+ individual = i.individual_level_analysis
1639
+ current_tuple = tuples_map[individual.pk]
1640
+
1641
+ # make sure we only have one analysis per individual
1642
+ assert (
1643
+ individual.pk not in existing
1644
+ ), f"Multiple analyses for {individual}"
1645
+ existing[individual.pk] = i
1646
+
1647
+ # patch analysis if tuples differ
1648
+ for ix, key in enumerate(["targets", "references", "analyses"]):
1649
+ if {getattr(j, "pk", j) for j in i[key]} != {
1650
+ getattr(j, "pk", j) for j in current_tuple[ix]
1651
+ }:
1652
+ existing[individual.pk] = api.patch_instance(
1653
+ "analyses",
1654
+ i.pk,
1655
+ targets=current_tuple[0],
1656
+ references=current_tuple[1],
1657
+ analyses=current_tuple[2],
1658
+ )
1659
+ break
1660
+
1661
+ return list(existing.values()), [i for i in tuples if i[-1].pk not in existing]
1662
+
1663
+ def _patch_analysis(self, analysis):
1664
+ analysis["storage_url"] = data.get_storage_url(
1665
+ endpoint="analyses", identifier=analysis["pk"], use_hash=True
1666
+ )
1667
+
1668
+ return api.patch_instance(
1669
+ "analyses",
1670
+ analysis["pk"],
1671
+ results=self._get_analysis_results(analysis, created=True),
1672
+ storage_url=analysis["storage_url"],
1673
+ )
1674
+
1675
+ def _get_individual_from_tuple(self, targets, references):
1676
+ individual = {
1677
+ i.sample.individual.pk: i.sample.individual for i in targets + references
1678
+ }
1679
+
1680
+ assert len(individual) == 1, "More than one individual passed!"
1681
+ return list(individual.values())[0]
1682
+
1683
+ # ---------------
1684
+ # SPECIAL METHODS
1685
+ # ---------------
1686
+
1687
+ def __repr__(self):
1688
+ """Print name, version and assembly."""
1689
+ return f"{self.NAME} {self.VERSION}" + (
1690
+ f" ({self.ASSEMBLY})" if self.ASSEMBLY else ""
1691
+ )
1692
+
1693
+ # -------------------------
1694
+ # ANALYSES VALIDATION UTILS
1695
+ # -------------------------
1696
+
1697
+ def validate_is_file(self, path): # pragma: no cover
1698
+ """Validate path is file."""
1699
+ assert isfile(path), f"{path} is not a file."
1700
+
1701
+ def validate_is_dir(self, path): # pragma: no cover
1702
+ """Validate path is directory."""
1703
+ assert isdir(path), f"{path} is not a file."
1704
+
1705
+ def validate_reference_genome(self, reference):
1706
+ """Validate genome exists and has required indexes."""
1707
+ required = ".fai", ".amb", ".ann", ".bwt", ".pac", ".sa"
1708
+
1709
+ assert all(isfile(reference + i) for i in required), (
1710
+ f"Missing indexes please run:\n\n\t"
1711
+ f"bwa index {reference}\n\tsamtools faidx {reference}"
1712
+ )
1713
+
1714
+ assert isfile(reference + ".dict"), (
1715
+ f'Please generate {reference + ".dict"}, e.g.\n\n\t'
1716
+ f"samtools dict -a {self.ASSEMBLY} -s {self.SPECIES} "
1717
+ f'{reference} > {reference + ".dict"}'
1718
+ )
1719
+
1720
+ def validate_has_raw_data(self, experiments):
1721
+ """Validate experiments have raw data."""
1722
+ msg = []
1723
+
1724
+ for i in experiments:
1725
+ if not i["raw_data"]:
1726
+ msg.append(f'{i["system_id"]} has no raw data...')
1727
+
1728
+ assert not msg, "\n".join(msg)
1729
+
1730
+ def validate_single_data_type(self, experiments):
1731
+ """Validate experiments have only one type of raw data."""
1732
+ self.validate_has_raw_data(experiments)
1733
+ types = defaultdict(list)
1734
+
1735
+ for i in experiments:
1736
+ for j in i["raw_data"]:
1737
+ file_type = j["file_type"]
1738
+
1739
+ if file_type.startswith("FASTQ_"):
1740
+ file_type = "FASTQ"
1741
+
1742
+ types[file_type].append(i["system_id"])
1743
+
1744
+ assert len(types) == 1, f"Multiple types not supported: {dict(types)}"
1745
+ return list(types.keys())[0]
1746
+
1747
+ def validate_fastq_only(self, experiments):
1748
+ """Validate raw data is only fastq."""
1749
+ dtype = self.validate_single_data_type(experiments)
1750
+ assert dtype == "FASTQ", f"Only FASTQ supported, found: {dtype}"
1751
+
1752
+ def validate_is_pair(self, targets, references):
1753
+ """Validate targets, references tuple is a pair."""
1754
+ assert len(targets) == 1 and len(references) == 1, "Pairs only."
1755
+ assert (
1756
+ targets[0]["pk"] != references[0]["pk"]
1757
+ ), "Target can't be same as reference."
1758
+
1759
+ def validate_one_target(self, targets):
1760
+ """Validate only one target."""
1761
+ assert len(targets) == 1, f"Only 1 target allowed, got: {len(targets)}"
1762
+
1763
+ def validate_one_target_no_references(self, targets, references):
1764
+ """Validate only one sample is passed targets and none on references."""
1765
+ self.validate_one_target(targets)
1766
+ assert not references, f"No reference experiments, got: {len(references)}"
1767
+
1768
+ def validate_at_least_one_target_one_reference(
1769
+ self, targets, references
1770
+ ): # pylint: disable=C0103
1771
+ """Validate that at least one reference and target are passed."""
1772
+ assert targets and references, "References and targets required."
1773
+
1774
+ def validate_targets_not_in_references(self, targets, references):
1775
+ """Make sure targets are not passed as references also."""
1776
+ refset = set(i["pk"] for i in references)
1777
+ template = "%s was also used as reference."
1778
+ msg = [template % i["system_id"] for i in targets if i["pk"] in refset]
1779
+ assert not msg, "\n".join(msg)
1780
+
1781
+ def validate_methods(self, experiments, methods):
1782
+ """Make sure all experimental methods are those expected."""
1783
+ msg = []
1784
+
1785
+ for i in experiments:
1786
+ if i["technique"]["method"] not in methods:
1787
+ msg.append(
1788
+ f"Only '{methods}' method(s) allowed, "
1789
+ f"found {i['technique']['method']} for {i['system_id']}."
1790
+ )
1791
+
1792
+ assert not msg, "\n".join(msg)
1793
+
1794
+ def validate_pdx_only(self, experiments):
1795
+ """Make sure experiments come from PDX samples."""
1796
+ msg = []
1797
+
1798
+ for i in experiments:
1799
+ if not i.get("is_pdx"):
1800
+ msg.append(f"{i['system_id']} sample is not PDX derived")
1801
+
1802
+ assert not msg, "\n".join(msg)
1803
+
1804
+ def validate_dna_only(self, experiments):
1805
+ """Make sure experiments are DNA data."""
1806
+ msg = []
1807
+
1808
+ for i in experiments:
1809
+ if i["technique"]["category"] != "DNA":
1810
+ msg.append(f"{i['system_id']} category is not DNA")
1811
+
1812
+ assert not msg, "\n".join(msg)
1813
+
1814
+ def validate_rna_only(self, experiments):
1815
+ """Make sure experiments are RNA data."""
1816
+ msg = []
1817
+
1818
+ for i in experiments:
1819
+ if i["technique"]["category"] != "RNA":
1820
+ msg.append(f"{i['system_id']} category is not RNA")
1821
+
1822
+ assert not msg, "\n".join(msg)
1823
+
1824
+ def validate_dna_pairs(self, targets, references):
1825
+ """Validate targets, references tuples for base dna applications."""
1826
+ self.validate_is_pair(targets, references)
1827
+ self.validate_dna_only(targets + references)
1828
+
1829
+ def validate_same_technique(self, targets, references):
1830
+ """Validate targets and references have same bedfile."""
1831
+ ttec = {i["technique"]["slug"] for i in targets}
1832
+ rtec = {i["technique"]["slug"] for i in references}
1833
+ assert len(rtec) == 1, f"Expected one technique, got: {rtec}"
1834
+ assert len(ttec) == 1, f"Expected one technique, got: {ttec}"
1835
+ assert rtec == ttec, f"Same techniques required: {ttec}, {rtec}."
1836
+
1837
+ def validate_same_platform(self, targets, references):
1838
+ """Validate targets and references are sequenced on the same platform."""
1839
+ tpla = {i["platform"]["slug"] for i in targets}
1840
+ rpla = {i["platform"]["slug"] for i in references}
1841
+ assert len(rpla) == 1, f"Expected one platform, got: {rpla}"
1842
+ assert len(tpla) == 1, f"Expected one platform, got: {tpla}"
1843
+ assert rpla == tpla, f"Same platforms required: {tpla}, {rpla}."
1844
+
1845
+ def validate_species(self, experiments):
1846
+ """Validate experiments's species is same as application's setting."""
1847
+ msg = []
1848
+
1849
+ for i in experiments:
1850
+ if self.ASSEMBLY and i["sample"]["individual"]["species"] != self.SPECIES:
1851
+ msg.append(f'{i["system_id"]} species not supported')
1852
+
1853
+ assert not msg, "\n".join(msg)
1854
+
1855
+ def validate_are_normals(self, experiments):
1856
+ """Raise error not all experiments come from NORMAL sample."""
1857
+ for i in experiments:
1858
+ msg = f"Experiment Sample {i.sample.system_id} is not NORMAL."
1859
+ assert i.sample.category == "NORMAL", msg
1860
+
1861
+ def validate_individuals(self, targets, references):
1862
+ """
1863
+ Validate the individual of the targets and references.
1864
+
1865
+ Validate pairs are of the same individual if the pipeline is matched.
1866
+ Validate pairs are of the different individuals if the pipeline is unmatched.
1867
+ """
1868
+ if references:
1869
+ targets_set = list(
1870
+ {v["sample"]["individual"]["pk"]: v for v in targets}.values()
1871
+ )
1872
+ references_set = list(
1873
+ {v["sample"]["individual"]["pk"]: v for v in references}.values()
1874
+ )
1875
+
1876
+ assert len(targets_set) == 1, "One unique target individual is supported."
1877
+ assert (
1878
+ len(references_set) == 1
1879
+ ), "One unique reference individual is supported."
1880
+
1881
+ tind = targets_set[0]["sample"]["individual"]
1882
+ rind = references_set[0]["sample"]["individual"]
1883
+
1884
+ if (
1885
+ hasattr(self, "IS_UNMATCHED") and self.IS_UNMATCHED
1886
+ ): # pylint: disable=no-member
1887
+ assert tind["pk"] != rind["pk"], (
1888
+ "Different individuals required: "
1889
+ f"{tind['system_id']} and {rind['system_id']} "
1890
+ "are of the same individual."
1891
+ )
1892
+ else: # application is designed for matched analyses
1893
+ assert tind["pk"] == rind["pk"], (
1894
+ "Same individual required: "
1895
+ f"{tind['system_id']} and {rind['system_id']} "
1896
+ "are of different individuals."
1897
+ )
1898
+
1899
+ def validate_source(self, experiments, source):
1900
+ """Validate experiments are from a specific source material."""
1901
+ for i in experiments:
1902
+ assert (
1903
+ i["sample"]["source"] == source
1904
+ ), f"Sample source for {i['sample']['system_id']} does not match {source}."
1905
+
1906
+ # -------------------------
1907
+ # NOTIFICATION UTILS
1908
+ # -------------------------
1909
+
1910
+ def notify_project_analyst(self, analysis, subject, message):
1911
+ """Send email notification to project's analysts of projects."""
1912
+ projects = []
1913
+ for target in analysis.targets:
1914
+ projects.extend(target.projects)
1915
+ analysts = set([project.analyst for project in projects if project.analyst])
1916
+ if not analysts:
1917
+ click.secho(
1918
+ "Skipping notification as projects have no registered analysts",
1919
+ err=True,
1920
+ fg="red",
1921
+ )
1922
+ return
1923
+ kwargs = {
1924
+ "data": {"recipients": analysts, "subject": subject, "content": message}
1925
+ }
1926
+ return api.api_request("post", url=f"/send_email", **kwargs)