Skip to content

acquisition_data

acquisition_data

Interface class for acquisition data.

AcquisitionData dataclass

AcquisitionData(receive_data: list[RxData], acquisition_parameters: AcquisitionParameter, sequence: SequenceProvider | Sequence, session_path: str | Path, meta: dict[str, Any] = dict(), _additional_numpy_data: dict = dict())

Result of an acquisition: receive data, sequence, acquisition parameters and meta data.

Returned by AcquisitionControl.run. The data can be stored with save (HDF5, JSON, .seq) and exported to ISMRMRD with save_ismrmrd.

receive_data instance-attribute

receive_data: list[RxData]

Flat list of RxData objects, one per ADC event and average, ordered by average and then by ADC index ([avg0/adc0, ..., avg0/adcN, avg1/adc0, ...]). The average index of each entry is stored in RxData.average_index.

acquisition_parameters instance-attribute

acquisition_parameters: AcquisitionParameter

Acquisition parameters.

sequence instance-attribute

sequence: SequenceProvider | Sequence

Sequence object used for the acquisition acquisition.

session_path instance-attribute

session_path: str | Path

Directory the acquisition data will be stored in. Within the given storage_path a new directory with time stamp and sequence name will be created.

meta class-attribute instance-attribute

meta: dict[str, Any] = field(default_factory=dict)

Meta data dictionary for additional acquisition info. Dictionary is updated (extended) by post-init method with some general information.

save

save(user_path: str | None = None, overwrite: bool = False) -> None

Save all the acquisition data to a given data path.

Parameters:

  • user_path (str | None, default: None ) –

    Optional user path, default is None. If provided, it is taken to store the acquisition data. Other wise a datetime-based folder is created.

  • overwrite (bool, default: False ) –

    Flag which indicates whether the acquisition data should be overwritten in case it already exists from a previous call to this function, default is False.

Source code in src/console/interfaces/acquisition_data.py
def save(self, user_path: str | None = None, overwrite: bool = False) -> None:
    """Save all the acquisition data to a given data path.

    Parameters
    ----------
    user_path
        Optional user path, default is None.
        If provided, it is taken to store the acquisition data.
        Other wise a datetime-based folder is created.
    overwrite
        Flag which indicates whether the acquisition data should be overwritten
        in case it already exists from a previous call to this function, default is False.
    """
    # Add trailing slash and make dir
    base_path = Path(user_path) if user_path is not None else Path(self.session_path)
    base_path.mkdir(parents=True, exist_ok=True)
    acq_folder_path = base_path / self.meta["folder_name"]
    acq_folder_path.mkdir(parents=True, exist_ok=True)

    try:
        self._write_acquisition_data(acq_folder_path / "rx_data.h5")
    except TypeError as exc:
        log.warning("Type error when saving acquisition data to h5 format.", exc_info=exc)
    except Exception as exc:
        log.warning("Unexpected error when saving acquisition data to h5 format.", exc_info=exc)

    # Save meta data
    if not (meta_file := acq_folder_path / "meta.json").exists() or overwrite:
        with meta_file.open("w", encoding="utf-8") as outfile:
            json.dump(self.meta, outfile, indent=4, cls=JSONEncoder)

    if not (sequence_file := acq_folder_path / "sequence.seq").exists() or overwrite:
        try:
            # Write sequence .seq file
            self.sequence.write(sequence_file)
        except Exception as exc:  # noqa: BLE001 - best effort, saving must continue with remaining files
            log.warning("Could not save sequence: %s", exc)

    if len(self._additional_numpy_data) > 0:
        for key, value in self._additional_numpy_data.items():
            np.save(acq_folder_path / f"{key}.npy", value)

    log.info("Saved acquisition data to: %s", acq_folder_path)

add_info

add_info(info: dict[str, Any]) -> None

Add entries to meta data dictionary.

Parameters:

  • info (dict[str, Any]) –

    Information as dictionary to be added.

Source code in src/console/interfaces/acquisition_data.py
def add_info(self, info: dict[str, Any]) -> None:
    """Add entries to meta data dictionary.

    Parameters
    ----------
    info
        Information as dictionary to be added.
    """
    try:
        json.dumps(info, cls=JSONEncoder)
    except TypeError as exc:
        log.error("Could not append info to meta data.", exc)
    self.meta["info"].update(info)

add_data

add_data(data: dict[str, ndarray]) -> None

Add data to additional_data dictionary.

Parameters:

  • data (dict[str, ndarray]) –

    Data which is to be added to acquisition data.

Source code in src/console/interfaces/acquisition_data.py
def add_data(self, data: dict[str, np.ndarray]) -> None:
    """Add data to additional_data dictionary.

    Parameters
    ----------
    data
        Data which is to be added to acquisition data.
    """
    for key, val in data.items():
        if isinstance(key, str) and isinstance(val, np.ndarray) and hasattr(val, "shape"):
            self._additional_numpy_data.update(data)
        else:
            detail = f"Could not add `{key}` to acquisition data...\n\
                Key-value pairs of str: np.ndarray are required."
            log.error(detail)
            continue

save_ismrmrd

save_ismrmrd(header: ismrmrdHeader | str | Path | None = None, user_path: str | None = None) -> Path | None

Store acquisition data in ISMRMRD format.

The file data.mrd is written to the acquisition folder. Measurement information, experimental conditions (Larmor frequency) and acquisition system information are added to the header. PyPulseq labels of the ADC events are mapped to the ISMRMRD acquisition counters and flags.

Parameters:

  • header (ismrmrdHeader | str | Path | None, default: None ) –

    ISMRMRD header, e.g. as returned by a sequence constructor, or path to an ISMRMRD file whose XML header is used. If None, a header without encoding information is created.

  • user_path (str | None, default: None ) –

    Base directory of the output, by default the session path.

Returns:

  • Path or None –

    Path of the written MRD file, or None if the header is invalid.

Raises:

Source code in src/console/interfaces/acquisition_data.py
def save_ismrmrd(
    self,
    header: ismrmrd.xsd.ismrmrdHeader | str | Path | None = None,
    user_path: str | None = None,
) -> Path | None:
    """Store acquisition data in ISMRMRD format.

    The file ``data.mrd`` is written to the acquisition folder. Measurement information,
    experimental conditions (Larmor frequency) and acquisition system information are added to the header.
    PyPulseq labels of the ADC events are mapped to the ISMRMRD acquisition counters and flags.

    Parameters
    ----------
    header
        ISMRMRD header, e.g. as returned by a sequence constructor, or path to an ISMRMRD file
        whose XML header is used. If None, a header without encoding information is created.
    user_path
        Base directory of the output, by default the session path.

    Returns
    -------
    Path or None
        Path of the written MRD file, or None if the header is invalid.

    Raises
    ------
    AttributeError
        No processed receive data available.
    """
    # Ensure that receive data is available
    if not self.receive_data or self.receive_data[0].processed_data is None:
        detail = "Processed data not found in receive data. Cannot export ISMRMRD."
        raise AttributeError(detail)

    # Get MRD data path
    base_path = Path(user_path) if user_path else Path(self.session_path)
    base_path = base_path / self.meta["folder_name"]
    base_path.mkdir(parents=True, exist_ok=True)
    dataset_path = base_path / "data.mrd"

    # Create measurement info from meta
    info = ismrmrd.xsd.measurementInformationType(
        measurementID=self.meta["acquisition_id"],
        seriesDate=self.meta["date"],
        seriesTime=self.meta["time"],
    )
    # Get number of coils per receive event and create acquisition system info
    coils_per_rx = [
        rx_data.processed_data.shape[0] for rx_data in self.receive_data if rx_data.processed_data is not None
    ]
    system_info = get_nexus_acquisition_system(
        num_coils=max(coils_per_rx),
        larmor_frequency=int(self.acquisition_parameters.larmor_frequency),
    )
    # Define experimental conditions with true larmor frequency
    conditions = ismrmrd.xsd.experimentalConditionsType(
        H1resonanceFrequency_Hz=int(self.acquisition_parameters.larmor_frequency),
    )

    # Create header if not given
    if header is None:
        log.info("ISMRMRD header not given, creating header without encoding/reconstruction info.")
        header = ismrmrd.xsd.ismrmrdHeader()

    # Load header from xml file
    if isinstance(header, (str, Path)):
        header_path = Path(header)
        log.info("Loading ISMRMRD header from file: %s", header_path.name)
        # Open the dataset
        dataset = ismrmrd.Dataset(header_path)
        # Read the XML file and create header
        xml_header = dataset.read_xml_header()
        header = ismrmrd.xsd.CreateFromDocument(xml_header)

    # Extend header if given
    if isinstance(header, ismrmrd.xsd.ismrmrdHeader):
        # Update existing ismrmrd header with measurement info, conditions and system info
        header.measurementInformation = info
        header.experimentalConditions = conditions
        header.acquisitionSystemInformation = system_info

        return write_acquisition_to_mrd(
            data=self.receive_data,
            header=header,
            sequence=self.sequence,
            dataset_path=dataset_path,
            channel_assignment=self.acquisition_parameters.channel_assignment,
        )

    log.warning("Invalid MRD header, could not write MRD file.")
    return None