-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.py
More file actions
262 lines (232 loc) · 9.26 KB
/
context.py
File metadata and controls
262 lines (232 loc) · 9.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from __future__ import annotations
import logging
from importlib.metadata import entry_points
from pathlib import Path
from typing import Any, NamedTuple, OrderedDict
import xmltodict
from murfey.client.instance_environment import MurfeyInstanceEnvironment, SampleInfo
from murfey.util.client import capture_post
logger = logging.getLogger("murfey.client.context")
def _file_transferred_to(
environment: MurfeyInstanceEnvironment,
source: Path,
file_path: Path,
rsync_basepath: Path,
):
if environment.visit in environment.default_destinations[source]:
return (
rsync_basepath
/ Path(environment.default_destinations[source])
/ file_path.relative_to(source) # need to strip out the rsync_module name
)
return (
rsync_basepath
/ Path(environment.default_destinations[source])
/ environment.visit
/ file_path.relative_to(source)
)
def _get_source(file_path: Path, environment: MurfeyInstanceEnvironment) -> Path | None:
possible_sources = []
for s in environment.sources:
if file_path.is_relative_to(s):
possible_sources.append(s)
if not possible_sources:
return None
elif len(possible_sources) == 1:
return possible_sources[0]
source = possible_sources[0]
for extra_source in possible_sources[1:]:
if extra_source.is_relative_to(source):
source = extra_source
return source
def _atlas_destination(
environment: MurfeyInstanceEnvironment,
source: Path,
rsync_basepath: Path,
) -> Path:
for i, destination_part in enumerate(
Path(environment.default_destinations[source]).parts
):
if destination_part == environment.visit:
return rsync_basepath / "/".join(
Path(environment.default_destinations[source]).parent.parts[: i + 1]
)
return (
rsync_basepath
/ Path(environment.default_destinations[source]).parent
/ environment.visit
)
def ensure_dcg_exists(
collection_type: str,
metadata_source: Path,
environment: MurfeyInstanceEnvironment,
machine_config: dict,
token: str,
) -> str | None:
"""Create a data collection group"""
if collection_type == "tomo":
experiment_type_id = 36
session_file = metadata_source / "Session.dm"
source_visit_dir = metadata_source.parent
elif collection_type == "spa":
experiment_type_id = 37
# For SPA the metadata source sent should include the Images-Disc
session_file = metadata_source.parent / "EpuSession.dm"
source_visit_dir = metadata_source.parent.parent
for h in entry_points(group="murfey.hooks"):
try:
if h.name == "get_epu_session_metadata":
h.load()(
destination_dir=session_file.parent,
environment=environment,
token=token,
)
except Exception as e:
logger.warning(f"Get EPU session hook failed: {e}")
elif collection_type == "sxt":
experiment_type_id = 47
session_file = metadata_source / "Session.dm"
source_visit_dir = metadata_source.parent
else:
logger.error(f"Unknown collection type {collection_type}")
return None
if not session_file.is_file():
logger.warning(f"Cannot find session file {str(session_file)}")
dcg_tag = "/".join(
[part for part in metadata_source.parts if part != environment.visit]
).replace("//", "/")
dcg_data = {
"experiment_type_id": experiment_type_id,
"tag": dcg_tag,
}
else:
with open(session_file, "r") as session_xml:
session_data = xmltodict.parse(session_xml.read())
if collection_type == "tomo":
windows_path = session_data["TomographySession"]["AtlasId"]
else:
windows_path = session_data["EpuSessionXml"]["Samples"]["_items"][
"SampleXml"
][0]["AtlasId"]["#text"]
logger.info(f"Windows path to atlas metadata found: {windows_path}")
if not windows_path:
logger.warning("No atlas metadata path found")
return None
if environment.visit in windows_path.split("\\"):
# Case of atlas in the correct location
visit_index = windows_path.split("\\").index(environment.visit)
partial_path = "/".join(windows_path.split("\\")[visit_index + 1 :])
logger.info(
f"Partial Linux path successfully constructed from Windows path: {partial_path}"
)
else:
# Atlas not in visit, so come up with where it should have been
# Assumes /structure/to/Supervisor/Sample/Atlas/Atlas.dm
partial_path = "atlas/" + "/".join(windows_path.split("\\")[-4:])
logger.info(f"Partial Linux path estimated: {partial_path}")
logger.info(
f"Looking for atlas XML file in metadata directory {str((source_visit_dir / partial_path).parent)}"
)
dcg_tag = "/".join(
[part for part in metadata_source.parts if part != environment.visit]
).replace("//", "/")
for p in partial_path.split("/"):
if p.startswith("Sample"):
sample = int(p.replace("Sample", ""))
break
else:
logger.warning(f"Sample could not be identified for {metadata_source}")
return None
environment.samples[metadata_source] = SampleInfo(
atlas=Path(partial_path), sample=sample
)
if atlas_xml_search := list(
(source_visit_dir / partial_path).parent.glob("Atlas_*.xml")
):
atlas_xml_path = atlas_xml_search[0]
logger.info(f"Atlas XML path {str(atlas_xml_path)} found")
with open(atlas_xml_path, "rb") as atlas_xml:
atlas_xml_data = xmltodict.parse(atlas_xml)
atlas_original_pixel_size = float(
atlas_xml_data["MicroscopeImage"]["SpatialScale"]["pixelSize"]["x"][
"numericValue"
]
)
# need to calculate the pixel size of the downscaled image
atlas_pixel_size = atlas_original_pixel_size * 7.8
logger.info(f"Atlas image pixel size determined to be {atlas_pixel_size}")
dcg_data = {
"experiment_type_id": experiment_type_id,
"tag": dcg_tag,
"atlas": str(
_atlas_destination(
environment,
session_file.parent,
Path(machine_config.get("rsync_basepath", "")),
)
/ environment.samples[metadata_source].atlas.parent
/ atlas_xml_path.with_suffix(".jpg").name
).replace("//", "/"),
"sample": environment.samples[metadata_source].sample,
"atlas_pixel_size": atlas_pixel_size,
}
else:
dcg_data = {
"experiment_type_id": experiment_type_id,
"tag": dcg_tag,
"sample": environment.samples[metadata_source].sample,
}
capture_post(
base_url=str(environment.url.geturl()),
router_name="workflow.router",
function_name="register_dc_group",
token=token,
instrument_name=environment.instrument_name,
visit_name=environment.visit,
session_id=environment.murfey_session,
data=dcg_data,
)
return dcg_tag
def detect_acquisition_software(dir_for_transfer: Path) -> str:
glob = dir_for_transfer.glob("*")
for f in glob:
if f.name.startswith("EPU") or f.name.startswith("GridSquare"):
return "epu"
if f.name.startswith("Position") or f.suffix == ".mdoc":
return "tomo"
return ""
class ProcessingParameter(NamedTuple):
name: str
label: str
default: Any = None
class Context:
user_params: list[ProcessingParameter] = []
metadata_params: list[ProcessingParameter] = []
def __init__(self, name: str, acquisition_software: str, token: str):
self._acquisition_software = acquisition_software
self._token = token
self.name = name
self.data_collection_parameters: dict = {}
def post_transfer(
self,
transferred_file: Path,
environment: MurfeyInstanceEnvironment | None = None,
**kwargs,
):
# Search external packages for additional hooks to include in Murfey
for h in entry_points(group="murfey.post_transfer_hooks"):
if h.name == self.name:
h.load()(transferred_file, environment=environment, **kwargs)
def post_first_transfer(
self,
transferred_file: Path,
environment: MurfeyInstanceEnvironment | None = None,
**kwargs,
):
self.post_transfer(transferred_file, environment=environment, **kwargs)
def gather_metadata(
self, metadata_file: Path, environment: MurfeyInstanceEnvironment | None = None
) -> OrderedDict | None:
raise NotImplementedError(
f"gather_metadata must be declared in derived class to be used: {self}"
)