Skip to content

Commit 84a5579

Browse files
author
Yash Karan
committed
dict to weakref dict, type information, naming/structural changes
1 parent 68df1e2 commit 84a5579

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

newsfragments/789.feature

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Store static masks in FormatNXmx.py in a dict to avoid duplication
1+
Store unique masks in a dictionary to avoid duplication (FormatNXmx.py)

src/dxtbx/format/FormatNXmx.py

+27-11
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,39 @@
11
from __future__ import annotations
22

3+
import weakref
4+
35
import h5py
46
import nxmx
57

8+
import scitbx.array_family.flex as flex
9+
610
import dxtbx.nexus
711
from dxtbx.format.FormatNexus import FormatNexus
812

913

10-
# A singleton to hold unique static_mask objects to avoid duplications
11-
class MaskDict(dict):
12-
def hash_func(self, mask):
13-
return hash(mask[0].as_numpy_array().tobytes())
14+
class _MaskCache:
15+
"""A singleton to hold unique static_mask objects to avoid duplications"""
16+
17+
def __init__(self):
18+
self.local_mask_cache = weakref.WeakValueDictionary()
1419

15-
def insert(self, mask):
16-
mask_hash = self.hash_func(mask)
17-
if mask_hash not in self:
18-
mask_dict[mask_hash] = mask
19-
return mask_dict[mask_hash]
20+
def _mask_hasher(self, mask: flex.bool) -> int:
21+
return hash(mask.as_numpy_array().tobytes())
2022

23+
def store_unique_and_get(
24+
self, mask_tuple: tuple[flex.bool, ...] | None
25+
) -> tuple[flex.bool, ...] | None:
26+
if mask_tuple is None:
27+
return None
28+
output = []
29+
for mask in mask_tuple:
30+
mask_hash = self._mask_hasher(mask)
31+
self.local_mask_cache[mask_hash] = mask
32+
output.append(mask)
33+
return tuple(output)
2134

22-
mask_dict = MaskDict()
35+
36+
mask_cache = _MaskCache()
2337

2438

2539
def detector_between_sample_and_source(detector, beam):
@@ -98,7 +112,9 @@ def _start(self):
98112
self._detector_model = inverted_distance_detector(self._detector_model)
99113

100114
self._scan_model = dxtbx.nexus.get_dxtbx_scan(nxsample, nxdetector)
101-
self._static_mask = mask_dict.insert(dxtbx.nexus.get_static_mask(nxdetector))
115+
self._static_mask = mask_cache.store_unique_and_get(
116+
dxtbx.nexus.get_static_mask(nxdetector)
117+
)
102118
self._bit_depth_readout = nxdetector.bit_depth_readout
103119

104120
if self._scan_model:

0 commit comments

Comments
 (0)