Repository: matchms/matchms
Pull request #287 (2022-01-03 09:53:10)

move peak_comments into metadata


Patch:
diff --git a/matchms/Spectrum.py b/matchms/Spectrum.py
index 7fd409b2..34edbd59 100644
--- a/matchms/Spectrum.py
+++ b/matchms/Spectrum.py
@@ -19,8 +19,8 @@ class Spectrum:
 
         spectrum = Spectrum(mz=np.array([100, 150, 200.]),
                               intensities=np.array([0.7, 0.2, 0.1]),
-                              metadata={'id': 'spectrum1'},
-                              peak_comments={200.: "the peak at 200 m/z"})
+                              metadata={'id': 'spectrum1',
+                                        "peak_comments": {200.: "the peak at 200 m/z"}})
 
         print(spectrum.peaks.mz[0])
         print(spectrum.peaks.intensities[0])
@@ -51,8 +51,6 @@ class Spectrum:
             spectrum.losess = Spikes(mz=np.array([50.]), intensities=np.array([0.1]))
     metadata: dict
         Dict of metadata with for example the scan number of precursor m/z.
-    peak_comments: dict
-        Dict of comments for each m/z peak.
 
     """
 
@@ -61,8 +59,7 @@ class Spectrum:
     def __init__(self,
                  mz: numpy.array,
                  intensities: numpy.array,
-                 metadata: Optional[dict] = None,
-                 peak_comments: Optional[dict] = None):
+                 metadata: Optional[dict] = None):
         """
 
         Parameters
@@ -73,19 +70,13 @@ class Spectrum:
             Array of intensities for the peaks
         metadata
             Dictionary with for example the scan number of precursor m/z.
-        peak_comments
-            Dictionary with comments assigned to their m/z peaks.
         """
-        self.peaks = Spikes(mz=mz, intensities=intensities)
-        self.losses = None
         if metadata is None:
-            self.metadata = {}
-        else:
-            self.metadata = metadata
-        if peak_comments:
-            self.peak_comments = peak_comments
+            self._metadata = {}
         else:
-            self.peak_comments = {}
+            self._metadata = metadata
+        self.peaks = Spikes(mz=mz, intensities=intensities)
+        self.losses = None
 
     def __eq__(self, other):
         return \
@@ -240,17 +231,17 @@ class Spectrum:
 
     @peaks.setter
     def peaks(self, value: Spikes):
-        if hasattr(self, "_peak_comments"):
+        if isinstance(self.get("peak_comments"), dict):
             self._reiterate_peak_comments(value)
         self._peaks = value
 
     @property
     def peak_comments(self):
-        return self._peak_comments
+        return self.get("peak_comments")
 
     @peak_comments.setter
     def peak_comments(self, value):
-        self._peak_comments = value
+        self.set("peak_comments", value)
 
     @classmethod
     def update_peak_comments_mz_tolerance(cls, mz_tolerance: float):
@@ -258,20 +249,23 @@ class Spectrum:
 
     def _reiterate_peak_comments(self, peaks: Spikes):
         """Update the peak comments to reflect the new peaks."""
+        if not isinstance(self.get("peak_comments", None), dict):
+            return None
+
         mz_tolerance = self._peak_comments_mz_tolerance
 
         def _append_new_comment(key):
             if new_key_comment is not None:
-                comment = "; ".join([new_key_comment, self.peak_comments[key]])
+                comment = "; ".join([new_key_comment, self.metadata["peak_comments"].get(key)])
             else:
-                comment = self.peak_comments[key]
+                comment = self.metadata["peak_comments"].get(key)
             return comment
 
-        for key in list(self.peak_comments.keys()):
+        for key in list(self.metadata["peak_comments"].keys()):
             if key not in peaks.mz:
                 if numpy.isclose(key, peaks.mz, rtol=mz_tolerance).any():
                     new_key = peaks.mz[numpy.isclose(key, peaks.mz, rtol=mz_tolerance).argmax()]
-                    new_key_comment = self.peak_comments.get(new_key, None)
+                    new_key_comment = self.metadata["peak_comments"].get(new_key, None)
                     new_key_comment = _append_new_comment(key)
-                    self.peak_comments[new_key] = new_key_comment
-                self.peak_comments.pop(key)
+                    self._metadata["peak_comments"][new_key] = new_key_comment
+                self._metadata["peak_comments"].pop(key)
diff --git a/matchms/exporting/save_as_msp.py b/matchms/exporting/save_as_msp.py
index 047a7c5d..e0bf8fcd 100644
--- a/matchms/exporting/save_as_msp.py
+++ b/matchms/exporting/save_as_msp.py
@@ -78,6 +78,8 @@ def _write_metadata(metadata: dict, outfile: IO):
 
 def _format_peak_comment(mz: Union[int, float], peak_comments: Dict):
     """Format peak comment for given mz to return the quoted comment or empty string if no peak comment is present."""
+    if peak_comments is None:
+        return ""
     peak_comment = peak_comments.get(mz, None)
     if peak_comment is None:
         return ""
diff --git a/matchms/importing/load_from_msp.py b/matchms/importing/load_from_msp.py
index 7229346e..6366b203 100644
--- a/matchms/importing/load_from_msp.py
+++ b/matchms/importing/load_from_msp.py
@@ -133,6 +133,8 @@ def load_from_msp(filename: str) -> Generator[Spectrum, None, None]:
         mz = spectrum["m/z array"]
         intensities = spectrum["intensity array"]
         peak_comments = spectrum["peak comments"]
+        if peak_comments != {}:
+            metadata["peak_comments"] = peak_comments
 
         # Sort by mz (if not sorted already)
         if not numpy.all(mz[:-1] <= mz[1:]):
@@ -140,4 +142,4 @@ def load_from_msp(filename: str) -> Generator[Spectrum, None, None]:
             mz = mz[idx_sorted]
             intensities = intensities[idx_sorted]
 
-        yield Spectrum(mz=mz, intensities=intensities, metadata=metadata, peak_comments=peak_comments)
+        yield Spectrum(mz=mz, intensities=intensities, metadata=metadata)


Test patch:
diff --git a/tests/test_spectrum.py b/tests/test_spectrum.py
index b5dc8a02..33cfad66 100644
--- a/tests/test_spectrum.py
+++ b/tests/test_spectrum.py
@@ -199,7 +199,8 @@ def test_reiterating_peak_comments():
     intensities = numpy.array([1, 2, 3, 4, 5, 6, 7], dtype='float')
     peak_comments = ["m/z 100.0003", None, "m/z 100.0005", "m/z 110.", "m/z 200.", "m/z 300.", "m/z 400.0176"]
     peak_comments = {mz[i]: peak_comments[i] for i in range(len(mz))}
-    spectrum = Spectrum(mz=mz, intensities=intensities, peak_comments=peak_comments)
+    spectrum = Spectrum(mz=mz, intensities=intensities,
+                        metadata={"peak_comments": peak_comments})
 
     spectrum.peaks = Spikes(mz=numpy.array([100.0004, 110., 400.018], dtype='float'),
                             intensities=numpy.array([5, 4, 7], dtype='float'))