EXtra-proposal 0.1__tar.gz

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.
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2022, European X-Ray Free-Electron Laser Facility GmbH
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,22 @@
1
+ Metadata-Version: 2.4
2
+ Name: EXtra-proposal
3
+ Version: 0.1
4
+ Summary: An interface to a European XFEL proposal
5
+ Author-email: James Wrigley <james.wrigley@xfel.eu>, Luca Gelisio <luca.gelisio@xfel.eu>, Thomas Kluyver <thomas.kluyver@xfel.eu>
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE
10
+ Requires-Dist: pyyaml
11
+ Requires-Dist: requests
12
+ Requires-Dist: oauth2_xfel_client
13
+ Requires-Dist: matplotlib
14
+ Requires-Dist: pytest ; extra == "test"
15
+ Requires-Dist: pytest-cov ; extra == "test"
16
+ Project-URL: Home, https://github.com/European-XFEL/extra-mymdc
17
+ Provides-Extra: test
18
+
19
+ # MyMdC
20
+
21
+ This package provides the `MyMdcProposal` class for easy access to MyMdC.
22
+
@@ -0,0 +1,3 @@
1
+ # MyMdC
2
+
3
+ This package provides the `MyMdcProposal` class for easy access to MyMdC.
@@ -0,0 +1,4 @@
1
+ """An interface to a European XFEL proposal"""
2
+ __version__ = "0.1"
3
+
4
+ from .proposal import Proposal
@@ -0,0 +1,111 @@
1
+ import json
2
+ import os
3
+ from glob import iglob
4
+ from pathlib import Path
5
+ from urllib.parse import urljoin
6
+
7
+ import yaml
8
+ import requests
9
+ from oauth2_xfel_client import Oauth2ClientBackend
10
+
11
+ MYMDC_BASE_URL = "https://in.xfel.eu/metadata"
12
+ ZWOP_BASE_URL = "https://exfldadev01.desy.de/zwop"
13
+
14
+ # Copied from extra-data
15
+ def find_proposal(propno):
16
+ root_dir = Path(os.environ.get('EXTRA_DATA_DATA_ROOT', '/gpfs/exfel/exp'))
17
+ for d in iglob(str(root_dir / f'*/*/{propno}')):
18
+ return Path(d)
19
+
20
+ raise Exception(f"Couldn't find proposal dir for {propno!r}")
21
+
22
+
23
+ class MyMdcAccess:
24
+ _oauth_cache = {} # Keyed by client ID
25
+
26
+ def __init__(self, base_api_url: str, auth_headers, oauth_client=None):
27
+ self.base_api_url = base_api_url.rstrip("/") + "/" # Ensure trailing /
28
+ self.auth_headers = auth_headers.copy()
29
+ self.oauth_client = oauth_client
30
+ if oauth_client is not None:
31
+ self.session = self.oauth_client.session
32
+ else:
33
+ self.session = requests.Session()
34
+
35
+ @classmethod
36
+ def oauth(cls, client_id, client_secret, user_email):
37
+ if client_id in cls._oauth_cache:
38
+ return cls._oauth_cache[client_id]
39
+
40
+ oauth_client = Oauth2ClientBackend(
41
+ client_id=client_id,
42
+ client_secret=client_secret,
43
+ scope="",
44
+ token_url=f"{MYMDC_BASE_URL}/oauth/token"
45
+ )
46
+ inst = cls(f"{MYMDC_BASE_URL}/api", {"X-User-Email": user_email}, oauth_client)
47
+ cls._oauth_cache[client_id] = inst
48
+ return inst
49
+
50
+ @classmethod
51
+ def zwop(cls, proposal, timeout=10):
52
+ proposal_path = find_proposal(f"p{proposal:06d}")
53
+ credentials_path = proposal_path / "usr/mymdc-credentials.yml"
54
+ if not credentials_path.is_file():
55
+ params = {
56
+ "proposal_no": str(proposal),
57
+ "kinds": "mymdc",
58
+ "overwrite": "false",
59
+ "dry_run": "false"
60
+ }
61
+ response = requests.post(
62
+ f"{ZWOP_BASE_URL}/api/write_tokens", params=params, timeout=timeout
63
+ )
64
+ response.raise_for_status()
65
+
66
+ with open(credentials_path) as f:
67
+ document = yaml.safe_load(f)
68
+ token = document["token"]
69
+ server = document["server"]
70
+
71
+ return cls(f"{server}/api/mymdc", {"X-API-key": token})
72
+
73
+ def default_headers(self):
74
+ from . import __version__
75
+ return {
76
+ "content-type": "application/json",
77
+ "Accept": "application/json; version=1",
78
+ "User-Agent": f"EXtra-proposal/{__version__}",
79
+ } | self.auth_headers
80
+
81
+ def get_request(self, relative_url, params=None, headers=None, **kwargs):
82
+ """Make a GET request, return the HTTP response object"""
83
+ # Base URL may include e.g. '/api/'. This is a prefix for all URLs;
84
+ # even if they look like an absolute path.
85
+ url = urljoin(self.base_api_url, relative_url.lstrip("/"))
86
+ headers = self.default_headers() | (headers or {})
87
+ return self.session.get(url, params=params, headers=headers, **kwargs)
88
+
89
+ @staticmethod
90
+ def _parse_response(resp: requests.Response):
91
+ if resp.status_code >= 400:
92
+ try:
93
+ d = json.loads(resp.content.decode("utf-8"))
94
+ except Exception:
95
+ resp.raise_for_status()
96
+ else: # Add the error message from the API
97
+ raise requests.HTTPError(
98
+ f"Error {resp.status_code} from API: "
99
+ f"{d.get('info', 'missing details')}",
100
+ response=resp,
101
+ )
102
+
103
+ if resp.content == b"":
104
+ return None
105
+ else:
106
+ return resp.json()
107
+
108
+ def get(self, relative_url, params=None, **kwargs):
109
+ """Make a GET request, return response content from JSON"""
110
+ resp = self.get_request(relative_url, params, **kwargs)
111
+ return self._parse_response(resp)
@@ -0,0 +1,385 @@
1
+ import fnmatch
2
+ import glob
3
+ import logging
4
+ import os
5
+ import re
6
+ from datetime import datetime
7
+ from functools import wraps
8
+ from glob import iglob
9
+ from itertools import count, groupby
10
+ from pathlib import Path
11
+ from typing import Any, Optional
12
+
13
+ import numpy as np
14
+
15
+ from .mymdc import MyMdcAccess
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class ProposalNotFoundError(Exception):
21
+ """
22
+ Raised when the proposal is not found.
23
+ """
24
+
25
+ pass
26
+
27
+
28
+ # Copied from extra-data
29
+ def find_proposal(propno):
30
+ data_root_dir = Path(os.environ.get('EXTRA_DATA_DATA_ROOT', '/gpfs/exfel/exp'))
31
+ for d in iglob(str(data_root_dir / f'*/*/{propno}')):
32
+ return Path(d)
33
+
34
+ raise ProposalNotFoundError(f"Proposal {propno!r} was not found")
35
+
36
+
37
+ class RunReference:
38
+ def __init__(self, proposal: 'Proposal', run_num: int):
39
+ self.proposal = proposal
40
+ self.run_num = run_num
41
+
42
+ def data(self, **kwargs):
43
+ """Open the data of this run with extra_data"""
44
+ from extra_data import open_run
45
+ return open_run(self.proposal.directory, self.run_num, **kwargs)
46
+
47
+ def damnit(self):
48
+ """Access DAMNIT results from this run through the damnit API"""
49
+ return self.proposal.damnit()[self.run_num]
50
+
51
+ def sample_name(self):
52
+ """Get the sample name from myMdC for this run"""
53
+ return self.proposal.run_sample_name(self.run_num)
54
+
55
+ def run_type(self):
56
+ """Get the run type from myMdC for this run"""
57
+ return self.proposal.run_type(self.run_num)
58
+
59
+ def plot_timeline(self):
60
+ """Make a timeline of when this run was taken, migrated & calibrated"""
61
+ import matplotlib.pyplot as plt
62
+
63
+ run_info = self.proposal._run_info(self.run_num)
64
+ cal_requests = run_info["cal_num_requests"]
65
+ event_names = {
66
+ "Run begin": "begin_at",
67
+ "Run end": "end_at",
68
+ "Migration requested": "migration_request_at",
69
+ "Migration begin": "migration_begin_at",
70
+ "Migration end": "migration_end_at",
71
+ "Cal begin": "cal_last_begin_at",
72
+ "Cal end": "cal_last_end_at"
73
+ }
74
+
75
+ events = dict()
76
+ for name, key in event_names.items():
77
+ if run_info[key] is not None:
78
+ events[name] = datetime.fromisoformat(run_info[key])
79
+
80
+ times = dict()
81
+ if "Run end" in events and "Run begin" in events:
82
+ times["Run"] = events["Run end"] - events["Run begin"]
83
+ if "Migration end" in events and "Migration begin" in events:
84
+ times["Migration"] = events["Migration end"] - events["Migration begin"]
85
+ if "Cal end" in events and "Cal begin" in events:
86
+ key = "Calibration" if cal_requests == 1 else f"Calibration attempt {cal_requests}"
87
+ times[key] = events["Cal end"] - events["Cal begin"]
88
+
89
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(9, 5))
90
+ for (event, x) in events.items():
91
+ if not (event.startswith("Cal") and cal_requests > 1):
92
+ ax1.scatter(x, 1, label=event)
93
+
94
+ ax1.legend(bbox_to_anchor=(1.01, 1.05))
95
+ ax1.tick_params(left=False, labelleft=False)
96
+ ax1.set_title("Timeline of run events")
97
+ ax1.grid(axis="x")
98
+
99
+ ax2.bar(times.keys(), [x.total_seconds() / 60 for x in times.values()])
100
+ ax2.set_ylabel("Time [minutes]")
101
+ ax2.set_title("Time taken in each state")
102
+ ax2.grid(axis="y")
103
+
104
+ fig.suptitle(f"p{self.proposal.number}, r{self.run_num} - {self.run_type()} - {self.sample_name()}")
105
+
106
+ fig.tight_layout()
107
+
108
+ return ax1
109
+
110
+ def _cache_by_run(func):
111
+ @wraps(func)
112
+ def wrapper(self: 'Proposal', run):
113
+ key = (run, func.__name__)
114
+ if key in self._cached_data:
115
+ return self._cached_data[key]
116
+
117
+ value = func(self, run)
118
+ self._cached_data[key] = value
119
+
120
+ return value
121
+
122
+ return wrapper
123
+
124
+
125
+ class Proposal:
126
+ def __init__(
127
+ self,
128
+ proposal: int | str,
129
+ user_id: Optional[str] = None,
130
+ user_secret: Optional[str] = None,
131
+ user_email: Optional[str] = None,
132
+ timeout=10,
133
+ ):
134
+ """Proposal object.
135
+ It can be instantiated as Proposal(2112) or Proposal("p002112")
136
+
137
+ Args:
138
+ proposal (int | str): Proposal number.
139
+ user_id (Optional[str], optional): UID (can be generated at https://in.xfel.eu/metadata/oauth/applications). Defaults to None.
140
+ user_secret (Optional[str], optional): Secret (can be generated at https://in.xfel.eu/metadata/oauth/applications). Defaults to None.
141
+ user_email (Optional[str], optional): User's email. Defaults to None.
142
+
143
+ Raises:
144
+ ProposalNotFoundError: The proposal does not exist.
145
+ """
146
+ # proposal ID and number
147
+ if isinstance(proposal, str):
148
+ if proposal[0] == "p":
149
+ proposal = proposal[1:]
150
+
151
+ self.number = int(proposal)
152
+ self.directory_name = "p{:06d}".format(self.number)
153
+ else:
154
+ self.number = proposal
155
+ self.directory_name = "p{:06d}".format(proposal)
156
+
157
+ # is there a proposal with this ID?
158
+ self.directory = find_proposal(self.directory_name).absolute()
159
+
160
+ logger.info("Found proposal {}.".format(self.directory_name))
161
+
162
+ if user_id is not None:
163
+ self.mymdc = MyMdcAccess.oauth(
164
+ client_id=user_id, client_secret=user_secret, user_email=user_email,
165
+ )
166
+ else:
167
+ self.mymdc = MyMdcAccess.zwop(self.number)
168
+
169
+ self._cached_data = {}
170
+ self._timeout = 10
171
+
172
+ def __repr__(self):
173
+ return f"Proposal({self.number})"
174
+
175
+ def __getitem__(self, run) -> RunReference:
176
+ return RunReference(self, run) # TODO: check that run exists?
177
+
178
+ def damnit(self):
179
+ """Access DAMNIT results from this proposal through the damnit API"""
180
+ if 'damnit' in self._cached_data:
181
+ return self._cached_data['damnit']
182
+
183
+ from damnit import Damnit # Optional dependency
184
+ dmnt = self._cached_data['damnit'] = Damnit(self.number)
185
+ return dmnt
186
+
187
+ def _get_runs_filesystem(self) -> list[int]:
188
+ """List runs available in RAW.
189
+
190
+ Returns:
191
+ list[int]: List of runs.
192
+ """
193
+ _runs_filesystem = sorted(
194
+ [
195
+ int(di.split("/")[-1][1:])
196
+ for di in glob.glob("{}/raw/r????".format(self.directory))
197
+ ]
198
+ )
199
+ return _runs_filesystem
200
+
201
+ def _by_number_api_url(self, suffix=""):
202
+ return f"proposals/by_number/{self.number}{suffix}"
203
+
204
+ def _mymdc_info(self):
205
+ if 'mymdc_info' in self._cached_data:
206
+ return self._cached_data['mymdc_info']
207
+
208
+ inf = self.mymdc.get(self._by_number_api_url())
209
+ self._cached_data['mymdc_info'] = inf
210
+ return inf
211
+
212
+ def _get_runs_mymdc(self) -> list:
213
+ return self.mymdc.get(self._by_number_api_url("/runs"))["runs"]
214
+
215
+ def title(self):
216
+ """Get the proposal title from myMdC"""
217
+ return self._mymdc_info()["title"]
218
+
219
+ def runs(self) -> list[int]:
220
+ """Runs available in RAW.
221
+
222
+ Returns:
223
+ list[int]: List of runs.
224
+ """
225
+ return self._get_runs_filesystem()
226
+
227
+
228
+ @_cache_by_run
229
+ def _run_info(self, run: int) -> dict[str, Any]:
230
+ data = self.mymdc.get(self._by_number_api_url("/runs/{run}"),
231
+ timeout=self._timeout)
232
+ if len(data["runs"]) == 0:
233
+ raise RuntimeError(f"Couldn't get run information from mymdc for p{self.number}, r{run}")
234
+
235
+ return data["runs"][0]
236
+
237
+ @_cache_by_run
238
+ def run_techniques(self, run: int) -> dict[str, Any]:
239
+ run_info = self._run_info(run)
240
+ data = self.mymdc.get(f'runs/{run_info["id"]}', timeout=self._timeout)
241
+ return data['techniques']
242
+
243
+ @_cache_by_run
244
+ def run_sample_name(self, run: int) -> str:
245
+ run_info = self._run_info(run)
246
+ sample_id = run_info["sample_id"]
247
+ data = self.mymdc.get(f"samples/{sample_id}", timeout=self._timeout)
248
+ return data["name"]
249
+
250
+ @_cache_by_run
251
+ def run_type(self, run: int) -> str:
252
+ run_info = self._run_info(run)
253
+ experiment_id = run_info["experiment_id"]
254
+ data = self.mymdc.get(f"experiments/{experiment_id}",
255
+ timeout=self._timeout)
256
+
257
+ return data["name"]
258
+
259
+ def _get_samples_mymdc(self) -> list:
260
+ prop_id = self._mymdc_info()["id"]
261
+ return self.mymdc.get("samples", params={"proposal_id": prop_id})
262
+
263
+ def samples_table(self):
264
+ import pandas as pd
265
+ runs_metadata = self._get_runs_mymdc()
266
+
267
+ name, index, url, description, runs = [], [], [], [], []
268
+ for si in self._get_samples_mymdc():
269
+ _runs = []
270
+ for ri in runs_metadata:
271
+ if ri["sample_id"] == si["id"]:
272
+ _runs.append(ri["run_number"])
273
+
274
+ name.append(si["name"])
275
+ index.append(si["id"])
276
+ url.append(si["url"])
277
+ description.append(si["description"])
278
+ runs.append(_runs)
279
+
280
+ return pd.DataFrame.from_dict(
281
+ {
282
+ "name": name,
283
+ "id": index,
284
+ "url": url,
285
+ "description": description,
286
+ "runs": runs,
287
+ }
288
+ )
289
+
290
+ @property
291
+ def instrument(self):
292
+ return self.directory.relative_to(DATA_ROOT_DIR).parts[0]
293
+
294
+ def info(self):
295
+ """Display information on a given proposal."""
296
+
297
+ # runs available in myMdC, and other information
298
+
299
+ def run_ranges(sequence):
300
+ # Adapted from:
301
+ # https://stackoverflow.com/questions/3429510/pythonic-way-to-convert-a-list-of-integers-into-a-string-of-comma-separated-rang
302
+
303
+ # relevant to DAMNIT
304
+ sequence = np.unique(sequence)
305
+
306
+ grouped_sequence = (
307
+ list(x) for _, x in groupby(sequence, lambda x, c=count(): next(c) - x)
308
+ )
309
+ return (
310
+ ",".join(
311
+ "-".join(map(str, (gi[0], gi[-1])[: len(gi)]))
312
+ for gi in grouped_sequence
313
+ ),
314
+ sequence.size,
315
+ )
316
+
317
+ print(f"Proposal {self.number} ── scientific instrument {self.instrument}")
318
+ print(f"Data stored at {self.directory}")
319
+
320
+ # title
321
+ if self.title() is not None:
322
+ print(f"'{self.title()}'")
323
+
324
+ # runs
325
+ runs = self.runs()
326
+ print("\nRuns collected: {} (total {})".format(*run_ranges(runs)))
327
+ if self.damnit() is not None:
328
+ grouped_sequence, size = run_ranges(self.damnit().runs())
329
+ print(
330
+ " └── {:.1f}% processed by DAMNIT".format(100 * size / len(runs)),
331
+ end="",
332
+ )
333
+ if size != len(runs):
334
+ print(": {} (total {})".format(grouped_sequence, size))
335
+ else:
336
+ print(".")
337
+
338
+ def search_source(
339
+ self, pattern: str, run: int | list[int] | None = None
340
+ ) -> dict[int, list[str]]:
341
+ """Perform a case insensitive search of the glob pattern in all data sources and aliases.
342
+
343
+ Args:
344
+ pattern (str): A glob-style pattern
345
+ run (Optional[int | list[int]], optional): Specific run or list of runs. Defaults to None.
346
+
347
+ Returns:
348
+ dict[int, list[str]]: A dictionary of runs, and for each a list of
349
+ strings matching the regular expression.
350
+
351
+ Example:
352
+ proposal = Proposal(1234)
353
+
354
+ proposal.search_sources("*ENERGY*", run=[43, 44, 45, 46])
355
+ """
356
+
357
+ # TODO: look into aliases
358
+
359
+ if run is None:
360
+ run_list = self.runs()
361
+ elif type(run) is int:
362
+ run_list = [run]
363
+ elif type(run) is list:
364
+ run_list = run
365
+ if not all(type(i) is int for i in run):
366
+ raise TypeError("Each entry in the list must be an integer (run number)")
367
+ else:
368
+ raise TypeError(f"{type(run)} is not supported")
369
+
370
+ source_re = re.compile(fnmatch.translate(pattern))
371
+
372
+ run_match = {}
373
+ for ri in run_list:
374
+ run_match[ri] = []
375
+ for si in self[ri].data().all_sources:
376
+ if source_re.match(si):
377
+ run_match[ri].append(si)
378
+
379
+ return run_match
380
+
381
+
382
+ if __name__ == "__main__":
383
+ proposal = Proposal(5686)
384
+ proposal.info()
385
+ print("Run 42 sample:", proposal[42].sample_name())
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["flit_core >=3.2,<4"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+ [project]
6
+ name = "EXtra-proposal"
7
+ authors = [
8
+ {name = "James Wrigley", email = "james.wrigley@xfel.eu"},
9
+ {name = "Luca Gelisio", email = "luca.gelisio@xfel.eu"},
10
+ {name = "Thomas Kluyver", email = "thomas.kluyver@xfel.eu"},
11
+ ]
12
+ license = "BSD-3-Clause"
13
+ license-files = ["LICENSE"]
14
+ requires-python = ">=3.9"
15
+ dynamic = ["version", "description"]
16
+ readme = "README.md"
17
+ dependencies = [
18
+ "pyyaml",
19
+ "requests",
20
+ "oauth2_xfel_client",
21
+ "matplotlib",
22
+ ]
23
+
24
+ [tool.flit.module]
25
+ name = "extra_proposal"
26
+
27
+ [project.optional-dependencies]
28
+ test = [
29
+ "pytest",
30
+ "pytest-cov"
31
+ ]
32
+
33
+ [project.urls]
34
+ Home = "https://github.com/European-XFEL/extra-mymdc"