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/commands.py ADDED
@@ -0,0 +1,480 @@
1
+ """commands logic."""
2
+
3
+ from collections import OrderedDict
4
+ from glob import glob
5
+ from os.path import join
6
+ from requests.exceptions import HTTPError
7
+ from subprocess import CalledProcessError
8
+ import json
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import tempfile
13
+
14
+ import click
15
+
16
+ from isabl_cli import api
17
+ from isabl_cli import exceptions
18
+ from isabl_cli import options
19
+ from isabl_cli import utils
20
+ from isabl_cli.settings import import_from_string
21
+ from isabl_cli.settings import user_settings
22
+
23
+
24
+ def cb_app_results_keys(ctx, param, value):
25
+ """Print applications results keys."""
26
+ if not value or ctx.resilient_parsing: # pragma: no cover
27
+ return
28
+
29
+ click.echo(
30
+ "\n".join(
31
+ f"{click.style(i, fg='green')}\t{j.description}"
32
+ for i, j in sorted(api.get_instance("applications", value).results.items())
33
+ ).expandtabs(30)
34
+ )
35
+ ctx.exit()
36
+
37
+
38
+ def _filters_or_identifiers(endpoint, identifiers, filters, fields=None):
39
+ if filters and identifiers: # pragma: no cover
40
+ raise click.UsageError("Can't combine filters and identifiers.")
41
+
42
+ if fields:
43
+ filters["fields"] = fields
44
+ filters["limit"] = 100_000
45
+
46
+ return (
47
+ [api.get_instance(endpoint, i, fields=fields) for i in identifiers]
48
+ if identifiers
49
+ else api.get_instances(endpoint, verbose=True, **filters)
50
+ )
51
+
52
+
53
+ @click.command()
54
+ def login(): # pragma: no cover
55
+ """Login with isabl credentials."""
56
+ user_settings.api_token = None
57
+ api.get_token_headers.cache_clear()
58
+ api.get_token_headers()
59
+
60
+
61
+ @click.command()
62
+ @click.option("--project", help="primary key of project to merge by", type=int)
63
+ @click.option("--application", help="analyses application primary key", type=int)
64
+ def merge_project_analyses(project, application): # pragma: no cover
65
+ """Merge analyses by project."""
66
+ project = api.get_instance("projects", project)
67
+ application = api.get_instance("applications", application)
68
+ application = import_from_string(application["application_class"])()
69
+ application.run_project_merge(project)
70
+
71
+
72
+ @click.command()
73
+ @click.option("--individual", help="primary key of individual to merge by", type=int)
74
+ @click.option("--application", help="analyses application primary key", type=int)
75
+ def merge_individual_analyses(individual, application): # pragma: no cover
76
+ """Merge analyses by individual."""
77
+ individual = api.get_instance("individuals", individual)
78
+ application = api.get_instance("applications", application)
79
+ application = import_from_string(application["application_class"])()
80
+ application.run_individual_merge(individual)
81
+
82
+
83
+ @click.command()
84
+ @click.option("--force", help="Update previously patched results.", is_flag=True)
85
+ @options.NULLABLE_FILTERS
86
+ def process_finished(filters, force):
87
+ """Process and update finished analyses."""
88
+ utils.check_admin()
89
+ filters.update(status="FINISHED", fields="pk")
90
+ tag = "PROCESSING FINISHED"
91
+
92
+ # refetch analysis to avoid race conditions
93
+ n_not_patched = 0
94
+ n_patched = 0
95
+ for i in api.get_instances("analyses", verbose=True, **filters):
96
+ i = api.Analysis(i.pk)
97
+
98
+ if i.status == "FINISHED":
99
+ if not force and tag in {j.name for j in i.tags}:
100
+ n_not_patched += 1
101
+ else:
102
+ api.patch_instance("analyses", i.pk, tags=i.tags + [{"name": tag}])
103
+ try:
104
+ api.patch_analysis_status(i, "SUCCEEDED")
105
+ n_patched += 1
106
+ patch_error = None
107
+ except (PermissionError, AssertionError, CalledProcessError) as error:
108
+ patch_error = error
109
+
110
+ api.patch_instance("analyses", i.pk, tags=i.tags)
111
+
112
+ if patch_error:
113
+ raise Exception(patch_error)
114
+ if n_not_patched:
115
+ click.echo(
116
+ f"Successfully processed {n_patched} analyses, but skipped "
117
+ + f"{n_not_patched} analyses in use by other processes"
118
+ )
119
+
120
+
121
+ @click.command()
122
+ @options.FILTERS
123
+ @click.option("--force", help="Update previously patched results.", is_flag=True)
124
+ def patch_results(filters, force):
125
+ """Update the results field of many analyses."""
126
+ utils.check_admin()
127
+ skipped = []
128
+
129
+ with click.progressbar(
130
+ api.get_instances("analyses", verbose=True, **filters),
131
+ label="Patching analyses...",
132
+ ) as bar:
133
+ for i in bar:
134
+ if force or not i.results:
135
+ results = api._get_analysis_results(i, raise_error=False)
136
+ api.patch_instance("analyses", i.pk, results=results)
137
+ else: # pragma: no cover
138
+ skipped.append(i)
139
+
140
+ if skipped: # pragma: no cover
141
+ click.echo(f"{len(skipped)} analyses had results, use --force to update...")
142
+
143
+
144
+ @click.command(hidden=True)
145
+ @options.ANALYSIS_PRIMARY_KEY
146
+ @options.ANALYSIS_STATUS
147
+ def patch_status(key, status):
148
+ """Patch status of a given analysis."""
149
+ analysis = api.get_instance("analyses", key)
150
+ api.patch_analysis_status(analysis, status)
151
+
152
+
153
+ @click.command(
154
+ epilog="Learn more about fx: "
155
+ "https://github.com/antonmedv/fx/blob/master/doc/doc.md#interactive-mode"
156
+ )
157
+ @options.ENDPOINT
158
+ @options.FIELDS
159
+ @options.NULLABLE_FILTERS
160
+ @options.NO_HEADERS
161
+ @options.NULLABLE_IDENTIFIERS
162
+ @click.option("--json", "json_", help="Print as JSON", is_flag=True)
163
+ @click.option("--fx", "use_fx", help="Visualize json with fx", is_flag=True)
164
+ @click.option("--pretty", "pretty", help="prettified output", is_flag=True)
165
+ @click.option("--all", "output_all", help="include all fields in the tabular output", is_flag=True)
166
+ def get_metadata(identifiers, endpoint, field, filters, no_headers, json_, use_fx, output_all, pretty):
167
+ """Retrieve metadata for multiple instances."""
168
+ if not field and not (json_ or use_fx or output_all): # pragma: no cover
169
+ raise click.UsageError("Pass --field or use --json/--fx/--all")
170
+
171
+ if use_fx and not shutil.which("fx"): # pragma: no cover
172
+ raise click.UsageError("fx is not installed")
173
+
174
+ instances = _filters_or_identifiers(
175
+ endpoint=endpoint,
176
+ identifiers=identifiers,
177
+ filters=filters,
178
+ fields=",".join([i[0] for i in field]),
179
+ )
180
+
181
+ if field: # if fields were passed, update the instances list
182
+ instances = [
183
+ OrderedDict([(".".join(j), utils.traverse_dict(i, j)) for j in field])
184
+ for i in instances
185
+ ]
186
+ elif output_all:
187
+ field = [[i] for i in instances[0].__dict__.keys()]
188
+
189
+ if json_:
190
+ click.echo(json.dumps(instances, sort_keys=True, indent=4))
191
+ elif use_fx: # pragma: no cover
192
+ fp = tempfile.NamedTemporaryFile("w+", delete=False)
193
+ json.dump(instances, fp)
194
+ fp.close()
195
+ subprocess.check_call(["fx", fp.name])
196
+ os.unlink(fp.name)
197
+ else:
198
+ result = [] if no_headers else ["\t".join(".".join(i) for i in field)]
199
+ result += ["\t".join(map(str, i.values())) for i in instances]
200
+ if pretty:
201
+ click.echo("\n".join(result).expandtabs(30))
202
+ else:
203
+ click.echo("\n".join(result))
204
+
205
+
206
+ @click.command()
207
+ @options.ENDPOINT
208
+ @options.NULLABLE_FILTERS
209
+ def get_count(endpoint, filters):
210
+ """Get count of database instances."""
211
+ click.echo(api.get_instances_count(endpoint, **filters))
212
+
213
+
214
+ @click.command()
215
+ @options.ENDPOINT
216
+ @options.FILE_PATTERN
217
+ @options.NULLABLE_FILTERS
218
+ @options.NULLABLE_IDENTIFIERS
219
+ def get_paths(endpoint, pattern, filters, identifiers):
220
+ """Get storage directories, use `pattern` to match files inside the directories."""
221
+ for i in _filters_or_identifiers(
222
+ endpoint=endpoint,
223
+ identifiers=identifiers,
224
+ filters=filters,
225
+ fields="storage_url",
226
+ ):
227
+ if i["storage_url"]:
228
+ if pattern:
229
+ click.echo("\n".join(glob(join(i["storage_url"], pattern))))
230
+ else:
231
+ click.echo(i["storage_url"])
232
+
233
+
234
+ @click.command()
235
+ @options.FILE_PATTERN
236
+ @options.NULLABLE_FILTERS
237
+ @options.NULLABLE_IDENTIFIERS
238
+ def get_outdirs(pattern, filters, identifiers):
239
+ """Get analyses outdirs, use `pattern` to match files inside the directories."""
240
+ for i in _filters_or_identifiers(
241
+ endpoint="analyses",
242
+ identifiers=identifiers,
243
+ filters=filters,
244
+ fields="storage_url",
245
+ ):
246
+ if i["storage_url"]:
247
+ if pattern:
248
+ click.echo("\n".join(glob(join(i["storage_url"], pattern))))
249
+ else:
250
+ click.echo(i["storage_url"])
251
+
252
+
253
+ @click.command()
254
+ @options.NULLABLE_FILTERS
255
+ @options.NULLABLE_IDENTIFIERS
256
+ @options.VERBOSE
257
+ @click.option("--dtypes", help="Limit data types to be printed.", multiple=True)
258
+ def get_data(filters, identifiers, verbose, dtypes):
259
+ """Get file paths for experiments raw data."""
260
+ for i in _filters_or_identifiers(
261
+ endpoint="experiments",
262
+ identifiers=identifiers,
263
+ filters=filters,
264
+ fields="raw_data,system_id",
265
+ ):
266
+ system_id = i["system_id"]
267
+
268
+ if not i["raw_data"] and not verbose:
269
+ raise click.UsageError(f"No data for {system_id}, ignore with --verbose")
270
+
271
+ for j in i["raw_data"] or ["None"]:
272
+ if not dtypes or j["file_type"] in dtypes:
273
+ click.echo(j["file_url"] if not verbose else f"{system_id}\t{j}")
274
+
275
+
276
+ @click.command()
277
+ @options.BED_TYPE
278
+ @click.option("--assembly", help="required if multiple options for assembly")
279
+ @click.argument("technique", required=True)
280
+ def get_bed(technique, bed_type, assembly):
281
+ """Get a BED file for a given Sequencing Tehcnique."""
282
+ instance = api.get_instance("techniques", technique)
283
+ data_id = f"{assembly}_{bed_type}_bedfile"
284
+ paths = {}
285
+
286
+ for i, j in instance.reference_data.items():
287
+ if i.endswith(f"{bed_type}_bedfile"):
288
+ paths[i] = j["url"]
289
+
290
+ if not paths:
291
+ raise click.UsageError("No BED files registered yet...")
292
+ elif len(paths) > 1 and not assembly:
293
+ raise click.UsageError(f"Multiple BEDs for {technique}, pass --assembly")
294
+
295
+ click.echo(paths[data_id] if assembly else list(paths.values())[0])
296
+
297
+
298
+ @click.command()
299
+ @click.argument("identifier", required=True)
300
+ @click.option(
301
+ "--data-id",
302
+ help="data identifier of the reference resource",
303
+ default="genome_fasta",
304
+ show_default=True,
305
+ )
306
+ @click.option(
307
+ "--resources",
308
+ help="Print the list of available reference files for this assembly.",
309
+ is_flag=True,
310
+ )
311
+ @click.option(
312
+ "--model",
313
+ help="default model is assemblies",
314
+ type=click.Choice(["assemblies", "techniques"]),
315
+ default="assemblies",
316
+ )
317
+ def get_reference(identifier, data_id, resources, model):
318
+ """Retrieve reference data from assemblies (default) or techniques."""
319
+ instance = api.get_instance(model, identifier)
320
+
321
+ if resources:
322
+ click.echo(
323
+ "\n".join(
324
+ f"{click.style(i, fg='green')}\t{j.description}"
325
+ for i, j in sorted(instance["reference_data"].items())
326
+ ).expandtabs(30)
327
+ )
328
+ else:
329
+ try:
330
+ click.echo(instance["reference_data"][data_id]["url"])
331
+ except KeyError: # pragma: no cover
332
+ raise click.UsageError(f"No {data_id} reference for {instance['name']}.")
333
+
334
+
335
+ @click.command()
336
+ @options.NULLABLE_IDENTIFIERS
337
+ @options.NULLABLE_FILTERS
338
+ @options.VERBOSE
339
+ @click.option("-r", "--result-key", help="result identifier", required=True)
340
+ @click.option(
341
+ "--app-results",
342
+ help="Provide an application primary key to get a list of available results.",
343
+ callback=cb_app_results_keys,
344
+ expose_value=False,
345
+ is_eager=True,
346
+ type=click.INT,
347
+ )
348
+ def get_results(filters, identifiers, result_key, verbose):
349
+ """Get analyses results."""
350
+ for i in _filters_or_identifiers(
351
+ endpoint="analyses",
352
+ identifiers=identifiers,
353
+ filters=filters,
354
+ fields="results,pk",
355
+ ):
356
+ if result_key in i["results"]:
357
+ result = i["results"][result_key]
358
+ click.echo(result if not verbose else f"{i['pk']}\t{result}")
359
+ elif verbose: # pragma: no cover
360
+ click.echo(f"{i['pk']}\t- No result available")
361
+ else: # pragma: no cover
362
+ raise click.UsageError(
363
+ f"No '{result_key}' for {i['pk']}, ignore with --verbose"
364
+ )
365
+
366
+
367
+ @click.command()
368
+ @options.NULLABLE_IDENTIFIERS
369
+ @options.NULLABLE_FILTERS
370
+ @options.VERBOSE
371
+ @click.option("--assembly", help="required if multiple options for assembly")
372
+ def get_bams(filters, assembly, verbose, identifiers):
373
+ """Get storage directories, use `pattern` to match files inside dirs."""
374
+ for i in _filters_or_identifiers(
375
+ endpoint="experiments",
376
+ identifiers=identifiers,
377
+ filters=filters,
378
+ fields="bam_files,system_id",
379
+ ):
380
+ bam_path = None
381
+ system_id = i["system_id"]
382
+
383
+ if assembly:
384
+ bam_path = i["bam_files"][assembly]["url"]
385
+ elif len(i["bam_files"]) == 1:
386
+ bam_path = list(i["bam_files"].values())[0]["url"]
387
+
388
+ if bam_path or verbose:
389
+ click.echo(bam_path if not verbose else f"{system_id}\t{bam_path}")
390
+ elif not i["bam_files"]:
391
+ raise click.UsageError(f"No bams for {system_id}, ignore with --verbose")
392
+ else:
393
+ raise click.UsageError(f"Multiple bams for {system_id}, pass --assembly")
394
+
395
+
396
+ @click.command()
397
+ @options.NULLABLE_FILTERS
398
+ def rerun_signals(filters):
399
+ """Rerun failed signals."""
400
+ for i in api.get_instances(
401
+ "signals", pk__gt=0, data__failure_traceback__isnull=False, **filters
402
+ ):
403
+ click.secho(f"Rerunning signal: {i.slug}", fg="yellow")
404
+
405
+ try:
406
+ instance = api.get_instance(i.target_endpoint, i.target_id)
407
+ api._run_signals(
408
+ endpoint=i.target_endpoint,
409
+ instance=instance,
410
+ signals=[import_from_string(i.import_string)],
411
+ raise_error=True,
412
+ )
413
+
414
+ api.delete_instance("signals", i.pk)
415
+ except HTTPError as error:
416
+ # Delete the signal if the object doesn't exist anymore
417
+ if "Object not found try a different ID" in error.response.text:
418
+ api.delete_instance("signals", i.pk)
419
+ except exceptions.AutomationError:
420
+ pass
421
+
422
+
423
+ @click.command()
424
+ @options.NULLABLE_FILTERS
425
+ def run_web_signals(filters):
426
+ """Run signals triggered from the frontend."""
427
+ for i in api.get_instances(
428
+ "signals",
429
+ import_string__in=[
430
+ "isabl_cli.signals.resume_analysis_signal",
431
+ "isabl_cli.signals.force_analysis_signal",
432
+ ],
433
+ **filters,
434
+ ):
435
+ click.secho(f"Running web signal: {i.slug}", fg="yellow")
436
+ instance = api.get_instance(i.target_endpoint, i.target_id)
437
+
438
+ try:
439
+ api._run_signals(
440
+ endpoint=i.target_endpoint,
441
+ instance=instance,
442
+ signals=[import_from_string(i.import_string)],
443
+ raise_error=True,
444
+ )
445
+
446
+ api.delete_instance("signals", i.pk)
447
+ except exceptions.AutomationError:
448
+ pass
449
+
450
+
451
+ @click.command()
452
+ @options.NULLABLE_FILTERS
453
+ @click.option(
454
+ "--signals",
455
+ "-s",
456
+ help="Signal import string (e.g. isabl_cli.data.trigger_analyses_merge)",
457
+ required=True,
458
+ multiple=True,
459
+ )
460
+ @click.argument(
461
+ "endpoint", required=True, type=click.Choice(["experiments", "analyses"])
462
+ )
463
+ def run_signals(endpoint, filters, signals):
464
+ """Run any arbitrary signal on analyses or experiments using import strings."""
465
+ count = api.get_instances_count(endpoint, **filters)
466
+ click.secho(f"Running {', '.join(signals)} for {count} {endpoint}...", fg="blue")
467
+ signals = [import_from_string(i) for i in signals]
468
+
469
+ for i in api.get_instances(endpoint, **filters):
470
+ api._run_signals(endpoint, i, signals, raise_error=True, create_record=False)
471
+
472
+
473
+ @click.command(hidden=True)
474
+ @options.ANALYSIS_PRIMARY_KEY
475
+ @click.option("--reason", help="Rejection reason. (Will be stored in Analysis.notes)")
476
+ def reject_analysis(key, reason):
477
+ """Patch an analysis status as REJECTED, providing the rejection reason."""
478
+ analysis = api.get_instance("analyses", key)
479
+ api.patch_analysis_status(analysis, "REJECTED")
480
+ api.patch_instance("analyses", key, notes=reason)
@@ -0,0 +1,7 @@
1
+ 📦 This directory is used to include package data. Files included in this
2
+ directory will be available even after `pip install`.
3
+
4
+ ⚠️ Please don't include big files in this directory since it will be included
5
+ python's site-packages repository.
6
+
7
+ 🔧 The `setup.json` is used to define package specific options.