-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclem.py
More file actions
438 lines (380 loc) · 17 KB
/
clem.py
File metadata and controls
438 lines (380 loc) · 17 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""
Provides instructions to the server side on how different file types associated with
the CLEM workflow should be processed.
"""
import logging
from pathlib import Path
from typing import Dict, Generator, List, Optional
from urllib.parse import quote
from xml.etree import ElementTree as ET
from defusedxml.ElementTree import parse
from murfey.client.context import Context
from murfey.client.instance_environment import MurfeyInstanceEnvironment
from murfey.util.client import capture_post, get_machine_config_client
# Create logger object
logger = logging.getLogger("murfey.client.contexts.clem")
def _file_transferred_to(
environment: MurfeyInstanceEnvironment, source: Path, file_path: Path
) -> Optional[Path]:
"""
Returns the Path of the transferred file on the DLS file system.
"""
machine_config = get_machine_config_client(
str(environment.url.geturl()),
instrument_name=environment.instrument_name,
demo=environment.demo,
)
# Construct destination path
base_destination = Path(machine_config.get("rsync_basepath", "")) / Path(
environment.default_destinations[source]
)
# Add visit number to the path if it's not present in default destination
if environment.visit not in environment.default_destinations[source]:
base_destination = base_destination / environment.visit
destination = base_destination / file_path.relative_to(source)
return destination
def _get_source(
file_path: Path, environment: MurfeyInstanceEnvironment
) -> Optional[Path]:
"""
Returns the Path of the file on the client PC.
"""
for s in environment.sources:
if file_path.is_relative_to(s):
return s
return None
def _get_image_elements(root: ET.Element) -> List[ET.Element]:
"""
Searches the XML metadata recursively to find the nodes tagged as "Element" that
have image-related tags. Some LIF datasets have layers of nested elements, so a
recursive approach is needed to avoid certain datasets breaking it.
"""
# Nested function which generates list of elements
def _find_elements_recursively(
node: ET.Element,
) -> Generator[ET.Element, None, None]:
# Find items labelled "Element" under current node
elem_list = node.findall("./Children/Element")
if len(elem_list) < 1: # Try alternative path for top-level of XML tree
elem_list = node.findall("./Element")
# Recursively search for items tagged as Element under child branches
for elem in elem_list:
yield elem
new_node = elem # New starting point for the search
new_elem_list = _find_elements_recursively(new_node) # Call self
for new_elem in new_elem_list:
yield new_elem
# Get initial list of elements
elem_list = list(_find_elements_recursively(root))
# Keep only the element nodes that have image-related tags
elem_list = [elem for elem in elem_list if elem.find("./Data/Image")]
return elem_list
class CLEMContext(Context):
def __init__(self, acquisition_software: str, basepath: Path):
super().__init__("CLEM", acquisition_software)
self._basepath = basepath
# CLEM contexts for "auto-save" acquisition mode
self._tiff_series: Dict[str, List[str]] = {} # {Series name : TIFF path list}
self._series_metadata: Dict[str, str] = {} # {Series name : Metadata file path}
self._files_in_series: Dict[str, int] = {} # {Series name : Total TIFFs}
def post_transfer(
self,
transferred_file: Path,
environment: Optional[MurfeyInstanceEnvironment] = None,
**kwargs,
) -> bool:
super().post_transfer(transferred_file, environment=environment, **kwargs)
# Process files generated by "auto-save" acquisition mode
# These include TIF/TIFF and XLIF files
if transferred_file.suffix in (".tif", ".tiff", ".xlif"):
logger.debug(f"File extension {transferred_file.suffix!r} detected")
# Type checking to satisfy MyPy
if not environment:
logger.warning("No environment passed in")
return False
# Location of the file on the client PC
source = _get_source(transferred_file, environment)
# Type checking to satisfy MyPy
if not source:
logger.warning(f"No source found for file {transferred_file}")
return False
# Get the file Path at the destination
destination_file = _file_transferred_to(
environment=environment,
source=source,
file_path=transferred_file,
)
if not destination_file:
logger.warning(
f"File {transferred_file.name!r} not found on the storage system"
)
return False
# Skip processing of binned "_pmd" image series
if "_pmd_" in transferred_file.stem:
logger.debug(
f"File {transferred_file.name!r} belongs to the '_pmd_' series of binned images; skipping processing"
)
return True
# Process TIF/TIFF files
if transferred_file.suffix in (".tif", ".tiff"):
# Files should be named "PositionX--ZXX--CXX.tif" by default
# If Position is repeated, it will add an additional --00X to the end
if len(transferred_file.stem.split("--")) not in [3, 4]:
logger.warning(
f"File {transferred_file.name!r} is likely not part of the CLEM workflow"
)
return False
logger.debug(
f"File {transferred_file.name!r} is part of a TIFF image series"
)
# Create a unique name for the series
# For standard file name
if len(transferred_file.stem.split("--")) == 3:
series_name = "--".join(
[
*destination_file.parent.parts[
-2:
], # Upper 2 parent directories
destination_file.stem.split("--")[0],
]
)
# When this a repeated position
elif len(transferred_file.stem.split("--")) == 4:
series_name = "--".join(
[
*destination_file.parent.parts[
-2:
], # Upper 2 parent directories
"--".join(
destination_file.stem.split("--")[i] for i in [0, -1]
),
]
)
else:
logger.error(
f"Series name could not be generated from file {transferred_file.name!r}"
)
return False
logger.debug(
f"File {transferred_file.name!r} given the series name {series_name!r}"
)
# Create key-value pairs containing empty list if not already present
if series_name not in self._tiff_series.keys():
self._tiff_series[series_name] = []
# Append information to list
self._tiff_series[series_name].append(str(destination_file))
logger.debug(
f"Created TIFF file dictionary entries for {series_name!r}"
)
# Register the TIFF file in the database
post_result = self.register_tiff_file(destination_file, environment)
if post_result is False:
return False
# Process XLIF files
if transferred_file.suffix == ".xlif":
# Skip processing of "_histo" histogram XLIF files
if transferred_file.stem.endswith("_histo"):
logger.debug(
f"File {transferred_file.name!r} contains histogram metadata; skipping processing"
)
return True
# Skip processing of "IOManagerConfiguation.xlif" files
# YES, the 'Configuation' typo IS part of the file name
if "IOManagerConfiguation" in transferred_file.stem:
logger.debug(
f"File {transferred_file.name!r} is a Leica configuration file; skipping processing"
)
return True
logger.debug(
f"File {transferred_file.name!r} contains metadata for an image series"
)
# Create series name for XLIF file
# XLIF files don't have the "--ZXX--CXX" additions in the file name
# But they have "/Metadata/" as the immediate parent
series_name = "--".join(
[*destination_file.parent.parent.parts[-2:], destination_file.stem]
) # The previous 2 parent directories should be unique enough
logger.debug(
f"File {transferred_file.name!r} given the series name {series_name!r}"
)
# Extract metadata to get the expected size of the series
metadata = parse(transferred_file).getroot()
metadata = _get_image_elements(metadata)[0]
# Get channel and dimension information
channels = metadata.findall(
"Data/Image/ImageDescription/Channels/ChannelDescription"
)
dimensions = metadata.findall(
"Data/Image/ImageDescription/Dimensions/DimensionDescription"
)
# Calculate expected number of files for this series
num_channels = len(channels)
num_frames = (
int(dimensions[2].attrib["NumberOfElements"])
if len(dimensions) > 2
else 1
)
num_files = num_channels * num_frames
logger.debug(
f"Expected number of files in {series_name!r}: {num_files}"
)
# Update dictionary entries
self._files_in_series[series_name] = num_files
self._series_metadata[series_name] = str(destination_file)
logger.debug(f"Created dictionary entries for {series_name!r} metadata")
# A new copy of the metadata file is created in 'processed', so no need
# to register this instance of it
# Post message if all files for the associated series have been collected
# .get(series_name, 0) returns 0 if no associated key is found
if not len(self._tiff_series.get(series_name, [])):
logger.debug(f"TIFF series {series_name!r} not yet loaded")
return True
elif self._files_in_series.get(series_name, 0) == 0:
logger.debug(
f"Metadata for TIFF series {series_name!r} not yet processed"
)
return True
elif len(
self._tiff_series.get(series_name, [])
) == self._files_in_series.get(series_name, 0):
logger.debug(
f"Collected expected number of TIFF files for series {series_name!r}; posting job to server"
)
# Post the message and log any errors that arise
tiff_dataset = {
"series_name": series_name,
"tiff_files": self._tiff_series[series_name],
"series_metadata": self._series_metadata[series_name],
}
post_result = self.process_tiff_series(tiff_dataset, environment)
if post_result is False:
return False
logger.info(f"Started preprocessing of TIFF series {series_name!r}")
else:
logger.debug(f"TIFF series {series_name!r} is still being processed")
# Process LIF files
if transferred_file.suffix == ".lif":
# Type checking to satisfy MyPy
if not environment:
logger.warning("No environment passed in")
return False
# Location of the file on the client PC
source = _get_source(transferred_file, environment)
# Type checking to satisfy MyPy
if not source:
logger.warning(f"No source found for file {transferred_file}")
return False
logger.debug(
f"File {transferred_file.name!r} is a valid LIF file; starting processing"
)
# Get the Path at the destination
destination_file = _file_transferred_to(
environment=environment,
source=source,
file_path=transferred_file,
)
if not destination_file:
logger.warning(
f"File {transferred_file.name!r} not found on the storage system"
)
return False
# Post URL to register LIF file in database
post_result = self.register_lif_file(destination_file, environment)
if post_result is False:
return False
logger.info(f"Registered {destination_file.name!r} in the database")
# Post URL to trigger job and convert LIF file into image stacks
post_result = self.process_lif_file(destination_file, environment)
if post_result is False:
return False
logger.info(f"Started preprocessing of {destination_file.name!r}")
# Function has completed as expected
return True
def register_lif_file(
self,
lif_file: Path,
environment: MurfeyInstanceEnvironment,
):
"""
Constructs the URL and dictionary to be posted to the server, which will then
register the LIF file in the database correctly as part of the CLEM workflow.
"""
try:
capture_post(
base_url=str(environment.url.geturl()),
router_name="clem.router",
function_name="register_lif_file",
session_id=environment.murfey_session,
data={"lif_file": quote(str(lif_file), safe="")},
)
return True
except Exception as e:
logger.error(
f"Error encountered when registering the LIF file in the database: {e}"
)
return False
def process_lif_file(
self,
lif_file: Path,
environment: MurfeyInstanceEnvironment,
):
"""
Constructs the URL and dictionary to be posted to the server, which will then
trigger the preprocessing of the LIF file.
"""
try:
capture_post(
base_url=str(environment.url.geturl()),
router_name="clem.router",
function_name="process_raw_lifs",
session_id=environment.murfey_session,
data={"lif_file": quote(str(lif_file), safe="")},
)
return True
except Exception as e:
logger.error(f"Error encountered processing LIF file: {e}")
return False
def register_tiff_file(
self,
tiff_file: Path,
environment: MurfeyInstanceEnvironment,
):
"""
Constructs the URL and dictionary to be posted to the server, which will then
register the TIFF file in the database correctly as part of the CLEM workflow.
"""
try:
capture_post(
base_url=str(environment.url.geturl()),
router_name="clem.router",
function_name="register_tiff_file",
session_id=environment.murfey_session,
data={"tiff_file": quote(str(tiff_file), safe="")},
)
return True
except Exception as e:
logger.error(
f"Error encountered when registering the TIFF file in the database: {e}"
)
return False
def process_tiff_series(
self,
tiff_dataset: dict,
environment: MurfeyInstanceEnvironment,
):
"""
Constructs the URL and dictionary to be posted to the server, which will then
trigger the preprocessing of this instance of a TIFF series.
"""
try:
capture_post(
base_url=str(environment.url.geturl()),
router_name="clem.router",
function_name="process_raw_tiffs",
session_id=environment.murfey_session,
data=tiff_dataset,
)
return True
except Exception as e:
logger.error(f"Error encountered processing the TIFF series: {e}")
return False