corems.mass_spectrum.input.coremsHDF5

  1import json
  2
  3from pandas import DataFrame
  4import h5py
  5from io import BytesIO
  6from s3path import S3Path
  7
  8from corems.encapsulation.input.parameter_from_json import _set_dict_data_ms
  9from corems.mass_spectrum.input.massList import ReadCoremsMasslist
 10from corems.mass_spectrum.factory.MassSpectrumClasses import MassSpecCentroid
 11from corems.encapsulation.factory.parameters import default_parameters
 12
 13
 14class ReadCoreMSHDF_MassSpectrum(ReadCoremsMasslist):
 15    """Class for reading mass spectrum data from a CoreMS HDF5 file.
 16
 17    Attributes
 18    ----------
 19    h5pydata : h5py.File
 20        The HDF5 file object.
 21    scans : list
 22        List of scan labels in the HDF5 file.
 23
 24    Parameters
 25    ----------
 26    file_location : str or S3Path
 27        The path to the CoreMS HDF5 file.
 28
 29    Methods
 30    -------
 31    * load_raw_data(mass_spectrum, scan_index=0) Load raw data into the mass spectrum object.
 32    * get_mass_spectrum(scan_number=0, time_index=-1, auto_process=True, load_settings=True, load_raw=True).Get a mass spectrum object.
 33    * load_settings(mass_spectrum, scan_index=0, time_index=-1). Load settings into the mass spectrum object.
 34    * get_dataframe(scan_index=0, time_index=-1). Get a pandas DataFrame representing the mass spectrum.
 35    * get_time_index_to_pull(scan_label, time_index). Get the time index to pull from the HDF5 file.
 36    * get_high_level_attr_data(attr_str). Get high-level attribute data from the HDF5 file.
 37    * get_scan_group_attr_data(scan_index, time_index, attr_group, attr_srt=None). Get scan group attribute data from the HDF5 file.
 38    * get_raw_data_attr_data(scan_index, attr_group, attr_str). Get raw data attribute data from the HDF5 file.
 39    * get_output_parameters(polarity, scan_index=0). Get the output parameters for the mass spectrum.
 40    """
 41
 42    def __init__(self, file_location):
 43        super().__init__(file_location)
 44
 45        if isinstance(self.file_location, S3Path):
 46            data = BytesIO(self.file_location.open("rb").read())
 47        else:
 48            data = self.file_location
 49
 50        self.h5pydata = h5py.File(data, "r")
 51
 52        self.scans = list(self.h5pydata.keys())
 53
 54    def close(self):
 55        """Close the underlying HDF5 file handle."""
 56        if self.h5pydata and self.h5pydata.id.valid:
 57            self.h5pydata.close()
 58
 59    def __enter__(self):
 60        return self
 61
 62    def __exit__(self, *args):
 63        self.close()
 64
 65    def load_raw_data(self, mass_spectrum, scan_index=0):
 66        """
 67        Load raw data into the mass spectrum object.
 68
 69        Parameters
 70        ----------
 71        mass_spectrum : MassSpecCentroid
 72            The mass spectrum object to load the raw data into.
 73        scan_index : int, optional
 74            The index of the scan to load the raw data from. Default is 0.
 75        """
 76
 77        scan_label = self.scans[scan_index]
 78
 79        # Check if the "raw_ms" dataset exists and has data
 80        if "raw_ms" in self.h5pydata[scan_label] and self.h5pydata[scan_label]["raw_ms"].shape is not None:
 81            mz_profile = self.h5pydata[scan_label]["raw_ms"][0]
 82
 83            abundance_profile = self.h5pydata[scan_label]["raw_ms"][1]
 84
 85            mass_spectrum.mz_exp_profile = mz_profile
 86
 87            mass_spectrum.abundance_profile = abundance_profile
 88
 89    def get_mass_spectrum(
 90        self,
 91        scan_number=0,
 92        time_index=-1,
 93        auto_process=True,
 94        load_settings=True,
 95        load_raw=True,
 96        load_molecular_formula=True,
 97    ):
 98        """
 99        Instantiate a mass spectrum object from the CoreMS HDF5 file.
100        Note that this always returns a centroid mass spectrum object; functionality for profile and
101        frequency mass spectra is not yet implemented.
102
103        Parameters
104        ----------
105        scan_number : int, optional
106            The index of the scan to retrieve the mass spectrum from. Default is 0.
107        time_index : int, optional
108            The index of the time point to retrieve the mass spectrum from. Default is -1.
109        auto_process : bool, optional
110            Whether to automatically process the mass spectrum. Default is True.
111        load_settings : bool, optional
112            Whether to load the settings into the mass spectrum object. Default is True.
113        load_raw : bool, optional
114            Whether to load the raw data into the mass spectrum object. Default is True.
115        load_molecular_formula : bool, optional
116            Whether to load the molecular formula into the mass spectrum object.
117            Default is True.
118
119        Returns
120        -------
121        MassSpecCentroid
122            The mass spectrum object.
123
124        Raises
125        ------
126        ValueError
127            If the CoreMS file is not valid.
128            If the mass spectrum has not been processed and load_molecular_formula is True.
129        """
130        if "mass_spectra" in self.scans[0]:
131            scan_index = self.scans.index("mass_spectra/" + str(scan_number))
132        else:
133            scan_index = self.scans.index(str(scan_number))
134        dataframe = self.get_dataframe(scan_index, time_index=time_index)
135        if dataframe["Molecular Formula"].any() and not dataframe["C"].any():
136            cols = dataframe.columns.tolist()
137            cols = cols[cols.index("Molecular Formula") + 1 :]
138            for index, row in dataframe.iterrows():
139                if row["Molecular Formula"] is not None:
140                    og_formula = row["Molecular Formula"]
141                    for col in cols:
142                        if "col" in og_formula:
143                            # get the digit after the element ("col") in the molecular formula and set it to the dataframe
144                            row[col] = int(og_formula.split(col)[1].split(" ")[0])
145
146        if not set(
147            ["H/C", "O/C", "Heteroatom Class", "Ion Type", "Is Isotopologue"]
148        ).issubset(dataframe.columns):
149            raise ValueError(
150                "%s it is not a valid CoreMS file" % str(self.file_location)
151            )
152
153        dataframe.rename(columns=self.parameters.header_translate, inplace=True)
154
155        # Cast m/z, and 'Peak Height' to float
156        dataframe["m/z"] = dataframe["m/z"].astype(float)
157        dataframe["Peak Height"] = dataframe["Peak Height"].astype(float)
158
159        polarity = dataframe["Ion Charge"].values[0]
160
161        output_parameters = self.get_output_parameters(polarity, scan_index=scan_index)
162
163        mass_spec_obj = MassSpecCentroid(
164            dataframe.to_dict(orient="list"), output_parameters, auto_process=False
165        )
166
167        if auto_process:
168            # Set the settings on the mass spectrum object to relative abuncance of 0 so all peaks get added
169            mass_spec_obj.settings.noise_threshold_method = "absolute_abundance"
170            mass_spec_obj.settings.noise_threshold_absolute_abundance = 0
171            mass_spec_obj.process_mass_spec()
172
173        if load_settings:
174            # Load settings into the mass spectrum object
175            self.load_settings(
176                mass_spec_obj, scan_index=scan_index, time_index=time_index
177            )
178
179        if load_raw:
180            self.load_raw_data(mass_spec_obj, scan_index=scan_index)
181
182        if load_molecular_formula:
183            if not auto_process:
184                raise ValueError(
185                    "Can only add molecular formula if the mass spectrum has been processed"
186                )
187            else:
188                self.add_molecular_formula(mass_spec_obj, dataframe)
189
190        return mass_spec_obj
191
192    def load_settings(self, mass_spectrum, scan_index=0, time_index=-1):
193        """
194        Load settings into the mass spectrum object.
195
196        Parameters
197        ----------
198        mass_spectrum : MassSpecCentroid
199            The mass spectrum object to load the settings into.
200        scan_index : int, optional
201            The index of the scan to load the settings from. Default is 0.
202        time_index : int, optional
203            The index of the time point to load the settings from. Default is -1.
204        """
205
206        loaded_settings = {}
207        loaded_settings["MoleculaSearch"] = self.get_scan_group_attr_data(
208            scan_index, time_index, "MoleculaSearchSetting"
209        )
210        loaded_settings["MassSpecPeak"] = self.get_scan_group_attr_data(
211            scan_index, time_index, "MassSpecPeakSetting"
212        )
213        loaded_settings["MassSpectrum"] = self.get_scan_group_attr_data(
214            scan_index, time_index, "MassSpectrumSetting"
215        )
216        loaded_settings["Transient"] = self.get_scan_group_attr_data(
217            scan_index, time_index, "TransientSetting"
218        )
219
220        _set_dict_data_ms(loaded_settings, mass_spectrum)
221
222    def get_dataframe(self, scan_index=0, time_index=-1):
223        """
224        Get a pandas DataFrame representing the mass spectrum.
225
226        Parameters
227        ----------
228        scan_index : int, optional
229            The index of the scan to retrieve the DataFrame from. Default is 0.
230        time_index : int, optional
231            The index of the time point to retrieve the DataFrame from. Default is -1.
232
233        Returns
234        -------
235        DataFrame
236            The pandas DataFrame representing the mass spectrum.
237        """
238
239        columnsLabels = self.get_scan_group_attr_data(
240            scan_index, time_index, "ColumnsLabels"
241        )
242
243        scan_label = self.scans[scan_index]
244
245        index_to_pull = self.get_time_index_to_pull(scan_label, time_index)
246
247        corems_table_data = self.h5pydata[scan_label][index_to_pull]
248
249        list_dict = []
250        for row in corems_table_data:
251            data_dict = {}
252            for data_index, data in enumerate(row):
253                label = columnsLabels[data_index]
254                # if data starts with a b' it is a byte string, so decode it
255                if isinstance(data, bytes):
256                    data = data.decode("utf-8")
257                if data == "nan":
258                    data = None
259                data_dict[label] = data
260
261            list_dict.append(data_dict)
262
263        # Reorder the columns from low to high "Index" to match the order of the dataframe
264        df = DataFrame(list_dict)
265        # set the "Index" column to int so it sorts correctly
266        df["Index"] = df["Index"].astype(int)
267        df = df.sort_values(by="Index")
268        # Reset index to match the "Index" column
269        df = df.set_index("Index", drop=False)
270
271        return df
272
273    def get_time_index_to_pull(self, scan_label, time_index):
274        """
275        Get the time index to pull from the HDF5 file.
276
277        Parameters
278        ----------
279        scan_label : str
280            The label of the scan.
281        time_index : int
282            The index of the time point.
283
284        Returns
285        -------
286        str
287            The time index to pull.
288        """
289
290        time_data = sorted(
291            [(i, int(i)) for i in self.h5pydata[scan_label].keys() if i != "raw_ms"],
292            key=lambda m: m[1],
293        )
294
295        index_to_pull = time_data[time_index][0]
296
297        return index_to_pull
298
299    def get_high_level_attr_data(self, attr_str):
300        """
301        Get high-level attribute data from the HDF5 file.
302
303        Parameters
304        ----------
305        attr_str : str
306            The attribute string.
307
308        Returns
309        -------
310        dict
311            The attribute data.
312
313        Raises
314        ------
315        KeyError
316            If the attribute string is not found in the HDF5 file.
317        """
318
319        return self.h5pydata.attrs[attr_str]
320
321    def get_scan_group_attr_data(
322        self, scan_index, time_index, attr_group, attr_srt=None
323    ):
324        """
325        Get scan group attribute data from the HDF5 file.
326
327        Parameters
328        ----------
329        scan_index : int
330            The index of the scan.
331        time_index : int
332            The index of the time point.
333        attr_group : str
334            The attribute group.
335        attr_srt : str, optional
336            The attribute string. Default is None.
337
338        Returns
339        -------
340        dict
341            The attribute data.
342
343        Notes
344        -----
345        This method retrieves attribute data from the HDF5 file for a specific scan and time point.
346        The attribute data is stored in the specified attribute group.
347        If an attribute string is provided, only the corresponding attribute value is returned.
348        If no attribute string is provided, all attribute data in the group is returned as a dictionary.
349        """
350        # Get index of self.scans where scan_index_str is found
351        scan_label = self.scans[scan_index]
352
353        index_to_pull = self.get_time_index_to_pull(scan_label, time_index)
354
355        if attr_srt:
356            return json.loads(
357                self.h5pydata[scan_label][index_to_pull].attrs[attr_group]
358            )[attr_srt]
359
360        else:
361            data = self.h5pydata[scan_label][index_to_pull].attrs.get(attr_group)
362            if data:
363                return json.loads(data)
364            else:
365                return {}
366
367    def get_raw_data_attr_data(self, scan_index, attr_group, attr_str):
368        """
369        Get raw data attribute data from the HDF5 file.
370
371        Parameters
372        ----------
373        scan_index : int
374            The index of the scan.
375        attr_group : str
376            The attribute group.
377        attr_str : str
378            The attribute string.
379
380        Returns
381        -------
382        dict
383            The attribute data.
384
385        Raises
386        ------
387        KeyError
388            If the attribute string is not found in the attribute group.
389
390        Notes
391        -----
392        This method retrieves the attribute data associated with a specific scan, attribute group, and attribute string
393        from the HDF5 file. It returns the attribute data as a dictionary.
394
395        Example usage:
396        >>> data = get_raw_data_attr_data(0, "group1", "attribute1")
397        >>> print(data)
398        {'key1': 'value1', 'key2': 'value2'}
399        """
400        scan_label = self.scans[scan_index]
401        
402        # First try to get from raw_ms dataset attributes (backward compatibility)
403        if "raw_ms" in self.h5pydata[scan_label] and attr_group in self.h5pydata[scan_label]["raw_ms"].attrs:
404            try:
405                return json.loads(self.h5pydata[scan_label]["raw_ms"].attrs[attr_group])[attr_str]
406            except KeyError:
407                attr_str = attr_str.replace("baseline", "baselise")
408                return json.loads(self.h5pydata[scan_label]["raw_ms"].attrs[attr_group])[attr_str]
409        
410        # If not found in raw_ms, try to get from scan group attributes (new format)
411        elif attr_group in self.h5pydata[scan_label].attrs:
412            try:
413                return json.loads(self.h5pydata[scan_label].attrs[attr_group])[attr_str]
414            except KeyError:
415                attr_str = attr_str.replace("baseline", "baselise")
416                return json.loads(self.h5pydata[scan_label].attrs[attr_group])[attr_str]
417        
418        else:
419            raise KeyError(f"Attribute group '{attr_group}' not found in either raw_ms dataset or scan group for scan {scan_label}")
420
421    def get_output_parameters(self, polarity, scan_index=0):
422        """
423        Get the output parameters for the mass spectrum.
424
425        Parameters
426        ----------
427        polarity : str
428            The polarity of the mass spectrum.
429        scan_index : int, optional
430            The index of the scan. Default is 0.
431
432        Returns
433        -------
434        dict
435            The output parameters.
436        """
437
438        d_params = default_parameters(self.file_location)
439        d_params["filename_path"] = self.file_location
440        d_params["polarity"] = self.get_raw_data_attr_data(
441            scan_index, "MassSpecAttrs", "polarity"
442        )
443        d_params["rt"] = self.get_raw_data_attr_data(scan_index, "MassSpecAttrs", "rt")
444
445        d_params["tic"] = self.get_raw_data_attr_data(
446            scan_index, "MassSpecAttrs", "tic"
447        )
448
449        d_params["mobility_scan"] = self.get_raw_data_attr_data(
450            scan_index, "MassSpecAttrs", "mobility_scan"
451        )
452        d_params["mobility_rt"] = self.get_raw_data_attr_data(
453            scan_index, "MassSpecAttrs", "mobility_rt"
454        )
455        d_params["Aterm"] = self.get_raw_data_attr_data(
456            scan_index, "MassSpecAttrs", "Aterm"
457        )
458        d_params["Bterm"] = self.get_raw_data_attr_data(
459            scan_index, "MassSpecAttrs", "Bterm"
460        )
461        d_params["Cterm"] = self.get_raw_data_attr_data(
462            scan_index, "MassSpecAttrs", "Cterm"
463        )
464        d_params["baseline_noise"] = self.get_raw_data_attr_data(
465            scan_index, "MassSpecAttrs", "baseline_noise"
466        )
467        d_params["baseline_noise_std"] = self.get_raw_data_attr_data(
468            scan_index, "MassSpecAttrs", "baseline_noise_std"
469        )
470
471        d_params["analyzer"] = self.get_high_level_attr_data("analyzer")
472        d_params["instrument_label"] = self.get_high_level_attr_data("instrument_label")
473        d_params["sample_name"] = self.get_high_level_attr_data("sample_name")
474
475        return d_params
class ReadCoreMSHDF_MassSpectrum(corems.mass_spectrum.input.massList.ReadCoremsMasslist):
 15class ReadCoreMSHDF_MassSpectrum(ReadCoremsMasslist):
 16    """Class for reading mass spectrum data from a CoreMS HDF5 file.
 17
 18    Attributes
 19    ----------
 20    h5pydata : h5py.File
 21        The HDF5 file object.
 22    scans : list
 23        List of scan labels in the HDF5 file.
 24
 25    Parameters
 26    ----------
 27    file_location : str or S3Path
 28        The path to the CoreMS HDF5 file.
 29
 30    Methods
 31    -------
 32    * load_raw_data(mass_spectrum, scan_index=0) Load raw data into the mass spectrum object.
 33    * get_mass_spectrum(scan_number=0, time_index=-1, auto_process=True, load_settings=True, load_raw=True).Get a mass spectrum object.
 34    * load_settings(mass_spectrum, scan_index=0, time_index=-1). Load settings into the mass spectrum object.
 35    * get_dataframe(scan_index=0, time_index=-1). Get a pandas DataFrame representing the mass spectrum.
 36    * get_time_index_to_pull(scan_label, time_index). Get the time index to pull from the HDF5 file.
 37    * get_high_level_attr_data(attr_str). Get high-level attribute data from the HDF5 file.
 38    * get_scan_group_attr_data(scan_index, time_index, attr_group, attr_srt=None). Get scan group attribute data from the HDF5 file.
 39    * get_raw_data_attr_data(scan_index, attr_group, attr_str). Get raw data attribute data from the HDF5 file.
 40    * get_output_parameters(polarity, scan_index=0). Get the output parameters for the mass spectrum.
 41    """
 42
 43    def __init__(self, file_location):
 44        super().__init__(file_location)
 45
 46        if isinstance(self.file_location, S3Path):
 47            data = BytesIO(self.file_location.open("rb").read())
 48        else:
 49            data = self.file_location
 50
 51        self.h5pydata = h5py.File(data, "r")
 52
 53        self.scans = list(self.h5pydata.keys())
 54
 55    def close(self):
 56        """Close the underlying HDF5 file handle."""
 57        if self.h5pydata and self.h5pydata.id.valid:
 58            self.h5pydata.close()
 59
 60    def __enter__(self):
 61        return self
 62
 63    def __exit__(self, *args):
 64        self.close()
 65
 66    def load_raw_data(self, mass_spectrum, scan_index=0):
 67        """
 68        Load raw data into the mass spectrum object.
 69
 70        Parameters
 71        ----------
 72        mass_spectrum : MassSpecCentroid
 73            The mass spectrum object to load the raw data into.
 74        scan_index : int, optional
 75            The index of the scan to load the raw data from. Default is 0.
 76        """
 77
 78        scan_label = self.scans[scan_index]
 79
 80        # Check if the "raw_ms" dataset exists and has data
 81        if "raw_ms" in self.h5pydata[scan_label] and self.h5pydata[scan_label]["raw_ms"].shape is not None:
 82            mz_profile = self.h5pydata[scan_label]["raw_ms"][0]
 83
 84            abundance_profile = self.h5pydata[scan_label]["raw_ms"][1]
 85
 86            mass_spectrum.mz_exp_profile = mz_profile
 87
 88            mass_spectrum.abundance_profile = abundance_profile
 89
 90    def get_mass_spectrum(
 91        self,
 92        scan_number=0,
 93        time_index=-1,
 94        auto_process=True,
 95        load_settings=True,
 96        load_raw=True,
 97        load_molecular_formula=True,
 98    ):
 99        """
100        Instantiate a mass spectrum object from the CoreMS HDF5 file.
101        Note that this always returns a centroid mass spectrum object; functionality for profile and
102        frequency mass spectra is not yet implemented.
103
104        Parameters
105        ----------
106        scan_number : int, optional
107            The index of the scan to retrieve the mass spectrum from. Default is 0.
108        time_index : int, optional
109            The index of the time point to retrieve the mass spectrum from. Default is -1.
110        auto_process : bool, optional
111            Whether to automatically process the mass spectrum. Default is True.
112        load_settings : bool, optional
113            Whether to load the settings into the mass spectrum object. Default is True.
114        load_raw : bool, optional
115            Whether to load the raw data into the mass spectrum object. Default is True.
116        load_molecular_formula : bool, optional
117            Whether to load the molecular formula into the mass spectrum object.
118            Default is True.
119
120        Returns
121        -------
122        MassSpecCentroid
123            The mass spectrum object.
124
125        Raises
126        ------
127        ValueError
128            If the CoreMS file is not valid.
129            If the mass spectrum has not been processed and load_molecular_formula is True.
130        """
131        if "mass_spectra" in self.scans[0]:
132            scan_index = self.scans.index("mass_spectra/" + str(scan_number))
133        else:
134            scan_index = self.scans.index(str(scan_number))
135        dataframe = self.get_dataframe(scan_index, time_index=time_index)
136        if dataframe["Molecular Formula"].any() and not dataframe["C"].any():
137            cols = dataframe.columns.tolist()
138            cols = cols[cols.index("Molecular Formula") + 1 :]
139            for index, row in dataframe.iterrows():
140                if row["Molecular Formula"] is not None:
141                    og_formula = row["Molecular Formula"]
142                    for col in cols:
143                        if "col" in og_formula:
144                            # get the digit after the element ("col") in the molecular formula and set it to the dataframe
145                            row[col] = int(og_formula.split(col)[1].split(" ")[0])
146
147        if not set(
148            ["H/C", "O/C", "Heteroatom Class", "Ion Type", "Is Isotopologue"]
149        ).issubset(dataframe.columns):
150            raise ValueError(
151                "%s it is not a valid CoreMS file" % str(self.file_location)
152            )
153
154        dataframe.rename(columns=self.parameters.header_translate, inplace=True)
155
156        # Cast m/z, and 'Peak Height' to float
157        dataframe["m/z"] = dataframe["m/z"].astype(float)
158        dataframe["Peak Height"] = dataframe["Peak Height"].astype(float)
159
160        polarity = dataframe["Ion Charge"].values[0]
161
162        output_parameters = self.get_output_parameters(polarity, scan_index=scan_index)
163
164        mass_spec_obj = MassSpecCentroid(
165            dataframe.to_dict(orient="list"), output_parameters, auto_process=False
166        )
167
168        if auto_process:
169            # Set the settings on the mass spectrum object to relative abuncance of 0 so all peaks get added
170            mass_spec_obj.settings.noise_threshold_method = "absolute_abundance"
171            mass_spec_obj.settings.noise_threshold_absolute_abundance = 0
172            mass_spec_obj.process_mass_spec()
173
174        if load_settings:
175            # Load settings into the mass spectrum object
176            self.load_settings(
177                mass_spec_obj, scan_index=scan_index, time_index=time_index
178            )
179
180        if load_raw:
181            self.load_raw_data(mass_spec_obj, scan_index=scan_index)
182
183        if load_molecular_formula:
184            if not auto_process:
185                raise ValueError(
186                    "Can only add molecular formula if the mass spectrum has been processed"
187                )
188            else:
189                self.add_molecular_formula(mass_spec_obj, dataframe)
190
191        return mass_spec_obj
192
193    def load_settings(self, mass_spectrum, scan_index=0, time_index=-1):
194        """
195        Load settings into the mass spectrum object.
196
197        Parameters
198        ----------
199        mass_spectrum : MassSpecCentroid
200            The mass spectrum object to load the settings into.
201        scan_index : int, optional
202            The index of the scan to load the settings from. Default is 0.
203        time_index : int, optional
204            The index of the time point to load the settings from. Default is -1.
205        """
206
207        loaded_settings = {}
208        loaded_settings["MoleculaSearch"] = self.get_scan_group_attr_data(
209            scan_index, time_index, "MoleculaSearchSetting"
210        )
211        loaded_settings["MassSpecPeak"] = self.get_scan_group_attr_data(
212            scan_index, time_index, "MassSpecPeakSetting"
213        )
214        loaded_settings["MassSpectrum"] = self.get_scan_group_attr_data(
215            scan_index, time_index, "MassSpectrumSetting"
216        )
217        loaded_settings["Transient"] = self.get_scan_group_attr_data(
218            scan_index, time_index, "TransientSetting"
219        )
220
221        _set_dict_data_ms(loaded_settings, mass_spectrum)
222
223    def get_dataframe(self, scan_index=0, time_index=-1):
224        """
225        Get a pandas DataFrame representing the mass spectrum.
226
227        Parameters
228        ----------
229        scan_index : int, optional
230            The index of the scan to retrieve the DataFrame from. Default is 0.
231        time_index : int, optional
232            The index of the time point to retrieve the DataFrame from. Default is -1.
233
234        Returns
235        -------
236        DataFrame
237            The pandas DataFrame representing the mass spectrum.
238        """
239
240        columnsLabels = self.get_scan_group_attr_data(
241            scan_index, time_index, "ColumnsLabels"
242        )
243
244        scan_label = self.scans[scan_index]
245
246        index_to_pull = self.get_time_index_to_pull(scan_label, time_index)
247
248        corems_table_data = self.h5pydata[scan_label][index_to_pull]
249
250        list_dict = []
251        for row in corems_table_data:
252            data_dict = {}
253            for data_index, data in enumerate(row):
254                label = columnsLabels[data_index]
255                # if data starts with a b' it is a byte string, so decode it
256                if isinstance(data, bytes):
257                    data = data.decode("utf-8")
258                if data == "nan":
259                    data = None
260                data_dict[label] = data
261
262            list_dict.append(data_dict)
263
264        # Reorder the columns from low to high "Index" to match the order of the dataframe
265        df = DataFrame(list_dict)
266        # set the "Index" column to int so it sorts correctly
267        df["Index"] = df["Index"].astype(int)
268        df = df.sort_values(by="Index")
269        # Reset index to match the "Index" column
270        df = df.set_index("Index", drop=False)
271
272        return df
273
274    def get_time_index_to_pull(self, scan_label, time_index):
275        """
276        Get the time index to pull from the HDF5 file.
277
278        Parameters
279        ----------
280        scan_label : str
281            The label of the scan.
282        time_index : int
283            The index of the time point.
284
285        Returns
286        -------
287        str
288            The time index to pull.
289        """
290
291        time_data = sorted(
292            [(i, int(i)) for i in self.h5pydata[scan_label].keys() if i != "raw_ms"],
293            key=lambda m: m[1],
294        )
295
296        index_to_pull = time_data[time_index][0]
297
298        return index_to_pull
299
300    def get_high_level_attr_data(self, attr_str):
301        """
302        Get high-level attribute data from the HDF5 file.
303
304        Parameters
305        ----------
306        attr_str : str
307            The attribute string.
308
309        Returns
310        -------
311        dict
312            The attribute data.
313
314        Raises
315        ------
316        KeyError
317            If the attribute string is not found in the HDF5 file.
318        """
319
320        return self.h5pydata.attrs[attr_str]
321
322    def get_scan_group_attr_data(
323        self, scan_index, time_index, attr_group, attr_srt=None
324    ):
325        """
326        Get scan group attribute data from the HDF5 file.
327
328        Parameters
329        ----------
330        scan_index : int
331            The index of the scan.
332        time_index : int
333            The index of the time point.
334        attr_group : str
335            The attribute group.
336        attr_srt : str, optional
337            The attribute string. Default is None.
338
339        Returns
340        -------
341        dict
342            The attribute data.
343
344        Notes
345        -----
346        This method retrieves attribute data from the HDF5 file for a specific scan and time point.
347        The attribute data is stored in the specified attribute group.
348        If an attribute string is provided, only the corresponding attribute value is returned.
349        If no attribute string is provided, all attribute data in the group is returned as a dictionary.
350        """
351        # Get index of self.scans where scan_index_str is found
352        scan_label = self.scans[scan_index]
353
354        index_to_pull = self.get_time_index_to_pull(scan_label, time_index)
355
356        if attr_srt:
357            return json.loads(
358                self.h5pydata[scan_label][index_to_pull].attrs[attr_group]
359            )[attr_srt]
360
361        else:
362            data = self.h5pydata[scan_label][index_to_pull].attrs.get(attr_group)
363            if data:
364                return json.loads(data)
365            else:
366                return {}
367
368    def get_raw_data_attr_data(self, scan_index, attr_group, attr_str):
369        """
370        Get raw data attribute data from the HDF5 file.
371
372        Parameters
373        ----------
374        scan_index : int
375            The index of the scan.
376        attr_group : str
377            The attribute group.
378        attr_str : str
379            The attribute string.
380
381        Returns
382        -------
383        dict
384            The attribute data.
385
386        Raises
387        ------
388        KeyError
389            If the attribute string is not found in the attribute group.
390
391        Notes
392        -----
393        This method retrieves the attribute data associated with a specific scan, attribute group, and attribute string
394        from the HDF5 file. It returns the attribute data as a dictionary.
395
396        Example usage:
397        >>> data = get_raw_data_attr_data(0, "group1", "attribute1")
398        >>> print(data)
399        {'key1': 'value1', 'key2': 'value2'}
400        """
401        scan_label = self.scans[scan_index]
402        
403        # First try to get from raw_ms dataset attributes (backward compatibility)
404        if "raw_ms" in self.h5pydata[scan_label] and attr_group in self.h5pydata[scan_label]["raw_ms"].attrs:
405            try:
406                return json.loads(self.h5pydata[scan_label]["raw_ms"].attrs[attr_group])[attr_str]
407            except KeyError:
408                attr_str = attr_str.replace("baseline", "baselise")
409                return json.loads(self.h5pydata[scan_label]["raw_ms"].attrs[attr_group])[attr_str]
410        
411        # If not found in raw_ms, try to get from scan group attributes (new format)
412        elif attr_group in self.h5pydata[scan_label].attrs:
413            try:
414                return json.loads(self.h5pydata[scan_label].attrs[attr_group])[attr_str]
415            except KeyError:
416                attr_str = attr_str.replace("baseline", "baselise")
417                return json.loads(self.h5pydata[scan_label].attrs[attr_group])[attr_str]
418        
419        else:
420            raise KeyError(f"Attribute group '{attr_group}' not found in either raw_ms dataset or scan group for scan {scan_label}")
421
422    def get_output_parameters(self, polarity, scan_index=0):
423        """
424        Get the output parameters for the mass spectrum.
425
426        Parameters
427        ----------
428        polarity : str
429            The polarity of the mass spectrum.
430        scan_index : int, optional
431            The index of the scan. Default is 0.
432
433        Returns
434        -------
435        dict
436            The output parameters.
437        """
438
439        d_params = default_parameters(self.file_location)
440        d_params["filename_path"] = self.file_location
441        d_params["polarity"] = self.get_raw_data_attr_data(
442            scan_index, "MassSpecAttrs", "polarity"
443        )
444        d_params["rt"] = self.get_raw_data_attr_data(scan_index, "MassSpecAttrs", "rt")
445
446        d_params["tic"] = self.get_raw_data_attr_data(
447            scan_index, "MassSpecAttrs", "tic"
448        )
449
450        d_params["mobility_scan"] = self.get_raw_data_attr_data(
451            scan_index, "MassSpecAttrs", "mobility_scan"
452        )
453        d_params["mobility_rt"] = self.get_raw_data_attr_data(
454            scan_index, "MassSpecAttrs", "mobility_rt"
455        )
456        d_params["Aterm"] = self.get_raw_data_attr_data(
457            scan_index, "MassSpecAttrs", "Aterm"
458        )
459        d_params["Bterm"] = self.get_raw_data_attr_data(
460            scan_index, "MassSpecAttrs", "Bterm"
461        )
462        d_params["Cterm"] = self.get_raw_data_attr_data(
463            scan_index, "MassSpecAttrs", "Cterm"
464        )
465        d_params["baseline_noise"] = self.get_raw_data_attr_data(
466            scan_index, "MassSpecAttrs", "baseline_noise"
467        )
468        d_params["baseline_noise_std"] = self.get_raw_data_attr_data(
469            scan_index, "MassSpecAttrs", "baseline_noise_std"
470        )
471
472        d_params["analyzer"] = self.get_high_level_attr_data("analyzer")
473        d_params["instrument_label"] = self.get_high_level_attr_data("instrument_label")
474        d_params["sample_name"] = self.get_high_level_attr_data("sample_name")
475
476        return d_params

Class for reading mass spectrum data from a CoreMS HDF5 file.

Attributes
  • h5pydata (h5py.File): The HDF5 file object.
  • scans (list): List of scan labels in the HDF5 file.
Parameters
  • file_location (str or S3Path): The path to the CoreMS HDF5 file.
Methods
  • load_raw_data(mass_spectrum, scan_index=0) Load raw data into the mass spectrum object.
  • get_mass_spectrum(scan_number=0, time_index=-1, auto_process=True, load_settings=True, load_raw=True).Get a mass spectrum object.
  • load_settings(mass_spectrum, scan_index=0, time_index=-1). Load settings into the mass spectrum object.
  • get_dataframe(scan_index=0, time_index=-1). Get a pandas DataFrame representing the mass spectrum.
  • get_time_index_to_pull(scan_label, time_index). Get the time index to pull from the HDF5 file.
  • get_high_level_attr_data(attr_str). Get high-level attribute data from the HDF5 file.
  • get_scan_group_attr_data(scan_index, time_index, attr_group, attr_srt=None). Get scan group attribute data from the HDF5 file.
  • get_raw_data_attr_data(scan_index, attr_group, attr_str). Get raw data attribute data from the HDF5 file.
  • get_output_parameters(polarity, scan_index=0). Get the output parameters for the mass spectrum.
ReadCoreMSHDF_MassSpectrum(file_location)
43    def __init__(self, file_location):
44        super().__init__(file_location)
45
46        if isinstance(self.file_location, S3Path):
47            data = BytesIO(self.file_location.open("rb").read())
48        else:
49            data = self.file_location
50
51        self.h5pydata = h5py.File(data, "r")
52
53        self.scans = list(self.h5pydata.keys())
h5pydata
scans
def close(self):
55    def close(self):
56        """Close the underlying HDF5 file handle."""
57        if self.h5pydata and self.h5pydata.id.valid:
58            self.h5pydata.close()

Close the underlying HDF5 file handle.

def load_raw_data(self, mass_spectrum, scan_index=0):
66    def load_raw_data(self, mass_spectrum, scan_index=0):
67        """
68        Load raw data into the mass spectrum object.
69
70        Parameters
71        ----------
72        mass_spectrum : MassSpecCentroid
73            The mass spectrum object to load the raw data into.
74        scan_index : int, optional
75            The index of the scan to load the raw data from. Default is 0.
76        """
77
78        scan_label = self.scans[scan_index]
79
80        # Check if the "raw_ms" dataset exists and has data
81        if "raw_ms" in self.h5pydata[scan_label] and self.h5pydata[scan_label]["raw_ms"].shape is not None:
82            mz_profile = self.h5pydata[scan_label]["raw_ms"][0]
83
84            abundance_profile = self.h5pydata[scan_label]["raw_ms"][1]
85
86            mass_spectrum.mz_exp_profile = mz_profile
87
88            mass_spectrum.abundance_profile = abundance_profile

Load raw data into the mass spectrum object.

Parameters
  • mass_spectrum (MassSpecCentroid): The mass spectrum object to load the raw data into.
  • scan_index (int, optional): The index of the scan to load the raw data from. Default is 0.
def get_mass_spectrum( self, scan_number=0, time_index=-1, auto_process=True, load_settings=True, load_raw=True, load_molecular_formula=True):
 90    def get_mass_spectrum(
 91        self,
 92        scan_number=0,
 93        time_index=-1,
 94        auto_process=True,
 95        load_settings=True,
 96        load_raw=True,
 97        load_molecular_formula=True,
 98    ):
 99        """
100        Instantiate a mass spectrum object from the CoreMS HDF5 file.
101        Note that this always returns a centroid mass spectrum object; functionality for profile and
102        frequency mass spectra is not yet implemented.
103
104        Parameters
105        ----------
106        scan_number : int, optional
107            The index of the scan to retrieve the mass spectrum from. Default is 0.
108        time_index : int, optional
109            The index of the time point to retrieve the mass spectrum from. Default is -1.
110        auto_process : bool, optional
111            Whether to automatically process the mass spectrum. Default is True.
112        load_settings : bool, optional
113            Whether to load the settings into the mass spectrum object. Default is True.
114        load_raw : bool, optional
115            Whether to load the raw data into the mass spectrum object. Default is True.
116        load_molecular_formula : bool, optional
117            Whether to load the molecular formula into the mass spectrum object.
118            Default is True.
119
120        Returns
121        -------
122        MassSpecCentroid
123            The mass spectrum object.
124
125        Raises
126        ------
127        ValueError
128            If the CoreMS file is not valid.
129            If the mass spectrum has not been processed and load_molecular_formula is True.
130        """
131        if "mass_spectra" in self.scans[0]:
132            scan_index = self.scans.index("mass_spectra/" + str(scan_number))
133        else:
134            scan_index = self.scans.index(str(scan_number))
135        dataframe = self.get_dataframe(scan_index, time_index=time_index)
136        if dataframe["Molecular Formula"].any() and not dataframe["C"].any():
137            cols = dataframe.columns.tolist()
138            cols = cols[cols.index("Molecular Formula") + 1 :]
139            for index, row in dataframe.iterrows():
140                if row["Molecular Formula"] is not None:
141                    og_formula = row["Molecular Formula"]
142                    for col in cols:
143                        if "col" in og_formula:
144                            # get the digit after the element ("col") in the molecular formula and set it to the dataframe
145                            row[col] = int(og_formula.split(col)[1].split(" ")[0])
146
147        if not set(
148            ["H/C", "O/C", "Heteroatom Class", "Ion Type", "Is Isotopologue"]
149        ).issubset(dataframe.columns):
150            raise ValueError(
151                "%s it is not a valid CoreMS file" % str(self.file_location)
152            )
153
154        dataframe.rename(columns=self.parameters.header_translate, inplace=True)
155
156        # Cast m/z, and 'Peak Height' to float
157        dataframe["m/z"] = dataframe["m/z"].astype(float)
158        dataframe["Peak Height"] = dataframe["Peak Height"].astype(float)
159
160        polarity = dataframe["Ion Charge"].values[0]
161
162        output_parameters = self.get_output_parameters(polarity, scan_index=scan_index)
163
164        mass_spec_obj = MassSpecCentroid(
165            dataframe.to_dict(orient="list"), output_parameters, auto_process=False
166        )
167
168        if auto_process:
169            # Set the settings on the mass spectrum object to relative abuncance of 0 so all peaks get added
170            mass_spec_obj.settings.noise_threshold_method = "absolute_abundance"
171            mass_spec_obj.settings.noise_threshold_absolute_abundance = 0
172            mass_spec_obj.process_mass_spec()
173
174        if load_settings:
175            # Load settings into the mass spectrum object
176            self.load_settings(
177                mass_spec_obj, scan_index=scan_index, time_index=time_index
178            )
179
180        if load_raw:
181            self.load_raw_data(mass_spec_obj, scan_index=scan_index)
182
183        if load_molecular_formula:
184            if not auto_process:
185                raise ValueError(
186                    "Can only add molecular formula if the mass spectrum has been processed"
187                )
188            else:
189                self.add_molecular_formula(mass_spec_obj, dataframe)
190
191        return mass_spec_obj

Instantiate a mass spectrum object from the CoreMS HDF5 file. Note that this always returns a centroid mass spectrum object; functionality for profile and frequency mass spectra is not yet implemented.

Parameters
  • scan_number (int, optional): The index of the scan to retrieve the mass spectrum from. Default is 0.
  • time_index (int, optional): The index of the time point to retrieve the mass spectrum from. Default is -1.
  • auto_process (bool, optional): Whether to automatically process the mass spectrum. Default is True.
  • load_settings (bool, optional): Whether to load the settings into the mass spectrum object. Default is True.
  • load_raw (bool, optional): Whether to load the raw data into the mass spectrum object. Default is True.
  • load_molecular_formula (bool, optional): Whether to load the molecular formula into the mass spectrum object. Default is True.
Returns
  • MassSpecCentroid: The mass spectrum object.
Raises
  • ValueError: If the CoreMS file is not valid. If the mass spectrum has not been processed and load_molecular_formula is True.
def load_settings(self, mass_spectrum, scan_index=0, time_index=-1):
193    def load_settings(self, mass_spectrum, scan_index=0, time_index=-1):
194        """
195        Load settings into the mass spectrum object.
196
197        Parameters
198        ----------
199        mass_spectrum : MassSpecCentroid
200            The mass spectrum object to load the settings into.
201        scan_index : int, optional
202            The index of the scan to load the settings from. Default is 0.
203        time_index : int, optional
204            The index of the time point to load the settings from. Default is -1.
205        """
206
207        loaded_settings = {}
208        loaded_settings["MoleculaSearch"] = self.get_scan_group_attr_data(
209            scan_index, time_index, "MoleculaSearchSetting"
210        )
211        loaded_settings["MassSpecPeak"] = self.get_scan_group_attr_data(
212            scan_index, time_index, "MassSpecPeakSetting"
213        )
214        loaded_settings["MassSpectrum"] = self.get_scan_group_attr_data(
215            scan_index, time_index, "MassSpectrumSetting"
216        )
217        loaded_settings["Transient"] = self.get_scan_group_attr_data(
218            scan_index, time_index, "TransientSetting"
219        )
220
221        _set_dict_data_ms(loaded_settings, mass_spectrum)

Load settings into the mass spectrum object.

Parameters
  • mass_spectrum (MassSpecCentroid): The mass spectrum object to load the settings into.
  • scan_index (int, optional): The index of the scan to load the settings from. Default is 0.
  • time_index (int, optional): The index of the time point to load the settings from. Default is -1.
def get_dataframe(self, scan_index=0, time_index=-1):
223    def get_dataframe(self, scan_index=0, time_index=-1):
224        """
225        Get a pandas DataFrame representing the mass spectrum.
226
227        Parameters
228        ----------
229        scan_index : int, optional
230            The index of the scan to retrieve the DataFrame from. Default is 0.
231        time_index : int, optional
232            The index of the time point to retrieve the DataFrame from. Default is -1.
233
234        Returns
235        -------
236        DataFrame
237            The pandas DataFrame representing the mass spectrum.
238        """
239
240        columnsLabels = self.get_scan_group_attr_data(
241            scan_index, time_index, "ColumnsLabels"
242        )
243
244        scan_label = self.scans[scan_index]
245
246        index_to_pull = self.get_time_index_to_pull(scan_label, time_index)
247
248        corems_table_data = self.h5pydata[scan_label][index_to_pull]
249
250        list_dict = []
251        for row in corems_table_data:
252            data_dict = {}
253            for data_index, data in enumerate(row):
254                label = columnsLabels[data_index]
255                # if data starts with a b' it is a byte string, so decode it
256                if isinstance(data, bytes):
257                    data = data.decode("utf-8")
258                if data == "nan":
259                    data = None
260                data_dict[label] = data
261
262            list_dict.append(data_dict)
263
264        # Reorder the columns from low to high "Index" to match the order of the dataframe
265        df = DataFrame(list_dict)
266        # set the "Index" column to int so it sorts correctly
267        df["Index"] = df["Index"].astype(int)
268        df = df.sort_values(by="Index")
269        # Reset index to match the "Index" column
270        df = df.set_index("Index", drop=False)
271
272        return df

Get a pandas DataFrame representing the mass spectrum.

Parameters
  • scan_index (int, optional): The index of the scan to retrieve the DataFrame from. Default is 0.
  • time_index (int, optional): The index of the time point to retrieve the DataFrame from. Default is -1.
Returns
  • DataFrame: The pandas DataFrame representing the mass spectrum.
def get_time_index_to_pull(self, scan_label, time_index):
274    def get_time_index_to_pull(self, scan_label, time_index):
275        """
276        Get the time index to pull from the HDF5 file.
277
278        Parameters
279        ----------
280        scan_label : str
281            The label of the scan.
282        time_index : int
283            The index of the time point.
284
285        Returns
286        -------
287        str
288            The time index to pull.
289        """
290
291        time_data = sorted(
292            [(i, int(i)) for i in self.h5pydata[scan_label].keys() if i != "raw_ms"],
293            key=lambda m: m[1],
294        )
295
296        index_to_pull = time_data[time_index][0]
297
298        return index_to_pull

Get the time index to pull from the HDF5 file.

Parameters
  • scan_label (str): The label of the scan.
  • time_index (int): The index of the time point.
Returns
  • str: The time index to pull.
def get_high_level_attr_data(self, attr_str):
300    def get_high_level_attr_data(self, attr_str):
301        """
302        Get high-level attribute data from the HDF5 file.
303
304        Parameters
305        ----------
306        attr_str : str
307            The attribute string.
308
309        Returns
310        -------
311        dict
312            The attribute data.
313
314        Raises
315        ------
316        KeyError
317            If the attribute string is not found in the HDF5 file.
318        """
319
320        return self.h5pydata.attrs[attr_str]

Get high-level attribute data from the HDF5 file.

Parameters
  • attr_str (str): The attribute string.
Returns
  • dict: The attribute data.
Raises
  • KeyError: If the attribute string is not found in the HDF5 file.
def get_scan_group_attr_data(self, scan_index, time_index, attr_group, attr_srt=None):
322    def get_scan_group_attr_data(
323        self, scan_index, time_index, attr_group, attr_srt=None
324    ):
325        """
326        Get scan group attribute data from the HDF5 file.
327
328        Parameters
329        ----------
330        scan_index : int
331            The index of the scan.
332        time_index : int
333            The index of the time point.
334        attr_group : str
335            The attribute group.
336        attr_srt : str, optional
337            The attribute string. Default is None.
338
339        Returns
340        -------
341        dict
342            The attribute data.
343
344        Notes
345        -----
346        This method retrieves attribute data from the HDF5 file for a specific scan and time point.
347        The attribute data is stored in the specified attribute group.
348        If an attribute string is provided, only the corresponding attribute value is returned.
349        If no attribute string is provided, all attribute data in the group is returned as a dictionary.
350        """
351        # Get index of self.scans where scan_index_str is found
352        scan_label = self.scans[scan_index]
353
354        index_to_pull = self.get_time_index_to_pull(scan_label, time_index)
355
356        if attr_srt:
357            return json.loads(
358                self.h5pydata[scan_label][index_to_pull].attrs[attr_group]
359            )[attr_srt]
360
361        else:
362            data = self.h5pydata[scan_label][index_to_pull].attrs.get(attr_group)
363            if data:
364                return json.loads(data)
365            else:
366                return {}

Get scan group attribute data from the HDF5 file.

Parameters
  • scan_index (int): The index of the scan.
  • time_index (int): The index of the time point.
  • attr_group (str): The attribute group.
  • attr_srt (str, optional): The attribute string. Default is None.
Returns
  • dict: The attribute data.
Notes

This method retrieves attribute data from the HDF5 file for a specific scan and time point. The attribute data is stored in the specified attribute group. If an attribute string is provided, only the corresponding attribute value is returned. If no attribute string is provided, all attribute data in the group is returned as a dictionary.

def get_raw_data_attr_data(self, scan_index, attr_group, attr_str):
368    def get_raw_data_attr_data(self, scan_index, attr_group, attr_str):
369        """
370        Get raw data attribute data from the HDF5 file.
371
372        Parameters
373        ----------
374        scan_index : int
375            The index of the scan.
376        attr_group : str
377            The attribute group.
378        attr_str : str
379            The attribute string.
380
381        Returns
382        -------
383        dict
384            The attribute data.
385
386        Raises
387        ------
388        KeyError
389            If the attribute string is not found in the attribute group.
390
391        Notes
392        -----
393        This method retrieves the attribute data associated with a specific scan, attribute group, and attribute string
394        from the HDF5 file. It returns the attribute data as a dictionary.
395
396        Example usage:
397        >>> data = get_raw_data_attr_data(0, "group1", "attribute1")
398        >>> print(data)
399        {'key1': 'value1', 'key2': 'value2'}
400        """
401        scan_label = self.scans[scan_index]
402        
403        # First try to get from raw_ms dataset attributes (backward compatibility)
404        if "raw_ms" in self.h5pydata[scan_label] and attr_group in self.h5pydata[scan_label]["raw_ms"].attrs:
405            try:
406                return json.loads(self.h5pydata[scan_label]["raw_ms"].attrs[attr_group])[attr_str]
407            except KeyError:
408                attr_str = attr_str.replace("baseline", "baselise")
409                return json.loads(self.h5pydata[scan_label]["raw_ms"].attrs[attr_group])[attr_str]
410        
411        # If not found in raw_ms, try to get from scan group attributes (new format)
412        elif attr_group in self.h5pydata[scan_label].attrs:
413            try:
414                return json.loads(self.h5pydata[scan_label].attrs[attr_group])[attr_str]
415            except KeyError:
416                attr_str = attr_str.replace("baseline", "baselise")
417                return json.loads(self.h5pydata[scan_label].attrs[attr_group])[attr_str]
418        
419        else:
420            raise KeyError(f"Attribute group '{attr_group}' not found in either raw_ms dataset or scan group for scan {scan_label}")

Get raw data attribute data from the HDF5 file.

Parameters
  • scan_index (int): The index of the scan.
  • attr_group (str): The attribute group.
  • attr_str (str): The attribute string.
Returns
  • dict: The attribute data.
Raises
  • KeyError: If the attribute string is not found in the attribute group.
Notes

This method retrieves the attribute data associated with a specific scan, attribute group, and attribute string from the HDF5 file. It returns the attribute data as a dictionary.

Example usage:

>>> data = get_raw_data_attr_data(0, "group1", "attribute1")
>>> print(data)
{'key1': 'value1', 'key2': 'value2'}
def get_output_parameters(self, polarity, scan_index=0):
422    def get_output_parameters(self, polarity, scan_index=0):
423        """
424        Get the output parameters for the mass spectrum.
425
426        Parameters
427        ----------
428        polarity : str
429            The polarity of the mass spectrum.
430        scan_index : int, optional
431            The index of the scan. Default is 0.
432
433        Returns
434        -------
435        dict
436            The output parameters.
437        """
438
439        d_params = default_parameters(self.file_location)
440        d_params["filename_path"] = self.file_location
441        d_params["polarity"] = self.get_raw_data_attr_data(
442            scan_index, "MassSpecAttrs", "polarity"
443        )
444        d_params["rt"] = self.get_raw_data_attr_data(scan_index, "MassSpecAttrs", "rt")
445
446        d_params["tic"] = self.get_raw_data_attr_data(
447            scan_index, "MassSpecAttrs", "tic"
448        )
449
450        d_params["mobility_scan"] = self.get_raw_data_attr_data(
451            scan_index, "MassSpecAttrs", "mobility_scan"
452        )
453        d_params["mobility_rt"] = self.get_raw_data_attr_data(
454            scan_index, "MassSpecAttrs", "mobility_rt"
455        )
456        d_params["Aterm"] = self.get_raw_data_attr_data(
457            scan_index, "MassSpecAttrs", "Aterm"
458        )
459        d_params["Bterm"] = self.get_raw_data_attr_data(
460            scan_index, "MassSpecAttrs", "Bterm"
461        )
462        d_params["Cterm"] = self.get_raw_data_attr_data(
463            scan_index, "MassSpecAttrs", "Cterm"
464        )
465        d_params["baseline_noise"] = self.get_raw_data_attr_data(
466            scan_index, "MassSpecAttrs", "baseline_noise"
467        )
468        d_params["baseline_noise_std"] = self.get_raw_data_attr_data(
469            scan_index, "MassSpecAttrs", "baseline_noise_std"
470        )
471
472        d_params["analyzer"] = self.get_high_level_attr_data("analyzer")
473        d_params["instrument_label"] = self.get_high_level_attr_data("instrument_label")
474        d_params["sample_name"] = self.get_high_level_attr_data("sample_name")
475
476        return d_params

Get the output parameters for the mass spectrum.

Parameters
  • polarity (str): The polarity of the mass spectrum.
  • scan_index (int, optional): The index of the scan. Default is 0.
Returns
  • dict: The output parameters.