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/settings.py ADDED
@@ -0,0 +1,315 @@
1
+ """System and user settings."""
2
+
3
+ from getpass import getuser
4
+ from importlib import import_module
5
+ from os.path import abspath
6
+ from os.path import dirname
7
+ from os.path import expanduser
8
+ from os.path import join
9
+ import getpass
10
+ import json
11
+ import os
12
+
13
+ from cached_property import cached_property
14
+ from munch import Munch
15
+ import analytics
16
+ import click
17
+ import pytz
18
+ import six
19
+
20
+ from isabl_cli import exceptions
21
+
22
+ _DEFAULTS = {
23
+ "SUBMIT_ANALYSES": "isabl_cli.batch_systems.submit_local",
24
+ "SUBMIT_CONFIGURATION": {},
25
+ "DEFAULT_LINUX_GROUP": None,
26
+ "MAKE_STORAGE_DIRECTORY": "isabl_cli.data._make_storage_directory",
27
+ "TRASH_ANALYSIS_STORAGE": "isabl_cli.data.trash_analysis_storage",
28
+ "REFERENCE_DATA_IMPORTER": "isabl_cli.data.LocalReferenceDataImporter",
29
+ "REFERENCE_GENOME_IMPORTER": "isabl_cli.data.LocalReferenceGenomeImporter",
30
+ "DATA_IMPORTER": "isabl_cli.data.LocalDataImporter",
31
+ "YAML_DATA_IMPORTER": "isabl_cli.data.LocalYamlDataImporter",
32
+ "BED_IMPORTER": "isabl_cli.data.LocalBedImporter",
33
+ "BASE_STORAGE_DIRECTORY": join(expanduser("~"), "isabl_storage"),
34
+ "FASTQ_READ_SUFFIX": "",
35
+ "ADMIN_USER": getpass.getuser(),
36
+ "CLIENT_NAME": None,
37
+ "TIME_ZONE": "America/New_York",
38
+ "INSTALLED_APPLICATIONS": [],
39
+ "CUSTOM_COMMANDS": [],
40
+ "ON_DATA_IMPORT": [],
41
+ "ON_STATUS_CHANGE": [],
42
+ "CREATE_SYMLINKS": True,
43
+ "SUBMIT_MERGE_ANALYSIS": None,
44
+ "ON_SIGNAL_FAILURE": None,
45
+ "ADMIN_COMMANDS": [
46
+ "isabl_cli.commands.process_finished",
47
+ "isabl_cli.commands.patch_results",
48
+ ],
49
+ "SYSTEM_COMMANDS": [
50
+ "isabl_cli.commands.get_bams",
51
+ "isabl_cli.commands.get_bed",
52
+ "isabl_cli.commands.get_count",
53
+ "isabl_cli.commands.get_data",
54
+ "isabl_cli.commands.get_metadata",
55
+ "isabl_cli.commands.get_outdirs",
56
+ "isabl_cli.commands.get_paths",
57
+ "isabl_cli.commands.get_reference",
58
+ "isabl_cli.commands.get_results",
59
+ "isabl_cli.commands.login",
60
+ "isabl_cli.commands.merge_individual_analyses",
61
+ "isabl_cli.commands.merge_project_analyses",
62
+ "isabl_cli.commands.patch_status",
63
+ "isabl_cli.commands.reject_analysis",
64
+ "isabl_cli.commands.rerun_signals",
65
+ "isabl_cli.commands.run_signals",
66
+ "isabl_cli.commands.run_web_signals",
67
+ ],
68
+ "EXTRA_RAW_DATA_FORMATS": [],
69
+ }
70
+
71
+ _IMPORT_STRINGS = {
72
+ "SUBMIT_ANALYSES",
73
+ "ADMIN_COMMANDS",
74
+ "BED_IMPORTER",
75
+ "CUSTOM_COMMANDS",
76
+ "DATA_IMPORTER",
77
+ "YAML_DATA_IMPORTER",
78
+ "INSTALLED_APPLICATIONS",
79
+ "MAKE_STORAGE_DIRECTORY",
80
+ "ON_DATA_IMPORT",
81
+ "ON_SIGNAL_FAILURE",
82
+ "ON_STATUS_CHANGE",
83
+ "REFERENCE_DATA_IMPORTER",
84
+ "REFERENCE_GENOME_IMPORTER",
85
+ "SUBMIT_MERGE_ANALYSIS",
86
+ "SYSTEM_COMMANDS",
87
+ "TRASH_ANALYSIS_STORAGE",
88
+ }
89
+
90
+ _PATH_STRINGS = {"BASE_STORAGE_DIRECTORY"}
91
+
92
+
93
+ def import_valid_applications(val, setting_name):
94
+ """Import all valid applications strings specified on the client settings."""
95
+ if setting_name == "INSTALLED_APPLICATIONS":
96
+ apps = []
97
+ for item in val:
98
+ try:
99
+ apps.append(import_from_string(item, setting_name))
100
+ except ImportError as error:
101
+ click.secho(f"Failed to import applications: {error}", err=True, fg="red")
102
+ return apps
103
+ return [import_from_string(item, setting_name) for item in val]
104
+
105
+
106
+ def perform_import(val, setting_name):
107
+ """Perform the necessary import or imports."""
108
+ if isinstance(val, six.string_types):
109
+ return import_from_string(val, setting_name)
110
+ elif isinstance(val, (list, tuple)):
111
+ return import_valid_applications(val, setting_name)
112
+ return val # pragma: no cover
113
+
114
+
115
+ def import_from_string(val, setting_name=None):
116
+ """Attempt to import a class from a string representation."""
117
+ try:
118
+ module_path, class_name = val.rsplit(".", 1)
119
+ module = import_module(module_path)
120
+ return getattr(module, class_name)
121
+ except (ImportError, AttributeError) as error: # pragma: no cover
122
+ raise ImportError(
123
+ f"Could not import '{val}' for setting '{setting_name}'. "
124
+ f"{error.__class__.__name__}: {error}."
125
+ )
126
+
127
+
128
+ class UserSettings:
129
+
130
+ """A class used to manage user specific configurations."""
131
+
132
+ settings_path = join(expanduser("~"), ".isabl", "settings.json")
133
+
134
+ def __repr__(self): # pragma: no cover
135
+ """Show all configurations in `settings_path`."""
136
+ return f"UserSettings({self._read()})"
137
+
138
+ def __setattr__(self, name, value):
139
+ """Write attribute to `settings_path`."""
140
+ self._write(name, value)
141
+
142
+ def __getattr__(self, name):
143
+ """Get attribute from `settings_path`."""
144
+ return self._read().get(name, None)
145
+
146
+ def _read(self):
147
+ """Read settings.json."""
148
+ try:
149
+ with open(self.settings_path, "r") as f:
150
+ return json.load(f) or {}
151
+ except: # pylint: disable=W0702
152
+ return {}
153
+
154
+ def _write(self, name, value):
155
+ """Write key, value to settings.json."""
156
+ os.makedirs(dirname(self.settings_path), exist_ok=True)
157
+ data = self._read()
158
+
159
+ with open(self.settings_path, "w") as f:
160
+ data[name] = value
161
+ json.dump(data, f, indent=4, sort_keys=True)
162
+
163
+ os.chmod(self.settings_path, 0o600)
164
+ return data
165
+
166
+
167
+ class BaseSettings:
168
+
169
+ """Obtained from drf-yasg/rest_framework."""
170
+
171
+ def __init__(self, defaults, import_strings=None, path_strings=None):
172
+ """See: https://github.com/axnsan12/drf-yasg/."""
173
+ self.defaults = defaults
174
+ self.path_strings = path_strings or []
175
+ self.import_strings = import_strings or []
176
+
177
+ @property
178
+ def _settings(self):
179
+ """Return dictionary system with settings."""
180
+ raise NotImplementedError
181
+
182
+ def __getattr__(self, attr):
183
+ """Check if present in user settings or fall back to defaults."""
184
+ if attr not in self.defaults: # pragma: no cover
185
+ raise AttributeError("Invalid setting: '%s'" % attr)
186
+
187
+ try:
188
+ val = self._settings[attr]
189
+ except KeyError:
190
+ val = self.defaults[attr]
191
+
192
+ if attr in self.import_strings: # coerce import strings into object
193
+ val = perform_import(val, attr)
194
+ elif val and attr in self.path_strings:
195
+ val = abspath(val)
196
+ elif attr == "TIME_ZONE":
197
+ val = pytz.timezone(val)
198
+
199
+ return val
200
+
201
+
202
+ class SystemSettings(BaseSettings):
203
+
204
+ client_id = os.environ.get("ISABL_CLIENT_ID")
205
+
206
+ @cached_property
207
+ def is_admin_user(self):
208
+ """Return True if current user is ADMIN_USER."""
209
+ return getuser() == self.ADMIN_USER
210
+
211
+ @cached_property
212
+ def api_username(self):
213
+ """Get current username from database."""
214
+ from isabl_cli.api import api_request
215
+
216
+ return api_request("get", url="/rest-auth/user/").json()["username"]
217
+
218
+ @cached_property
219
+ def client(self):
220
+ """Get client configuration from database."""
221
+ from isabl_cli.api import get_instance
222
+
223
+ if not self.client_id:
224
+ click.secho(
225
+ "Set environment variable ISABL_CLIENT_ID "
226
+ "to your databased client primary key or slug "
227
+ "to configure Isabl CLI directly from the API.",
228
+ err=True,
229
+ fg="yellow",
230
+ )
231
+
232
+ return {}
233
+ return get_instance("clients", self.client_id)
234
+
235
+ @cached_property
236
+ def _settings(self):
237
+ """Return dictionary system with settings."""
238
+ return self.client.get("settings", {})
239
+
240
+
241
+ def get_application_settings(defaults, settings, reference_data, import_strings):
242
+ """Build settings dot dict given defaults."""
243
+ reference_data = reference_data or {}
244
+ import_strings = import_strings or set()
245
+ errors = []
246
+
247
+ def _validate(default, setting, attr):
248
+ setting = (
249
+ NotImplemented
250
+ if (setting is None and default == NotImplemented)
251
+ else setting or default
252
+ )
253
+
254
+ if isinstance(setting, str) and "reference_data_id:" in setting:
255
+ setting = reference_data.get(setting.split(":", 1)[1])
256
+ setting = setting["url"] if setting else NotImplemented
257
+ elif attr in import_strings: # coerce import strings into object
258
+ setting = perform_import(setting, attr)
259
+
260
+ if setting == NotImplemented:
261
+ errors.append(f"Missing required setting: '{attr}'")
262
+
263
+ return setting
264
+
265
+ def _settingfy(default, setting=None, attr=None, skip_check=False):
266
+ if isinstance(default, dict):
267
+ skip_check = skip_check or default.get("skip_check", False)
268
+ setting = setting or {}
269
+ tuples = {}
270
+
271
+ if not isinstance(setting, dict):
272
+ errors.append(f"Invalid setting expected dict, got: {setting}")
273
+ setting = {}
274
+
275
+ for i in [] if skip_check else setting.keys():
276
+ if i not in default:
277
+ errors.append(f"Got unexpected setting '{i}' for '{attr}'...")
278
+
279
+ for key, value in (
280
+ setting.items() if skip_check and setting else default.items()
281
+ ):
282
+ tuples[key] = _settingfy(
283
+ default=value,
284
+ setting=setting.get(key),
285
+ attr=key,
286
+ skip_check=skip_check, # propagate skip_check
287
+ )
288
+
289
+ return Munch(**tuples)
290
+
291
+ # if the default setting is a list, it's not possible to validate inner keys
292
+ elif isinstance(default, (list, tuple)):
293
+ return type(default)(
294
+ _settingfy(default=i, attr=attr, skip_check=True)
295
+ for i in setting or default
296
+ )
297
+
298
+ return _validate(default, setting, attr)
299
+
300
+ settings = _settingfy(defaults, settings, f"App Settings")
301
+
302
+ if errors:
303
+ raise exceptions.ConfigurationError(
304
+ "Invalid app configuration:\n\t- " + "\n\t- ".join(errors)
305
+ )
306
+
307
+ return settings
308
+
309
+
310
+ # load analytics token
311
+ analytics.write_key = "y1bj5g2hqjZJXEA2berZ7WIick8IDSdc"
312
+
313
+ # pylint: disable=C0103
314
+ system_settings = SystemSettings(_DEFAULTS, _IMPORT_STRINGS, _PATH_STRINGS)
315
+ user_settings = UserSettings()
isabl_cli/signals.py ADDED
@@ -0,0 +1,23 @@
1
+
2
+ import click
3
+
4
+ from isabl_cli.settings import import_from_string
5
+
6
+
7
+ def resume_analysis_signal(analysis):
8
+ """Signal to resume analysis execution."""
9
+ click.secho(f"Resuming analysis {analysis}", fg="yellow")
10
+ run_web_signals(analysis, restart=True)
11
+
12
+
13
+ def force_analysis_signal(analysis):
14
+ """Signal to wipe analysis and restart."""
15
+ click.secho(f"Forcing analysis {analysis}", fg="yellow")
16
+ run_web_signals(analysis, force=True)
17
+
18
+
19
+ def run_web_signals(analysis, restart=False, force=False):
20
+ """Signal to trigger analyses executions."""
21
+ tuples = [(analysis.targets, analysis.references)]
22
+ app = import_from_string(analysis.application.application_class)
23
+ app().run(tuples=tuples, commit=True, restart=restart, force=force)
@@ -0,0 +1 @@
1
+ """Isabl CLI testing utilities for apps development."""
@@ -0,0 +1,159 @@
1
+ import json
2
+ import uuid
3
+
4
+ from isabl_cli import api
5
+ from isabl_cli import factories
6
+
7
+
8
+ def create_experiment(
9
+ bam,
10
+ bedfile="/a/fake/bedfile",
11
+ assembly="GRCh37",
12
+ raw_data=None,
13
+ method="TD",
14
+ species="HUMAN",
15
+ category=None,
16
+ technique_name=None,
17
+ sample=None,
18
+ ):
19
+ """Easily create an experiment for testing purposes."""
20
+ # create technique
21
+ technique = factories.TechniqueFactory(
22
+ method=method, name=technique_name or str(uuid.uuid4())
23
+ )
24
+
25
+ # create experiment
26
+ bed_file_dict = dict(url=bedfile, description="")
27
+ technique["reference_data"][f"{assembly}_targets_bedfile"] = bed_file_dict
28
+ technique["reference_data"][f"{assembly}_baits_bedfile"] = bed_file_dict
29
+ experiment = factories.ExperimentFactory(technique=technique)
30
+
31
+ # force sample if provided
32
+ if sample: # pragma: no cover
33
+ experiment["sample"] = sample
34
+ else:
35
+ category = category or experiment["sample"]["category"]
36
+ experiment["sample"]["individual"]["species"] = species
37
+ experiment["sample"]["category"] = category
38
+
39
+ experiment["raw_data"] = raw_data or []
40
+ experiment["bam_files"][assembly] = dict(url=bam, analysis=1)
41
+ return api.create_instance("experiments", **experiment)
42
+
43
+
44
+ def create_pair(
45
+ tumor_bam,
46
+ normal_bam,
47
+ bedfile="/a/fake/bedfile",
48
+ assembly="GRCh37",
49
+ method="TD",
50
+ species="HUMAN",
51
+ ):
52
+ """Create pair."""
53
+ pair = []
54
+ bed_file_dict = dict(url=bedfile, description="")
55
+ technique = factories.TechniqueFactory(method=method)
56
+ technique["reference_data"][f"{assembly}_targets_bedfile"] = bed_file_dict
57
+ technique["reference_data"][f"{assembly}_baits_bedfile"] = bed_file_dict
58
+
59
+ for (i, category) in [(tumor_bam, "TUMOR"), (normal_bam, "NORMAL")]:
60
+ experiment = factories.ExperimentFactory(technique=technique)
61
+ experiment["sample"]["individual"]["species"] = species
62
+ experiment["sample"]["category"] = category
63
+ experiment["bam_files"][assembly] = dict(url=i, analysis=1)
64
+ pair.append(api.create_instance("experiments", **experiment))
65
+
66
+ return pair[0], pair[1]
67
+
68
+
69
+ def create_test_result(
70
+ application=None, results=None, targets=None, references=None, analyses=None
71
+ ):
72
+ """Return an analysis object."""
73
+ return api.create_instance(
74
+ "analyses",
75
+ **factories.AnalysisFactory(
76
+ targets=targets or [],
77
+ references=references or [],
78
+ analyses=analyses or [],
79
+ application=application or factories.ApplicationFactory(),
80
+ status="SUCCEEDED",
81
+ results=results or {},
82
+ ),
83
+ )
84
+
85
+
86
+ def assert_run(
87
+ application,
88
+ tuples,
89
+ commit,
90
+ run_args=None,
91
+ results=None,
92
+ project_results=None,
93
+ individual_results=None,
94
+ assert_valid=True,
95
+ assert_skipped=False,
96
+ assert_invalid=False,
97
+ ):
98
+ """Run application, check results, and return analyses."""
99
+ ret = []
100
+ valid, skipped, invalid = application.run(tuples, commit=commit, run_args=run_args)
101
+
102
+ if assert_valid:
103
+ assert valid, "No valid RAN analyses."
104
+
105
+ for i, status in valid:
106
+ ret.append(i)
107
+ results = results or []
108
+
109
+ if not commit:
110
+ assert status == application._staged_message
111
+ continue
112
+
113
+ for j in results:
114
+ assert i["results"].get(j) is not None, (
115
+ f"Result {j} is missing in: "
116
+ + json.dumps(i["results"], sort_keys=True, indent=4)
117
+ )
118
+
119
+ if assert_skipped:
120
+ assert skipped, "No SKIPPED analyses."
121
+
122
+ if assert_invalid:
123
+ assert invalid, "No INVALID analyses."
124
+
125
+ if project_results:
126
+ project = tuples[0][0][0].projects[0].pk
127
+ analyses = api.get_instances(
128
+ endpoint="analyses", project_level_analysis=project, limit=1
129
+ )
130
+
131
+ if analyses:
132
+ assert (
133
+ analyses[0]["status"] == "SUCCEEDED"
134
+ ), f"Project level analysis {analyses[0].pk} has not SUCCEEDED status."
135
+
136
+ for j in project_results:
137
+ assert analyses[0]["results"].get(j) is not None, (
138
+ f"Result {j} is missing in: "
139
+ + json.dumps(analyses[0]["results"], sort_keys=True, indent=4)
140
+ )
141
+
142
+ if individual_results:
143
+ individual = tuples[0][0][0].sample.individual.pk
144
+ analyses = api.get_instances(
145
+ endpoint="analyses", individual_level_analysis=individual, limit=1
146
+ )
147
+
148
+ if analyses:
149
+ assert (
150
+ analyses[0]["status"] == "SUCCEEDED"
151
+ ), f"Individual level analysis {analyses[0].pk} has not SUCCEEDED status."
152
+
153
+ for j in individual_results:
154
+ assert analyses[0]["results"].get(j) is not None, (
155
+ f"Result {j} is missing in: "
156
+ + json.dumps(analyses[0]["results"], sort_keys=True, indent=4)
157
+ )
158
+
159
+ return ret