brimfile.data v1.7.6
1from __future__ import annotations 2 3from typing import TYPE_CHECKING 4if TYPE_CHECKING: 5 from typing import Any 6 from numpy.typing import NDArray 7 8import numpy as np 9import asyncio 10 11import warnings 12 13from .file_abstraction import FileAbstraction, sync, _async_getitem, _gather_sync 14from .utils import concatenate_paths, list_objects_matching_pattern_async, get_object_name, set_object_name 15from .utils import np_array_to_smallest_int_type, _determine_chunk_size 16 17from .metadata import Metadata 18from .metadata.types import MetadataItem 19 20from numbers import Number 21import itertools 22 23from . import units 24from .analysis_results import AnalysisResults 25from .calibration import Calibration 26from .constants import brim_obj_names 27 28 29class Data: 30 """ 31 Represents a data group within the brim file. 32 """ 33 # make AnalysisResults available as an attribute of Data 34 AnalysisResults = AnalysisResults 35 36 def __init__(self, file: FileAbstraction, path: str, *, 37 newly_created: bool = False, _initialize: bool = True): 38 """ 39 Initialize the Data object. This constructor should not be called directly. 40 41 Args: 42 file (File): The parent File object. 43 path (str): The path to the data group within the file. 44 newly_created (bool): Whether this data group is being created as new. 45 If True, the constructor will not attempt to load spatial mapping. 46 _initialize (bool): FOR INTERNAL USE ONLY. Whether to automatically initialize the current data group. 47 Set to False if you want to initialize them manually later using the _init_async() method. Default is True. 48 """ 49 self._file = file 50 self._path = path 51 52 53 if _initialize: 54 sync(self._init_async(newly_created=newly_created)) 55 56 async def _init_async(self, newly_created: bool = False) -> None: 57 """ 58 See __init__() for the description of the arguments. 59 """ 60 self._group = await self._file.open_group(self._path) 61 62 self._sparse = await self._load_sparse_flag_async() 63 # the _spatial_map is None for non sparse data but the _spatial_map_px_size should always be valid 64 self._spatial_map, self._spatial_map_px_size = await self._load_spatial_mapping_async() if not newly_created else (None, None) 65 66 def get_name(self): 67 """ 68 Returns the name of the data group. 69 """ 70 return sync(get_object_name(self._file, self._path)) 71 72 def get_index(self): 73 """ 74 Returns the index of the data group. 75 """ 76 return int(self._path.split('/')[-1].split('_')[-1]) 77 78 async def _load_sparse_flag_async(self) -> bool: 79 """ 80 Load the 'Sparse' flag for the data group. 81 82 Returns: 83 bool: The value of the 'Sparse' flag, or False if the attribute is not found or invalid. 84 """ 85 try: 86 sparse = await self._file.get_attr(self._group, 'Sparse') 87 if isinstance(sparse, bool): 88 return sparse 89 else: 90 warnings.warn( 91 f"Invalid value for 'Sparse' attribute in {self._path}. Expected a boolean, got {type(sparse)}. Defaulting to False.") 92 return False 93 except Exception: 94 # if the attribute is not found, return the default value False 95 return False 96 97 async def _load_spatial_mapping_async(self, load_in_memory: bool=True) -> tuple: 98 """ 99 Load a spatial mapping in the same format as 'Cartesian visualisation', 100 irrespectively on whether 'Spatial_map' is defined instead. 101 -1 is used for "empty" pixels in the image 102 Args: 103 load_in_memory (bool): Specify whether the map should be forced to load in memory or just opened as a dataset. 104 Returns: 105 The spatial map and the corresponding pixel size as a tuple of 3 Metadata.Item, both in the order z, y, x. 106 If the spatial mapping is not defined in the file, returns None for the spatial map. 107 The pixel size is read from the data group for non-sparse data. 108 """ 109 cv = None 110 px_size = 3*(Metadata.Item(value=1, units=None),) 111 112 cv_path = concatenate_paths( 113 self._path, brim_obj_names.data.cartesian_visualisation) 114 sm_path = concatenate_paths( 115 self._path, brim_obj_names.data.spatial_map) 116 117 if await self._file.object_exists(cv_path): 118 cv = await self._file.open_dataset(cv_path) 119 120 #read the pixel size from the 'Cartesian visualisation' dataset 121 px_size_val = None 122 px_size_units = None 123 try: 124 px_size_val = await self._file.get_attr(cv, 'element_size') 125 if px_size_val is None or len(px_size_val) != 3: 126 raise ValueError( 127 "The 'element_size' attribute of 'Cartesian_visualisation' must be a tuple of 3 elements") 128 except Exception: 129 px_size_val = 3*(1,) 130 warnings.warn( 131 "No pixel size defined for Cartesian visualisation") 132 px_size_units = await units.of_attribute( 133 self._file, cv, 'element_size') 134 px_size = () 135 for i in range(3): 136 # if px_size_val[i] is not a number, set it to 1 and px_size_units to None 137 if isinstance(px_size_val[i], Number): 138 px_size += (Metadata.Item(px_size_val[i], px_size_units), ) 139 else: 140 px_size += (Metadata.Item(1, None), ) 141 142 143 if load_in_memory: 144 cv = await cv.to_np_array() # load the spatial map in memory as a numpy array 145 cv = np_array_to_smallest_int_type(cv) 146 147 elif await self._file.object_exists(sm_path): 148 async def load_spatial_map_from_file(): 149 async def load_coordinate_from_sm(coord: str): 150 res = np.empty(0) # empty array 151 try: 152 res = await self._file.open_dataset( 153 concatenate_paths(sm_path, coord)) 154 res = await res.to_np_array() 155 res = np.squeeze(res) # remove single-dimensional entries 156 except Exception as e: 157 # if the coordinate does not exist, return an empty array 158 pass 159 if len(res.shape) > 1: 160 raise ValueError( 161 f"The 'Spatial_map/{coord}' dataset is not a 1D array as expected") 162 return res 163 164 def check_coord_array(arr, size): 165 if arr.size == 0: 166 return np.zeros(size) 167 elif arr.size != size: 168 raise ValueError( 169 "The 'Spatial_map' dataset is invalid") 170 return arr 171 172 x, y, z = await asyncio.gather( 173 load_coordinate_from_sm('x'), 174 load_coordinate_from_sm('y'), 175 load_coordinate_from_sm('z') 176 ) 177 size = max([x.size, y.size, z.size]) 178 if size == 0: 179 raise ValueError("The 'Spatial_map' dataset is empty") 180 x = check_coord_array(x, size) 181 y = check_coord_array(y, size) 182 z = check_coord_array(z, size) 183 return x, y, z 184 185 def calculate_step(x): 186 n = len(np.unique(x)) 187 if n == 1: 188 d = None 189 else: 190 d = (np.max(x)-np.min(x))/(n-1) 191 return n, d 192 193 x, y, z = await load_spatial_map_from_file() 194 195 # TODO extend the reconstruction to non-cartesian cases 196 197 nX, dX = calculate_step(x) 198 nY, dY = calculate_step(y) 199 nZ, dZ = calculate_step(z) 200 201 indices = np_array_to_smallest_int_type(np.lexsort((x, y, z))) 202 cv = np.reshape(indices, (nZ, nY, nX)) 203 204 px_size_units = await units.of_object(self._file, sm_path) 205 px_size = () 206 for i in range(3): 207 px_sz = (dZ, dY, dX)[i] 208 px_unit = px_size_units 209 if px_sz is None: 210 px_sz = 1 211 px_unit = None 212 px_size += (Metadata.Item(px_sz, px_unit),) 213 elif not self._sparse: 214 try: 215 px_sz = await self._file.get_attr(self._group, 'element_size') 216 if len(px_sz) != 3: 217 raise ValueError( 218 "The 'element_size' attribute must be a tuple of 3 elements") 219 px_unit = None 220 try: 221 px_unit = await units.of_attribute(self._file, self._group, 'element_size') 222 except Exception: 223 warnings.warn("Pixel size unit is not provided for non-sparse data.") 224 px_size = tuple(Metadata.Item(el, px_unit) for el in px_sz) 225 except Exception: 226 warnings.warn("Pixel size is not provided for non-sparse data.") 227 228 return cv, px_size 229 230 def _get_spatial_index_from_coor(self, coor: tuple) -> tuple: 231 """ 232 Retrieve the spatial index for a given spatial coordinate. 233 234 Args: 235 coor (tuple): Spatial coordinate as ``(z, y, x)``. 236 Raises: 237 ValueError: If `coor` does not contain three coordinates 238 Returns: 239 tuple: The spatial index corresponding to the given coordinate. 240 It is always a tuple containing 1 or 3 integers, depending on whether the data is sparse or not. 241 """ 242 if len(coor) != 3: 243 raise ValueError("coor must contain 3 values for z, y, x") 244 index = coor 245 if self._sparse: 246 index = (int(self._spatial_map[coor]),) 247 return index 248 249 def get_PSD(self) -> tuple: 250 """ 251 LOW LEVEL FUNCTION 252 253 Retrieve the Power Spectral Density (PSD) and frequency from the current data group. 254 Note: this function exposes the internals of the brim file and thus the interface might change in future versions. 255 Use only if more specialized functions are not working for your application! 256 Returns: 257 tuple: (PSD, frequency, PSD_units, frequency_units) 258 - PSD: A 2D (or more) numpy array containing all the spectra (see [specs](https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md) for more details). 259 - frequency: A numpy array representing the frequency data (see [specs](https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md) for more details). 260 - PSD_units: The units of the PSD. 261 - frequency_units: The units of the frequency. 262 """ 263 warnings.warn( 264 "Data.get_PSD is deprecated and will be removed in a future release. " 265 "Use Data.get_PSD_as_spatial_map instead.", 266 DeprecationWarning, 267 stacklevel=2, 268 ) 269 PSD, frequency = _gather_sync( 270 self._file.open_dataset(concatenate_paths( 271 self._path, brim_obj_names.data.PSD)), 272 self._file.open_dataset(concatenate_paths( 273 self._path, brim_obj_names.data.frequency)) 274 ) 275 # retrieve the units of the PSD and frequency 276 PSD_units, frequency_units = _gather_sync( 277 units.of_object(self._file, PSD), 278 units.of_object(self._file, frequency) 279 ) 280 281 return PSD, frequency, PSD_units, frequency_units 282 283 @staticmethod 284 def interpolate_spectra(PSD: np.ndarray, frequency: np.ndarray, *, 285 new_frequency: np.ndarray | None = None 286 ) -> tuple[np.ndarray, np.ndarray]: 287 """Interpolate spectra along their final axis. 288 289 Each spectrum is interpolated from its corresponding values in 290 ``frequency`` onto ``new_frequency``. Both frequency arrays must be 291 broadcastable to ``PSD.shape``; for example, a 1D array can be shared 292 across all spectra. The final axis contains the frequency samples. 293 294 If ``new_frequency`` is omitted and ``frequency`` is multidimensional, 295 a shared 1D frequency array is generated by averaging ``frequency`` 296 across all dimensions except its final (sample) axis. If the input 297 frequency is 1D, the original ``PSD`` and ``frequency`` are returned 298 unchanged. 299 300 Values outside a spectrum's frequency range use ``numpy.interp``'s 301 endpoint behavior. 302 303 Args: 304 PSD: Spectral values, with samples along the final axis. 305 frequency: Frequencies corresponding to ``PSD``. Must contain only finite values. 306 new_frequency (optional): Target frequencies, finite and broadcastable to 307 ``PSD.shape``. May be 1D or have additional broadcastable 308 dimensions. If omitted, a new frequency array is generated. 309 310 Returns: 311 A tuple of the spectra and the target frequencies. The spectra 312 retain the original ``PSD`` dtype when no interpolation is done; 313 otherwise, they have dtype ``float64``. When ``new_frequency`` is 314 supplied, it is returned in its original shape; when generated, 315 the returned array is 1D. 316 317 Raises: 318 ValueError: If frequencies are non-finite, or either frequency array 319 cannot be broadcast as required. 320 """ 321 322 # the frequency is already the same for all spectra and no new frequency is provided, 323 # so we can just return the original PSD 324 if new_frequency is None and frequency.ndim == 1: 325 return PSD, frequency 326 327 # check the frequency array 328 if not np.all(np.isfinite(frequency)): 329 raise ValueError("The frequency array must contain only finite values for interpolation.") 330 try: 331 frequency = np.broadcast_to(frequency, PSD.shape) 332 except ValueError as e: 333 raise ValueError("`frequency` must be broadcastable to the shape of PSD.") from e 334 if not np.all(np.diff(frequency, axis=-1) >= 0): 335 # the array is not increasing along the last axis, we need to sort it and the PSD accordingly 336 sort_indices = np.argsort(frequency, axis=-1) 337 frequency = np.take_along_axis(frequency, sort_indices, axis=-1) 338 PSD = np.take_along_axis(PSD, sort_indices, axis=-1) 339 # check or generate the new frequency array 340 if new_frequency is None: 341 # if the user does not provide a new frequency array, we will create a new frequency array that 342 # is the mean of the original frequency array along all dimensions except the last one 343 new_frequency = np.mean(frequency, axis=tuple(range(frequency.ndim - 1))) 344 else: 345 if new_frequency.ndim > PSD.ndim: 346 raise ValueError("`new_frequency` must have less or equal number of dimensions than PSD") 347 if not np.all(np.isfinite(new_frequency)): 348 raise ValueError("`new_frequency` must contain only finite values.") 349 try: 350 np.broadcast_shapes(new_frequency.shape, PSD.shape) 351 except Exception as e: 352 raise ValueError("`new_frequency` must have the same number of dimensions as PSD or be 1D.") from e 353 354 # Interpolate each spectrum in the PSD along the last axis 355 interpolated_PSD = np.empty_like(PSD, dtype=np.float64) 356 interp_freq = np.broadcast_to(new_frequency, PSD.shape) 357 for idx in itertools.product(*[range(s) for s in PSD.shape[:-1]]): 358 interpolated_PSD[idx] = np.interp(interp_freq[idx], frequency[idx], PSD[idx]) 359 return interpolated_PSD, new_frequency 360 361 def get_PSD_as_spatial_map(self, *, broadcast_frequency: bool = True) -> tuple: 362 """ 363 Retrieve the Power Spectral Density (PSD) as a spatial map and the frequency from the current data group. 364 Arguments: 365 broadcast_frequency (bool): Whether to broadcast the frequency array to match the shape of the PSD if they have different shapes. 366 This is useful when the frequency is the same for all spectra and thus stored as a 1D array, while the PSD has a spatial dimension. 367 If False, the function will return the frequency with the same shape as it is stored in the file (which could be any shape broadcastable to PSD); 368 consider using `Data.interpolate_spectra` to interpolate the PSD to a new (1D) frequency array if needed. 369 Returns: 370 tuple: (PSD, frequency, PSD_units, frequency_units) 371 - PSD: A 4D (or more) numpy array containing all the spectra. Dimensions are z, y, x, [parameters], spectrum. 372 - frequency: A numpy array representing the frequency data, which has the same shape as PSD or a 1D array (see `broadcast_frequency`). 373 - PSD_units: The units of the PSD. 374 - frequency_units: The units of the frequency. 375 """ 376 PSD, frequency = _gather_sync( 377 self._file.open_dataset(concatenate_paths( 378 self._path, brim_obj_names.data.PSD)), 379 self._file.open_dataset(concatenate_paths( 380 self._path, brim_obj_names.data.frequency)) 381 ) 382 # retrieve the units of the PSD and frequency 383 PSD_units, frequency_units = _gather_sync( 384 units.of_object(self._file, PSD), 385 units.of_object(self._file, frequency) 386 ) 387 388 # ensure PSD and frequency are numpy arrays 389 PSD = np.array(PSD) 390 frequency = np.array(frequency) # ensure it's a numpy array 391 392 # if the frequency is not the same for all spectra, broadcast it to match the shape of PSD 393 # if it is the same for all spectra, broadcast_frequency determines whether to return it as a 1D array or broadcast it to match the shape of PSD 394 if frequency.ndim > 1 or (broadcast_frequency and frequency.shape != PSD.shape): 395 frequency = np.broadcast_to(frequency, PSD.shape) 396 397 if self._sparse: 398 if self._spatial_map is None: 399 raise ValueError("The data is defined as sparse, but no spatial mapping is provided.") 400 sm = np.array(self._spatial_map) 401 # reshape the PSD and frequency to have the spatial dimensions first 402 PSD = PSD[sm, ...] 403 # reshape the frequency only if it is not the same for all spectra 404 if frequency.ndim > 1: 405 frequency = frequency[sm, ...] 406 407 return PSD, frequency, PSD_units, frequency_units 408 409 def _get_spectrum(self, index: int | tuple[int, int, int]) -> tuple: 410 """ 411 Synchronous wrapper for `_get_spectrum_async`. 412 """ 413 return sync(self._get_spectrum_async(index)) 414 async def _get_spectrum_async(self, index: int | tuple[int, int, int]) -> tuple: 415 """ 416 @public 417 418 Retrieve a spectrum from the data group by its index or coordinates. 419 420 Args: 421 index (int | tuple[int, int, int]): The index (for sparse data) or z, y, x coordinates (for non-sparse data) of the spectrum to retrieve. 422 423 Returns: 424 tuple: (PSD, frequency, PSD_units, frequency_units) for the specified index. 425 PSD can be 1D or more (if there are additional parameters); 426 frequency has the same size as PSD 427 Raises: 428 IndexError: If the index is out of range for the PSD dataset. 429 """ 430 if self._sparse and not isinstance(index, int): 431 raise ValueError("For sparse data, index must be an integer.") 432 elif not self._sparse and not (isinstance(index, tuple) and len(index) == 3): 433 raise ValueError("For non-sparse data, index must be a tuple of (z, y, x) coordinates.") 434 435 # index = -1 corresponds to no spectrum 436 if self._sparse and index < 0: 437 return None, None, None, None 438 elif not self._sparse and any(i < 0 for i in index): 439 return None, None, None, None 440 PSD, frequency = await asyncio.gather( 441 self._file.open_dataset(concatenate_paths( 442 self._path, brim_obj_names.data.PSD)), 443 self._file.open_dataset(concatenate_paths( 444 self._path, brim_obj_names.data.frequency)) 445 ) 446 if self._sparse and index >= PSD.shape[0]: 447 raise IndexError( 448 f"index {index} out of range for PSD with shape {PSD.shape}") 449 elif not self._sparse and any(i >= PSD.shape[j] for j, i in enumerate(index)): 450 raise IndexError( 451 f"index {index} out of range for PSD with shape {PSD.shape}") 452 # retrieve the units of the PSD and frequency 453 PSD_units, frequency_units = await asyncio.gather( 454 units.of_object(self._file, PSD), 455 units.of_object(self._file, frequency) 456 ) 457 # add ellipsis to the index to select the spectrum and the corresponding frequency 458 if self._sparse: 459 index = (index, ...) 460 else: 461 index = index + (..., ) 462 # map index to the frequency array, considering the broadcasting rules 463 index_frequency = index 464 if frequency.ndim < PSD.ndim: 465 if self._sparse: 466 # given the definition of the brim file format, 467 # if the frequency has less dimensions that PSD, 468 # it can only be because it is the same for all the spatial position (first dimension) 469 index_frequency = (..., ) 470 else: 471 unassigned_indices = PSD.ndim - frequency.ndim 472 if unassigned_indices == 3: 473 # if the frequency has no spatial dimension, it is the same for all the spatial positions 474 index_frequency = (..., ) 475 else: 476 # if the frequency has some spatial dimensions but not all, we need to add the corresponding indices to the index of the frequency 477 index_frequency = index[-unassigned_indices:] + (..., ) 478 #get the spectrum and the corresponding frequency at the specified index 479 PSD, frequency = await asyncio.gather( 480 _async_getitem(PSD, index), 481 _async_getitem(frequency, index_frequency) 482 ) 483 #broadcast the frequency to match the shape of PSD if needed 484 if frequency.ndim < PSD.ndim: 485 frequency = np.broadcast_to(frequency, PSD.shape) 486 return PSD, frequency, PSD_units, frequency_units 487 488 def get_spectrum_in_image(self, coor: tuple) -> tuple: 489 """ 490 Retrieve a spectrum from the data group using spatial coordinates. 491 492 Args: 493 coor (tuple): A tuple containing the z, y, x coordinates of the spectrum to retrieve. 494 495 Returns: 496 tuple: A tuple containing the PSD, frequency, PSD_units, and 497 frequency_units for the specified coordinates. See 498 `brimfile.data.Data._get_spectrum_async` for details. 499 500 Raises: 501 ValueError: If `coor` does not contain three coordinates `(z, y, x)`. 502 IndexError: If coordinates map outside the available data. 503 """ 504 if len(coor) != 3: 505 raise ValueError("coor must contain 3 values for z, y, x") 506 507 if self._sparse: 508 index = int(self._spatial_map[coor]) 509 return self._get_spectrum(index) 510 else: 511 return self._get_spectrum(coor) 512 513 async def get_spectrum_and_all_quantities_in_image_async(self, ar: 'Data.AnalysisResults', coor: tuple, index_peak: int = 0) -> tuple[tuple, dict]: 514 """ 515 Retrieve the spectrum and all available quantities from the analysis results at a specific spatial coordinate. 516 517 Args: 518 ar (Data.AnalysisResults): The analysis results object to retrieve quantities from. 519 coor (tuple): A tuple containing the z, y, x coordinates in the image. 520 index_peak (int, optional): The index of the peak to retrieve (for multi-peak fits). Defaults to 0. 521 522 Returns: 523 tuple: A tuple containing: 524 - spectrum (tuple): (PSD, frequency, PSD_units, frequency_units) at the specified coordinate 525 - quantities (dict): Dictionary of Metadata.Item in the form result[quantity.name][peak.name] 526 """ 527 if len(coor) != 3: 528 raise ValueError("coor must contain 3 values for z, y, x") 529 index = coor 530 if self._sparse: 531 index = int(self._spatial_map[coor]) 532 spectrum, quantities = await asyncio.gather( 533 self._get_spectrum_async(index), 534 ar._get_all_quantities_at_index(index, index_peak) 535 ) 536 return spectrum, quantities 537 def get_spectrum_and_all_quantities_in_image(self, ar: 'Data.AnalysisResults', coor: tuple, index_peak: int = 0) -> tuple[tuple, dict]: 538 """ 539 Synchronous wrapper for `get_spectrum_and_all_quantities_in_image_async` (see doc for `brimfile.data.Data.get_spectrum_and_all_quantities_in_image_async`) 540 """ 541 return sync(self.get_spectrum_and_all_quantities_in_image_async(ar, coor, index_peak)) 542 543 def get_metadata(self): 544 """ 545 Returns the metadata associated with the current Data group 546 Note that this contains both the general metadata stored in the file (which might be redifined by the specific data group) 547 and the ones specific for this data group 548 """ 549 return Metadata(self._file, self._path) 550 551 def get_num_parameters(self) -> tuple: 552 """ 553 Retrieves the number of parameters 554 555 Returns: 556 tuple: The shape of the parameters if they exist, otherwise an empty tuple. 557 """ 558 pars, _ = self.get_parameters() 559 return pars.shape if pars is not None else () 560 561 def get_parameters(self) -> list: 562 """ 563 Retrieves the parameters and their associated names. 564 565 If PSD.ndims > 2, the parameters are stored in a separate dataset. 566 567 Returns: 568 list: A tuple containing the parameters and their names if there are any, otherwise None. 569 """ 570 pars_full_path = concatenate_paths( 571 self._path, brim_obj_names.data.parameters) 572 if sync(self._file.object_exists(pars_full_path)): 573 pars = sync(self._file.open_dataset(pars_full_path)) 574 pars_names = sync(self._file.get_attr(pars, 'Name')) 575 return (pars, pars_names) 576 return (None, None) 577 578 def create_calibration_group(self, *, index: NDArray[np.integer] | None = None, calibration_data: list[dict[str, Any]] | None = None, 579 same_as: int | None = None, attributes: dict[str, MetadataItem] = None, 580 compression: FileAbstraction.Compression = FileAbstraction.Compression()) -> Calibration: 581 """ 582 Create a new calibration group in the current data group. 583 For more details on the expected format of the calibration data, see https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md. 584 585 Parameters: 586 index (np.array | None, optional): Index array for the calibration spectra. For sparse data, 587 this must be 1D; for non-sparse data, this must be 3D. 588 It can be omitted if each element in `calibration_data` contains only one spectrum. 589 calibration_data (list[dict[str, Any]] | None, optional): Calibration entries to store. 590 Each dictionary must contain `spectra` and `shift` keys, and may provide `shift_units`. 591 same_as (int | None, optional): If provided, links this calibration group to an existing 592 calibration via the `Same_as` attribute. When set, the other data arguments are ignored. 593 Defaults to None. 594 attributes (dict[str, MetadataItem], optional): Additional attributes to attach to the calibration group. 595 Can be one of ('Datetime', 'Description', 'Temperature', 'FSR') with the relative units (when relevant). 596 compression (FileAbstraction.Compression, optional): Compression settings used for created 597 datasets. Defaults to FileAbstraction.Compression(). 598 599 Returns: 600 Calibration: The newly created calibration group. 601 602 Raises: 603 ValueError: If the provided calibration data or index is invalid or inconsistent. 604 """ 605 calibration_path = concatenate_paths(self._path, brim_obj_names.data.calibration) 606 calibration_group = sync(self._file.create_group(calibration_path)) 607 608 # if same_as is provided, create the 'Same_as' attribute to link the calibration group to an existing one 609 if same_as is not None: 610 sync(self._file.create_attr(calibration_group, 'Same_as', same_as)) 611 else: # if same_as is provided, the other parameters are ignored 612 # check that calibration_data is provided and valid 613 if calibration_data is None: 614 raise ValueError("'calibration_data' is required when 'same_as' is not provided") 615 if not isinstance(calibration_data, (list, tuple)): 616 calibration_data = [calibration_data,] 617 # check that index is valid if provided 618 if index is not None: 619 # TODO: check of the shape of 'index' is compatible with PSD 620 if self._sparse and index.ndim != 1: 621 raise ValueError("'index' must be a 1D array for sparse data") 622 if not self._sparse and index.ndim != 3: 623 raise ValueError("'index' must be a 3D array for non-sparse data") 624 625 for m, calib in enumerate(calibration_data): 626 # check that each element in calibration_data is a dictionary containing 'spectra' and 'shift' keys 627 if not isinstance(calib, dict): 628 raise ValueError("Each element in 'calibration_data' must be a dictionary") 629 if 'spectra' not in calib.keys() or 'shift' not in calib.keys(): 630 raise ValueError("Each calibration data dictionary must contain 'spectra' and 'shift' keys") 631 # retrieve the spectra, shift and shift_units from the calibration data and check that they are valid 632 cal_spectra = np.array(calib['spectra']) 633 if cal_spectra.ndim != 2: 634 raise ValueError("'spectra' in calibration data must be a 2D array. If only one spectrum is provided, set the first dimension to 1.") 635 cal_shift = calib['shift'] 636 cal_shift_units = calib.get('shift_units', None) 637 if cal_shift_units is None: 638 cal_shift_units = 'GHz' 639 warnings.warn("No units provided for 'shift' in calibration data, defaulting to GHz") 640 # check that index is compatible with the shape of the spectra 641 if index is None and cal_spectra.shape[0] != 1: 642 raise ValueError("If 'index' is not provided, each element in 'calibration_data' must contain only one spectrum (i.e. have shape (1, n))") 643 if index is not None and np.max(index) >= cal_spectra.shape[0]: 644 raise ValueError("If 'index' is provided, its maximum value must be less than the number of spectra in each calibration data element") 645 # add the m arrays together with their attributes to the file 646 spectra_dataset = sync(self._file.create_dataset(calibration_group, f'{m}', cal_spectra, chunk_size=_determine_chunk_size(cal_spectra), compression=compression)) 647 sync(self._file.create_attr(spectra_dataset, 'Shift', cal_shift)) 648 units.add_to_attribute(self._file, spectra_dataset, 'Shift', cal_shift_units) 649 # add the index array to the file 650 if index is not None: 651 sync(self._file.create_dataset(calibration_group, 'Index', index, compression=compression)) 652 653 from .calibration import _STANDARD_ATTRIBUTES 654 # add any additional attributes to the calibration group, checking that they do not overwrite the standard 655 if attributes is not None: 656 for key, value in attributes.items(): 657 if key not in _STANDARD_ATTRIBUTES: 658 warnings.warn(f"Attribute '{key}' is not a standard attribute for calibration groups.\ 659 Standard attributes are: {', '.join(_STANDARD_ATTRIBUTES)}. \ 660 Make sure this is intentional!") 661 if not isinstance(value, MetadataItem): 662 value = MetadataItem(value) 663 sync(self._file.create_attr(calibration_group, key, value.value)) 664 if value.units is not None: 665 units.add_to_attribute(self._file, calibration_group, key, value.units) 666 667 return Calibration(self._file, calibration_path, data_group=self) 668 669 def get_calibration(self) -> Calibration: 670 """ 671 Synchronous wrapper for `get_calibration_async` (see doc for `brimfile.data.Data.get_calibration_async`) 672 """ 673 return sync(self.get_calibration_async()) 674 675 async def get_calibration_async(self) -> Calibration: 676 """ 677 Retrieve the calibration group associated with the current data group. 678 679 Returns: 680 Calibration: The calibration group associated with the current data group. 681 682 Raises: 683 ValueError: If no calibration group is found in the current data group or the referenced calibration group does not exist. 684 """ 685 calibration_path = concatenate_paths(self._path, brim_obj_names.data.calibration) 686 if not await self._file.object_exists(calibration_path): 687 raise ValueError(f"No calibration group found in {self._path}") 688 same_as = None 689 try: 690 same_as = await self._file.get_attr(calibration_path, 'Same_as') 691 except Exception: 692 pass # same_as attribute is optional, if it does not exist we just ignore it 693 # if the 'Same_as' attribute exists, find the calibration group with the corresponding index 694 if same_as is not None: 695 try: 696 d_m = await Data.from_existing_async(self._file, same_as) 697 return await d_m.get_calibration_async() 698 except IndexError: 699 raise ValueError(f"Calibration group in {self._path} references non-existing calibration index {same_as} in the file") 700 cal_group = Calibration(self._file, calibration_path, data_group=self, _initialize=False) 701 await cal_group._init_async() 702 return cal_group 703 704 def create_analysis_results_group(self, data_AntiStokes, data_Stokes=None, *, 705 index: int = None, name: str = None, fit_model: 'Data.AnalysisResults.FitModel' = None) -> AnalysisResults: 706 """ 707 Adds a new AnalysisResults entry to the current data group. 708 Parameters: 709 data_AntiStokes (dict or list[dict]): see documentation for `brimfile.analysis_results.AnalysisResults.add_data` 710 data_Stokes (dict or list[dict]): same as data_AntiStokes for the Stokes peaks. 711 index (int, optional): The index for the new data entry. If None, the next available index is used. Defaults to None. 712 name (str, optional): The name for the new Analysis group. Defaults to None. 713 fit_model (Data.AnalysisResults.FitModel, optional): The fit model used for the analysis. Defaults to None (no attribute is set). 714 Returns: 715 AnalysisResults: The newly created AnalysisResults object. 716 Raises: 717 IndexError: If the specified index already exists in the dataset. 718 ValueError: If any of the data provided is not valid or consistent 719 """ 720 if index is not None: 721 try: 722 self.get_analysis_results(index) 723 except IndexError: 724 pass 725 else: 726 # If the group already exists, raise an error 727 raise IndexError( 728 f"Analysis {index} already exists in {self._path}") 729 else: 730 ar_groups = self.list_AnalysisResults() 731 indices = [ar['index'] for ar in ar_groups] 732 indices.sort() 733 index = indices[-1] + 1 if indices else 0 # Next available index 734 735 ar = Data.AnalysisResults._create_new(self, index=index, sparse=self._sparse) 736 if name is not None: 737 set_object_name(self._file, ar._path, name) 738 ar.add_data(data_AntiStokes, data_Stokes, fit_model=fit_model) 739 740 return ar 741 742 def list_AnalysisResults(self, retrieve_custom_name=False) -> list: 743 """ 744 List all AnalysisResults groups in the current data group. The list is ordered by index. 745 746 Returns: 747 list: A list of dictionaries, each containing: 748 - 'name' (str): The name of the AnalysisResults group. 749 - 'index' (int): The index extracted from the group name. 750 - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the AnalysisResults group as returned from utils.get_object_name. 751 """ 752 753 analysis_results_groups = [] 754 755 matched_objs = sync(list_objects_matching_pattern_async( 756 self._file, self._group, brim_obj_names.data.analysis_results + r"_(\d+)$")) 757 async def _make_dict_item(matched_obj, retrieve_custom_name): 758 name = matched_obj[0] 759 index = int(matched_obj[1]) 760 curr_obj_dict = {'name': name, 'index': index} 761 if retrieve_custom_name: 762 ar_path = concatenate_paths(self._path, name) 763 custom_name = await get_object_name(self._file, ar_path) 764 curr_obj_dict['custom_name'] = custom_name 765 return curr_obj_dict 766 coros = [_make_dict_item(matched_obj, retrieve_custom_name) for matched_obj in matched_objs] 767 dicts = _gather_sync(*coros) 768 for dict_item in dicts: 769 analysis_results_groups.append(dict_item) 770 # Sort the data groups by index 771 analysis_results_groups.sort(key=lambda x: x['index']) 772 773 return analysis_results_groups 774 775 def get_analysis_results(self, index: int = 0) -> AnalysisResults: 776 """ 777 Returns the AnalysisResults at the specified index 778 779 Args: 780 index (int) 781 782 Raises: 783 IndexError: If there is no analysis with the corresponding index 784 """ 785 name = None 786 ls = self.list_AnalysisResults() 787 for el in ls: 788 if el['index'] == index: 789 name = el['name'] 790 break 791 if name is None: 792 raise IndexError(f"Analysis {index} not found") 793 path = concatenate_paths(self._path, name) 794 return Data.AnalysisResults(self._file, path, data_group_path=self._path, 795 spatial_map=self._spatial_map, spatial_map_px_size=self._spatial_map_px_size, sparse=self._sparse) 796 797 def _add_data(self, PSD: np.ndarray, frequency: np.ndarray, *, scanning: dict = None, freq_units='GHz', 798 compression: FileAbstraction.Compression = FileAbstraction.Compression()): 799 """ 800 @public 801 802 Add data to the current data group. 803 804 This method adds the provided PSD, frequency, and scanning data to the HDF5 group 805 associated with this `Data` object. It validates the inputs to ensure they meet 806 the required specifications before adding them. 807 808 Args: 809 PSD (np.ndarray): A 2D numpy array representing the Power Spectral Density (PSD) data. The last dimension contains the spectra. 810 frequency (np.ndarray): A 1D or 2D numpy array representing the frequency data. 811 It must be broadcastable to the shape of the PSD array. 812 scanning (dict, optional): A dictionary containing scanning-related data. 813 Required for sparse data (sparse=True), optional for non-sparse data. 814 For sparse data, must include at least one of 'Spatial_map' or 'Cartesian_visualisation'. 815 It may include the following keys: 816 - 'Spatial_map' (optional): A dictionary containing coordinate arrays: 817 - 'x', 'y', 'z' (optional): 1D numpy arrays of same length with coordinate values 818 - 'units' (optional): string with the unit (e.g., 'um') 819 - 'Cartesian_visualisation' (optional): A 3D numpy array (z, y, x) with integer values 820 mapping spatial positions to spectra indices. Values must be -1 (invalid/empty pixel) 821 or between 0 and PSD.shape[0]-1. 822 - 'Cartesian_visualisation_pixel' (recommended with Cartesian_visualisation): 823 Tuple/list of 3 float values (z, y, x) representing pixel size. Unused dimensions can be None. 824 - 'Cartesian_visualisation_pixel_unit' (optional): String for pixel size unit (default: 'um'). 825 826 Raises: 827 ValueError: If any of the data provided is not valid or consistent 828 """ 829 830 # Check if frequency is broadcastable to PSD 831 try: 832 np.broadcast_shapes(tuple(frequency.shape), tuple(PSD.shape)) 833 except ValueError as e: 834 raise ValueError(f"frequency (shape: {frequency.shape}) is not broadcastable to PSD (shape: {PSD.shape}): {e}") 835 836 # Check if at least one of 'Spatial_map' or 'Cartesian_visualisation' is present in the scanning dictionary 837 # This is required for sparse data to establish the spatial mapping 838 has_spatial_mapping = False 839 if scanning is not None: 840 if 'Spatial_map' in scanning: 841 sm = scanning['Spatial_map'] 842 size = 0 843 844 def check_coor(coor: str): 845 if coor in sm: 846 sm[coor] = np.array(sm[coor]) 847 size1 = sm[coor].size 848 if size1 != size and size != 0: 849 raise ValueError( 850 f"'{coor}' in 'Spatial_map' is invalid!") 851 return size1 852 return size 853 size = check_coor('x') 854 size = check_coor('y') 855 size = check_coor('z') 856 if size == 0: 857 raise ValueError( 858 "'Spatial_map' should contain at least one x, y or z") 859 has_spatial_mapping = True 860 if 'Cartesian_visualisation' in scanning: 861 cv = scanning['Cartesian_visualisation'] 862 if not isinstance(cv, np.ndarray) or cv.ndim != 3: 863 raise ValueError( 864 "Cartesian_visualisation must be a 3D numpy array") 865 if not np.issubdtype(cv.dtype, np.integer) or np.min(cv) < -1 or np.max(cv) >= PSD.shape[0]: 866 raise ValueError( 867 "Cartesian_visualisation values must be integers between -1 and PSD.shape[0]-1") 868 if 'Cartesian_visualisation_pixel' in scanning: 869 if len(scanning['Cartesian_visualisation_pixel']) != 3: 870 raise ValueError( 871 "Cartesian_visualisation_pixel must always contain 3 values for z, y, x (set to None if not used)") 872 else: 873 warnings.warn( 874 "It is recommended to include 'Cartesian_visualisation_pixel' in the scanning dictionary to define pixel size for proper spatial calibration") 875 has_spatial_mapping = True 876 if not has_spatial_mapping and self._sparse: 877 raise ValueError("For sparse data, 'scanning' must be provided and must contain at least one of 'Spatial_map' or 'Cartesian_visualisation'") 878 879 # TODO: add and validate additional datasets (i.e. 'Parameters', 'Calibration_index', etc.) 880 881 # Add datasets to the group 882 sync(self._file.create_dataset( 883 self._group, brim_obj_names.data.PSD, data=PSD, 884 chunk_size=_determine_chunk_size(PSD), compression=compression)) 885 freq_ds = sync(self._file.create_dataset( 886 self._group, brim_obj_names.data.frequency, data=frequency, 887 chunk_size=_determine_chunk_size(frequency), compression=compression)) 888 units.add_to_object(self._file, freq_ds, freq_units) 889 890 if scanning is not None: 891 if 'Spatial_map' in scanning: 892 sm = scanning['Spatial_map'] 893 sm_group = sync(self._file.create_group(concatenate_paths( 894 self._path, brim_obj_names.data.spatial_map))) 895 if 'units' in sm: 896 units.add_to_object(self._file, sm_group, sm['units']) 897 898 def add_sm_dataset(coord: str): 899 if coord in sm: 900 sync(self._file.create_dataset( 901 sm_group, coord, data=sm[coord], compression=compression)) 902 903 add_sm_dataset('x') 904 add_sm_dataset('y') 905 add_sm_dataset('z') 906 if 'Cartesian_visualisation' in scanning: 907 # convert the Cartesian_visualisation to the smallest integer type 908 cv_arr = np_array_to_smallest_int_type(scanning['Cartesian_visualisation']) 909 cv = sync(self._file.create_dataset(self._group, brim_obj_names.data.cartesian_visualisation, 910 data=cv_arr, compression=compression)) 911 if 'Cartesian_visualisation_pixel' in scanning: 912 sync(self._file.create_attr( 913 cv, 'element_size', scanning['Cartesian_visualisation_pixel'])) 914 if 'Cartesian_visualisation_pixel_unit' in scanning: 915 px_unit = scanning['Cartesian_visualisation_pixel_unit'] 916 else: 917 warnings.warn( 918 "No unit provided for Cartesian_visualisation_pixel, defaulting to 'um'") 919 px_unit = 'um' 920 units.add_to_attribute(self._file, cv, 'element_size', px_unit) 921 922 self._spatial_map, self._spatial_map_px_size = sync(self._load_spatial_mapping_async()) 923 924 @staticmethod 925 def list_data_groups(file: FileAbstraction, retrieve_custom_name=False) -> list: 926 """ 927 Synchronous wrapper for `list_data_groups_async` (see doc for `brimfile.data.Data.list_data_groups_async`) 928 """ 929 return sync(Data.list_data_groups_async(file, retrieve_custom_name)) 930 931 @staticmethod 932 async def list_data_groups_async(file: FileAbstraction, retrieve_custom_name=False) -> list: 933 """ 934 List all data groups in the brim file. The list is ordered by index. 935 936 Returns: 937 list: A list of dictionaries, each containing: 938 - 'name' (str): The name of the data group in the file. 939 - 'index' (int): The index extracted from the group name. 940 - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the data group as returned from utils.get_object_name. 941 """ 942 943 data_groups = [] 944 945 matched_objs = await list_objects_matching_pattern_async( 946 file, brim_obj_names.Brillouin_base_path, brim_obj_names.data.base_group + r"_(\d+)$") 947 948 async def _make_dict_item(matched_obj, retrieve_custom_name): 949 name = matched_obj[0] 950 index = int(matched_obj[1]) 951 curr_obj_dict = {'name': name, 'index': index} 952 if retrieve_custom_name: 953 path = concatenate_paths( 954 brim_obj_names.Brillouin_base_path, name) 955 custom_name = await get_object_name(file, path) 956 curr_obj_dict['custom_name'] = custom_name 957 return curr_obj_dict 958 959 coros = [_make_dict_item(matched_obj, retrieve_custom_name) for matched_obj in matched_objs] 960 dicts = await asyncio.gather(*coros) 961 for dict_item in dicts: 962 data_groups.append(dict_item) 963 # Sort the data groups by index 964 data_groups.sort(key=lambda x: x['index']) 965 966 return data_groups 967 968 @staticmethod 969 async def _get_existing_group_name_async(file: FileAbstraction, index: int) -> str: 970 """ 971 Get the name of an existing data group by index. 972 973 Args: 974 file (File): The parent File object. 975 index (int): The index of the data group. 976 977 Returns: 978 str: The name of the data group, or None if not found. 979 """ 980 group_name: str = None 981 data_groups = await Data.list_data_groups_async(file) 982 for dg in data_groups: 983 if dg['index'] == index: 984 group_name = dg['name'] 985 break 986 return group_name 987 988 @classmethod 989 async def from_existing_async(cls, file: FileAbstraction, index: int) -> 'Data': 990 """ 991 Create a Data object from an existing data group in the file. 992 Args: 993 file (File): The parent File object. 994 index (int): The index of the existing data group. 995 Returns: 996 Data: A Data object corresponding to the existing data group. 997 Raises: 998 IndexError: If no data group with the specified index is found in the file. 999 """ 1000 group_name: str = await cls._get_existing_group_name_async(file, index) 1001 if group_name is None: 1002 raise IndexError(f"No data group with index {index} found in the file") 1003 dg = cls(file, concatenate_paths(brim_obj_names.Brillouin_base_path, group_name), _initialize=False) 1004 await dg._init_async() 1005 return dg 1006 1007 @classmethod 1008 def _create_new(cls, file: FileAbstraction, index: int, sparse: bool = False, name: str = None) -> 'Data': 1009 """ 1010 Create a new data group with the specified index. 1011 1012 Args: 1013 file (File): The parent File object. 1014 index (int): The index for the new data group. 1015 sparse (bool): Whether the data is sparse. See https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md for details. Defaults to False. 1016 name (str, optional): The name for the new data group. Defaults to None. 1017 1018 Returns: 1019 Data: The newly created Data object. 1020 """ 1021 group_name = Data._generate_group_name(index) 1022 group = sync(file.create_group(concatenate_paths( 1023 brim_obj_names.Brillouin_base_path, group_name))) 1024 sync(file.create_attr(group, 'Sparse', sparse)) 1025 if name is not None: 1026 set_object_name(file, group, name) 1027 return cls(file, concatenate_paths(brim_obj_names.Brillouin_base_path, group_name), newly_created=True) 1028 1029 @staticmethod 1030 def _generate_group_name(index: int, n_digits: int = None) -> str: 1031 """ 1032 Generate a name for a data group based on the index. 1033 1034 Args: 1035 index (int): The index for the data group. 1036 n_digits (int, optional): The number of digits to pad the index with. If None no padding is applied. Defaults to None. 1037 1038 Returns: 1039 str: The generated group name. 1040 1041 Raises: 1042 ValueError: If the index is negative. 1043 """ 1044 if index < 0: 1045 raise ValueError("index must be positive") 1046 num = str(index) 1047 if n_digits is not None: 1048 num = num.zfill(n_digits) 1049 return f"{brim_obj_names.data.base_group}_{num}"
30class Data: 31 """ 32 Represents a data group within the brim file. 33 """ 34 # make AnalysisResults available as an attribute of Data 35 AnalysisResults = AnalysisResults 36 37 def __init__(self, file: FileAbstraction, path: str, *, 38 newly_created: bool = False, _initialize: bool = True): 39 """ 40 Initialize the Data object. This constructor should not be called directly. 41 42 Args: 43 file (File): The parent File object. 44 path (str): The path to the data group within the file. 45 newly_created (bool): Whether this data group is being created as new. 46 If True, the constructor will not attempt to load spatial mapping. 47 _initialize (bool): FOR INTERNAL USE ONLY. Whether to automatically initialize the current data group. 48 Set to False if you want to initialize them manually later using the _init_async() method. Default is True. 49 """ 50 self._file = file 51 self._path = path 52 53 54 if _initialize: 55 sync(self._init_async(newly_created=newly_created)) 56 57 async def _init_async(self, newly_created: bool = False) -> None: 58 """ 59 See __init__() for the description of the arguments. 60 """ 61 self._group = await self._file.open_group(self._path) 62 63 self._sparse = await self._load_sparse_flag_async() 64 # the _spatial_map is None for non sparse data but the _spatial_map_px_size should always be valid 65 self._spatial_map, self._spatial_map_px_size = await self._load_spatial_mapping_async() if not newly_created else (None, None) 66 67 def get_name(self): 68 """ 69 Returns the name of the data group. 70 """ 71 return sync(get_object_name(self._file, self._path)) 72 73 def get_index(self): 74 """ 75 Returns the index of the data group. 76 """ 77 return int(self._path.split('/')[-1].split('_')[-1]) 78 79 async def _load_sparse_flag_async(self) -> bool: 80 """ 81 Load the 'Sparse' flag for the data group. 82 83 Returns: 84 bool: The value of the 'Sparse' flag, or False if the attribute is not found or invalid. 85 """ 86 try: 87 sparse = await self._file.get_attr(self._group, 'Sparse') 88 if isinstance(sparse, bool): 89 return sparse 90 else: 91 warnings.warn( 92 f"Invalid value for 'Sparse' attribute in {self._path}. Expected a boolean, got {type(sparse)}. Defaulting to False.") 93 return False 94 except Exception: 95 # if the attribute is not found, return the default value False 96 return False 97 98 async def _load_spatial_mapping_async(self, load_in_memory: bool=True) -> tuple: 99 """ 100 Load a spatial mapping in the same format as 'Cartesian visualisation', 101 irrespectively on whether 'Spatial_map' is defined instead. 102 -1 is used for "empty" pixels in the image 103 Args: 104 load_in_memory (bool): Specify whether the map should be forced to load in memory or just opened as a dataset. 105 Returns: 106 The spatial map and the corresponding pixel size as a tuple of 3 Metadata.Item, both in the order z, y, x. 107 If the spatial mapping is not defined in the file, returns None for the spatial map. 108 The pixel size is read from the data group for non-sparse data. 109 """ 110 cv = None 111 px_size = 3*(Metadata.Item(value=1, units=None),) 112 113 cv_path = concatenate_paths( 114 self._path, brim_obj_names.data.cartesian_visualisation) 115 sm_path = concatenate_paths( 116 self._path, brim_obj_names.data.spatial_map) 117 118 if await self._file.object_exists(cv_path): 119 cv = await self._file.open_dataset(cv_path) 120 121 #read the pixel size from the 'Cartesian visualisation' dataset 122 px_size_val = None 123 px_size_units = None 124 try: 125 px_size_val = await self._file.get_attr(cv, 'element_size') 126 if px_size_val is None or len(px_size_val) != 3: 127 raise ValueError( 128 "The 'element_size' attribute of 'Cartesian_visualisation' must be a tuple of 3 elements") 129 except Exception: 130 px_size_val = 3*(1,) 131 warnings.warn( 132 "No pixel size defined for Cartesian visualisation") 133 px_size_units = await units.of_attribute( 134 self._file, cv, 'element_size') 135 px_size = () 136 for i in range(3): 137 # if px_size_val[i] is not a number, set it to 1 and px_size_units to None 138 if isinstance(px_size_val[i], Number): 139 px_size += (Metadata.Item(px_size_val[i], px_size_units), ) 140 else: 141 px_size += (Metadata.Item(1, None), ) 142 143 144 if load_in_memory: 145 cv = await cv.to_np_array() # load the spatial map in memory as a numpy array 146 cv = np_array_to_smallest_int_type(cv) 147 148 elif await self._file.object_exists(sm_path): 149 async def load_spatial_map_from_file(): 150 async def load_coordinate_from_sm(coord: str): 151 res = np.empty(0) # empty array 152 try: 153 res = await self._file.open_dataset( 154 concatenate_paths(sm_path, coord)) 155 res = await res.to_np_array() 156 res = np.squeeze(res) # remove single-dimensional entries 157 except Exception as e: 158 # if the coordinate does not exist, return an empty array 159 pass 160 if len(res.shape) > 1: 161 raise ValueError( 162 f"The 'Spatial_map/{coord}' dataset is not a 1D array as expected") 163 return res 164 165 def check_coord_array(arr, size): 166 if arr.size == 0: 167 return np.zeros(size) 168 elif arr.size != size: 169 raise ValueError( 170 "The 'Spatial_map' dataset is invalid") 171 return arr 172 173 x, y, z = await asyncio.gather( 174 load_coordinate_from_sm('x'), 175 load_coordinate_from_sm('y'), 176 load_coordinate_from_sm('z') 177 ) 178 size = max([x.size, y.size, z.size]) 179 if size == 0: 180 raise ValueError("The 'Spatial_map' dataset is empty") 181 x = check_coord_array(x, size) 182 y = check_coord_array(y, size) 183 z = check_coord_array(z, size) 184 return x, y, z 185 186 def calculate_step(x): 187 n = len(np.unique(x)) 188 if n == 1: 189 d = None 190 else: 191 d = (np.max(x)-np.min(x))/(n-1) 192 return n, d 193 194 x, y, z = await load_spatial_map_from_file() 195 196 # TODO extend the reconstruction to non-cartesian cases 197 198 nX, dX = calculate_step(x) 199 nY, dY = calculate_step(y) 200 nZ, dZ = calculate_step(z) 201 202 indices = np_array_to_smallest_int_type(np.lexsort((x, y, z))) 203 cv = np.reshape(indices, (nZ, nY, nX)) 204 205 px_size_units = await units.of_object(self._file, sm_path) 206 px_size = () 207 for i in range(3): 208 px_sz = (dZ, dY, dX)[i] 209 px_unit = px_size_units 210 if px_sz is None: 211 px_sz = 1 212 px_unit = None 213 px_size += (Metadata.Item(px_sz, px_unit),) 214 elif not self._sparse: 215 try: 216 px_sz = await self._file.get_attr(self._group, 'element_size') 217 if len(px_sz) != 3: 218 raise ValueError( 219 "The 'element_size' attribute must be a tuple of 3 elements") 220 px_unit = None 221 try: 222 px_unit = await units.of_attribute(self._file, self._group, 'element_size') 223 except Exception: 224 warnings.warn("Pixel size unit is not provided for non-sparse data.") 225 px_size = tuple(Metadata.Item(el, px_unit) for el in px_sz) 226 except Exception: 227 warnings.warn("Pixel size is not provided for non-sparse data.") 228 229 return cv, px_size 230 231 def _get_spatial_index_from_coor(self, coor: tuple) -> tuple: 232 """ 233 Retrieve the spatial index for a given spatial coordinate. 234 235 Args: 236 coor (tuple): Spatial coordinate as ``(z, y, x)``. 237 Raises: 238 ValueError: If `coor` does not contain three coordinates 239 Returns: 240 tuple: The spatial index corresponding to the given coordinate. 241 It is always a tuple containing 1 or 3 integers, depending on whether the data is sparse or not. 242 """ 243 if len(coor) != 3: 244 raise ValueError("coor must contain 3 values for z, y, x") 245 index = coor 246 if self._sparse: 247 index = (int(self._spatial_map[coor]),) 248 return index 249 250 def get_PSD(self) -> tuple: 251 """ 252 LOW LEVEL FUNCTION 253 254 Retrieve the Power Spectral Density (PSD) and frequency from the current data group. 255 Note: this function exposes the internals of the brim file and thus the interface might change in future versions. 256 Use only if more specialized functions are not working for your application! 257 Returns: 258 tuple: (PSD, frequency, PSD_units, frequency_units) 259 - PSD: A 2D (or more) numpy array containing all the spectra (see [specs](https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md) for more details). 260 - frequency: A numpy array representing the frequency data (see [specs](https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md) for more details). 261 - PSD_units: The units of the PSD. 262 - frequency_units: The units of the frequency. 263 """ 264 warnings.warn( 265 "Data.get_PSD is deprecated and will be removed in a future release. " 266 "Use Data.get_PSD_as_spatial_map instead.", 267 DeprecationWarning, 268 stacklevel=2, 269 ) 270 PSD, frequency = _gather_sync( 271 self._file.open_dataset(concatenate_paths( 272 self._path, brim_obj_names.data.PSD)), 273 self._file.open_dataset(concatenate_paths( 274 self._path, brim_obj_names.data.frequency)) 275 ) 276 # retrieve the units of the PSD and frequency 277 PSD_units, frequency_units = _gather_sync( 278 units.of_object(self._file, PSD), 279 units.of_object(self._file, frequency) 280 ) 281 282 return PSD, frequency, PSD_units, frequency_units 283 284 @staticmethod 285 def interpolate_spectra(PSD: np.ndarray, frequency: np.ndarray, *, 286 new_frequency: np.ndarray | None = None 287 ) -> tuple[np.ndarray, np.ndarray]: 288 """Interpolate spectra along their final axis. 289 290 Each spectrum is interpolated from its corresponding values in 291 ``frequency`` onto ``new_frequency``. Both frequency arrays must be 292 broadcastable to ``PSD.shape``; for example, a 1D array can be shared 293 across all spectra. The final axis contains the frequency samples. 294 295 If ``new_frequency`` is omitted and ``frequency`` is multidimensional, 296 a shared 1D frequency array is generated by averaging ``frequency`` 297 across all dimensions except its final (sample) axis. If the input 298 frequency is 1D, the original ``PSD`` and ``frequency`` are returned 299 unchanged. 300 301 Values outside a spectrum's frequency range use ``numpy.interp``'s 302 endpoint behavior. 303 304 Args: 305 PSD: Spectral values, with samples along the final axis. 306 frequency: Frequencies corresponding to ``PSD``. Must contain only finite values. 307 new_frequency (optional): Target frequencies, finite and broadcastable to 308 ``PSD.shape``. May be 1D or have additional broadcastable 309 dimensions. If omitted, a new frequency array is generated. 310 311 Returns: 312 A tuple of the spectra and the target frequencies. The spectra 313 retain the original ``PSD`` dtype when no interpolation is done; 314 otherwise, they have dtype ``float64``. When ``new_frequency`` is 315 supplied, it is returned in its original shape; when generated, 316 the returned array is 1D. 317 318 Raises: 319 ValueError: If frequencies are non-finite, or either frequency array 320 cannot be broadcast as required. 321 """ 322 323 # the frequency is already the same for all spectra and no new frequency is provided, 324 # so we can just return the original PSD 325 if new_frequency is None and frequency.ndim == 1: 326 return PSD, frequency 327 328 # check the frequency array 329 if not np.all(np.isfinite(frequency)): 330 raise ValueError("The frequency array must contain only finite values for interpolation.") 331 try: 332 frequency = np.broadcast_to(frequency, PSD.shape) 333 except ValueError as e: 334 raise ValueError("`frequency` must be broadcastable to the shape of PSD.") from e 335 if not np.all(np.diff(frequency, axis=-1) >= 0): 336 # the array is not increasing along the last axis, we need to sort it and the PSD accordingly 337 sort_indices = np.argsort(frequency, axis=-1) 338 frequency = np.take_along_axis(frequency, sort_indices, axis=-1) 339 PSD = np.take_along_axis(PSD, sort_indices, axis=-1) 340 # check or generate the new frequency array 341 if new_frequency is None: 342 # if the user does not provide a new frequency array, we will create a new frequency array that 343 # is the mean of the original frequency array along all dimensions except the last one 344 new_frequency = np.mean(frequency, axis=tuple(range(frequency.ndim - 1))) 345 else: 346 if new_frequency.ndim > PSD.ndim: 347 raise ValueError("`new_frequency` must have less or equal number of dimensions than PSD") 348 if not np.all(np.isfinite(new_frequency)): 349 raise ValueError("`new_frequency` must contain only finite values.") 350 try: 351 np.broadcast_shapes(new_frequency.shape, PSD.shape) 352 except Exception as e: 353 raise ValueError("`new_frequency` must have the same number of dimensions as PSD or be 1D.") from e 354 355 # Interpolate each spectrum in the PSD along the last axis 356 interpolated_PSD = np.empty_like(PSD, dtype=np.float64) 357 interp_freq = np.broadcast_to(new_frequency, PSD.shape) 358 for idx in itertools.product(*[range(s) for s in PSD.shape[:-1]]): 359 interpolated_PSD[idx] = np.interp(interp_freq[idx], frequency[idx], PSD[idx]) 360 return interpolated_PSD, new_frequency 361 362 def get_PSD_as_spatial_map(self, *, broadcast_frequency: bool = True) -> tuple: 363 """ 364 Retrieve the Power Spectral Density (PSD) as a spatial map and the frequency from the current data group. 365 Arguments: 366 broadcast_frequency (bool): Whether to broadcast the frequency array to match the shape of the PSD if they have different shapes. 367 This is useful when the frequency is the same for all spectra and thus stored as a 1D array, while the PSD has a spatial dimension. 368 If False, the function will return the frequency with the same shape as it is stored in the file (which could be any shape broadcastable to PSD); 369 consider using `Data.interpolate_spectra` to interpolate the PSD to a new (1D) frequency array if needed. 370 Returns: 371 tuple: (PSD, frequency, PSD_units, frequency_units) 372 - PSD: A 4D (or more) numpy array containing all the spectra. Dimensions are z, y, x, [parameters], spectrum. 373 - frequency: A numpy array representing the frequency data, which has the same shape as PSD or a 1D array (see `broadcast_frequency`). 374 - PSD_units: The units of the PSD. 375 - frequency_units: The units of the frequency. 376 """ 377 PSD, frequency = _gather_sync( 378 self._file.open_dataset(concatenate_paths( 379 self._path, brim_obj_names.data.PSD)), 380 self._file.open_dataset(concatenate_paths( 381 self._path, brim_obj_names.data.frequency)) 382 ) 383 # retrieve the units of the PSD and frequency 384 PSD_units, frequency_units = _gather_sync( 385 units.of_object(self._file, PSD), 386 units.of_object(self._file, frequency) 387 ) 388 389 # ensure PSD and frequency are numpy arrays 390 PSD = np.array(PSD) 391 frequency = np.array(frequency) # ensure it's a numpy array 392 393 # if the frequency is not the same for all spectra, broadcast it to match the shape of PSD 394 # if it is the same for all spectra, broadcast_frequency determines whether to return it as a 1D array or broadcast it to match the shape of PSD 395 if frequency.ndim > 1 or (broadcast_frequency and frequency.shape != PSD.shape): 396 frequency = np.broadcast_to(frequency, PSD.shape) 397 398 if self._sparse: 399 if self._spatial_map is None: 400 raise ValueError("The data is defined as sparse, but no spatial mapping is provided.") 401 sm = np.array(self._spatial_map) 402 # reshape the PSD and frequency to have the spatial dimensions first 403 PSD = PSD[sm, ...] 404 # reshape the frequency only if it is not the same for all spectra 405 if frequency.ndim > 1: 406 frequency = frequency[sm, ...] 407 408 return PSD, frequency, PSD_units, frequency_units 409 410 def _get_spectrum(self, index: int | tuple[int, int, int]) -> tuple: 411 """ 412 Synchronous wrapper for `_get_spectrum_async`. 413 """ 414 return sync(self._get_spectrum_async(index)) 415 async def _get_spectrum_async(self, index: int | tuple[int, int, int]) -> tuple: 416 """ 417 @public 418 419 Retrieve a spectrum from the data group by its index or coordinates. 420 421 Args: 422 index (int | tuple[int, int, int]): The index (for sparse data) or z, y, x coordinates (for non-sparse data) of the spectrum to retrieve. 423 424 Returns: 425 tuple: (PSD, frequency, PSD_units, frequency_units) for the specified index. 426 PSD can be 1D or more (if there are additional parameters); 427 frequency has the same size as PSD 428 Raises: 429 IndexError: If the index is out of range for the PSD dataset. 430 """ 431 if self._sparse and not isinstance(index, int): 432 raise ValueError("For sparse data, index must be an integer.") 433 elif not self._sparse and not (isinstance(index, tuple) and len(index) == 3): 434 raise ValueError("For non-sparse data, index must be a tuple of (z, y, x) coordinates.") 435 436 # index = -1 corresponds to no spectrum 437 if self._sparse and index < 0: 438 return None, None, None, None 439 elif not self._sparse and any(i < 0 for i in index): 440 return None, None, None, None 441 PSD, frequency = await asyncio.gather( 442 self._file.open_dataset(concatenate_paths( 443 self._path, brim_obj_names.data.PSD)), 444 self._file.open_dataset(concatenate_paths( 445 self._path, brim_obj_names.data.frequency)) 446 ) 447 if self._sparse and index >= PSD.shape[0]: 448 raise IndexError( 449 f"index {index} out of range for PSD with shape {PSD.shape}") 450 elif not self._sparse and any(i >= PSD.shape[j] for j, i in enumerate(index)): 451 raise IndexError( 452 f"index {index} out of range for PSD with shape {PSD.shape}") 453 # retrieve the units of the PSD and frequency 454 PSD_units, frequency_units = await asyncio.gather( 455 units.of_object(self._file, PSD), 456 units.of_object(self._file, frequency) 457 ) 458 # add ellipsis to the index to select the spectrum and the corresponding frequency 459 if self._sparse: 460 index = (index, ...) 461 else: 462 index = index + (..., ) 463 # map index to the frequency array, considering the broadcasting rules 464 index_frequency = index 465 if frequency.ndim < PSD.ndim: 466 if self._sparse: 467 # given the definition of the brim file format, 468 # if the frequency has less dimensions that PSD, 469 # it can only be because it is the same for all the spatial position (first dimension) 470 index_frequency = (..., ) 471 else: 472 unassigned_indices = PSD.ndim - frequency.ndim 473 if unassigned_indices == 3: 474 # if the frequency has no spatial dimension, it is the same for all the spatial positions 475 index_frequency = (..., ) 476 else: 477 # if the frequency has some spatial dimensions but not all, we need to add the corresponding indices to the index of the frequency 478 index_frequency = index[-unassigned_indices:] + (..., ) 479 #get the spectrum and the corresponding frequency at the specified index 480 PSD, frequency = await asyncio.gather( 481 _async_getitem(PSD, index), 482 _async_getitem(frequency, index_frequency) 483 ) 484 #broadcast the frequency to match the shape of PSD if needed 485 if frequency.ndim < PSD.ndim: 486 frequency = np.broadcast_to(frequency, PSD.shape) 487 return PSD, frequency, PSD_units, frequency_units 488 489 def get_spectrum_in_image(self, coor: tuple) -> tuple: 490 """ 491 Retrieve a spectrum from the data group using spatial coordinates. 492 493 Args: 494 coor (tuple): A tuple containing the z, y, x coordinates of the spectrum to retrieve. 495 496 Returns: 497 tuple: A tuple containing the PSD, frequency, PSD_units, and 498 frequency_units for the specified coordinates. See 499 `brimfile.data.Data._get_spectrum_async` for details. 500 501 Raises: 502 ValueError: If `coor` does not contain three coordinates `(z, y, x)`. 503 IndexError: If coordinates map outside the available data. 504 """ 505 if len(coor) != 3: 506 raise ValueError("coor must contain 3 values for z, y, x") 507 508 if self._sparse: 509 index = int(self._spatial_map[coor]) 510 return self._get_spectrum(index) 511 else: 512 return self._get_spectrum(coor) 513 514 async def get_spectrum_and_all_quantities_in_image_async(self, ar: 'Data.AnalysisResults', coor: tuple, index_peak: int = 0) -> tuple[tuple, dict]: 515 """ 516 Retrieve the spectrum and all available quantities from the analysis results at a specific spatial coordinate. 517 518 Args: 519 ar (Data.AnalysisResults): The analysis results object to retrieve quantities from. 520 coor (tuple): A tuple containing the z, y, x coordinates in the image. 521 index_peak (int, optional): The index of the peak to retrieve (for multi-peak fits). Defaults to 0. 522 523 Returns: 524 tuple: A tuple containing: 525 - spectrum (tuple): (PSD, frequency, PSD_units, frequency_units) at the specified coordinate 526 - quantities (dict): Dictionary of Metadata.Item in the form result[quantity.name][peak.name] 527 """ 528 if len(coor) != 3: 529 raise ValueError("coor must contain 3 values for z, y, x") 530 index = coor 531 if self._sparse: 532 index = int(self._spatial_map[coor]) 533 spectrum, quantities = await asyncio.gather( 534 self._get_spectrum_async(index), 535 ar._get_all_quantities_at_index(index, index_peak) 536 ) 537 return spectrum, quantities 538 def get_spectrum_and_all_quantities_in_image(self, ar: 'Data.AnalysisResults', coor: tuple, index_peak: int = 0) -> tuple[tuple, dict]: 539 """ 540 Synchronous wrapper for `get_spectrum_and_all_quantities_in_image_async` (see doc for `brimfile.data.Data.get_spectrum_and_all_quantities_in_image_async`) 541 """ 542 return sync(self.get_spectrum_and_all_quantities_in_image_async(ar, coor, index_peak)) 543 544 def get_metadata(self): 545 """ 546 Returns the metadata associated with the current Data group 547 Note that this contains both the general metadata stored in the file (which might be redifined by the specific data group) 548 and the ones specific for this data group 549 """ 550 return Metadata(self._file, self._path) 551 552 def get_num_parameters(self) -> tuple: 553 """ 554 Retrieves the number of parameters 555 556 Returns: 557 tuple: The shape of the parameters if they exist, otherwise an empty tuple. 558 """ 559 pars, _ = self.get_parameters() 560 return pars.shape if pars is not None else () 561 562 def get_parameters(self) -> list: 563 """ 564 Retrieves the parameters and their associated names. 565 566 If PSD.ndims > 2, the parameters are stored in a separate dataset. 567 568 Returns: 569 list: A tuple containing the parameters and their names if there are any, otherwise None. 570 """ 571 pars_full_path = concatenate_paths( 572 self._path, brim_obj_names.data.parameters) 573 if sync(self._file.object_exists(pars_full_path)): 574 pars = sync(self._file.open_dataset(pars_full_path)) 575 pars_names = sync(self._file.get_attr(pars, 'Name')) 576 return (pars, pars_names) 577 return (None, None) 578 579 def create_calibration_group(self, *, index: NDArray[np.integer] | None = None, calibration_data: list[dict[str, Any]] | None = None, 580 same_as: int | None = None, attributes: dict[str, MetadataItem] = None, 581 compression: FileAbstraction.Compression = FileAbstraction.Compression()) -> Calibration: 582 """ 583 Create a new calibration group in the current data group. 584 For more details on the expected format of the calibration data, see https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md. 585 586 Parameters: 587 index (np.array | None, optional): Index array for the calibration spectra. For sparse data, 588 this must be 1D; for non-sparse data, this must be 3D. 589 It can be omitted if each element in `calibration_data` contains only one spectrum. 590 calibration_data (list[dict[str, Any]] | None, optional): Calibration entries to store. 591 Each dictionary must contain `spectra` and `shift` keys, and may provide `shift_units`. 592 same_as (int | None, optional): If provided, links this calibration group to an existing 593 calibration via the `Same_as` attribute. When set, the other data arguments are ignored. 594 Defaults to None. 595 attributes (dict[str, MetadataItem], optional): Additional attributes to attach to the calibration group. 596 Can be one of ('Datetime', 'Description', 'Temperature', 'FSR') with the relative units (when relevant). 597 compression (FileAbstraction.Compression, optional): Compression settings used for created 598 datasets. Defaults to FileAbstraction.Compression(). 599 600 Returns: 601 Calibration: The newly created calibration group. 602 603 Raises: 604 ValueError: If the provided calibration data or index is invalid or inconsistent. 605 """ 606 calibration_path = concatenate_paths(self._path, brim_obj_names.data.calibration) 607 calibration_group = sync(self._file.create_group(calibration_path)) 608 609 # if same_as is provided, create the 'Same_as' attribute to link the calibration group to an existing one 610 if same_as is not None: 611 sync(self._file.create_attr(calibration_group, 'Same_as', same_as)) 612 else: # if same_as is provided, the other parameters are ignored 613 # check that calibration_data is provided and valid 614 if calibration_data is None: 615 raise ValueError("'calibration_data' is required when 'same_as' is not provided") 616 if not isinstance(calibration_data, (list, tuple)): 617 calibration_data = [calibration_data,] 618 # check that index is valid if provided 619 if index is not None: 620 # TODO: check of the shape of 'index' is compatible with PSD 621 if self._sparse and index.ndim != 1: 622 raise ValueError("'index' must be a 1D array for sparse data") 623 if not self._sparse and index.ndim != 3: 624 raise ValueError("'index' must be a 3D array for non-sparse data") 625 626 for m, calib in enumerate(calibration_data): 627 # check that each element in calibration_data is a dictionary containing 'spectra' and 'shift' keys 628 if not isinstance(calib, dict): 629 raise ValueError("Each element in 'calibration_data' must be a dictionary") 630 if 'spectra' not in calib.keys() or 'shift' not in calib.keys(): 631 raise ValueError("Each calibration data dictionary must contain 'spectra' and 'shift' keys") 632 # retrieve the spectra, shift and shift_units from the calibration data and check that they are valid 633 cal_spectra = np.array(calib['spectra']) 634 if cal_spectra.ndim != 2: 635 raise ValueError("'spectra' in calibration data must be a 2D array. If only one spectrum is provided, set the first dimension to 1.") 636 cal_shift = calib['shift'] 637 cal_shift_units = calib.get('shift_units', None) 638 if cal_shift_units is None: 639 cal_shift_units = 'GHz' 640 warnings.warn("No units provided for 'shift' in calibration data, defaulting to GHz") 641 # check that index is compatible with the shape of the spectra 642 if index is None and cal_spectra.shape[0] != 1: 643 raise ValueError("If 'index' is not provided, each element in 'calibration_data' must contain only one spectrum (i.e. have shape (1, n))") 644 if index is not None and np.max(index) >= cal_spectra.shape[0]: 645 raise ValueError("If 'index' is provided, its maximum value must be less than the number of spectra in each calibration data element") 646 # add the m arrays together with their attributes to the file 647 spectra_dataset = sync(self._file.create_dataset(calibration_group, f'{m}', cal_spectra, chunk_size=_determine_chunk_size(cal_spectra), compression=compression)) 648 sync(self._file.create_attr(spectra_dataset, 'Shift', cal_shift)) 649 units.add_to_attribute(self._file, spectra_dataset, 'Shift', cal_shift_units) 650 # add the index array to the file 651 if index is not None: 652 sync(self._file.create_dataset(calibration_group, 'Index', index, compression=compression)) 653 654 from .calibration import _STANDARD_ATTRIBUTES 655 # add any additional attributes to the calibration group, checking that they do not overwrite the standard 656 if attributes is not None: 657 for key, value in attributes.items(): 658 if key not in _STANDARD_ATTRIBUTES: 659 warnings.warn(f"Attribute '{key}' is not a standard attribute for calibration groups.\ 660 Standard attributes are: {', '.join(_STANDARD_ATTRIBUTES)}. \ 661 Make sure this is intentional!") 662 if not isinstance(value, MetadataItem): 663 value = MetadataItem(value) 664 sync(self._file.create_attr(calibration_group, key, value.value)) 665 if value.units is not None: 666 units.add_to_attribute(self._file, calibration_group, key, value.units) 667 668 return Calibration(self._file, calibration_path, data_group=self) 669 670 def get_calibration(self) -> Calibration: 671 """ 672 Synchronous wrapper for `get_calibration_async` (see doc for `brimfile.data.Data.get_calibration_async`) 673 """ 674 return sync(self.get_calibration_async()) 675 676 async def get_calibration_async(self) -> Calibration: 677 """ 678 Retrieve the calibration group associated with the current data group. 679 680 Returns: 681 Calibration: The calibration group associated with the current data group. 682 683 Raises: 684 ValueError: If no calibration group is found in the current data group or the referenced calibration group does not exist. 685 """ 686 calibration_path = concatenate_paths(self._path, brim_obj_names.data.calibration) 687 if not await self._file.object_exists(calibration_path): 688 raise ValueError(f"No calibration group found in {self._path}") 689 same_as = None 690 try: 691 same_as = await self._file.get_attr(calibration_path, 'Same_as') 692 except Exception: 693 pass # same_as attribute is optional, if it does not exist we just ignore it 694 # if the 'Same_as' attribute exists, find the calibration group with the corresponding index 695 if same_as is not None: 696 try: 697 d_m = await Data.from_existing_async(self._file, same_as) 698 return await d_m.get_calibration_async() 699 except IndexError: 700 raise ValueError(f"Calibration group in {self._path} references non-existing calibration index {same_as} in the file") 701 cal_group = Calibration(self._file, calibration_path, data_group=self, _initialize=False) 702 await cal_group._init_async() 703 return cal_group 704 705 def create_analysis_results_group(self, data_AntiStokes, data_Stokes=None, *, 706 index: int = None, name: str = None, fit_model: 'Data.AnalysisResults.FitModel' = None) -> AnalysisResults: 707 """ 708 Adds a new AnalysisResults entry to the current data group. 709 Parameters: 710 data_AntiStokes (dict or list[dict]): see documentation for `brimfile.analysis_results.AnalysisResults.add_data` 711 data_Stokes (dict or list[dict]): same as data_AntiStokes for the Stokes peaks. 712 index (int, optional): The index for the new data entry. If None, the next available index is used. Defaults to None. 713 name (str, optional): The name for the new Analysis group. Defaults to None. 714 fit_model (Data.AnalysisResults.FitModel, optional): The fit model used for the analysis. Defaults to None (no attribute is set). 715 Returns: 716 AnalysisResults: The newly created AnalysisResults object. 717 Raises: 718 IndexError: If the specified index already exists in the dataset. 719 ValueError: If any of the data provided is not valid or consistent 720 """ 721 if index is not None: 722 try: 723 self.get_analysis_results(index) 724 except IndexError: 725 pass 726 else: 727 # If the group already exists, raise an error 728 raise IndexError( 729 f"Analysis {index} already exists in {self._path}") 730 else: 731 ar_groups = self.list_AnalysisResults() 732 indices = [ar['index'] for ar in ar_groups] 733 indices.sort() 734 index = indices[-1] + 1 if indices else 0 # Next available index 735 736 ar = Data.AnalysisResults._create_new(self, index=index, sparse=self._sparse) 737 if name is not None: 738 set_object_name(self._file, ar._path, name) 739 ar.add_data(data_AntiStokes, data_Stokes, fit_model=fit_model) 740 741 return ar 742 743 def list_AnalysisResults(self, retrieve_custom_name=False) -> list: 744 """ 745 List all AnalysisResults groups in the current data group. The list is ordered by index. 746 747 Returns: 748 list: A list of dictionaries, each containing: 749 - 'name' (str): The name of the AnalysisResults group. 750 - 'index' (int): The index extracted from the group name. 751 - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the AnalysisResults group as returned from utils.get_object_name. 752 """ 753 754 analysis_results_groups = [] 755 756 matched_objs = sync(list_objects_matching_pattern_async( 757 self._file, self._group, brim_obj_names.data.analysis_results + r"_(\d+)$")) 758 async def _make_dict_item(matched_obj, retrieve_custom_name): 759 name = matched_obj[0] 760 index = int(matched_obj[1]) 761 curr_obj_dict = {'name': name, 'index': index} 762 if retrieve_custom_name: 763 ar_path = concatenate_paths(self._path, name) 764 custom_name = await get_object_name(self._file, ar_path) 765 curr_obj_dict['custom_name'] = custom_name 766 return curr_obj_dict 767 coros = [_make_dict_item(matched_obj, retrieve_custom_name) for matched_obj in matched_objs] 768 dicts = _gather_sync(*coros) 769 for dict_item in dicts: 770 analysis_results_groups.append(dict_item) 771 # Sort the data groups by index 772 analysis_results_groups.sort(key=lambda x: x['index']) 773 774 return analysis_results_groups 775 776 def get_analysis_results(self, index: int = 0) -> AnalysisResults: 777 """ 778 Returns the AnalysisResults at the specified index 779 780 Args: 781 index (int) 782 783 Raises: 784 IndexError: If there is no analysis with the corresponding index 785 """ 786 name = None 787 ls = self.list_AnalysisResults() 788 for el in ls: 789 if el['index'] == index: 790 name = el['name'] 791 break 792 if name is None: 793 raise IndexError(f"Analysis {index} not found") 794 path = concatenate_paths(self._path, name) 795 return Data.AnalysisResults(self._file, path, data_group_path=self._path, 796 spatial_map=self._spatial_map, spatial_map_px_size=self._spatial_map_px_size, sparse=self._sparse) 797 798 def _add_data(self, PSD: np.ndarray, frequency: np.ndarray, *, scanning: dict = None, freq_units='GHz', 799 compression: FileAbstraction.Compression = FileAbstraction.Compression()): 800 """ 801 @public 802 803 Add data to the current data group. 804 805 This method adds the provided PSD, frequency, and scanning data to the HDF5 group 806 associated with this `Data` object. It validates the inputs to ensure they meet 807 the required specifications before adding them. 808 809 Args: 810 PSD (np.ndarray): A 2D numpy array representing the Power Spectral Density (PSD) data. The last dimension contains the spectra. 811 frequency (np.ndarray): A 1D or 2D numpy array representing the frequency data. 812 It must be broadcastable to the shape of the PSD array. 813 scanning (dict, optional): A dictionary containing scanning-related data. 814 Required for sparse data (sparse=True), optional for non-sparse data. 815 For sparse data, must include at least one of 'Spatial_map' or 'Cartesian_visualisation'. 816 It may include the following keys: 817 - 'Spatial_map' (optional): A dictionary containing coordinate arrays: 818 - 'x', 'y', 'z' (optional): 1D numpy arrays of same length with coordinate values 819 - 'units' (optional): string with the unit (e.g., 'um') 820 - 'Cartesian_visualisation' (optional): A 3D numpy array (z, y, x) with integer values 821 mapping spatial positions to spectra indices. Values must be -1 (invalid/empty pixel) 822 or between 0 and PSD.shape[0]-1. 823 - 'Cartesian_visualisation_pixel' (recommended with Cartesian_visualisation): 824 Tuple/list of 3 float values (z, y, x) representing pixel size. Unused dimensions can be None. 825 - 'Cartesian_visualisation_pixel_unit' (optional): String for pixel size unit (default: 'um'). 826 827 Raises: 828 ValueError: If any of the data provided is not valid or consistent 829 """ 830 831 # Check if frequency is broadcastable to PSD 832 try: 833 np.broadcast_shapes(tuple(frequency.shape), tuple(PSD.shape)) 834 except ValueError as e: 835 raise ValueError(f"frequency (shape: {frequency.shape}) is not broadcastable to PSD (shape: {PSD.shape}): {e}") 836 837 # Check if at least one of 'Spatial_map' or 'Cartesian_visualisation' is present in the scanning dictionary 838 # This is required for sparse data to establish the spatial mapping 839 has_spatial_mapping = False 840 if scanning is not None: 841 if 'Spatial_map' in scanning: 842 sm = scanning['Spatial_map'] 843 size = 0 844 845 def check_coor(coor: str): 846 if coor in sm: 847 sm[coor] = np.array(sm[coor]) 848 size1 = sm[coor].size 849 if size1 != size and size != 0: 850 raise ValueError( 851 f"'{coor}' in 'Spatial_map' is invalid!") 852 return size1 853 return size 854 size = check_coor('x') 855 size = check_coor('y') 856 size = check_coor('z') 857 if size == 0: 858 raise ValueError( 859 "'Spatial_map' should contain at least one x, y or z") 860 has_spatial_mapping = True 861 if 'Cartesian_visualisation' in scanning: 862 cv = scanning['Cartesian_visualisation'] 863 if not isinstance(cv, np.ndarray) or cv.ndim != 3: 864 raise ValueError( 865 "Cartesian_visualisation must be a 3D numpy array") 866 if not np.issubdtype(cv.dtype, np.integer) or np.min(cv) < -1 or np.max(cv) >= PSD.shape[0]: 867 raise ValueError( 868 "Cartesian_visualisation values must be integers between -1 and PSD.shape[0]-1") 869 if 'Cartesian_visualisation_pixel' in scanning: 870 if len(scanning['Cartesian_visualisation_pixel']) != 3: 871 raise ValueError( 872 "Cartesian_visualisation_pixel must always contain 3 values for z, y, x (set to None if not used)") 873 else: 874 warnings.warn( 875 "It is recommended to include 'Cartesian_visualisation_pixel' in the scanning dictionary to define pixel size for proper spatial calibration") 876 has_spatial_mapping = True 877 if not has_spatial_mapping and self._sparse: 878 raise ValueError("For sparse data, 'scanning' must be provided and must contain at least one of 'Spatial_map' or 'Cartesian_visualisation'") 879 880 # TODO: add and validate additional datasets (i.e. 'Parameters', 'Calibration_index', etc.) 881 882 # Add datasets to the group 883 sync(self._file.create_dataset( 884 self._group, brim_obj_names.data.PSD, data=PSD, 885 chunk_size=_determine_chunk_size(PSD), compression=compression)) 886 freq_ds = sync(self._file.create_dataset( 887 self._group, brim_obj_names.data.frequency, data=frequency, 888 chunk_size=_determine_chunk_size(frequency), compression=compression)) 889 units.add_to_object(self._file, freq_ds, freq_units) 890 891 if scanning is not None: 892 if 'Spatial_map' in scanning: 893 sm = scanning['Spatial_map'] 894 sm_group = sync(self._file.create_group(concatenate_paths( 895 self._path, brim_obj_names.data.spatial_map))) 896 if 'units' in sm: 897 units.add_to_object(self._file, sm_group, sm['units']) 898 899 def add_sm_dataset(coord: str): 900 if coord in sm: 901 sync(self._file.create_dataset( 902 sm_group, coord, data=sm[coord], compression=compression)) 903 904 add_sm_dataset('x') 905 add_sm_dataset('y') 906 add_sm_dataset('z') 907 if 'Cartesian_visualisation' in scanning: 908 # convert the Cartesian_visualisation to the smallest integer type 909 cv_arr = np_array_to_smallest_int_type(scanning['Cartesian_visualisation']) 910 cv = sync(self._file.create_dataset(self._group, brim_obj_names.data.cartesian_visualisation, 911 data=cv_arr, compression=compression)) 912 if 'Cartesian_visualisation_pixel' in scanning: 913 sync(self._file.create_attr( 914 cv, 'element_size', scanning['Cartesian_visualisation_pixel'])) 915 if 'Cartesian_visualisation_pixel_unit' in scanning: 916 px_unit = scanning['Cartesian_visualisation_pixel_unit'] 917 else: 918 warnings.warn( 919 "No unit provided for Cartesian_visualisation_pixel, defaulting to 'um'") 920 px_unit = 'um' 921 units.add_to_attribute(self._file, cv, 'element_size', px_unit) 922 923 self._spatial_map, self._spatial_map_px_size = sync(self._load_spatial_mapping_async()) 924 925 @staticmethod 926 def list_data_groups(file: FileAbstraction, retrieve_custom_name=False) -> list: 927 """ 928 Synchronous wrapper for `list_data_groups_async` (see doc for `brimfile.data.Data.list_data_groups_async`) 929 """ 930 return sync(Data.list_data_groups_async(file, retrieve_custom_name)) 931 932 @staticmethod 933 async def list_data_groups_async(file: FileAbstraction, retrieve_custom_name=False) -> list: 934 """ 935 List all data groups in the brim file. The list is ordered by index. 936 937 Returns: 938 list: A list of dictionaries, each containing: 939 - 'name' (str): The name of the data group in the file. 940 - 'index' (int): The index extracted from the group name. 941 - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the data group as returned from utils.get_object_name. 942 """ 943 944 data_groups = [] 945 946 matched_objs = await list_objects_matching_pattern_async( 947 file, brim_obj_names.Brillouin_base_path, brim_obj_names.data.base_group + r"_(\d+)$") 948 949 async def _make_dict_item(matched_obj, retrieve_custom_name): 950 name = matched_obj[0] 951 index = int(matched_obj[1]) 952 curr_obj_dict = {'name': name, 'index': index} 953 if retrieve_custom_name: 954 path = concatenate_paths( 955 brim_obj_names.Brillouin_base_path, name) 956 custom_name = await get_object_name(file, path) 957 curr_obj_dict['custom_name'] = custom_name 958 return curr_obj_dict 959 960 coros = [_make_dict_item(matched_obj, retrieve_custom_name) for matched_obj in matched_objs] 961 dicts = await asyncio.gather(*coros) 962 for dict_item in dicts: 963 data_groups.append(dict_item) 964 # Sort the data groups by index 965 data_groups.sort(key=lambda x: x['index']) 966 967 return data_groups 968 969 @staticmethod 970 async def _get_existing_group_name_async(file: FileAbstraction, index: int) -> str: 971 """ 972 Get the name of an existing data group by index. 973 974 Args: 975 file (File): The parent File object. 976 index (int): The index of the data group. 977 978 Returns: 979 str: The name of the data group, or None if not found. 980 """ 981 group_name: str = None 982 data_groups = await Data.list_data_groups_async(file) 983 for dg in data_groups: 984 if dg['index'] == index: 985 group_name = dg['name'] 986 break 987 return group_name 988 989 @classmethod 990 async def from_existing_async(cls, file: FileAbstraction, index: int) -> 'Data': 991 """ 992 Create a Data object from an existing data group in the file. 993 Args: 994 file (File): The parent File object. 995 index (int): The index of the existing data group. 996 Returns: 997 Data: A Data object corresponding to the existing data group. 998 Raises: 999 IndexError: If no data group with the specified index is found in the file. 1000 """ 1001 group_name: str = await cls._get_existing_group_name_async(file, index) 1002 if group_name is None: 1003 raise IndexError(f"No data group with index {index} found in the file") 1004 dg = cls(file, concatenate_paths(brim_obj_names.Brillouin_base_path, group_name), _initialize=False) 1005 await dg._init_async() 1006 return dg 1007 1008 @classmethod 1009 def _create_new(cls, file: FileAbstraction, index: int, sparse: bool = False, name: str = None) -> 'Data': 1010 """ 1011 Create a new data group with the specified index. 1012 1013 Args: 1014 file (File): The parent File object. 1015 index (int): The index for the new data group. 1016 sparse (bool): Whether the data is sparse. See https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md for details. Defaults to False. 1017 name (str, optional): The name for the new data group. Defaults to None. 1018 1019 Returns: 1020 Data: The newly created Data object. 1021 """ 1022 group_name = Data._generate_group_name(index) 1023 group = sync(file.create_group(concatenate_paths( 1024 brim_obj_names.Brillouin_base_path, group_name))) 1025 sync(file.create_attr(group, 'Sparse', sparse)) 1026 if name is not None: 1027 set_object_name(file, group, name) 1028 return cls(file, concatenate_paths(brim_obj_names.Brillouin_base_path, group_name), newly_created=True) 1029 1030 @staticmethod 1031 def _generate_group_name(index: int, n_digits: int = None) -> str: 1032 """ 1033 Generate a name for a data group based on the index. 1034 1035 Args: 1036 index (int): The index for the data group. 1037 n_digits (int, optional): The number of digits to pad the index with. If None no padding is applied. Defaults to None. 1038 1039 Returns: 1040 str: The generated group name. 1041 1042 Raises: 1043 ValueError: If the index is negative. 1044 """ 1045 if index < 0: 1046 raise ValueError("index must be positive") 1047 num = str(index) 1048 if n_digits is not None: 1049 num = num.zfill(n_digits) 1050 return f"{brim_obj_names.data.base_group}_{num}"
Represents a data group within the brim file.
37 def __init__(self, file: FileAbstraction, path: str, *, 38 newly_created: bool = False, _initialize: bool = True): 39 """ 40 Initialize the Data object. This constructor should not be called directly. 41 42 Args: 43 file (File): The parent File object. 44 path (str): The path to the data group within the file. 45 newly_created (bool): Whether this data group is being created as new. 46 If True, the constructor will not attempt to load spatial mapping. 47 _initialize (bool): FOR INTERNAL USE ONLY. Whether to automatically initialize the current data group. 48 Set to False if you want to initialize them manually later using the _init_async() method. Default is True. 49 """ 50 self._file = file 51 self._path = path 52 53 54 if _initialize: 55 sync(self._init_async(newly_created=newly_created))
Initialize the Data object. This constructor should not be called directly.
Arguments:
- file (File): The parent File object.
- path (str): The path to the data group within the file.
- newly_created (bool): Whether this data group is being created as new. If True, the constructor will not attempt to load spatial mapping.
- _initialize (bool): FOR INTERNAL USE ONLY. Whether to automatically initialize the current data group. Set to False if you want to initialize them manually later using the _init_async() method. Default is True.
67 def get_name(self): 68 """ 69 Returns the name of the data group. 70 """ 71 return sync(get_object_name(self._file, self._path))
Returns the name of the data group.
73 def get_index(self): 74 """ 75 Returns the index of the data group. 76 """ 77 return int(self._path.split('/')[-1].split('_')[-1])
Returns the index of the data group.
250 def get_PSD(self) -> tuple: 251 """ 252 LOW LEVEL FUNCTION 253 254 Retrieve the Power Spectral Density (PSD) and frequency from the current data group. 255 Note: this function exposes the internals of the brim file and thus the interface might change in future versions. 256 Use only if more specialized functions are not working for your application! 257 Returns: 258 tuple: (PSD, frequency, PSD_units, frequency_units) 259 - PSD: A 2D (or more) numpy array containing all the spectra (see [specs](https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md) for more details). 260 - frequency: A numpy array representing the frequency data (see [specs](https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md) for more details). 261 - PSD_units: The units of the PSD. 262 - frequency_units: The units of the frequency. 263 """ 264 warnings.warn( 265 "Data.get_PSD is deprecated and will be removed in a future release. " 266 "Use Data.get_PSD_as_spatial_map instead.", 267 DeprecationWarning, 268 stacklevel=2, 269 ) 270 PSD, frequency = _gather_sync( 271 self._file.open_dataset(concatenate_paths( 272 self._path, brim_obj_names.data.PSD)), 273 self._file.open_dataset(concatenate_paths( 274 self._path, brim_obj_names.data.frequency)) 275 ) 276 # retrieve the units of the PSD and frequency 277 PSD_units, frequency_units = _gather_sync( 278 units.of_object(self._file, PSD), 279 units.of_object(self._file, frequency) 280 ) 281 282 return PSD, frequency, PSD_units, frequency_units
LOW LEVEL FUNCTION
Retrieve the Power Spectral Density (PSD) and frequency from the current data group. Note: this function exposes the internals of the brim file and thus the interface might change in future versions. Use only if more specialized functions are not working for your application!
Returns:
tuple: (PSD, frequency, PSD_units, frequency_units) - PSD: A 2D (or more) numpy array containing all the spectra (see specs for more details). - frequency: A numpy array representing the frequency data (see specs for more details). - PSD_units: The units of the PSD. - frequency_units: The units of the frequency.
284 @staticmethod 285 def interpolate_spectra(PSD: np.ndarray, frequency: np.ndarray, *, 286 new_frequency: np.ndarray | None = None 287 ) -> tuple[np.ndarray, np.ndarray]: 288 """Interpolate spectra along their final axis. 289 290 Each spectrum is interpolated from its corresponding values in 291 ``frequency`` onto ``new_frequency``. Both frequency arrays must be 292 broadcastable to ``PSD.shape``; for example, a 1D array can be shared 293 across all spectra. The final axis contains the frequency samples. 294 295 If ``new_frequency`` is omitted and ``frequency`` is multidimensional, 296 a shared 1D frequency array is generated by averaging ``frequency`` 297 across all dimensions except its final (sample) axis. If the input 298 frequency is 1D, the original ``PSD`` and ``frequency`` are returned 299 unchanged. 300 301 Values outside a spectrum's frequency range use ``numpy.interp``'s 302 endpoint behavior. 303 304 Args: 305 PSD: Spectral values, with samples along the final axis. 306 frequency: Frequencies corresponding to ``PSD``. Must contain only finite values. 307 new_frequency (optional): Target frequencies, finite and broadcastable to 308 ``PSD.shape``. May be 1D or have additional broadcastable 309 dimensions. If omitted, a new frequency array is generated. 310 311 Returns: 312 A tuple of the spectra and the target frequencies. The spectra 313 retain the original ``PSD`` dtype when no interpolation is done; 314 otherwise, they have dtype ``float64``. When ``new_frequency`` is 315 supplied, it is returned in its original shape; when generated, 316 the returned array is 1D. 317 318 Raises: 319 ValueError: If frequencies are non-finite, or either frequency array 320 cannot be broadcast as required. 321 """ 322 323 # the frequency is already the same for all spectra and no new frequency is provided, 324 # so we can just return the original PSD 325 if new_frequency is None and frequency.ndim == 1: 326 return PSD, frequency 327 328 # check the frequency array 329 if not np.all(np.isfinite(frequency)): 330 raise ValueError("The frequency array must contain only finite values for interpolation.") 331 try: 332 frequency = np.broadcast_to(frequency, PSD.shape) 333 except ValueError as e: 334 raise ValueError("`frequency` must be broadcastable to the shape of PSD.") from e 335 if not np.all(np.diff(frequency, axis=-1) >= 0): 336 # the array is not increasing along the last axis, we need to sort it and the PSD accordingly 337 sort_indices = np.argsort(frequency, axis=-1) 338 frequency = np.take_along_axis(frequency, sort_indices, axis=-1) 339 PSD = np.take_along_axis(PSD, sort_indices, axis=-1) 340 # check or generate the new frequency array 341 if new_frequency is None: 342 # if the user does not provide a new frequency array, we will create a new frequency array that 343 # is the mean of the original frequency array along all dimensions except the last one 344 new_frequency = np.mean(frequency, axis=tuple(range(frequency.ndim - 1))) 345 else: 346 if new_frequency.ndim > PSD.ndim: 347 raise ValueError("`new_frequency` must have less or equal number of dimensions than PSD") 348 if not np.all(np.isfinite(new_frequency)): 349 raise ValueError("`new_frequency` must contain only finite values.") 350 try: 351 np.broadcast_shapes(new_frequency.shape, PSD.shape) 352 except Exception as e: 353 raise ValueError("`new_frequency` must have the same number of dimensions as PSD or be 1D.") from e 354 355 # Interpolate each spectrum in the PSD along the last axis 356 interpolated_PSD = np.empty_like(PSD, dtype=np.float64) 357 interp_freq = np.broadcast_to(new_frequency, PSD.shape) 358 for idx in itertools.product(*[range(s) for s in PSD.shape[:-1]]): 359 interpolated_PSD[idx] = np.interp(interp_freq[idx], frequency[idx], PSD[idx]) 360 return interpolated_PSD, new_frequency
Interpolate spectra along their final axis.
Each spectrum is interpolated from its corresponding values in
frequency onto new_frequency. Both frequency arrays must be
broadcastable to PSD.shape; for example, a 1D array can be shared
across all spectra. The final axis contains the frequency samples.
If new_frequency is omitted and frequency is multidimensional,
a shared 1D frequency array is generated by averaging frequency
across all dimensions except its final (sample) axis. If the input
frequency is 1D, the original PSD and frequency are returned
unchanged.
Values outside a spectrum's frequency range use numpy.interp's
endpoint behavior.
Arguments:
- PSD: Spectral values, with samples along the final axis.
- frequency: Frequencies corresponding to
PSD. Must contain only finite values. - new_frequency (optional): Target frequencies, finite and broadcastable to
PSD.shape. May be 1D or have additional broadcastable dimensions. If omitted, a new frequency array is generated.
Returns:
A tuple of the spectra and the target frequencies. The spectra retain the original
PSDdtype when no interpolation is done; otherwise, they have dtypefloat64. Whennew_frequencyis supplied, it is returned in its original shape; when generated, the returned array is 1D.
Raises:
- ValueError: If frequencies are non-finite, or either frequency array cannot be broadcast as required.
362 def get_PSD_as_spatial_map(self, *, broadcast_frequency: bool = True) -> tuple: 363 """ 364 Retrieve the Power Spectral Density (PSD) as a spatial map and the frequency from the current data group. 365 Arguments: 366 broadcast_frequency (bool): Whether to broadcast the frequency array to match the shape of the PSD if they have different shapes. 367 This is useful when the frequency is the same for all spectra and thus stored as a 1D array, while the PSD has a spatial dimension. 368 If False, the function will return the frequency with the same shape as it is stored in the file (which could be any shape broadcastable to PSD); 369 consider using `Data.interpolate_spectra` to interpolate the PSD to a new (1D) frequency array if needed. 370 Returns: 371 tuple: (PSD, frequency, PSD_units, frequency_units) 372 - PSD: A 4D (or more) numpy array containing all the spectra. Dimensions are z, y, x, [parameters], spectrum. 373 - frequency: A numpy array representing the frequency data, which has the same shape as PSD or a 1D array (see `broadcast_frequency`). 374 - PSD_units: The units of the PSD. 375 - frequency_units: The units of the frequency. 376 """ 377 PSD, frequency = _gather_sync( 378 self._file.open_dataset(concatenate_paths( 379 self._path, brim_obj_names.data.PSD)), 380 self._file.open_dataset(concatenate_paths( 381 self._path, brim_obj_names.data.frequency)) 382 ) 383 # retrieve the units of the PSD and frequency 384 PSD_units, frequency_units = _gather_sync( 385 units.of_object(self._file, PSD), 386 units.of_object(self._file, frequency) 387 ) 388 389 # ensure PSD and frequency are numpy arrays 390 PSD = np.array(PSD) 391 frequency = np.array(frequency) # ensure it's a numpy array 392 393 # if the frequency is not the same for all spectra, broadcast it to match the shape of PSD 394 # if it is the same for all spectra, broadcast_frequency determines whether to return it as a 1D array or broadcast it to match the shape of PSD 395 if frequency.ndim > 1 or (broadcast_frequency and frequency.shape != PSD.shape): 396 frequency = np.broadcast_to(frequency, PSD.shape) 397 398 if self._sparse: 399 if self._spatial_map is None: 400 raise ValueError("The data is defined as sparse, but no spatial mapping is provided.") 401 sm = np.array(self._spatial_map) 402 # reshape the PSD and frequency to have the spatial dimensions first 403 PSD = PSD[sm, ...] 404 # reshape the frequency only if it is not the same for all spectra 405 if frequency.ndim > 1: 406 frequency = frequency[sm, ...] 407 408 return PSD, frequency, PSD_units, frequency_units
Retrieve the Power Spectral Density (PSD) as a spatial map and the frequency from the current data group.
Arguments:
- broadcast_frequency (bool): Whether to broadcast the frequency array to match the shape of the PSD if they have different shapes.
This is useful when the frequency is the same for all spectra and thus stored as a 1D array, while the PSD has a spatial dimension.
If False, the function will return the frequency with the same shape as it is stored in the file (which could be any shape broadcastable to PSD);
consider using
Data.interpolate_spectrato interpolate the PSD to a new (1D) frequency array if needed.
Returns:
tuple: (PSD, frequency, PSD_units, frequency_units) - PSD: A 4D (or more) numpy array containing all the spectra. Dimensions are z, y, x, [parameters], spectrum. - frequency: A numpy array representing the frequency data, which has the same shape as PSD or a 1D array (see
broadcast_frequency). - PSD_units: The units of the PSD. - frequency_units: The units of the frequency.
415 async def _get_spectrum_async(self, index: int | tuple[int, int, int]) -> tuple: 416 """ 417 @public 418 419 Retrieve a spectrum from the data group by its index or coordinates. 420 421 Args: 422 index (int | tuple[int, int, int]): The index (for sparse data) or z, y, x coordinates (for non-sparse data) of the spectrum to retrieve. 423 424 Returns: 425 tuple: (PSD, frequency, PSD_units, frequency_units) for the specified index. 426 PSD can be 1D or more (if there are additional parameters); 427 frequency has the same size as PSD 428 Raises: 429 IndexError: If the index is out of range for the PSD dataset. 430 """ 431 if self._sparse and not isinstance(index, int): 432 raise ValueError("For sparse data, index must be an integer.") 433 elif not self._sparse and not (isinstance(index, tuple) and len(index) == 3): 434 raise ValueError("For non-sparse data, index must be a tuple of (z, y, x) coordinates.") 435 436 # index = -1 corresponds to no spectrum 437 if self._sparse and index < 0: 438 return None, None, None, None 439 elif not self._sparse and any(i < 0 for i in index): 440 return None, None, None, None 441 PSD, frequency = await asyncio.gather( 442 self._file.open_dataset(concatenate_paths( 443 self._path, brim_obj_names.data.PSD)), 444 self._file.open_dataset(concatenate_paths( 445 self._path, brim_obj_names.data.frequency)) 446 ) 447 if self._sparse and index >= PSD.shape[0]: 448 raise IndexError( 449 f"index {index} out of range for PSD with shape {PSD.shape}") 450 elif not self._sparse and any(i >= PSD.shape[j] for j, i in enumerate(index)): 451 raise IndexError( 452 f"index {index} out of range for PSD with shape {PSD.shape}") 453 # retrieve the units of the PSD and frequency 454 PSD_units, frequency_units = await asyncio.gather( 455 units.of_object(self._file, PSD), 456 units.of_object(self._file, frequency) 457 ) 458 # add ellipsis to the index to select the spectrum and the corresponding frequency 459 if self._sparse: 460 index = (index, ...) 461 else: 462 index = index + (..., ) 463 # map index to the frequency array, considering the broadcasting rules 464 index_frequency = index 465 if frequency.ndim < PSD.ndim: 466 if self._sparse: 467 # given the definition of the brim file format, 468 # if the frequency has less dimensions that PSD, 469 # it can only be because it is the same for all the spatial position (first dimension) 470 index_frequency = (..., ) 471 else: 472 unassigned_indices = PSD.ndim - frequency.ndim 473 if unassigned_indices == 3: 474 # if the frequency has no spatial dimension, it is the same for all the spatial positions 475 index_frequency = (..., ) 476 else: 477 # if the frequency has some spatial dimensions but not all, we need to add the corresponding indices to the index of the frequency 478 index_frequency = index[-unassigned_indices:] + (..., ) 479 #get the spectrum and the corresponding frequency at the specified index 480 PSD, frequency = await asyncio.gather( 481 _async_getitem(PSD, index), 482 _async_getitem(frequency, index_frequency) 483 ) 484 #broadcast the frequency to match the shape of PSD if needed 485 if frequency.ndim < PSD.ndim: 486 frequency = np.broadcast_to(frequency, PSD.shape) 487 return PSD, frequency, PSD_units, frequency_units
Retrieve a spectrum from the data group by its index or coordinates.
Arguments:
- index (int | tuple[int, int, int]): The index (for sparse data) or z, y, x coordinates (for non-sparse data) of the spectrum to retrieve.
Returns:
tuple: (PSD, frequency, PSD_units, frequency_units) for the specified index. PSD can be 1D or more (if there are additional parameters); frequency has the same size as PSD
Raises:
- IndexError: If the index is out of range for the PSD dataset.
489 def get_spectrum_in_image(self, coor: tuple) -> tuple: 490 """ 491 Retrieve a spectrum from the data group using spatial coordinates. 492 493 Args: 494 coor (tuple): A tuple containing the z, y, x coordinates of the spectrum to retrieve. 495 496 Returns: 497 tuple: A tuple containing the PSD, frequency, PSD_units, and 498 frequency_units for the specified coordinates. See 499 `brimfile.data.Data._get_spectrum_async` for details. 500 501 Raises: 502 ValueError: If `coor` does not contain three coordinates `(z, y, x)`. 503 IndexError: If coordinates map outside the available data. 504 """ 505 if len(coor) != 3: 506 raise ValueError("coor must contain 3 values for z, y, x") 507 508 if self._sparse: 509 index = int(self._spatial_map[coor]) 510 return self._get_spectrum(index) 511 else: 512 return self._get_spectrum(coor)
Retrieve a spectrum from the data group using spatial coordinates.
Arguments:
- coor (tuple): A tuple containing the z, y, x coordinates of the spectrum to retrieve.
Returns:
tuple: A tuple containing the PSD, frequency, PSD_units, and frequency_units for the specified coordinates. See
brimfile.data.Data._get_spectrum_asyncfor details.
Raises:
- ValueError: If
coordoes not contain three coordinates(z, y, x). - IndexError: If coordinates map outside the available data.
514 async def get_spectrum_and_all_quantities_in_image_async(self, ar: 'Data.AnalysisResults', coor: tuple, index_peak: int = 0) -> tuple[tuple, dict]: 515 """ 516 Retrieve the spectrum and all available quantities from the analysis results at a specific spatial coordinate. 517 518 Args: 519 ar (Data.AnalysisResults): The analysis results object to retrieve quantities from. 520 coor (tuple): A tuple containing the z, y, x coordinates in the image. 521 index_peak (int, optional): The index of the peak to retrieve (for multi-peak fits). Defaults to 0. 522 523 Returns: 524 tuple: A tuple containing: 525 - spectrum (tuple): (PSD, frequency, PSD_units, frequency_units) at the specified coordinate 526 - quantities (dict): Dictionary of Metadata.Item in the form result[quantity.name][peak.name] 527 """ 528 if len(coor) != 3: 529 raise ValueError("coor must contain 3 values for z, y, x") 530 index = coor 531 if self._sparse: 532 index = int(self._spatial_map[coor]) 533 spectrum, quantities = await asyncio.gather( 534 self._get_spectrum_async(index), 535 ar._get_all_quantities_at_index(index, index_peak) 536 ) 537 return spectrum, quantities
Retrieve the spectrum and all available quantities from the analysis results at a specific spatial coordinate.
Arguments:
- ar (Data.AnalysisResults): The analysis results object to retrieve quantities from.
- coor (tuple): A tuple containing the z, y, x coordinates in the image.
- index_peak (int, optional): The index of the peak to retrieve (for multi-peak fits). Defaults to 0.
Returns:
tuple: A tuple containing: - spectrum (tuple): (PSD, frequency, PSD_units, frequency_units) at the specified coordinate - quantities (dict): Dictionary of Metadata.Item in the form result[quantity.name][peak.name]
538 def get_spectrum_and_all_quantities_in_image(self, ar: 'Data.AnalysisResults', coor: tuple, index_peak: int = 0) -> tuple[tuple, dict]: 539 """ 540 Synchronous wrapper for `get_spectrum_and_all_quantities_in_image_async` (see doc for `brimfile.data.Data.get_spectrum_and_all_quantities_in_image_async`) 541 """ 542 return sync(self.get_spectrum_and_all_quantities_in_image_async(ar, coor, index_peak))
Synchronous wrapper for get_spectrum_and_all_quantities_in_image_async (see doc for brimfile.data.Data.get_spectrum_and_all_quantities_in_image_async)
544 def get_metadata(self): 545 """ 546 Returns the metadata associated with the current Data group 547 Note that this contains both the general metadata stored in the file (which might be redifined by the specific data group) 548 and the ones specific for this data group 549 """ 550 return Metadata(self._file, self._path)
Returns the metadata associated with the current Data group Note that this contains both the general metadata stored in the file (which might be redifined by the specific data group) and the ones specific for this data group
552 def get_num_parameters(self) -> tuple: 553 """ 554 Retrieves the number of parameters 555 556 Returns: 557 tuple: The shape of the parameters if they exist, otherwise an empty tuple. 558 """ 559 pars, _ = self.get_parameters() 560 return pars.shape if pars is not None else ()
Retrieves the number of parameters
Returns:
tuple: The shape of the parameters if they exist, otherwise an empty tuple.
562 def get_parameters(self) -> list: 563 """ 564 Retrieves the parameters and their associated names. 565 566 If PSD.ndims > 2, the parameters are stored in a separate dataset. 567 568 Returns: 569 list: A tuple containing the parameters and their names if there are any, otherwise None. 570 """ 571 pars_full_path = concatenate_paths( 572 self._path, brim_obj_names.data.parameters) 573 if sync(self._file.object_exists(pars_full_path)): 574 pars = sync(self._file.open_dataset(pars_full_path)) 575 pars_names = sync(self._file.get_attr(pars, 'Name')) 576 return (pars, pars_names) 577 return (None, None)
Retrieves the parameters and their associated names.
If PSD.ndims > 2, the parameters are stored in a separate dataset.
Returns:
list: A tuple containing the parameters and their names if there are any, otherwise None.
579 def create_calibration_group(self, *, index: NDArray[np.integer] | None = None, calibration_data: list[dict[str, Any]] | None = None, 580 same_as: int | None = None, attributes: dict[str, MetadataItem] = None, 581 compression: FileAbstraction.Compression = FileAbstraction.Compression()) -> Calibration: 582 """ 583 Create a new calibration group in the current data group. 584 For more details on the expected format of the calibration data, see https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md. 585 586 Parameters: 587 index (np.array | None, optional): Index array for the calibration spectra. For sparse data, 588 this must be 1D; for non-sparse data, this must be 3D. 589 It can be omitted if each element in `calibration_data` contains only one spectrum. 590 calibration_data (list[dict[str, Any]] | None, optional): Calibration entries to store. 591 Each dictionary must contain `spectra` and `shift` keys, and may provide `shift_units`. 592 same_as (int | None, optional): If provided, links this calibration group to an existing 593 calibration via the `Same_as` attribute. When set, the other data arguments are ignored. 594 Defaults to None. 595 attributes (dict[str, MetadataItem], optional): Additional attributes to attach to the calibration group. 596 Can be one of ('Datetime', 'Description', 'Temperature', 'FSR') with the relative units (when relevant). 597 compression (FileAbstraction.Compression, optional): Compression settings used for created 598 datasets. Defaults to FileAbstraction.Compression(). 599 600 Returns: 601 Calibration: The newly created calibration group. 602 603 Raises: 604 ValueError: If the provided calibration data or index is invalid or inconsistent. 605 """ 606 calibration_path = concatenate_paths(self._path, brim_obj_names.data.calibration) 607 calibration_group = sync(self._file.create_group(calibration_path)) 608 609 # if same_as is provided, create the 'Same_as' attribute to link the calibration group to an existing one 610 if same_as is not None: 611 sync(self._file.create_attr(calibration_group, 'Same_as', same_as)) 612 else: # if same_as is provided, the other parameters are ignored 613 # check that calibration_data is provided and valid 614 if calibration_data is None: 615 raise ValueError("'calibration_data' is required when 'same_as' is not provided") 616 if not isinstance(calibration_data, (list, tuple)): 617 calibration_data = [calibration_data,] 618 # check that index is valid if provided 619 if index is not None: 620 # TODO: check of the shape of 'index' is compatible with PSD 621 if self._sparse and index.ndim != 1: 622 raise ValueError("'index' must be a 1D array for sparse data") 623 if not self._sparse and index.ndim != 3: 624 raise ValueError("'index' must be a 3D array for non-sparse data") 625 626 for m, calib in enumerate(calibration_data): 627 # check that each element in calibration_data is a dictionary containing 'spectra' and 'shift' keys 628 if not isinstance(calib, dict): 629 raise ValueError("Each element in 'calibration_data' must be a dictionary") 630 if 'spectra' not in calib.keys() or 'shift' not in calib.keys(): 631 raise ValueError("Each calibration data dictionary must contain 'spectra' and 'shift' keys") 632 # retrieve the spectra, shift and shift_units from the calibration data and check that they are valid 633 cal_spectra = np.array(calib['spectra']) 634 if cal_spectra.ndim != 2: 635 raise ValueError("'spectra' in calibration data must be a 2D array. If only one spectrum is provided, set the first dimension to 1.") 636 cal_shift = calib['shift'] 637 cal_shift_units = calib.get('shift_units', None) 638 if cal_shift_units is None: 639 cal_shift_units = 'GHz' 640 warnings.warn("No units provided for 'shift' in calibration data, defaulting to GHz") 641 # check that index is compatible with the shape of the spectra 642 if index is None and cal_spectra.shape[0] != 1: 643 raise ValueError("If 'index' is not provided, each element in 'calibration_data' must contain only one spectrum (i.e. have shape (1, n))") 644 if index is not None and np.max(index) >= cal_spectra.shape[0]: 645 raise ValueError("If 'index' is provided, its maximum value must be less than the number of spectra in each calibration data element") 646 # add the m arrays together with their attributes to the file 647 spectra_dataset = sync(self._file.create_dataset(calibration_group, f'{m}', cal_spectra, chunk_size=_determine_chunk_size(cal_spectra), compression=compression)) 648 sync(self._file.create_attr(spectra_dataset, 'Shift', cal_shift)) 649 units.add_to_attribute(self._file, spectra_dataset, 'Shift', cal_shift_units) 650 # add the index array to the file 651 if index is not None: 652 sync(self._file.create_dataset(calibration_group, 'Index', index, compression=compression)) 653 654 from .calibration import _STANDARD_ATTRIBUTES 655 # add any additional attributes to the calibration group, checking that they do not overwrite the standard 656 if attributes is not None: 657 for key, value in attributes.items(): 658 if key not in _STANDARD_ATTRIBUTES: 659 warnings.warn(f"Attribute '{key}' is not a standard attribute for calibration groups.\ 660 Standard attributes are: {', '.join(_STANDARD_ATTRIBUTES)}. \ 661 Make sure this is intentional!") 662 if not isinstance(value, MetadataItem): 663 value = MetadataItem(value) 664 sync(self._file.create_attr(calibration_group, key, value.value)) 665 if value.units is not None: 666 units.add_to_attribute(self._file, calibration_group, key, value.units) 667 668 return Calibration(self._file, calibration_path, data_group=self)
Create a new calibration group in the current data group. For more details on the expected format of the calibration data, see https://github.com/brillouin-imaging/Brillouin-standard-file/blob/main/docs/brim_file_specs.md.
Arguments:
- index (np.array | None, optional): Index array for the calibration spectra. For sparse data,
this must be 1D; for non-sparse data, this must be 3D.
It can be omitted if each element incalibration_datacontains only one spectrum. - calibration_data (list[dict[str, Any]] | None, optional): Calibration entries to store.
Each dictionary must contain
spectraandshiftkeys, and may provideshift_units. - same_as (int | None, optional): If provided, links this calibration group to an existing
calibration via the
Same_asattribute. When set, the other data arguments are ignored. Defaults to None. - attributes (dict[str, MetadataItem], optional): Additional attributes to attach to the calibration group. Can be one of ('Datetime', 'Description', 'Temperature', 'FSR') with the relative units (when relevant).
- compression (FileAbstraction.Compression, optional): Compression settings used for created datasets. Defaults to FileAbstraction.Compression().
Returns:
Calibration: The newly created calibration group.
Raises:
- ValueError: If the provided calibration data or index is invalid or inconsistent.
670 def get_calibration(self) -> Calibration: 671 """ 672 Synchronous wrapper for `get_calibration_async` (see doc for `brimfile.data.Data.get_calibration_async`) 673 """ 674 return sync(self.get_calibration_async())
Synchronous wrapper for get_calibration_async (see doc for brimfile.data.Data.get_calibration_async)
676 async def get_calibration_async(self) -> Calibration: 677 """ 678 Retrieve the calibration group associated with the current data group. 679 680 Returns: 681 Calibration: The calibration group associated with the current data group. 682 683 Raises: 684 ValueError: If no calibration group is found in the current data group or the referenced calibration group does not exist. 685 """ 686 calibration_path = concatenate_paths(self._path, brim_obj_names.data.calibration) 687 if not await self._file.object_exists(calibration_path): 688 raise ValueError(f"No calibration group found in {self._path}") 689 same_as = None 690 try: 691 same_as = await self._file.get_attr(calibration_path, 'Same_as') 692 except Exception: 693 pass # same_as attribute is optional, if it does not exist we just ignore it 694 # if the 'Same_as' attribute exists, find the calibration group with the corresponding index 695 if same_as is not None: 696 try: 697 d_m = await Data.from_existing_async(self._file, same_as) 698 return await d_m.get_calibration_async() 699 except IndexError: 700 raise ValueError(f"Calibration group in {self._path} references non-existing calibration index {same_as} in the file") 701 cal_group = Calibration(self._file, calibration_path, data_group=self, _initialize=False) 702 await cal_group._init_async() 703 return cal_group
Retrieve the calibration group associated with the current data group.
Returns:
Calibration: The calibration group associated with the current data group.
Raises:
- ValueError: If no calibration group is found in the current data group or the referenced calibration group does not exist.
705 def create_analysis_results_group(self, data_AntiStokes, data_Stokes=None, *, 706 index: int = None, name: str = None, fit_model: 'Data.AnalysisResults.FitModel' = None) -> AnalysisResults: 707 """ 708 Adds a new AnalysisResults entry to the current data group. 709 Parameters: 710 data_AntiStokes (dict or list[dict]): see documentation for `brimfile.analysis_results.AnalysisResults.add_data` 711 data_Stokes (dict or list[dict]): same as data_AntiStokes for the Stokes peaks. 712 index (int, optional): The index for the new data entry. If None, the next available index is used. Defaults to None. 713 name (str, optional): The name for the new Analysis group. Defaults to None. 714 fit_model (Data.AnalysisResults.FitModel, optional): The fit model used for the analysis. Defaults to None (no attribute is set). 715 Returns: 716 AnalysisResults: The newly created AnalysisResults object. 717 Raises: 718 IndexError: If the specified index already exists in the dataset. 719 ValueError: If any of the data provided is not valid or consistent 720 """ 721 if index is not None: 722 try: 723 self.get_analysis_results(index) 724 except IndexError: 725 pass 726 else: 727 # If the group already exists, raise an error 728 raise IndexError( 729 f"Analysis {index} already exists in {self._path}") 730 else: 731 ar_groups = self.list_AnalysisResults() 732 indices = [ar['index'] for ar in ar_groups] 733 indices.sort() 734 index = indices[-1] + 1 if indices else 0 # Next available index 735 736 ar = Data.AnalysisResults._create_new(self, index=index, sparse=self._sparse) 737 if name is not None: 738 set_object_name(self._file, ar._path, name) 739 ar.add_data(data_AntiStokes, data_Stokes, fit_model=fit_model) 740 741 return ar
Adds a new AnalysisResults entry to the current data group.
Arguments:
- data_AntiStokes (dict or list[dict]): see documentation for
brimfile.analysis_results.AnalysisResults.add_data - data_Stokes (dict or list[dict]): same as data_AntiStokes for the Stokes peaks.
- index (int, optional): The index for the new data entry. If None, the next available index is used. Defaults to None.
- name (str, optional): The name for the new Analysis group. Defaults to None.
- fit_model (Data.AnalysisResults.FitModel, optional): The fit model used for the analysis. Defaults to None (no attribute is set).
Returns:
AnalysisResults: The newly created AnalysisResults object.
Raises:
- IndexError: If the specified index already exists in the dataset.
- ValueError: If any of the data provided is not valid or consistent
743 def list_AnalysisResults(self, retrieve_custom_name=False) -> list: 744 """ 745 List all AnalysisResults groups in the current data group. The list is ordered by index. 746 747 Returns: 748 list: A list of dictionaries, each containing: 749 - 'name' (str): The name of the AnalysisResults group. 750 - 'index' (int): The index extracted from the group name. 751 - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the AnalysisResults group as returned from utils.get_object_name. 752 """ 753 754 analysis_results_groups = [] 755 756 matched_objs = sync(list_objects_matching_pattern_async( 757 self._file, self._group, brim_obj_names.data.analysis_results + r"_(\d+)$")) 758 async def _make_dict_item(matched_obj, retrieve_custom_name): 759 name = matched_obj[0] 760 index = int(matched_obj[1]) 761 curr_obj_dict = {'name': name, 'index': index} 762 if retrieve_custom_name: 763 ar_path = concatenate_paths(self._path, name) 764 custom_name = await get_object_name(self._file, ar_path) 765 curr_obj_dict['custom_name'] = custom_name 766 return curr_obj_dict 767 coros = [_make_dict_item(matched_obj, retrieve_custom_name) for matched_obj in matched_objs] 768 dicts = _gather_sync(*coros) 769 for dict_item in dicts: 770 analysis_results_groups.append(dict_item) 771 # Sort the data groups by index 772 analysis_results_groups.sort(key=lambda x: x['index']) 773 774 return analysis_results_groups
List all AnalysisResults groups in the current data group. The list is ordered by index.
Returns:
list: A list of dictionaries, each containing: - 'name' (str): The name of the AnalysisResults group. - 'index' (int): The index extracted from the group name. - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the AnalysisResults group as returned from utils.get_object_name.
776 def get_analysis_results(self, index: int = 0) -> AnalysisResults: 777 """ 778 Returns the AnalysisResults at the specified index 779 780 Args: 781 index (int) 782 783 Raises: 784 IndexError: If there is no analysis with the corresponding index 785 """ 786 name = None 787 ls = self.list_AnalysisResults() 788 for el in ls: 789 if el['index'] == index: 790 name = el['name'] 791 break 792 if name is None: 793 raise IndexError(f"Analysis {index} not found") 794 path = concatenate_paths(self._path, name) 795 return Data.AnalysisResults(self._file, path, data_group_path=self._path, 796 spatial_map=self._spatial_map, spatial_map_px_size=self._spatial_map_px_size, sparse=self._sparse)
Returns the AnalysisResults at the specified index
Arguments:
- index (int)
Raises:
- IndexError: If there is no analysis with the corresponding index
798 def _add_data(self, PSD: np.ndarray, frequency: np.ndarray, *, scanning: dict = None, freq_units='GHz', 799 compression: FileAbstraction.Compression = FileAbstraction.Compression()): 800 """ 801 @public 802 803 Add data to the current data group. 804 805 This method adds the provided PSD, frequency, and scanning data to the HDF5 group 806 associated with this `Data` object. It validates the inputs to ensure they meet 807 the required specifications before adding them. 808 809 Args: 810 PSD (np.ndarray): A 2D numpy array representing the Power Spectral Density (PSD) data. The last dimension contains the spectra. 811 frequency (np.ndarray): A 1D or 2D numpy array representing the frequency data. 812 It must be broadcastable to the shape of the PSD array. 813 scanning (dict, optional): A dictionary containing scanning-related data. 814 Required for sparse data (sparse=True), optional for non-sparse data. 815 For sparse data, must include at least one of 'Spatial_map' or 'Cartesian_visualisation'. 816 It may include the following keys: 817 - 'Spatial_map' (optional): A dictionary containing coordinate arrays: 818 - 'x', 'y', 'z' (optional): 1D numpy arrays of same length with coordinate values 819 - 'units' (optional): string with the unit (e.g., 'um') 820 - 'Cartesian_visualisation' (optional): A 3D numpy array (z, y, x) with integer values 821 mapping spatial positions to spectra indices. Values must be -1 (invalid/empty pixel) 822 or between 0 and PSD.shape[0]-1. 823 - 'Cartesian_visualisation_pixel' (recommended with Cartesian_visualisation): 824 Tuple/list of 3 float values (z, y, x) representing pixel size. Unused dimensions can be None. 825 - 'Cartesian_visualisation_pixel_unit' (optional): String for pixel size unit (default: 'um'). 826 827 Raises: 828 ValueError: If any of the data provided is not valid or consistent 829 """ 830 831 # Check if frequency is broadcastable to PSD 832 try: 833 np.broadcast_shapes(tuple(frequency.shape), tuple(PSD.shape)) 834 except ValueError as e: 835 raise ValueError(f"frequency (shape: {frequency.shape}) is not broadcastable to PSD (shape: {PSD.shape}): {e}") 836 837 # Check if at least one of 'Spatial_map' or 'Cartesian_visualisation' is present in the scanning dictionary 838 # This is required for sparse data to establish the spatial mapping 839 has_spatial_mapping = False 840 if scanning is not None: 841 if 'Spatial_map' in scanning: 842 sm = scanning['Spatial_map'] 843 size = 0 844 845 def check_coor(coor: str): 846 if coor in sm: 847 sm[coor] = np.array(sm[coor]) 848 size1 = sm[coor].size 849 if size1 != size and size != 0: 850 raise ValueError( 851 f"'{coor}' in 'Spatial_map' is invalid!") 852 return size1 853 return size 854 size = check_coor('x') 855 size = check_coor('y') 856 size = check_coor('z') 857 if size == 0: 858 raise ValueError( 859 "'Spatial_map' should contain at least one x, y or z") 860 has_spatial_mapping = True 861 if 'Cartesian_visualisation' in scanning: 862 cv = scanning['Cartesian_visualisation'] 863 if not isinstance(cv, np.ndarray) or cv.ndim != 3: 864 raise ValueError( 865 "Cartesian_visualisation must be a 3D numpy array") 866 if not np.issubdtype(cv.dtype, np.integer) or np.min(cv) < -1 or np.max(cv) >= PSD.shape[0]: 867 raise ValueError( 868 "Cartesian_visualisation values must be integers between -1 and PSD.shape[0]-1") 869 if 'Cartesian_visualisation_pixel' in scanning: 870 if len(scanning['Cartesian_visualisation_pixel']) != 3: 871 raise ValueError( 872 "Cartesian_visualisation_pixel must always contain 3 values for z, y, x (set to None if not used)") 873 else: 874 warnings.warn( 875 "It is recommended to include 'Cartesian_visualisation_pixel' in the scanning dictionary to define pixel size for proper spatial calibration") 876 has_spatial_mapping = True 877 if not has_spatial_mapping and self._sparse: 878 raise ValueError("For sparse data, 'scanning' must be provided and must contain at least one of 'Spatial_map' or 'Cartesian_visualisation'") 879 880 # TODO: add and validate additional datasets (i.e. 'Parameters', 'Calibration_index', etc.) 881 882 # Add datasets to the group 883 sync(self._file.create_dataset( 884 self._group, brim_obj_names.data.PSD, data=PSD, 885 chunk_size=_determine_chunk_size(PSD), compression=compression)) 886 freq_ds = sync(self._file.create_dataset( 887 self._group, brim_obj_names.data.frequency, data=frequency, 888 chunk_size=_determine_chunk_size(frequency), compression=compression)) 889 units.add_to_object(self._file, freq_ds, freq_units) 890 891 if scanning is not None: 892 if 'Spatial_map' in scanning: 893 sm = scanning['Spatial_map'] 894 sm_group = sync(self._file.create_group(concatenate_paths( 895 self._path, brim_obj_names.data.spatial_map))) 896 if 'units' in sm: 897 units.add_to_object(self._file, sm_group, sm['units']) 898 899 def add_sm_dataset(coord: str): 900 if coord in sm: 901 sync(self._file.create_dataset( 902 sm_group, coord, data=sm[coord], compression=compression)) 903 904 add_sm_dataset('x') 905 add_sm_dataset('y') 906 add_sm_dataset('z') 907 if 'Cartesian_visualisation' in scanning: 908 # convert the Cartesian_visualisation to the smallest integer type 909 cv_arr = np_array_to_smallest_int_type(scanning['Cartesian_visualisation']) 910 cv = sync(self._file.create_dataset(self._group, brim_obj_names.data.cartesian_visualisation, 911 data=cv_arr, compression=compression)) 912 if 'Cartesian_visualisation_pixel' in scanning: 913 sync(self._file.create_attr( 914 cv, 'element_size', scanning['Cartesian_visualisation_pixel'])) 915 if 'Cartesian_visualisation_pixel_unit' in scanning: 916 px_unit = scanning['Cartesian_visualisation_pixel_unit'] 917 else: 918 warnings.warn( 919 "No unit provided for Cartesian_visualisation_pixel, defaulting to 'um'") 920 px_unit = 'um' 921 units.add_to_attribute(self._file, cv, 'element_size', px_unit) 922 923 self._spatial_map, self._spatial_map_px_size = sync(self._load_spatial_mapping_async())
Add data to the current data group.
This method adds the provided PSD, frequency, and scanning data to the HDF5 group
associated with this Data object. It validates the inputs to ensure they meet
the required specifications before adding them.
Arguments:
- PSD (np.ndarray): A 2D numpy array representing the Power Spectral Density (PSD) data. The last dimension contains the spectra.
- frequency (np.ndarray): A 1D or 2D numpy array representing the frequency data. It must be broadcastable to the shape of the PSD array.
- scanning (dict, optional): A dictionary containing scanning-related data.
Required for sparse data (sparse=True), optional for non-sparse data.
For sparse data, must include at least one of 'Spatial_map' or 'Cartesian_visualisation'.
It may include the following keys:
- 'Spatial_map' (optional): A dictionary containing coordinate arrays:
- 'x', 'y', 'z' (optional): 1D numpy arrays of same length with coordinate values
- 'units' (optional): string with the unit (e.g., 'um')
- 'Cartesian_visualisation' (optional): A 3D numpy array (z, y, x) with integer values mapping spatial positions to spectra indices. Values must be -1 (invalid/empty pixel) or between 0 and PSD.shape[0]-1.
- 'Cartesian_visualisation_pixel' (recommended with Cartesian_visualisation): Tuple/list of 3 float values (z, y, x) representing pixel size. Unused dimensions can be None.
- 'Cartesian_visualisation_pixel_unit' (optional): String for pixel size unit (default: 'um').
- 'Spatial_map' (optional): A dictionary containing coordinate arrays:
Raises:
- ValueError: If any of the data provided is not valid or consistent
925 @staticmethod 926 def list_data_groups(file: FileAbstraction, retrieve_custom_name=False) -> list: 927 """ 928 Synchronous wrapper for `list_data_groups_async` (see doc for `brimfile.data.Data.list_data_groups_async`) 929 """ 930 return sync(Data.list_data_groups_async(file, retrieve_custom_name))
Synchronous wrapper for list_data_groups_async (see doc for brimfile.data.Data.list_data_groups_async)
932 @staticmethod 933 async def list_data_groups_async(file: FileAbstraction, retrieve_custom_name=False) -> list: 934 """ 935 List all data groups in the brim file. The list is ordered by index. 936 937 Returns: 938 list: A list of dictionaries, each containing: 939 - 'name' (str): The name of the data group in the file. 940 - 'index' (int): The index extracted from the group name. 941 - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the data group as returned from utils.get_object_name. 942 """ 943 944 data_groups = [] 945 946 matched_objs = await list_objects_matching_pattern_async( 947 file, brim_obj_names.Brillouin_base_path, brim_obj_names.data.base_group + r"_(\d+)$") 948 949 async def _make_dict_item(matched_obj, retrieve_custom_name): 950 name = matched_obj[0] 951 index = int(matched_obj[1]) 952 curr_obj_dict = {'name': name, 'index': index} 953 if retrieve_custom_name: 954 path = concatenate_paths( 955 brim_obj_names.Brillouin_base_path, name) 956 custom_name = await get_object_name(file, path) 957 curr_obj_dict['custom_name'] = custom_name 958 return curr_obj_dict 959 960 coros = [_make_dict_item(matched_obj, retrieve_custom_name) for matched_obj in matched_objs] 961 dicts = await asyncio.gather(*coros) 962 for dict_item in dicts: 963 data_groups.append(dict_item) 964 # Sort the data groups by index 965 data_groups.sort(key=lambda x: x['index']) 966 967 return data_groups
List all data groups in the brim file. The list is ordered by index.
Returns:
list: A list of dictionaries, each containing: - 'name' (str): The name of the data group in the file. - 'index' (int): The index extracted from the group name. - 'custom_name' (str, optional): if retrieve_custom_name==True, it contains the name of the data group as returned from utils.get_object_name.
989 @classmethod 990 async def from_existing_async(cls, file: FileAbstraction, index: int) -> 'Data': 991 """ 992 Create a Data object from an existing data group in the file. 993 Args: 994 file (File): The parent File object. 995 index (int): The index of the existing data group. 996 Returns: 997 Data: A Data object corresponding to the existing data group. 998 Raises: 999 IndexError: If no data group with the specified index is found in the file. 1000 """ 1001 group_name: str = await cls._get_existing_group_name_async(file, index) 1002 if group_name is None: 1003 raise IndexError(f"No data group with index {index} found in the file") 1004 dg = cls(file, concatenate_paths(brim_obj_names.Brillouin_base_path, group_name), _initialize=False) 1005 await dg._init_async() 1006 return dg
Create a Data object from an existing data group in the file.
Arguments:
- file (File): The parent File object.
- index (int): The index of the existing data group.
Returns:
Data: A Data object corresponding to the existing data group.
Raises:
- IndexError: If no data group with the specified index is found in the file.
27class AnalysisResults: 28 """ 29 Rapresents the analysis results associated with a Data object. 30 """ 31 32 class Quantity(Enum): 33 """ 34 Enum representing the type of analysis results. 35 """ 36 Shift = "Shift" 37 # elastic contrast as defined in https://doi.org/10.1007/s12551-020-00701-9 38 Elastic_contrast = "Elastic_contrast" 39 Width = "Width" 40 # viscous contrast as defined in https://doi.org/10.1007/s12551-020-00701-9 41 Viscous_contrast = "Viscous_contrast" 42 Amplitude = "Amplitude" 43 Offset = "Offset" 44 R2 = "R2" 45 RMSE = "RMSE" 46 Cov_matrix = "Cov_matrix" 47 48 class PeakType(Enum): 49 AntiStokes = "AS" 50 Stokes = "S" 51 average = "avg" 52 53 FitModel = FitModel 54 55 def __init__(self, file: FileAbstraction, full_path: str, *, data_group_path: str, 56 spatial_map = None, spatial_map_px_size = None, sparse: bool = False): 57 """ 58 Initialize the AnalysisResults object. 59 60 Args: 61 file (FileAbstraction): Parent file abstraction object. 62 full_path (str): Path of the group storing the analysis results. 63 data_group_path (str): Path of the data group associated with the analysis results. 64 spatial_map (optional): Spatial map used for sparse analysis results. 65 spatial_map_px_size (optional): Pixel size associated with ``spatial_map``. 66 sparse (bool): Whether the analysis results are stored in sparse format. 67 68 Raises: 69 ValueError: If ``sparse`` is ``True`` and either ``spatial_map`` or 70 ``spatial_map_px_size`` is not provided. 71 """ 72 self._file = file 73 self._path = full_path 74 self._data_group_path = data_group_path 75 # self._group = file.open_group(full_path) 76 self._spatial_map = spatial_map 77 self._spatial_map_px_size = spatial_map_px_size 78 self._sparse = sparse 79 if sparse: 80 if spatial_map is None or spatial_map_px_size is None: 81 raise ValueError("For sparse analysis results, the spatial map and pixel size must be provided.") 82 def _get_metadata(self) -> Metadata: 83 """ 84 Retrieve the Metadata object associated with the current AnalysisResults. 85 86 Returns: 87 Metadata: The Metadata object associated with the current Data group. 88 """ 89 return Metadata(self._file, self._data_group_path) 90 def get_name(self): 91 """ 92 Returns the name of the Analysis group. 93 """ 94 return sync(get_object_name(self._file, self._path)) 95 96 @classmethod 97 def _create_new(cls, data: 'Data', *, index: int, sparse: bool = False) -> 'AnalysisResults': 98 """ 99 Create a new AnalysisResults group. 100 101 Args: 102 file (FileAbstraction): The file. 103 index (int): The index for the new AnalysisResults group. 104 105 Returns: 106 AnalysisResults: The newly created AnalysisResults object. 107 """ 108 group_name = f"{brim_obj_names.data.analysis_results}_{index}" 109 ar_full_path = concatenate_paths(data._path, group_name) 110 sync(data._file.create_group(ar_full_path)) 111 return cls(data._file, ar_full_path, data_group_path=data._path, 112 spatial_map=data._spatial_map, spatial_map_px_size=data._spatial_map_px_size, 113 sparse=sparse) 114 115 def add_data(self, data_AntiStokes=None, data_Stokes=None, *, 116 fit_model: 'AnalysisResults.FitModel' = None): 117 """ 118 Adds data for the analysis results for AntiStokes and Stokes peaks to the file. 119 120 Args: 121 data_AntiStokes (dict or list[dict]): A dictionary containing the analysis results for AntiStokes peaks. 122 In case multiple peaks were fitted, it might be a list of dictionaries with each element corresponding to a single peak. 123 124 Each dictionary may include the following keys (plus the corresponding units, e.g. 'shift_units'): 125 - 'shift': The shift value. 126 - 'width': The width value. 127 - 'amplitude': The amplitude value. 128 - 'offset': The offset value. 129 - 'R2': The R-squared value. 130 - 'RMSE': The root mean square error value. 131 - 'Cov_matrix': The covariance matrix. 132 The above arrays must have one less dimension than the PSD dataset, with the same shape as the first n-1 dimensions of the PSD (i.e. all the dimensions except the last (spectral) one). 133 The 'Cov_matrix' should have 2 additional last dimensions which define the matrix. 134 data_Stokes (dict or list[dict]): same as `data_AntiStokes` for the Stokes peaks. 135 fit_model (AnalysisResults.FitModel, optional): The fit model used for the analysis. Defaults to None (no attribute is set). 136 137 Both `data_AntiStokes` and `data_Stokes` are optional, but at least one of them must be provided. 138 """ 139 140 ar_cls = self.__class__ 141 ar_group = sync(self._file.open_group(self._path)) 142 143 def add_quantity(qt: AnalysisResults.Quantity, pt: AnalysisResults.PeakType, data, index: int = 0): 144 # PSD_nonspectral_shape is an closure variable that is used to check the shape of the data being added, if the PSD dataset is already present in the current data group. 145 if PSD_nonspectral_shape is not None: 146 expected_shape = PSD_nonspectral_shape 147 if qt is AnalysisResults.Quantity.Cov_matrix: 148 expected_shape += (data.shape[-2], data.shape[-1]) 149 if data.shape != expected_shape: 150 raise ValueError(f"The shape of the '{qt.value}' data is {data.shape}, but it should be {expected_shape} to match the shape of the PSD.") 151 sync(self._file.create_dataset( 152 ar_group, ar_cls._get_quantity_name(qt, pt, index), data)) 153 154 def add_data_pt(pt: AnalysisResults.PeakType, data, index: int = 0): 155 if 'shift' in data: 156 add_quantity(ar_cls.Quantity.Shift, 157 pt, data['shift'], index) 158 if 'shift_units' in data: 159 self._set_units(data['shift_units'], 160 ar_cls.Quantity.Shift, pt, index) 161 if 'width' in data: 162 add_quantity(ar_cls.Quantity.Width, 163 pt, data['width'], index) 164 if 'width_units' in data: 165 self._set_units(data['width_units'], 166 ar_cls.Quantity.Width, pt, index) 167 if 'amplitude' in data: 168 add_quantity(ar_cls.Quantity.Amplitude, 169 pt, data['amplitude'], index) 170 if 'amplitude_units' in data: 171 self._set_units( 172 data['amplitude_units'], ar_cls.Quantity.Amplitude, pt, index) 173 if 'offset' in data: 174 add_quantity(ar_cls.Quantity.Offset, 175 pt, data['offset'], index) 176 if 'offset_units' in data: 177 self._set_units( 178 data['offset_units'], ar_cls.Quantity.Offset, pt, index) 179 if 'R2' in data: 180 add_quantity(ar_cls.Quantity.R2, pt, data['R2'], index) 181 if 'R2_units' in data: 182 self._set_units(data['R2_units'], 183 ar_cls.Quantity.R2, pt, index) 184 if 'RMSE' in data: 185 add_quantity(ar_cls.Quantity.RMSE, pt, data['RMSE'], index) 186 if 'RMSE_units' in data: 187 self._set_units(data['RMSE_units'], 188 ar_cls.Quantity.RMSE, pt, index) 189 if 'Cov_matrix' in data: 190 add_quantity(ar_cls.Quantity.Cov_matrix, 191 pt, data['Cov_matrix'], index) 192 if 'Cov_matrix_units' in data: 193 self._set_units( 194 data['Cov_matrix_units'], ar_cls.Quantity.Cov_matrix, pt, index) 195 196 PSD_nonspectral_shape = None 197 try: 198 PSD = sync(self._file.open_dataset(concatenate_paths( 199 self._data_group_path, brim_obj_names.data.PSD))) 200 PSD_nonspectral_shape = PSD.shape[:-1] 201 except Exception as e: 202 warnings.warn("It is recommended to add the PSD dataset before adding the analysis results, to ensure the correct shape of the analysis results data.") 203 204 if data_AntiStokes is not None: 205 data_AntiStokes = var_to_singleton(data_AntiStokes) 206 for i, d_as in enumerate(data_AntiStokes): 207 add_data_pt(ar_cls.PeakType.AntiStokes, d_as, i) 208 if data_Stokes is not None: 209 data_Stokes = var_to_singleton(data_Stokes) 210 for i, d_s in enumerate(data_Stokes): 211 add_data_pt(ar_cls.PeakType.Stokes, d_s, i) 212 if fit_model is not None: 213 sync(self._file.create_attr(ar_group, 'Fit_model', fit_model.value)) 214 215 def get_units(self, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0) -> str | None: 216 """ 217 Retrieve the units of a specified quantity from the data file. 218 219 Args: 220 qt (Quantity): The quantity for which the units are to be retrieved. 221 pt (PeakType, optional): The type of peak (e.g., Stokes or AntiStokes). Defaults to PeakType.AntiStokes. 222 index (int, optional): The index of the quantity in case multiple quantities exist. Defaults to 0. 223 224 Returns: 225 str | None: The units of the specified quantity as a string, or None if no units are defined. 226 """ 227 if qt in (AnalysisResults.Quantity.Elastic_contrast, AnalysisResults.Quantity.Viscous_contrast): 228 return None 229 dt_name = AnalysisResults._get_quantity_name(qt, pt, index) 230 full_path = concatenate_paths(self._path, dt_name) 231 return sync(units.of_object(self._file, full_path)) 232 233 def _set_units(self, un: str, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0) -> str: 234 """ 235 Set the units of a specified quantity. 236 237 Args: 238 un (str): The units to be set. 239 qt (Quantity): The quantity for which the units are to be set. 240 pt (PeakType, optional): The type of peak (e.g., Stokes or AntiStokes). Defaults to PeakType.AntiStokes. 241 index (int, optional): The index of the quantity in case multiple quantities exist. Defaults to 0. 242 243 Returns: 244 str: The units of the specified quantity as a string. 245 """ 246 if qt in (AnalysisResults.Quantity.Elastic_contrast, AnalysisResults.Quantity.Viscous_contrast): 247 raise ValueError(f"Units for {qt.name} are not settable because this quantity is computed on-the-fly.") 248 dt_name = AnalysisResults._get_quantity_name(qt, pt, index) 249 full_path = concatenate_paths(self._path, dt_name) 250 return units.add_to_object(self._file, full_path, un) 251 252 async def _compute_elastic_contrast_async(self, shift): 253 shift_arr = np.asarray(shift) 254 try: 255 md = self._get_metadata() 256 coros = [md._get_wavelength_nm_async(), md._get_temperature_c_async(), md._get_scattering_angle_deg_async()] 257 res = await asyncio.gather(*coros, return_exceptions=True) 258 wavelength_nm, temperature_c, scattering_angle_deg = res 259 if isinstance(wavelength_nm, Exception): 260 raise ValueError("Could not retrieve the wavelength for computing Elastic Contrast.") 261 if isinstance(temperature_c, Exception): 262 temperature_c = 22 # default value 263 warnings.warn("Could not retrieve the temperature for computing Elastic Contrast. Using default value of 22 °C.") 264 if isinstance(scattering_angle_deg, Exception): 265 scattering_angle_deg = 180 # default value 266 warnings.warn("Could not retrieve the scattering angle for computing Elastic Contrast. Using default value of 180 deg.") 267 water_shift = Brillouin_shift_water(wavelength_nm, temperature_c, scattering_angle_deg) 268 if np.nanmean(shift_arr) < 0: 269 water_shift = -water_shift 270 return shift_arr / water_shift - 1 271 except Exception as e: 272 raise ValueError( 273 f"Could not compute Elastic_contrast from metadata ({e}).") 274 275 async def _compute_viscous_contrast_async(self, width): 276 width_arr = np.asarray(width) 277 try: 278 md = self._get_metadata() 279 coros = [md._get_wavelength_nm_async(), md._get_temperature_c_async(), md._get_scattering_angle_deg_async()] 280 res = await asyncio.gather(*coros, return_exceptions=True) 281 wavelength_nm, temperature_c, scattering_angle_deg = res 282 if isinstance(wavelength_nm, Exception): 283 raise ValueError("Could not retrieve the wavelength for computing Viscous Contrast.") 284 if isinstance(temperature_c, Exception): 285 temperature_c = 22 # default value 286 warnings.warn("Could not retrieve the temperature for computing Viscous Contrast. Using default value of 22 °C.") 287 if isinstance(scattering_angle_deg, Exception): 288 scattering_angle_deg = 180 # default value 289 warnings.warn("Could not retrieve the scattering angle for computing Viscous Contrast. Using default value of 180 deg.") 290 water_width = Brillouin_width_water(wavelength_nm, temperature_c, scattering_angle_deg) 291 if np.nanmean(width_arr) < 0: 292 water_width = -water_width 293 return width_arr / water_width - 1 294 except Exception as e: 295 raise ValueError( 296 f"Could not compute Viscous_contrast from metadata ({e}).") 297 298 @property 299 def fit_model(self) -> 'AnalysisResults.FitModel': 300 """ 301 Retrieve the fit model used for the analysis. 302 303 Returns: 304 AnalysisResults.FitModel: The fit model used for the analysis. 305 """ 306 if not hasattr(self, '_fit_model'): 307 try: 308 fit_model_str = sync(self._file.get_attr(self._path, 'Fit_model')) 309 self._fit_model = AnalysisResults.FitModel(fit_model_str) 310 except Exception as e: 311 if isinstance(e, ValueError): 312 warnings.warn( 313 f"Unknown fit model '{fit_model_str}' found in the file.") 314 self._fit_model = AnalysisResults.FitModel.Undefined 315 return self._fit_model 316 317 def save_image_to_OMETiff(self, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0, filename: str = None) -> str: 318 """ 319 Saves the image corresponding to the specified quantity and index to an OMETiff file. 320 321 Args: 322 qt (Quantity): The quantity to retrieve the image for (e.g. shift). 323 pt (PeakType, optional): The type of peak to consider (default is PeakType.AntiStokes). 324 index (int, optional): The index of the data to retrieve, if multiple are present (default is 0). 325 filename (str, optional): The name of the file to save the image to. If None, a default name will be used. 326 327 Returns: 328 str: The path to the saved OMETiff file. 329 """ 330 try: 331 import tifffile 332 except ImportError: 333 raise ModuleNotFoundError( 334 "The tifffile module is required for saving to OME-Tiff. Please install it using 'pip install tifffile'.") 335 336 if filename is None: 337 filename = f"{qt.value}_{pt.value}_{index}.ome.tif" 338 if not filename.endswith('.ome.tif'): 339 filename += '.ome.tif' 340 img, px_size = self.get_image(qt, pt, index) 341 if img.ndim > 3: 342 raise NotImplementedError( 343 "Saving images with more than 3 dimensions is not supported yet.") 344 with tifffile.TiffWriter(filename, bigtiff=True) as tif: 345 metadata = { 346 'axes': 'ZYX', 347 'PhysicalSizeX': px_size[2].value, 348 'PhysicalSizeXUnit': px_size[2].units, 349 'PhysicalSizeY': px_size[1].value, 350 'PhysicalSizeYUnit': px_size[1].units, 351 'PhysicalSizeZ': px_size[0].value, 352 'PhysicalSizeZUnit': px_size[0].units, 353 } 354 tif.write(img, metadata=metadata) 355 return filename 356 357 def get_image(self, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0) -> tuple: 358 """ 359 Retrieves an image (spatial map) based on the specified quantity, peak type, and index. 360 361 Args: 362 qt (Quantity): The quantity to retrieve the image for (e.g. shift). 363 pt (PeakType, optional): The type of peak to consider (default is PeakType.AntiStokes). 364 index (int, optional): The index of the data to retrieve, if multiple are present (default is 0). 365 366 Returns: 367 A tuple containing the image corresponding to the specified quantity and index and the corresponding pixel size. 368 The image is a 3D dataset where the dimensions are z, y, x. 369 If there are additional parameters, more dimensions are added in the order z, y, x, par1, par2, ... 370 The pixel size is a tuple of 3 Metadata.Item in the order z, y, x. 371 372 Raises: 373 ValueError: If `pt=PeakType.average` is requested but no compatible 374 peaks are available for the selected index. 375 """ 376 if qt == AnalysisResults.Quantity.Elastic_contrast: 377 shift_img, px_size = self.get_image(AnalysisResults.Quantity.Shift, pt, index) 378 return sync(self._compute_elastic_contrast_async(shift_img)), px_size 379 if qt == AnalysisResults.Quantity.Viscous_contrast: 380 width_img, px_size = self.get_image(AnalysisResults.Quantity.Width, pt, index) 381 return sync(self._compute_viscous_contrast_async(width_img)), px_size 382 383 pt_type = AnalysisResults.PeakType 384 data = None 385 if pt == pt_type.average: 386 peaks = self.list_existing_peak_types(index) 387 match len(peaks): 388 case 0: 389 raise ValueError( 390 "No peaks found for the specified index. Cannot compute average.") 391 case 1: 392 data = np.array(sync(self._get_quantity(qt, peaks[0], index))) 393 case 2: 394 data1, data2 = _gather_sync( 395 self._get_quantity(qt, peaks[0], index), 396 self._get_quantity(qt, peaks[1], index) 397 ) 398 data = (np.abs(data1) + np.abs(data2))/2 399 else: 400 data = np.array(sync(self._get_quantity(qt, pt, index))) 401 if self._sparse: 402 sm = np.array(self._spatial_map) 403 img = data[sm, ...] 404 img[sm<0, ...] = np.nan # set invalid pixels to NaN 405 else: 406 img = data 407 return img, self._spatial_map_px_size 408 def get_quantity_at_pixel(self, coord: tuple, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0): 409 """ 410 Synchronous wrapper for `get_quantity_at_pixel_async` (see doc for `brimfile.analysis_results.AnalysisResults.get_quantity_at_pixel_async`) 411 """ 412 return sync(self.get_quantity_at_pixel_async(coord, qt, pt, index)) 413 async def get_quantity_at_pixel_async(self, coord: tuple, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0): 414 """ 415 Retrieves the specified quantity in the image at coord, based on the peak type and index. 416 417 Args: 418 coord (tuple): A tuple of 3 elements corresponding to the z, y, x coordinate in the image 419 qt (Quantity): The quantity to retrieve the image for (e.g. shift). 420 pt (PeakType, optional): The type of peak to consider (default is PeakType.AntiStokes). 421 index (int, optional): The index of the data to retrieve, if multiple peaks are present (default is 0). 422 423 Returns: 424 The requested quantity, which is a scalar or a multidimensional array (depending on whether there are additional parameters in the current Data group) 425 """ 426 if len(coord) != 3: 427 raise ValueError( 428 "'coord' must have 3 elements corresponding to z, y, x") 429 if qt == AnalysisResults.Quantity.Elastic_contrast: 430 shift_value = await self.get_quantity_at_pixel_async(coord, AnalysisResults.Quantity.Shift, pt, index) 431 return await self._compute_elastic_contrast_async(shift_value) 432 if qt == AnalysisResults.Quantity.Viscous_contrast: 433 width_value = await self.get_quantity_at_pixel_async(coord, AnalysisResults.Quantity.Width, pt, index) 434 return await self._compute_viscous_contrast_async(width_value) 435 if self._sparse: 436 i = self._spatial_map[*coord] 437 assert i.size == 1 438 if i<0: 439 return np.nan # invalid pixel 440 i = (int(i), ...) 441 else: 442 i = coord + (...,) 443 444 pt_type = AnalysisResults.PeakType 445 value = None 446 if pt == pt_type.average: 447 value = None 448 peaks = await self.list_existing_peak_types_async(index) 449 match len(peaks): 450 case 0: 451 raise ValueError( 452 "No peaks found for the specified index. Cannot compute average.") 453 case 1: 454 data = await self._get_quantity(qt, peaks[0], index) 455 value = await _async_getitem(data, i) 456 case 2: 457 data_p0, data_p1 = await asyncio.gather( 458 self._get_quantity(qt, peaks[0], index), 459 self._get_quantity(qt, peaks[1], index) 460 ) 461 value1, value2 = await asyncio.gather( 462 _async_getitem(data_p0, i), 463 _async_getitem(data_p1, i) 464 ) 465 value = (np.abs(value1) + np.abs(value2))/2 466 else: 467 data = await self._get_quantity(qt, pt, index) 468 value = await _async_getitem(data, i) 469 return value 470 def get_all_quantities_in_image(self, coor: tuple, index_peak: int = 0) -> dict: 471 """ 472 Retrieve all available quantities at a specific spatial coordinate. 473 474 Args: 475 coor (tuple): A tuple containing the z, y, x coordinates in the image. 476 index_peak (int, optional): The index of the data to retrieve, if multiple peaks are present (default is 0). 477 478 Returns: 479 dict: A dictionary of Metadata.Item in the form `result[quantity.name][peak.name] = Metadata.Item(value, units)`. 480 The dictionary contains all available quantities (e.g., Shift, Width, etc.) for both Stokes and AntiStokes peaks, 481 as well as their average values. 482 """ 483 if len(coor) != 3: 484 raise ValueError("coor must contain 3 values for z, y, x") 485 index = int(self._spatial_map[coor]) if self._sparse else coor 486 return sync(self._get_all_quantities_at_index(index, index_peak)) 487 async def _get_all_quantities_at_index(self, index: int | tuple[int, int, int], index_peak: int = 0) -> dict: 488 """ 489 Retrieve all available quantities for a specific spatial index. 490 Args: 491 index (int) | tuple[int, int, int]: The spatial index to retrieve quantities for, which can be a tuple for non-sparse data. 492 index_peak (int, optional): The index of the data to retrieve, if multiple peaks are present (default is 0). 493 Returns: 494 dict: A dictionary of Metadata.Item in the form `result[quantity.name][peak.name] = bls.Metadata.Item(value, units)` 495 """ 496 async def _get_existing_quantity_at_index_async(self, index: int | tuple[int, int, int], pt: AnalysisResults.PeakType = AnalysisResults.PeakType.AntiStokes): 497 as_cls = AnalysisResults 498 qts_ls = () 499 dts_ls = () 500 501 qts = [qt for qt in as_cls.Quantity if qt not in (as_cls.Quantity.Elastic_contrast, as_cls.Quantity.Viscous_contrast)] 502 coros = [self._file.open_dataset(concatenate_paths(self._path, as_cls._get_quantity_name(qt, pt, index_peak))) for qt in qts] 503 504 # open the datasets asynchronously, excluding those that do not exist 505 opened_dts = await asyncio.gather(*coros, return_exceptions=True) 506 for i, opened_qt in enumerate(opened_dts): 507 if not isinstance(opened_qt, Exception): 508 qts_ls += (qts[i],) 509 dts_ls += (opened_dts[i],) 510 # get the values at the specified index 511 if isinstance(index, tuple): 512 index += (..., ) 513 else: 514 index = (index, ...) 515 coros_values = [_async_getitem(dt, index) for dt in dts_ls] 516 coros_units = [units.of_object(self._file, dt) for dt in dts_ls] 517 ret_ls = await asyncio.gather(*coros_values, *coros_units) 518 n = len(coros_values) 519 value_ls = [Metadata.Item(ret_ls[i], ret_ls[n+i]) for i in range(n)] 520 return qts_ls, value_ls 521 antiStokes, stokes = await asyncio.gather( 522 _get_existing_quantity_at_index_async(self, index, AnalysisResults.PeakType.AntiStokes), 523 _get_existing_quantity_at_index_async(self, index, AnalysisResults.PeakType.Stokes) 524 ) 525 res = {} 526 # combine the results, including the average 527 for qt in (set(antiStokes[0]) | set(stokes[0])): 528 res[qt.name] = {} 529 pts = () 530 #Stokes 531 if qt in stokes[0]: 532 res[qt.name][AnalysisResults.PeakType.Stokes.name] = stokes[1][stokes[0].index(qt)] 533 pts += (AnalysisResults.PeakType.Stokes,) 534 #AntiStokes 535 if qt in antiStokes[0]: 536 res[qt.name][AnalysisResults.PeakType.AntiStokes.name] = antiStokes[1][antiStokes[0].index(qt)] 537 pts += (AnalysisResults.PeakType.AntiStokes,) 538 #average getting the units of the first peak 539 res[qt.name][AnalysisResults.PeakType.average.name] = Metadata.Item( 540 np.mean([np.abs(res[qt.name][pt.name].value) for pt in pts]), 541 res[qt.name][pts[0].name].units 542 ) 543 if not all(res[qt.name][pt.name].units == res[qt.name][pts[0].name].units for pt in pts): 544 warnings.warn(f"The units of {pts} are not consistent.") 545 546 if AnalysisResults.Quantity.Shift.name in res: 547 ec_name = AnalysisResults.Quantity.Elastic_contrast.name 548 for pt_name, item in res[AnalysisResults.Quantity.Shift.name].items(): 549 try: 550 ec = await self._compute_elastic_contrast_async(item.value) 551 res.setdefault(ec_name, {})[pt_name] = Metadata.Item(ec, None) 552 except Exception as e: 553 warnings.warn(f"Error computing elastic contrast for {pt_name}: {e}") 554 555 if AnalysisResults.Quantity.Width.name in res: 556 vc_name = AnalysisResults.Quantity.Viscous_contrast.name 557 for pt_name, item in res[AnalysisResults.Quantity.Width.name].items(): 558 try: 559 vc = await self._compute_viscous_contrast_async(item.value) 560 res.setdefault(vc_name, {})[pt_name] = Metadata.Item(vc, None) 561 except Exception as e: 562 warnings.warn(f"Error computing viscous contrast for {pt_name}: {e}") 563 return res 564 565 @classmethod 566 def _get_quantity_name(cls, qt: Quantity, pt: PeakType, index: int) -> str: 567 """ 568 Returns the name of the dataset correponding to the specific Quantity, PeakType and index 569 570 Args: 571 qt (Quantity) 572 pt (PeakType) 573 intex (int): in case of multiple peaks fitted, the index of the peak to consider 574 """ 575 if not pt in (cls.PeakType.AntiStokes, cls.PeakType.Stokes): 576 raise ValueError("pt has to be either Stokes or AntiStokes") 577 if qt in (cls.Quantity.Elastic_contrast, cls.Quantity.Viscous_contrast): 578 raise ValueError(f"{qt.value} is a computed quantity and is not stored in the file.") 579 if qt == cls.Quantity.R2 or qt == cls.Quantity.RMSE or qt == cls.Quantity.Cov_matrix: 580 name = f"Fit_error_{str(pt.value)}_{index}/{str(qt.value)}" 581 else: 582 name = f"{str(qt.value)}_{str(pt.value)}_{index}" 583 return name 584 585 async def _get_quantity(self, qt: Quantity, pt: PeakType = PeakType.AntiStokes, index: int = 0): 586 """ 587 Retrieve a specific quantity dataset from the file. 588 589 Args: 590 qt (Quantity): The type of quantity to retrieve. 591 pt (PeakType, optional): The peak type to consider (default is PeakType.AntiStokes). 592 index (int, optional): The index of the quantity if multiple peaks are available (default is 0). 593 594 Returns: 595 The dataset corresponding to the specified quantity, as stored in the file. 596 597 """ 598 599 dt_name = AnalysisResults._get_quantity_name(qt, pt, index) 600 full_path = concatenate_paths(self._path, dt_name) 601 return await self._file.open_dataset(full_path) 602 603 def list_existing_peak_types(self, index: int = 0) -> tuple: 604 """ 605 Synchronous wrapper for `list_existing_peak_types_async` (see doc for `brimfile.analysis_results.AnalysisResults.list_existing_peak_types_async`) 606 """ 607 return sync(self.list_existing_peak_types_async(index)) 608 async def list_existing_peak_types_async(self, index: int = 0) -> tuple: 609 """ 610 Returns a tuple of existing peak types (Stokes and/or AntiStokes) for the specified index. 611 Args: 612 index (int, optional): The index of the peak to check (in case of multi-peak fit). Defaults to 0. 613 Returns: 614 tuple: A tuple containing `PeakType` members (`Stokes`, `AntiStokes`) that exist for the given index. 615 """ 616 617 as_cls = AnalysisResults 618 shift_s_name = as_cls._get_quantity_name( 619 as_cls.Quantity.Shift, as_cls.PeakType.Stokes, index) 620 shift_as_name = as_cls._get_quantity_name( 621 as_cls.Quantity.Shift, as_cls.PeakType.AntiStokes, index) 622 ls = () 623 coro_as_exists = self._file.object_exists(concatenate_paths(self._path, shift_as_name)) 624 coro_s_exists = self._file.object_exists(concatenate_paths(self._path, shift_s_name)) 625 as_exists, s_exists = await asyncio.gather(coro_as_exists, coro_s_exists) 626 if as_exists: 627 ls += (as_cls.PeakType.AntiStokes,) 628 if s_exists: 629 ls += (as_cls.PeakType.Stokes,) 630 return ls 631 632 def list_existing_quantities(self, pt: PeakType = PeakType.AntiStokes, index: int = 0) -> tuple: 633 """ 634 Synchronous wrapper for `list_existing_quantities_async` (see doc for `brimfile.analysis_results.AnalysisResults.list_existing_quantities_async`) 635 """ 636 return sync(self.list_existing_quantities_async(pt, index)) 637 async def list_existing_quantities_async(self, pt: PeakType = PeakType.AntiStokes, index: int = 0) -> tuple: 638 """ 639 Returns a tuple of existing quantities for the specified index. 640 Args: 641 index (int, optional): The index of the peak to check (in case of multi-peak fit). Defaults to 0. 642 Returns: 643 tuple: A tuple containing `Quantity` members that exist for the given index. 644 """ 645 as_cls = AnalysisResults 646 ls = () 647 648 qts = [qt for qt in as_cls.Quantity if qt not in (as_cls.Quantity.Elastic_contrast, as_cls.Quantity.Viscous_contrast)] 649 coros = [self._file.object_exists(concatenate_paths(self._path, as_cls._get_quantity_name(qt, pt, index))) for qt in qts] 650 651 qt_exists = await asyncio.gather(*coros) 652 for i, exists in enumerate(qt_exists): 653 if exists: 654 ls += (qts[i],) 655 if as_cls.Quantity.Shift in ls: 656 ls += (as_cls.Quantity.Elastic_contrast,) 657 if as_cls.Quantity.Width in ls: 658 ls += (as_cls.Quantity.Viscous_contrast,) 659 return ls
Rapresents the analysis results associated with a Data object.
Inherited Members
- brimfile.analysis_results.AnalysisResults
- AnalysisResults
- Quantity
- PeakType
- FitModel
- get_name
- add_data
- get_units
- fit_model
- save_image_to_OMETiff
- get_image
- get_quantity_at_pixel
- get_quantity_at_pixel_async
- get_all_quantities_in_image
- list_existing_peak_types
- list_existing_peak_types_async
- list_existing_quantities
- list_existing_quantities_async