Documentation for Roi.py

Provides implementation of Regions-of-Interest (ROI) objects that are used for real-time ROI tracking in various controller. Additionally, ROIs can also be loaded from an mzML file and converted into Chemical objects for simulation input.

FrequentistRoiAligner

Bases: RoiAligner

TODO: add docstring comment This class does ...

Source code in vimms/Roi.py
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
class FrequentistRoiAligner(RoiAligner):
    """
    TODO: add docstring comment
    This class does ...
    """

    def get_boxes(self, method="mean"):
        """
        Converts peaksets to generic boxes in a different way

        Args:
            method:

        Returns: ???

        """
        boxes = super().get_boxes(method)
        categories = np.unique(np.array(self.sample_types))
        enough_categories = (
            min(Counter(self.sample_types).values()) > 1 and len(categories) == self.n_categories
        )
        pvalues = self.get_p_values(enough_categories)
        for i, box in enumerate(boxes):
            box.pvalue = pvalues[i]
        return boxes

    def get_p_values(self, enough_catergories):
        """

        Args:
            enough_catergories:

        Returns: ???

        """
        # need to match boxes, not base chemicals
        if enough_catergories:
            p_values = []
            # sort X
            X = np.array(self.to_matrix())
            # sort y
            categories = np.unique(np.array(self.sample_types))
            if self.n_categories == 2:  # logistic regression
                x = np.array([1 for i in self.sample_types])
                if "control" in categories:
                    control_type = "control"
                else:
                    control_type = categories[0]
                x[np.where(np.array(self.sample_types) == control_type)] = 0
                x = sm.add_constant(x)
                for i in range(X.shape[0]):
                    y = np.log(X[i, :] + 1)
                    model = sm.OLS(y, x)
                    p_values.append(model.fit(disp=0).pvalues[1])
            else:  # classification
                pass
        else:
            p_values = [None for ps in self.peaksets]
        return p_values

get_boxes(method='mean')

Converts peaksets to generic boxes in a different way

Parameters:
  • method

Returns: ???

Source code in vimms/Roi.py
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
def get_boxes(self, method="mean"):
    """
    Converts peaksets to generic boxes in a different way

    Args:
        method:

    Returns: ???

    """
    boxes = super().get_boxes(method)
    categories = np.unique(np.array(self.sample_types))
    enough_categories = (
        min(Counter(self.sample_types).values()) > 1 and len(categories) == self.n_categories
    )
    pvalues = self.get_p_values(enough_categories)
    for i, box in enumerate(boxes):
        box.pvalue = pvalues[i]
    return boxes

get_p_values(enough_catergories)

Parameters:
  • enough_catergories

Returns: ???

Source code in vimms/Roi.py
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
def get_p_values(self, enough_catergories):
    """

    Args:
        enough_catergories:

    Returns: ???

    """
    # need to match boxes, not base chemicals
    if enough_catergories:
        p_values = []
        # sort X
        X = np.array(self.to_matrix())
        # sort y
        categories = np.unique(np.array(self.sample_types))
        if self.n_categories == 2:  # logistic regression
            x = np.array([1 for i in self.sample_types])
            if "control" in categories:
                control_type = "control"
            else:
                control_type = categories[0]
            x[np.where(np.array(self.sample_types) == control_type)] = 0
            x = sm.add_constant(x)
            for i in range(X.shape[0]):
                y = np.log(X[i, :] + 1)
                model = sm.OLS(y, x)
                p_values.append(model.fit(disp=0).pvalues[1])
        else:  # classification
            pass
    else:
        p_values = [None for ps in self.peaksets]
    return p_values

Roi

A class to store an ROI (Regions-of-interest). An ROI is a region of consecutive scans that potentially form a chromatographic peak. This is the first step in peak detection but before the region is identified to be a peak or not. This class maintains 3 lists -- mz, rt and intensity. When a new point (mz,rt,intensity) is added, it updates the list and the mean mz which is required.

Source code in vimms/Roi.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
class Roi:
    """
    A class to store an ROI (Regions-of-interest). An ROI is a region of
    consecutive scans that potentially form a chromatographic peak. This is the
    first step in peak detection but before the region is identified to be a
    peak or not. This class maintains 3 lists -- mz, rt and intensity.
    When a new point (mz,rt,intensity) is added, it updates the list and the
    mean mz which is required.
    """

    def __init__(self, mz, rt, intensity, id=None):
        """
        Constructs a new ROI

        Args:
            mz: the initial m/z of this ROI. Can be either a single value
                or a list of values.
            rt: the initial rt  of this ROI. Can be either a single value
                or a list of values.
            intensity: the initial intensity  of this ROI. Can be either
                       a single value or a list of values.
            id: ID of this ROI if provided
        """
        self.id = id
        self.fragmentation_events = []
        self.fragmentation_intensities = []
        self.max_fragmentation_intensity = 0.0
        self.mz_list = [mz]
        self.rt_list = [rt]
        self.intensity_list = [intensity]
        self.n = len(self.mz_list)
        self.mz_sum = sum(self.mz_list)
        self.mean_mz = self.calculate_mean_mz()
        self.min_rt = self.rt_list[0]
        self.max_rt = self.rt_list[-1]
        self.length_in_seconds = self.max_rt - self.min_rt
        self.is_fragmented = False
        self.can_fragment = True
        self.last_frag_rt = None

    def fragmented(self, rt):
        """
        Sets flags to indicate that this ROI can or has been fragmented
        """
        self.is_fragmented = True
        self.can_fragment = True
        self.last_frag_rt = rt

    def calculate_mean_mz(self):
        return self.mz_sum / self.n

    def get_max_intensity(self):
        """
        Returns the maximum intensity value of this ROI
        """
        return max(self.intensity_list)

    def get_min_intensity(self):
        """
        Returns the minimum intensity value of this ROI
        """
        return min(self.intensity_list)

    def get_autocorrelation(self, lag=1):
        """
        Computes auto-correlation of this ROI intensity signal
        """
        return pd.Series(self.intensity_list).autocorr(lag=lag)

    def get_num_unique_scans(self):
        return np.unique(self.rt_list).shape[0]

    def estimate_apex(self):
        """
        Returns the apex retention time
        """
        return self.rt_list[np.argmax(self.intensity_list)]

    def add(self, mz, rt, intensity):
        """
        Adds a point to this ROI

        Args:
            mz: the m/z value to add
            rt: the retention time value to add
            intensity: the intensity value to add

        Returns: None

        """
        self.mz_list.append(mz)
        self.rt_list.append(rt)
        self.intensity_list.append(intensity)
        self.mz_sum += mz
        self.n += 1
        self.mean_mz = self.calculate_mean_mz()
        self.min_rt = self.rt_list[0]
        self.max_rt = self.rt_list[-1]
        self.length_in_seconds = self.max_rt - self.min_rt

    def add_fragmentation_event(self, scan, precursor_intensity):
        """
        Stores the fragmentation events (MS2 scan) linked to this ROI

        Args:
            scan: the MS2 scan
            precursor_intensity: the precursor intensity

        Returns: None

        """
        self.fragmentation_events.append(scan)
        self.fragmentation_intensities.append(precursor_intensity)
        self.max_fragmentation_intensity = max(self.fragmentation_intensities)

    def to_chromatogram(self):
        """
        Converts this ROI to a ViMMS EmpiricalChromatogram object
        """
        if self.n == 0:
            return None
        chrom = EmpiricalChromatogram(
            np.array(self.rt_list), np.array(self.mz_list), np.array(self.intensity_list)
        )
        return chrom

    @staticmethod
    def _set_fixed_bounds_for_box(dist, minm, maxm):
        if dist is not None:
            mid = (minm + maxm) / 2
            new_minm = mid - dist
            new_maxm = mid + dist
        else:
            new_minm, new_maxm = minm, maxm
        return new_minm, new_maxm

    def to_box(
        self,
        min_rt_width,
        min_mz_width,
        fixed_rt_dist=None,
        fixed_mz_dist=None,
        rt_shift=0,
        mz_shift=0,
    ):
        """
        Returns a generic box representation of this ROI

        Args:
            min_rt_width: minimum RT width of the box
            min_mz_width: minimum m/z width of the box
            fixed_rt_dist: if not set to None, overrides the default rt-width (in seconds)
            of the box, setting it to twice the parameter value. If set to None uses the
            maximum rt-range of points belonging to this RoI as the box's rt-width
            fixed_mz_width: if not set to None, overrides the default mz-width (in ppm) of
            the box, setting it twice the parameter value. If set to None uses the
            maximum mz-range of points belonging to this RoI as the box's rt-width
            rt_shift: shift in retention time, if any
            mz_shift: shift in m/z, if any

        Returns: a [vimms.Box.GenericBox][] object.

        """
        min_rt, max_rt = min(self.rt_list), max(self.rt_list)
        min_mz, max_mz = min(self.mz_list), max(self.mz_list)

        min_rt, max_rt = self._set_fixed_bounds_for_box(fixed_rt_dist, min_rt, max_rt)
        dalton_dist = self.mean_mz * fixed_mz_dist / 1e6 if fixed_mz_dist is not None else None
        min_mz, max_mz = self._set_fixed_bounds_for_box(dalton_dist, min_mz, max_mz)

        return GenericBox(
            min_rt + rt_shift,
            max_rt + rt_shift,
            min_mz + mz_shift,
            max_mz + mz_shift,
            min_xwidth=min_rt_width,
            min_ywidth=min_mz_width,
            intensity=self.max_fragmentation_intensity,
            id=self.id,
            roi=self,
        )

    def get_boxes_overlap(self, boxes, min_rt_width, min_mz_width, rt_shift=0, mz_shift=0):
        """
        TODO: ask Ross or Vinny to add comment

        Args:
            boxes: the boxes to check
            min_rt_width: minimum RT width of the box
            min_mz_width: minimum m/z width of the box
            rt_shift: shift in retention time, if any
            mz_shift: shift in m/z, if any

        Returns: ???

        """

        roi_box = self.to_box(min_rt_width, min_mz_width, rt_shift, mz_shift)
        # print(roi_box)
        overlaps = [roi_box.overlap_2(box) for box in boxes]
        return overlaps

    def get_roi_overlap(self, boxes, min_rt_width, min_mz_width, rt_shift=0, mz_shift=0):
        """
        TODO: ask Ross or Vinny to add comment

        Args:
            boxes: the boxes to check
            min_rt_width: minimum RT width of the box
            min_mz_width: minimum m/z width of the box
            rt_shift: shift in retention time, if any
            mz_shift: shift in m/z, if any

        Returns: ???

        """
        roi_box = self.to_box(min_rt_width, min_mz_width, rt_shift, mz_shift)
        overlaps = [roi_box.overlap_3(box) for box in boxes]
        return overlaps

    def get_last_datum(self):
        """
        Returns the last (m/z, rt, intensity) point of this ROI
        """
        return self.mz_list[-1], self.rt_list[-1], self.intensity_list[-1]

    def __getitem__(self, idx):
        """
        Returns a single point in this ROI at the
        specified index

        Args:
            idx: the index of item to retrieve

        Returns: a tuple of (rt, m/z, intensity) value

        """
        return list(zip(self.rt_list, self.mz_list, self.intensity_list))[idx]

    def __lt__(self, other):
        """
        Compares this ROI to other based on the mean m/z value.
        Used for sorting.

        Args:
            other: the other ROI object for comparison

        Returns: comparison is done by mean m/z of ROIs

        """
        return self.mean_mz <= other.mean_mz

    def __repr__(self):
        """
        Returns a string representation of this ROI
        """
        return "ROI with data points=%d fragmentations=%d mz " "(%.4f-%.4f) rt (%.4f-%.4f)" % (
            self.n,
            len(self.fragmentation_events),
            self.mz_list[0],
            self.mz_list[-1],
            self.rt_list[0],
            self.rt_list[-1],
        )

__getitem__(idx)

Returns a single point in this ROI at the specified index

Parameters:
  • idx

    the index of item to retrieve

Returns: a tuple of (rt, m/z, intensity) value

Source code in vimms/Roi.py
255
256
257
258
259
260
261
262
263
264
265
266
def __getitem__(self, idx):
    """
    Returns a single point in this ROI at the
    specified index

    Args:
        idx: the index of item to retrieve

    Returns: a tuple of (rt, m/z, intensity) value

    """
    return list(zip(self.rt_list, self.mz_list, self.intensity_list))[idx]

__init__(mz, rt, intensity, id=None)

Constructs a new ROI

Parameters:
  • mz

    the initial m/z of this ROI. Can be either a single value or a list of values.

  • rt

    the initial rt of this ROI. Can be either a single value or a list of values.

  • intensity

    the initial intensity of this ROI. Can be either a single value or a list of values.

  • id

    ID of this ROI if provided

Source code in vimms/Roi.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def __init__(self, mz, rt, intensity, id=None):
    """
    Constructs a new ROI

    Args:
        mz: the initial m/z of this ROI. Can be either a single value
            or a list of values.
        rt: the initial rt  of this ROI. Can be either a single value
            or a list of values.
        intensity: the initial intensity  of this ROI. Can be either
                   a single value or a list of values.
        id: ID of this ROI if provided
    """
    self.id = id
    self.fragmentation_events = []
    self.fragmentation_intensities = []
    self.max_fragmentation_intensity = 0.0
    self.mz_list = [mz]
    self.rt_list = [rt]
    self.intensity_list = [intensity]
    self.n = len(self.mz_list)
    self.mz_sum = sum(self.mz_list)
    self.mean_mz = self.calculate_mean_mz()
    self.min_rt = self.rt_list[0]
    self.max_rt = self.rt_list[-1]
    self.length_in_seconds = self.max_rt - self.min_rt
    self.is_fragmented = False
    self.can_fragment = True
    self.last_frag_rt = None

__lt__(other)

Compares this ROI to other based on the mean m/z value. Used for sorting.

Parameters:
  • other

    the other ROI object for comparison

Returns: comparison is done by mean m/z of ROIs

Source code in vimms/Roi.py
268
269
270
271
272
273
274
275
276
277
278
279
def __lt__(self, other):
    """
    Compares this ROI to other based on the mean m/z value.
    Used for sorting.

    Args:
        other: the other ROI object for comparison

    Returns: comparison is done by mean m/z of ROIs

    """
    return self.mean_mz <= other.mean_mz

__repr__()

Returns a string representation of this ROI

Source code in vimms/Roi.py
281
282
283
284
285
286
287
288
289
290
291
292
def __repr__(self):
    """
    Returns a string representation of this ROI
    """
    return "ROI with data points=%d fragmentations=%d mz " "(%.4f-%.4f) rt (%.4f-%.4f)" % (
        self.n,
        len(self.fragmentation_events),
        self.mz_list[0],
        self.mz_list[-1],
        self.rt_list[0],
        self.rt_list[-1],
    )

add(mz, rt, intensity)

Adds a point to this ROI

Parameters:
  • mz

    the m/z value to add

  • rt

    the retention time value to add

  • intensity

    the intensity value to add

Returns: None

Source code in vimms/Roi.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def add(self, mz, rt, intensity):
    """
    Adds a point to this ROI

    Args:
        mz: the m/z value to add
        rt: the retention time value to add
        intensity: the intensity value to add

    Returns: None

    """
    self.mz_list.append(mz)
    self.rt_list.append(rt)
    self.intensity_list.append(intensity)
    self.mz_sum += mz
    self.n += 1
    self.mean_mz = self.calculate_mean_mz()
    self.min_rt = self.rt_list[0]
    self.max_rt = self.rt_list[-1]
    self.length_in_seconds = self.max_rt - self.min_rt

add_fragmentation_event(scan, precursor_intensity)

Stores the fragmentation events (MS2 scan) linked to this ROI

Parameters:
  • scan

    the MS2 scan

  • precursor_intensity

    the precursor intensity

Returns: None

Source code in vimms/Roi.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def add_fragmentation_event(self, scan, precursor_intensity):
    """
    Stores the fragmentation events (MS2 scan) linked to this ROI

    Args:
        scan: the MS2 scan
        precursor_intensity: the precursor intensity

    Returns: None

    """
    self.fragmentation_events.append(scan)
    self.fragmentation_intensities.append(precursor_intensity)
    self.max_fragmentation_intensity = max(self.fragmentation_intensities)

estimate_apex()

Returns the apex retention time

Source code in vimms/Roi.py
101
102
103
104
105
def estimate_apex(self):
    """
    Returns the apex retention time
    """
    return self.rt_list[np.argmax(self.intensity_list)]

fragmented(rt)

Sets flags to indicate that this ROI can or has been fragmented

Source code in vimms/Roi.py
69
70
71
72
73
74
75
def fragmented(self, rt):
    """
    Sets flags to indicate that this ROI can or has been fragmented
    """
    self.is_fragmented = True
    self.can_fragment = True
    self.last_frag_rt = rt

get_autocorrelation(lag=1)

Computes auto-correlation of this ROI intensity signal

Source code in vimms/Roi.py
92
93
94
95
96
def get_autocorrelation(self, lag=1):
    """
    Computes auto-correlation of this ROI intensity signal
    """
    return pd.Series(self.intensity_list).autocorr(lag=lag)

get_boxes_overlap(boxes, min_rt_width, min_mz_width, rt_shift=0, mz_shift=0)

TODO: ask Ross or Vinny to add comment

Parameters:
  • boxes

    the boxes to check

  • min_rt_width

    minimum RT width of the box

  • min_mz_width

    minimum m/z width of the box

  • rt_shift

    shift in retention time, if any

  • mz_shift

    shift in m/z, if any

Returns: ???

Source code in vimms/Roi.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def get_boxes_overlap(self, boxes, min_rt_width, min_mz_width, rt_shift=0, mz_shift=0):
    """
    TODO: ask Ross or Vinny to add comment

    Args:
        boxes: the boxes to check
        min_rt_width: minimum RT width of the box
        min_mz_width: minimum m/z width of the box
        rt_shift: shift in retention time, if any
        mz_shift: shift in m/z, if any

    Returns: ???

    """

    roi_box = self.to_box(min_rt_width, min_mz_width, rt_shift, mz_shift)
    # print(roi_box)
    overlaps = [roi_box.overlap_2(box) for box in boxes]
    return overlaps

get_last_datum()

Returns the last (m/z, rt, intensity) point of this ROI

Source code in vimms/Roi.py
249
250
251
252
253
def get_last_datum(self):
    """
    Returns the last (m/z, rt, intensity) point of this ROI
    """
    return self.mz_list[-1], self.rt_list[-1], self.intensity_list[-1]

get_max_intensity()

Returns the maximum intensity value of this ROI

Source code in vimms/Roi.py
80
81
82
83
84
def get_max_intensity(self):
    """
    Returns the maximum intensity value of this ROI
    """
    return max(self.intensity_list)

get_min_intensity()

Returns the minimum intensity value of this ROI

Source code in vimms/Roi.py
86
87
88
89
90
def get_min_intensity(self):
    """
    Returns the minimum intensity value of this ROI
    """
    return min(self.intensity_list)

get_roi_overlap(boxes, min_rt_width, min_mz_width, rt_shift=0, mz_shift=0)

TODO: ask Ross or Vinny to add comment

Parameters:
  • boxes

    the boxes to check

  • min_rt_width

    minimum RT width of the box

  • min_mz_width

    minimum m/z width of the box

  • rt_shift

    shift in retention time, if any

  • mz_shift

    shift in m/z, if any

Returns: ???

Source code in vimms/Roi.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def get_roi_overlap(self, boxes, min_rt_width, min_mz_width, rt_shift=0, mz_shift=0):
    """
    TODO: ask Ross or Vinny to add comment

    Args:
        boxes: the boxes to check
        min_rt_width: minimum RT width of the box
        min_mz_width: minimum m/z width of the box
        rt_shift: shift in retention time, if any
        mz_shift: shift in m/z, if any

    Returns: ???

    """
    roi_box = self.to_box(min_rt_width, min_mz_width, rt_shift, mz_shift)
    overlaps = [roi_box.overlap_3(box) for box in boxes]
    return overlaps

to_box(min_rt_width, min_mz_width, fixed_rt_dist=None, fixed_mz_dist=None, rt_shift=0, mz_shift=0)

Returns a generic box representation of this ROI

Parameters:
  • min_rt_width

    minimum RT width of the box

  • min_mz_width

    minimum m/z width of the box

  • fixed_rt_dist

    if not set to None, overrides the default rt-width (in seconds)

  • fixed_mz_width

    if not set to None, overrides the default mz-width (in ppm) of

  • rt_shift

    shift in retention time, if any

  • mz_shift

    shift in m/z, if any

Returns: a vimms.Box.GenericBox object.

Source code in vimms/Roi.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def to_box(
    self,
    min_rt_width,
    min_mz_width,
    fixed_rt_dist=None,
    fixed_mz_dist=None,
    rt_shift=0,
    mz_shift=0,
):
    """
    Returns a generic box representation of this ROI

    Args:
        min_rt_width: minimum RT width of the box
        min_mz_width: minimum m/z width of the box
        fixed_rt_dist: if not set to None, overrides the default rt-width (in seconds)
        of the box, setting it to twice the parameter value. If set to None uses the
        maximum rt-range of points belonging to this RoI as the box's rt-width
        fixed_mz_width: if not set to None, overrides the default mz-width (in ppm) of
        the box, setting it twice the parameter value. If set to None uses the
        maximum mz-range of points belonging to this RoI as the box's rt-width
        rt_shift: shift in retention time, if any
        mz_shift: shift in m/z, if any

    Returns: a [vimms.Box.GenericBox][] object.

    """
    min_rt, max_rt = min(self.rt_list), max(self.rt_list)
    min_mz, max_mz = min(self.mz_list), max(self.mz_list)

    min_rt, max_rt = self._set_fixed_bounds_for_box(fixed_rt_dist, min_rt, max_rt)
    dalton_dist = self.mean_mz * fixed_mz_dist / 1e6 if fixed_mz_dist is not None else None
    min_mz, max_mz = self._set_fixed_bounds_for_box(dalton_dist, min_mz, max_mz)

    return GenericBox(
        min_rt + rt_shift,
        max_rt + rt_shift,
        min_mz + mz_shift,
        max_mz + mz_shift,
        min_xwidth=min_rt_width,
        min_ywidth=min_mz_width,
        intensity=self.max_fragmentation_intensity,
        id=self.id,
        roi=self,
    )

to_chromatogram()

Converts this ROI to a ViMMS EmpiricalChromatogram object

Source code in vimms/Roi.py
144
145
146
147
148
149
150
151
152
153
def to_chromatogram(self):
    """
    Converts this ROI to a ViMMS EmpiricalChromatogram object
    """
    if self.n == 0:
        return None
    chrom = EmpiricalChromatogram(
        np.array(self.rt_list), np.array(self.mz_list), np.array(self.intensity_list)
    )
    return chrom

RoiAligner

A class that aligns multiple ROIs in different samples

Source code in vimms/Roi.py
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
class RoiAligner:
    """
    A class that aligns multiple ROIs in different samples
    """

    def __init__(
        self,
        mz_tolerance_absolute=1e-8,
        mz_tolerance_ppm=10,
        rt_tolerance=0.5,
        mz_column_pos=1,
        rt_column_pos=2,
        intensity_column_pos=3,
        min_rt_width=0.000001,
        min_mz_width=0.000001,
        n_categories=1,
    ):
        """
        TODO: ask Ross or Vinny to add comment

        Args:
            mz_tolerance_absolute:
            mz_tolerance_ppm:
            rt_tolerance:
            mz_column_pos:
            rt_column_pos:
            intensity_column_pos:
            min_rt_width:
            min_mz_width:
            n_categories:
        """

        self.mz_tolerance_absolute, self.mz_tolerance_ppm, self.rt_tolerance = (
            mz_tolerance_absolute,
            mz_tolerance_ppm,
            rt_tolerance,
        )
        self.mz_column_pos, self.rt_column_pos, self.intensity_column_pos = (
            mz_column_pos,
            rt_column_pos,
            intensity_column_pos,
        )
        self.min_rt_width, self.min_mz_width = min_rt_width, min_mz_width

        self.n_categories = n_categories
        self.peaksets, self.files_loaded, self.list_of_boxes = [], [], []
        self.sample_names, self.sample_types = [], []
        self.mz_weight, self.rt_weight = 75, 25
        self.peaksets2boxes, self.peaksets2fragintensities = {}, {}
        self.addition_method = None

    def add_sample(self, rois, sample_name, sample_type=None, rt_shifts=None, mz_shifts=None):
        """
        TODO: ask Ross or Vinny to add comment

        Args:
            rois:
            sample_name:
            sample_type:
            rt_shifts:
            mz_shifts:

        Returns: ???

        """
        self.sample_names.append(sample_name)
        self.sample_types.append(sample_type)

        these_peaks, frag_intensities, temp_boxes = [], [], []
        for i, roi in enumerate(rois):
            source_id = f"{sample_name}_{i}"
            peak_mz = roi.mean_mz
            peak_rt = roi.estimate_apex()
            peak_intensity = roi.get_max_intensity()
            these_peaks.append(Peak(peak_mz, peak_rt, peak_intensity, sample_name, source_id))
            frag_intensities.append(roi.max_fragmentation_intensity)
            rt_shift = 0 if rt_shifts is None else rt_shifts[i]
            mz_shift = 0 if mz_shifts is None else mz_shifts[i]
            temp_boxes.append(roi.to_box(self.min_rt_width, self.min_mz_width, rt_shift, mz_shift))

        # do alignment, adding the peaks and boxes, and recalculating max
        # frag intensity
        self._align(these_peaks, temp_boxes, frag_intensities, sample_name)

    @staticmethod
    def load_boxes(peak_file, picking_method):
        if picking_method == "mzmine":
            boxes = load_picked_boxes(peak_file)
        elif picking_method == "peakonly":
            boxes = load_peakonly_boxes(peak_file)  # not tested
        elif picking_method == "xcms":
            boxes = load_xcms_boxes(peak_file)  # not tested
        else:
            raise NotImplementedError(f'Picking method "{picking_method}" not recognised!')
        return boxes

    def add_picked_peaks(
        self,
        mzml_file,
        peak_file,
        sample_name,
        picking_method="mzmine",
        sample_type=None,
        half_isolation_window=0,
        allow_last_overlap=False,
        rt_shifts=None,
        mz_shifts=None,
    ):
        """
        TODO: ask Ross or Vinny to add comment

        Args:
            mzml_file:
            peak_file:
            sample_name:
            picking_method:
            sample_type:
            half_isolation_window:
            allow_last_overlap:
            rt_shifts:
            mz_shifts:

        Returns: ???

        """
        self.sample_names.append(sample_name)
        self.sample_types.append(sample_type)

        these_peaks, frag_intensities = [], []
        temp_boxes = self.load_boxes(peak_file, picking_method)
        temp_boxes = update_picked_boxes(temp_boxes, rt_shifts, mz_shifts)
        self.list_of_boxes.append(temp_boxes)

        mzml = path_or_mzml(mzml_file)
        scans2boxes, boxes2scans = map_boxes_to_scans(
            mzml,
            temp_boxes,
            half_isolation_window=half_isolation_window,
            allow_last_overlap=allow_last_overlap,
        )
        precursor_intensities, scores = get_precursor_intensities(boxes2scans, temp_boxes, "max")

        for i, box in enumerate(temp_boxes):
            source_id = f"{sample_name}_{i}"
            peak_mz = box.mz
            peak_rt = box.rt_in_seconds
            these_peaks.append(Peak(peak_mz, peak_rt, box.height, sample_name, source_id))
            frag_intensities.append(precursor_intensities[i])

        self._align(these_peaks, temp_boxes, frag_intensities, sample_name)

    def _align(self, these_peaks, temp_boxes, frag_intensities, short_name):
        """
        TODO: ask Ross or Vinny to add comment

        Args:
            these_peaks:
            temp_boxes:
            frag_intensities:
            short_name:

        Returns: ???

        """
        seen_ps, unassigned = set(), []
        for peak, box, intensity in zip(these_peaks, temp_boxes, frag_intensities):
            candidates = [
                ps
                for ps in self.peaksets
                if ps not in seen_ps
                and ps.is_in_box(
                    peak, self.mz_tolerance_absolute, self.mz_tolerance_ppm, self.rt_tolerance
                )
            ]
            if len(candidates) > 0:
                scores = [
                    ps.compute_weight(
                        peak,
                        self.mz_tolerance_absolute,
                        self.mz_tolerance_ppm,
                        self.rt_tolerance,
                        self.mz_weight,
                        self.rt_weight,
                    )
                    for ps in candidates
                ]
                best_ps, _ = max(
                    ((ps, s) for ps, s in zip(candidates, scores)), key=lambda t: t[1]
                )
                best_ps.add_peak(peak)
                self.peaksets2boxes[best_ps].append(box)
                self.peaksets2fragintensities[best_ps].append(intensity)
                seen_ps.add(best_ps)
            else:
                unassigned.append((peak, box, intensity))

        for peak, box, intensity in unassigned:
            new_ps = PeakSet(peak)
            self.peaksets.append(new_ps)
            self.peaksets2boxes[new_ps] = [box]
            self.peaksets2fragintensities[new_ps] = [intensity]

        self.files_loaded.append(short_name)

    def to_matrix(self):
        """
        Converts aligned peaksets to nicely formatted intensity matrix
        (rows: peaksets, columns: files)
        """
        return np.array(
            [[ps.get_intensity(fname) for fname in self.files_loaded] for ps in self.peaksets],
            dtype=np.double,
        )

    def get_boxes(self, method="mean"):
        """
        Converts peaksets to generic boxes

        Args:
            method: which method to use for the conversion

        Returns: a list of [vimms.Box.GenericBox][] objects.

        """
        if method == "max":
            f1, f2 = min, max
        else:
            f1 = f2 = mean

        boxes = []
        for ps in self.peaksets:
            box_list = self.peaksets2boxes[ps]
            x1 = f1(b.pt1.x for b in box_list)
            x2 = f2(b.pt2.x for b in box_list)
            y1 = f1(b.pt1.y for b in box_list)
            y2 = f2(b.pt2.y for b in box_list)
            intensity = max(self.peaksets2fragintensities[ps])
            boxes.append(
                GenericBox(
                    x1,
                    x2,
                    y1,
                    y2,
                    intensity=intensity,
                    min_xwidth=self.min_rt_width,
                    min_ywidth=self.min_mz_width,
                )
            )
        return boxes

    def get_max_frag_intensities(self):
        """
        Returns the maximum fragmentation intensities of peaksets
        """
        return [max(self.peaksets2fragintensities[ps]) for ps in self.peaksets]

__init__(mz_tolerance_absolute=1e-08, mz_tolerance_ppm=10, rt_tolerance=0.5, mz_column_pos=1, rt_column_pos=2, intensity_column_pos=3, min_rt_width=1e-06, min_mz_width=1e-06, n_categories=1)

TODO: ask Ross or Vinny to add comment

Parameters:
  • mz_tolerance_absolute
  • mz_tolerance_ppm
  • rt_tolerance
  • mz_column_pos
  • rt_column_pos
  • intensity_column_pos
  • min_rt_width
  • min_mz_width
  • n_categories
Source code in vimms/Roi.py
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def __init__(
    self,
    mz_tolerance_absolute=1e-8,
    mz_tolerance_ppm=10,
    rt_tolerance=0.5,
    mz_column_pos=1,
    rt_column_pos=2,
    intensity_column_pos=3,
    min_rt_width=0.000001,
    min_mz_width=0.000001,
    n_categories=1,
):
    """
    TODO: ask Ross or Vinny to add comment

    Args:
        mz_tolerance_absolute:
        mz_tolerance_ppm:
        rt_tolerance:
        mz_column_pos:
        rt_column_pos:
        intensity_column_pos:
        min_rt_width:
        min_mz_width:
        n_categories:
    """

    self.mz_tolerance_absolute, self.mz_tolerance_ppm, self.rt_tolerance = (
        mz_tolerance_absolute,
        mz_tolerance_ppm,
        rt_tolerance,
    )
    self.mz_column_pos, self.rt_column_pos, self.intensity_column_pos = (
        mz_column_pos,
        rt_column_pos,
        intensity_column_pos,
    )
    self.min_rt_width, self.min_mz_width = min_rt_width, min_mz_width

    self.n_categories = n_categories
    self.peaksets, self.files_loaded, self.list_of_boxes = [], [], []
    self.sample_names, self.sample_types = [], []
    self.mz_weight, self.rt_weight = 75, 25
    self.peaksets2boxes, self.peaksets2fragintensities = {}, {}
    self.addition_method = None

add_picked_peaks(mzml_file, peak_file, sample_name, picking_method='mzmine', sample_type=None, half_isolation_window=0, allow_last_overlap=False, rt_shifts=None, mz_shifts=None)

TODO: ask Ross or Vinny to add comment

Parameters:
  • mzml_file
  • peak_file
  • sample_name
  • picking_method
  • sample_type
  • half_isolation_window
  • allow_last_overlap
  • rt_shifts
  • mz_shifts

Returns: ???

Source code in vimms/Roi.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
def add_picked_peaks(
    self,
    mzml_file,
    peak_file,
    sample_name,
    picking_method="mzmine",
    sample_type=None,
    half_isolation_window=0,
    allow_last_overlap=False,
    rt_shifts=None,
    mz_shifts=None,
):
    """
    TODO: ask Ross or Vinny to add comment

    Args:
        mzml_file:
        peak_file:
        sample_name:
        picking_method:
        sample_type:
        half_isolation_window:
        allow_last_overlap:
        rt_shifts:
        mz_shifts:

    Returns: ???

    """
    self.sample_names.append(sample_name)
    self.sample_types.append(sample_type)

    these_peaks, frag_intensities = [], []
    temp_boxes = self.load_boxes(peak_file, picking_method)
    temp_boxes = update_picked_boxes(temp_boxes, rt_shifts, mz_shifts)
    self.list_of_boxes.append(temp_boxes)

    mzml = path_or_mzml(mzml_file)
    scans2boxes, boxes2scans = map_boxes_to_scans(
        mzml,
        temp_boxes,
        half_isolation_window=half_isolation_window,
        allow_last_overlap=allow_last_overlap,
    )
    precursor_intensities, scores = get_precursor_intensities(boxes2scans, temp_boxes, "max")

    for i, box in enumerate(temp_boxes):
        source_id = f"{sample_name}_{i}"
        peak_mz = box.mz
        peak_rt = box.rt_in_seconds
        these_peaks.append(Peak(peak_mz, peak_rt, box.height, sample_name, source_id))
        frag_intensities.append(precursor_intensities[i])

    self._align(these_peaks, temp_boxes, frag_intensities, sample_name)

add_sample(rois, sample_name, sample_type=None, rt_shifts=None, mz_shifts=None)

TODO: ask Ross or Vinny to add comment

Parameters:
  • rois
  • sample_name
  • sample_type
  • rt_shifts
  • mz_shifts

Returns: ???

Source code in vimms/Roi.py
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def add_sample(self, rois, sample_name, sample_type=None, rt_shifts=None, mz_shifts=None):
    """
    TODO: ask Ross or Vinny to add comment

    Args:
        rois:
        sample_name:
        sample_type:
        rt_shifts:
        mz_shifts:

    Returns: ???

    """
    self.sample_names.append(sample_name)
    self.sample_types.append(sample_type)

    these_peaks, frag_intensities, temp_boxes = [], [], []
    for i, roi in enumerate(rois):
        source_id = f"{sample_name}_{i}"
        peak_mz = roi.mean_mz
        peak_rt = roi.estimate_apex()
        peak_intensity = roi.get_max_intensity()
        these_peaks.append(Peak(peak_mz, peak_rt, peak_intensity, sample_name, source_id))
        frag_intensities.append(roi.max_fragmentation_intensity)
        rt_shift = 0 if rt_shifts is None else rt_shifts[i]
        mz_shift = 0 if mz_shifts is None else mz_shifts[i]
        temp_boxes.append(roi.to_box(self.min_rt_width, self.min_mz_width, rt_shift, mz_shift))

    # do alignment, adding the peaks and boxes, and recalculating max
    # frag intensity
    self._align(these_peaks, temp_boxes, frag_intensities, sample_name)

get_boxes(method='mean')

Converts peaksets to generic boxes

Parameters:
  • method

    which method to use for the conversion

Returns: a list of vimms.Box.GenericBox objects.

Source code in vimms/Roi.py
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
def get_boxes(self, method="mean"):
    """
    Converts peaksets to generic boxes

    Args:
        method: which method to use for the conversion

    Returns: a list of [vimms.Box.GenericBox][] objects.

    """
    if method == "max":
        f1, f2 = min, max
    else:
        f1 = f2 = mean

    boxes = []
    for ps in self.peaksets:
        box_list = self.peaksets2boxes[ps]
        x1 = f1(b.pt1.x for b in box_list)
        x2 = f2(b.pt2.x for b in box_list)
        y1 = f1(b.pt1.y for b in box_list)
        y2 = f2(b.pt2.y for b in box_list)
        intensity = max(self.peaksets2fragintensities[ps])
        boxes.append(
            GenericBox(
                x1,
                x2,
                y1,
                y2,
                intensity=intensity,
                min_xwidth=self.min_rt_width,
                min_ywidth=self.min_mz_width,
            )
        )
    return boxes

get_max_frag_intensities()

Returns the maximum fragmentation intensities of peaksets

Source code in vimms/Roi.py
1078
1079
1080
1081
1082
def get_max_frag_intensities(self):
    """
    Returns the maximum fragmentation intensities of peaksets
    """
    return [max(self.peaksets2fragintensities[ps]) for ps in self.peaksets]

to_matrix()

Converts aligned peaksets to nicely formatted intensity matrix (rows: peaksets, columns: files)

Source code in vimms/Roi.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
def to_matrix(self):
    """
    Converts aligned peaksets to nicely formatted intensity matrix
    (rows: peaksets, columns: files)
    """
    return np.array(
        [[ps.get_intensity(fname) for fname in self.files_loaded] for ps in self.peaksets],
        dtype=np.double,
    )

RoiBuilder

A class to construct ROIs. This can be used in real-time to track ROIs in a controller, or for extracting ROIs from an mzML file.

Source code in vimms/Roi.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
class RoiBuilder:
    """
    A class to construct ROIs. This can be used in real-time to track ROIs
    in a controller, or for extracting ROIs from an mzML file.
    """

    def __init__(self, roi_params, smartroi_params=None):
        """
        Initialises an ROI Builder object.

        Args:
            roi_params: parameters for ROI building, as defined in [vimms.Roi.RoiBuilderParams][].
            smartroi_params: other SmartROI parameters, as defined in
                             [vimms.Roi.SmartRoiParams][].
            grid: a grid object, if available
        """
        self.roi_params = roi_params
        self.smartroi_params = smartroi_params

        self.roi_type = ROI_TYPE_NORMAL
        if self.smartroi_params is not None:
            self.roi_type = ROI_TYPE_SMART
        assert self.roi_type in [ROI_TYPE_NORMAL, ROI_TYPE_SMART]

        # Create ROI
        self.live_roi = []
        self.dead_roi = []
        self.junk_roi = []

        # fragmentation to Roi dictionaries
        self.frag_roi_dicts = []  # scan_id, roi_id, precursor_intensity
        self.roi_id_counter = 0

        # count how many times an ROI is not grown
        self.skipped_roi_count = defaultdict(int)

    # flake8: noqa: C901
    def update_roi(self, new_scan):
        """
        Updates ROI in real-time based on incoming scans

        Args:
            new_scan: a newly arriving Scan object

        Returns: None

        """
        if new_scan.ms_level == 1:

            # Sort ROIs in live_roi according to their m/z values.
            # Ensure that the live roi fragmented flags and the last RT
            # are also consistent with the sorting order.
            self.live_roi.sort()

            # Current scan retention time of the MS1 scan is the RT of all
            # points in this scan
            current_rt = new_scan.rt

            # check that there's no ROI with skip_count > self.max_skips_allowed
            skip_counts = np.array(list(self.skipped_roi_count.values()))
            assert np.sum(skip_counts > self.roi_params.max_gaps_allowed) == 0

            # The set of ROIs that are not grown yet.
            # Initially all currently live ROIs are included, and they're
            # removed once grown.
            not_grew = set(self.live_roi)

            # For every (mz, intensity) in scan ..
            for idx in range(len(new_scan.intensities)):
                current_intensity = new_scan.intensities[idx]
                current_mz = new_scan.mzs[idx]

                if current_intensity >= self.roi_params.min_roi_intensity:

                    # Create a dummy ROI object to represent the current m/z
                    # value. This produces either a normal ROI or smart ROI
                    # object, depending on self.roi_type
                    roi = self._get_roi_obj(current_mz, 0, 0, None)

                    # Match dummy ROI to currently live ROIs based on mean
                    # m/z values. If no match, then return None
                    match_roi = self._match(roi, self.live_roi, self.roi_params.mz_tol)
                    if match_roi:

                        # Got a match, so we grow this ROI
                        match_roi.add(current_mz, current_rt, current_intensity)

                        # ROI has been matched and can be removed from not_grew
                        if match_roi in not_grew:
                            not_grew.remove(match_roi)

                            # this ROI has been grown so delete from skip count if possible
                            try:
                                del self.skipped_roi_count[match_roi]
                            except KeyError:
                                pass

                    else:

                        # No match, so create a new ROI and insert it in the
                        # right place in the sorted list
                        new_roi = self._get_roi_obj(
                            current_mz, current_rt, current_intensity, self.roi_id_counter
                        )
                        self.roi_id_counter += 1
                        bisect.insort_right(self.live_roi, new_roi)

            # Separate the ROIs that have not been grown into dead or junk ROIs
            # Dead ROIs are longer than self.min_roi_length but they haven't
            # been grown. Junk ROIs are too short and not grown.
            for roi in not_grew:

                # if too much gaps ...
                self.skipped_roi_count[roi] += 1
                if self.skipped_roi_count[roi] > self.roi_params.max_gaps_allowed:

                    # then set the roi to either dead or junk (depending on length)
                    if roi.get_num_unique_scans() >= self.roi_params.min_roi_length:
                        self.dead_roi.append(roi)
                    else:
                        self.junk_roi.append(roi)

                    # Remove not-grown ROI from the list of live ROIs
                    pos = self.live_roi.index(roi)
                    del self.live_roi[pos]

                    # this ROI is either dead or junk, so delete from skip count
                    # as we don't need to track it anymore
                    del self.skipped_roi_count[roi]

            self.current_roi_ids = [roi.id for roi in self.live_roi]
            self.current_roi_mzs = [roi.mz_list[-1] for roi in self.live_roi]
            self.current_roi_intensities = [roi.intensity_list[-1] for roi in self.live_roi]
            self.current_roi_length = np.array(
                [roi.get_num_unique_scans() for roi in self.live_roi]
            )

    # flake8: noqa: C901
    def _match(self, mz, roi_list, mz_tol):
        """
        Find the RoI that a particular mz falls into. If it falls into nothing,
        return None.

        Args:
            mz: an ROI object containing the m/z we want to find
            roi_list: the list of other ROIs to determine where to place the
                      mz ROI into
            mz_tol: m/z tolerance. This is the window above and below the
                    mean_mz of the RoI.
                    E.g. if mz_tol = 10 ppm, then it looks plus and minus 10 ppm

        Returns: the ROI that has been matched, or None if not found.

        """
        if len(roi_list) == 0:
            return None
        pos = bisect.bisect_right(roi_list, mz)

        if pos == len(roi_list):
            dist_left = 1e6 * (mz.mean_mz - roi_list[pos - 1].mean_mz) / mz.mean_mz

            if dist_left < mz_tol:
                return roi_list[pos - 1]
            else:
                return None

        elif pos == 0:
            dist_right = 1e6 * (roi_list[pos].mean_mz - mz.mean_mz) / mz.mean_mz

            if dist_right < mz_tol:
                return roi_list[pos]
            else:
                return None

        else:
            dist_left = 1e6 * (mz.mean_mz - roi_list[pos - 1].mean_mz) / mz.mean_mz
            dist_right = 1e6 * (roi_list[pos].mean_mz - mz.mean_mz) / mz.mean_mz

            if dist_left < mz_tol < dist_right:
                return roi_list[pos - 1]
            elif dist_left > mz_tol > dist_right:
                return roi_list[pos]
            elif dist_left < mz_tol and dist_right < mz_tol:
                if dist_left <= dist_right:
                    return roi_list[pos - 1]
                else:
                    return roi_list[pos]
            else:
                return None

    def _get_roi_obj(self, mz, rt, intensity, roi_id):
        """
        Constructs a new ROI object based on the currently defined type in
        this builder

        Args:
            mz: the m/z value
            rt: the RT value
            intensity: the intensity value
            roi_id: the ROI id

        Returns: a new ROI object

        """
        if self.roi_type == ROI_TYPE_NORMAL:
            roi = Roi(mz, rt, intensity, id=roi_id)
        elif self.roi_type == ROI_TYPE_SMART:
            assert self.smartroi_params is not None
            roi = SmartRoi(mz, rt, intensity, self.smartroi_params, id=roi_id)
        return roi

    def get_mz_intensity(self, i):
        """
        Returns the (m/z, intensity, ROI ID) value of point at position i in
        this ROI

        Args:
            i: the index of point to return

        Returns: a tuple of (mz, intensity, roi ID)

        """
        mz = self.current_roi_mzs[i]
        intensity = self.current_roi_intensities[i]
        roi_id = self.current_roi_ids[i]
        return mz, intensity, roi_id

    def set_fragmented(self, current_task_id, i, roi_id, rt, intensity):
        """
        Updates this ROI to indicate that it has been fragmented

        Args:
            current_task_id:  the current task ID
            i: index of fragmented ROI in the live ROI list
            roi_id: the ID of ROI
            rt: time of fragmentation
            intensity: intensity at fragmentation

        Returns: None

        """
        self.live_roi[i].fragmented(rt)

        # Add information on which scan has fragmented this ROI
        self.frag_roi_dicts.append(
            {"scan_id": current_task_id, "roi_id": roi_id, "precursor_intensity": intensity}
        )

        # need to track for intensity non-overlap
        self.live_roi[i].max_fragmentation_intensity = max(
            self.live_roi[i].max_fragmentation_intensity, intensity
        )

    def add_scan_to_roi(self, scan):
        """
        Stores the information on which scans and frag events are associated
        to this ROI
        """
        frag_event_ids = np.array([event["scan_id"] for event in self.frag_roi_dicts])
        which_event = np.where(frag_event_ids == scan.scan_id)[0]
        live_roi_ids = np.array([roi.id for roi in self.live_roi])
        which_roi = np.where(live_roi_ids == self.frag_roi_dicts[which_event[0]]["roi_id"])[0]
        if len(which_roi) > 0:
            self.live_roi[which_roi[0]].add_fragmentation_event(
                scan, self.frag_roi_dicts[which_event[0]]["precursor_intensity"]
            )
            del self.frag_roi_dicts[which_event[0]]
        else:
            pass  # hopefully shouldnt happen

    def get_rois(self):
        """
        Returns all ROIs
        """
        return self.live_roi + self.dead_roi

    def get_good_rois(self):
        """
        Returns all ROIs above filtering criteria
        """
        # length check
        filtered_roi = [
            roi
            for roi in self.live_roi
            if roi.get_num_unique_scans() >= self.roi_params.min_roi_length
        ]

        # intensity check:
        # Keep only the ROIs that can be fragmented above
        # at_least_one_point_above threshold.
        all_roi = filtered_roi + self.dead_roi
        if self.roi_params.at_least_one_point_above > 0:
            keep = []
            for roi in all_roi:
                if any(it > self.roi_params.at_least_one_point_above for it in roi.intensity_list):
                    keep.append(roi)
        else:
            keep = all_roi
        return keep

__init__(roi_params, smartroi_params=None)

Initialises an ROI Builder object.

Parameters:
Source code in vimms/Roi.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def __init__(self, roi_params, smartroi_params=None):
    """
    Initialises an ROI Builder object.

    Args:
        roi_params: parameters for ROI building, as defined in [vimms.Roi.RoiBuilderParams][].
        smartroi_params: other SmartROI parameters, as defined in
                         [vimms.Roi.SmartRoiParams][].
        grid: a grid object, if available
    """
    self.roi_params = roi_params
    self.smartroi_params = smartroi_params

    self.roi_type = ROI_TYPE_NORMAL
    if self.smartroi_params is not None:
        self.roi_type = ROI_TYPE_SMART
    assert self.roi_type in [ROI_TYPE_NORMAL, ROI_TYPE_SMART]

    # Create ROI
    self.live_roi = []
    self.dead_roi = []
    self.junk_roi = []

    # fragmentation to Roi dictionaries
    self.frag_roi_dicts = []  # scan_id, roi_id, precursor_intensity
    self.roi_id_counter = 0

    # count how many times an ROI is not grown
    self.skipped_roi_count = defaultdict(int)

add_scan_to_roi(scan)

Stores the information on which scans and frag events are associated to this ROI

Source code in vimms/Roi.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
def add_scan_to_roi(self, scan):
    """
    Stores the information on which scans and frag events are associated
    to this ROI
    """
    frag_event_ids = np.array([event["scan_id"] for event in self.frag_roi_dicts])
    which_event = np.where(frag_event_ids == scan.scan_id)[0]
    live_roi_ids = np.array([roi.id for roi in self.live_roi])
    which_roi = np.where(live_roi_ids == self.frag_roi_dicts[which_event[0]]["roi_id"])[0]
    if len(which_roi) > 0:
        self.live_roi[which_roi[0]].add_fragmentation_event(
            scan, self.frag_roi_dicts[which_event[0]]["precursor_intensity"]
        )
        del self.frag_roi_dicts[which_event[0]]
    else:
        pass  # hopefully shouldnt happen

get_good_rois()

Returns all ROIs above filtering criteria

Source code in vimms/Roi.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def get_good_rois(self):
    """
    Returns all ROIs above filtering criteria
    """
    # length check
    filtered_roi = [
        roi
        for roi in self.live_roi
        if roi.get_num_unique_scans() >= self.roi_params.min_roi_length
    ]

    # intensity check:
    # Keep only the ROIs that can be fragmented above
    # at_least_one_point_above threshold.
    all_roi = filtered_roi + self.dead_roi
    if self.roi_params.at_least_one_point_above > 0:
        keep = []
        for roi in all_roi:
            if any(it > self.roi_params.at_least_one_point_above for it in roi.intensity_list):
                keep.append(roi)
    else:
        keep = all_roi
    return keep

get_mz_intensity(i)

Returns the (m/z, intensity, ROI ID) value of point at position i in this ROI

Parameters:
  • i

    the index of point to return

Returns: a tuple of (mz, intensity, roi ID)

Source code in vimms/Roi.py
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def get_mz_intensity(self, i):
    """
    Returns the (m/z, intensity, ROI ID) value of point at position i in
    this ROI

    Args:
        i: the index of point to return

    Returns: a tuple of (mz, intensity, roi ID)

    """
    mz = self.current_roi_mzs[i]
    intensity = self.current_roi_intensities[i]
    roi_id = self.current_roi_ids[i]
    return mz, intensity, roi_id

get_rois()

Returns all ROIs

Source code in vimms/Roi.py
797
798
799
800
801
def get_rois(self):
    """
    Returns all ROIs
    """
    return self.live_roi + self.dead_roi

set_fragmented(current_task_id, i, roi_id, rt, intensity)

Updates this ROI to indicate that it has been fragmented

Parameters:
  • current_task_id

    the current task ID

  • i

    index of fragmented ROI in the live ROI list

  • roi_id

    the ID of ROI

  • rt

    time of fragmentation

  • intensity

    intensity at fragmentation

Returns: None

Source code in vimms/Roi.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
def set_fragmented(self, current_task_id, i, roi_id, rt, intensity):
    """
    Updates this ROI to indicate that it has been fragmented

    Args:
        current_task_id:  the current task ID
        i: index of fragmented ROI in the live ROI list
        roi_id: the ID of ROI
        rt: time of fragmentation
        intensity: intensity at fragmentation

    Returns: None

    """
    self.live_roi[i].fragmented(rt)

    # Add information on which scan has fragmented this ROI
    self.frag_roi_dicts.append(
        {"scan_id": current_task_id, "roi_id": roi_id, "precursor_intensity": intensity}
    )

    # need to track for intensity non-overlap
    self.live_roi[i].max_fragmentation_intensity = max(
        self.live_roi[i].max_fragmentation_intensity, intensity
    )

update_roi(new_scan)

Updates ROI in real-time based on incoming scans

Parameters:
  • new_scan

    a newly arriving Scan object

Returns: None

Source code in vimms/Roi.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def update_roi(self, new_scan):
    """
    Updates ROI in real-time based on incoming scans

    Args:
        new_scan: a newly arriving Scan object

    Returns: None

    """
    if new_scan.ms_level == 1:

        # Sort ROIs in live_roi according to their m/z values.
        # Ensure that the live roi fragmented flags and the last RT
        # are also consistent with the sorting order.
        self.live_roi.sort()

        # Current scan retention time of the MS1 scan is the RT of all
        # points in this scan
        current_rt = new_scan.rt

        # check that there's no ROI with skip_count > self.max_skips_allowed
        skip_counts = np.array(list(self.skipped_roi_count.values()))
        assert np.sum(skip_counts > self.roi_params.max_gaps_allowed) == 0

        # The set of ROIs that are not grown yet.
        # Initially all currently live ROIs are included, and they're
        # removed once grown.
        not_grew = set(self.live_roi)

        # For every (mz, intensity) in scan ..
        for idx in range(len(new_scan.intensities)):
            current_intensity = new_scan.intensities[idx]
            current_mz = new_scan.mzs[idx]

            if current_intensity >= self.roi_params.min_roi_intensity:

                # Create a dummy ROI object to represent the current m/z
                # value. This produces either a normal ROI or smart ROI
                # object, depending on self.roi_type
                roi = self._get_roi_obj(current_mz, 0, 0, None)

                # Match dummy ROI to currently live ROIs based on mean
                # m/z values. If no match, then return None
                match_roi = self._match(roi, self.live_roi, self.roi_params.mz_tol)
                if match_roi:

                    # Got a match, so we grow this ROI
                    match_roi.add(current_mz, current_rt, current_intensity)

                    # ROI has been matched and can be removed from not_grew
                    if match_roi in not_grew:
                        not_grew.remove(match_roi)

                        # this ROI has been grown so delete from skip count if possible
                        try:
                            del self.skipped_roi_count[match_roi]
                        except KeyError:
                            pass

                else:

                    # No match, so create a new ROI and insert it in the
                    # right place in the sorted list
                    new_roi = self._get_roi_obj(
                        current_mz, current_rt, current_intensity, self.roi_id_counter
                    )
                    self.roi_id_counter += 1
                    bisect.insort_right(self.live_roi, new_roi)

        # Separate the ROIs that have not been grown into dead or junk ROIs
        # Dead ROIs are longer than self.min_roi_length but they haven't
        # been grown. Junk ROIs are too short and not grown.
        for roi in not_grew:

            # if too much gaps ...
            self.skipped_roi_count[roi] += 1
            if self.skipped_roi_count[roi] > self.roi_params.max_gaps_allowed:

                # then set the roi to either dead or junk (depending on length)
                if roi.get_num_unique_scans() >= self.roi_params.min_roi_length:
                    self.dead_roi.append(roi)
                else:
                    self.junk_roi.append(roi)

                # Remove not-grown ROI from the list of live ROIs
                pos = self.live_roi.index(roi)
                del self.live_roi[pos]

                # this ROI is either dead or junk, so delete from skip count
                # as we don't need to track it anymore
                del self.skipped_roi_count[roi]

        self.current_roi_ids = [roi.id for roi in self.live_roi]
        self.current_roi_mzs = [roi.mz_list[-1] for roi in self.live_roi]
        self.current_roi_intensities = [roi.intensity_list[-1] for roi in self.live_roi]
        self.current_roi_length = np.array(
            [roi.get_num_unique_scans() for roi in self.live_roi]
        )

RoiBuilderParams

A parameter object that stores various settings required for ROIBuilder

Source code in vimms/Roi.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
class RoiBuilderParams:
    """
    A parameter object that stores various settings required for ROIBuilder
    """

    def __init__(
        self,
        mz_tol=10,
        min_roi_length=0,
        min_roi_intensity=0,
        at_least_one_point_above=0,
        start_rt=0,
        stop_rt=1e5,
        max_gaps_allowed=0,
    ):
        """
        Initialises an RoiBuilderParams object

        Args:
            mz_tol: m/z tolerance
            min_roi_length: minimum ROI length
            min_roi_intensity: minimum intensity to be included for ROI building
            at_least_one_point_above: keep only the ROIs containing at least one point
                                      above this threshold
            start_rt: start RT of scans to be included for ROI building
            stop_rt: end RT of scans to be included for ROI building
            max_gaps_allowed: the number of gaps allowed in successive scans
                              when building ROIs
        """
        if mz_tol < 0.1:
            logger.warning(f"Is your m/z tolerance correct? mz_tol={mz_tol}")

        self.mz_tol = mz_tol
        self.min_roi_length = min_roi_length
        self.min_roi_intensity = min_roi_intensity
        self.at_least_one_point_above = at_least_one_point_above
        self.start_rt = start_rt
        self.stop_rt = stop_rt
        self.max_gaps_allowed = max_gaps_allowed

    def __repr__(self):
        return str(self.__dict__)

__init__(mz_tol=10, min_roi_length=0, min_roi_intensity=0, at_least_one_point_above=0, start_rt=0, stop_rt=100000.0, max_gaps_allowed=0)

Initialises an RoiBuilderParams object

Parameters:
  • mz_tol

    m/z tolerance

  • min_roi_length

    minimum ROI length

  • min_roi_intensity

    minimum intensity to be included for ROI building

  • at_least_one_point_above

    keep only the ROIs containing at least one point above this threshold

  • start_rt

    start RT of scans to be included for ROI building

  • stop_rt

    end RT of scans to be included for ROI building

  • max_gaps_allowed

    the number of gaps allowed in successive scans when building ROIs

Source code in vimms/Roi.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def __init__(
    self,
    mz_tol=10,
    min_roi_length=0,
    min_roi_intensity=0,
    at_least_one_point_above=0,
    start_rt=0,
    stop_rt=1e5,
    max_gaps_allowed=0,
):
    """
    Initialises an RoiBuilderParams object

    Args:
        mz_tol: m/z tolerance
        min_roi_length: minimum ROI length
        min_roi_intensity: minimum intensity to be included for ROI building
        at_least_one_point_above: keep only the ROIs containing at least one point
                                  above this threshold
        start_rt: start RT of scans to be included for ROI building
        stop_rt: end RT of scans to be included for ROI building
        max_gaps_allowed: the number of gaps allowed in successive scans
                          when building ROIs
    """
    if mz_tol < 0.1:
        logger.warning(f"Is your m/z tolerance correct? mz_tol={mz_tol}")

    self.mz_tol = mz_tol
    self.min_roi_length = min_roi_length
    self.min_roi_intensity = min_roi_intensity
    self.at_least_one_point_above = at_least_one_point_above
    self.start_rt = start_rt
    self.stop_rt = stop_rt
    self.max_gaps_allowed = max_gaps_allowed

SmartRoi

Bases: Roi

A smarter ROI class that can track the states in which it should be fragmented.

SmartROI is described further in the following paper: - Davies, Vinny, et al. "Rapid Development of Improved Data-Dependent Acquisition Strategies." Analytical chemistry 93.14 (2021): 5676-5683.

Source code in vimms/Roi.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
class SmartRoi(Roi):
    """
    A smarter ROI class that can track the states in which it should be
    fragmented.

    SmartROI is described further in the following paper:
    - Davies, Vinny, et al. "Rapid Development of Improved Data-Dependent
    Acquisition Strategies." Analytical chemistry 93.14 (2021): 5676-5683.
    """

    INITIAL_WAITING = 0
    CAN_FRAGMENT = 1
    AFTER_FRAGMENT = 2
    POST_PEAK = 3

    def __init__(self, mz, rt, intensity, smartroi_params, id=None):
        """
        Constructs a new Smart ROI object

        Args:
            mz: the initial m/z of this ROI.
                Can be either a single value or a list of values.
            rt: the initial rt  of this ROI.
                Can be either a single value or a list of values.
            intensity: the initial intensity  of this ROI.
                       Can be either a single value or a list of values.
            smartroi_params: other SmartROI parameters, as defined in
                             [vimms.Roi.SmartRoiParams][].
            id: the ID of this ROI
        """
        super().__init__(mz, rt, intensity, id=id)
        self.max_at_frag = 0.0
        self.max_since_last_frag = 0.0
        self.params = smartroi_params

        if self.params.initial_length_seconds > 0:
            self.status = SmartRoi.INITIAL_WAITING
            self.can_fragment = False
        else:
            self.status = SmartRoi.CAN_FRAGMENT
            self.can_fragment = True

        self.min_frag_intensity = None

    def fragmented(self, rt):
        """
        Sets this SmartROI as having been fragmented
        """
        self.is_fragmented = True
        self.can_fragment = False
        self.last_frag_rt = rt
        self.fragmented_index = len(self.mz_list) - 1
        self.max_at_frag = self.intensity_list[self.fragmented_index]
        self.max_since_last_frag = self.max_at_frag
        self.status = SmartRoi.AFTER_FRAGMENT

    def get_status(self):
        """
        Returns the current status of this SmartROI
        """
        if self.status == 0:
            return "INITIAL_WAITING"
        elif self.status == 1:
            return "CAN_FRAGMENT"
        elif self.status == 2:
            return "AFTER_FRAGMENT"
        elif self.status == 3:
            return "POST_PEAK"

    # flake8: noqa: C901
    def add(self, mz, rt, intensity):
        """
        Adds a point to this SmartROI

        Args:
            mz: the m/z value to add
            rt: the retention time value to add
            intensity: the intensity value to add

        Returns: None

        """
        super().add(mz, rt, intensity)
        if intensity > self.max_since_last_frag:
            self.max_since_last_frag = intensity

        if self.status == SmartRoi.INITIAL_WAITING:
            if self.length_in_seconds >= self.params.initial_length_seconds:
                self.status = SmartRoi.CAN_FRAGMENT
                self.can_fragment = True

        elif self.status == SmartRoi.AFTER_FRAGMENT:
            self.set_smartroi_rules()

        # code below never happens
        # elif self.status == SmartRoi.POST_PEAK:
        #     if self.rt_list[-1] - self.rt_list[
        #         self.fragmented_index] > self.params.dew:
        #         if self.intensity_list[-1] > self.min_frag_intensity:
        #             self.status = SmartRoi.CAN_FRAGMENT
        #             self.set_can_fragment(True)

    def set_smartroi_rules(self):
        # in a period after a fragmentation has happened
        # if enough time has elapsed, reset everything
        if (
            self.rt_list[-1] - self.rt_list[self.fragmented_index]
            > self.params.reset_length_seconds
        ):
            self.status = SmartRoi.CAN_FRAGMENT
            self.can_fragment = True

        elif self.rt_list[-1] - self.rt_list[self.fragmented_index] > self.params.dew:
            # standard DEW has expired so apply smartroi rules
            frag = self.intensity_list[self.fragmented_index]

            # too slow to recompute this each time
            # max_since_frag = max(self.intensity_list[self.fragmented_index:])
            # assert self.max_since_last_frag == max_since_frag

            if self.intensity_list[-1] > self.params.intensity_increase_factor * frag:
                self.status = SmartRoi.CAN_FRAGMENT
                self.can_fragment = True

            elif self.intensity_list[-1] < self.params.drop_perc * self.max_since_last_frag:
                # signal has dropped, but ROI still exists.
                self.status = SmartRoi.CAN_FRAGMENT
                self.can_fragment = True

    def get_can_fragment(self):
        """
        Returns the status of whether this SmartROI can be fragmented
        """
        return self.can_fragment

    def set_can_fragment(self, status):
        """
        Sets the status of this SmartROI

        Args:
            status: True if this SmartROI can be fragmented again,
                    False otherwise

        Returns: None

        """
        self.can_fragment = status

__init__(mz, rt, intensity, smartroi_params, id=None)

Constructs a new Smart ROI object

Parameters:
  • mz

    the initial m/z of this ROI. Can be either a single value or a list of values.

  • rt

    the initial rt of this ROI. Can be either a single value or a list of values.

  • intensity

    the initial intensity of this ROI. Can be either a single value or a list of values.

  • smartroi_params

    other SmartROI parameters, as defined in vimms.Roi.SmartRoiParams.

  • id

    the ID of this ROI

Source code in vimms/Roi.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def __init__(self, mz, rt, intensity, smartroi_params, id=None):
    """
    Constructs a new Smart ROI object

    Args:
        mz: the initial m/z of this ROI.
            Can be either a single value or a list of values.
        rt: the initial rt  of this ROI.
            Can be either a single value or a list of values.
        intensity: the initial intensity  of this ROI.
                   Can be either a single value or a list of values.
        smartroi_params: other SmartROI parameters, as defined in
                         [vimms.Roi.SmartRoiParams][].
        id: the ID of this ROI
    """
    super().__init__(mz, rt, intensity, id=id)
    self.max_at_frag = 0.0
    self.max_since_last_frag = 0.0
    self.params = smartroi_params

    if self.params.initial_length_seconds > 0:
        self.status = SmartRoi.INITIAL_WAITING
        self.can_fragment = False
    else:
        self.status = SmartRoi.CAN_FRAGMENT
        self.can_fragment = True

    self.min_frag_intensity = None

add(mz, rt, intensity)

Adds a point to this SmartROI

Parameters:
  • mz

    the m/z value to add

  • rt

    the retention time value to add

  • intensity

    the intensity value to add

Returns: None

Source code in vimms/Roi.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def add(self, mz, rt, intensity):
    """
    Adds a point to this SmartROI

    Args:
        mz: the m/z value to add
        rt: the retention time value to add
        intensity: the intensity value to add

    Returns: None

    """
    super().add(mz, rt, intensity)
    if intensity > self.max_since_last_frag:
        self.max_since_last_frag = intensity

    if self.status == SmartRoi.INITIAL_WAITING:
        if self.length_in_seconds >= self.params.initial_length_seconds:
            self.status = SmartRoi.CAN_FRAGMENT
            self.can_fragment = True

    elif self.status == SmartRoi.AFTER_FRAGMENT:
        self.set_smartroi_rules()

fragmented(rt)

Sets this SmartROI as having been fragmented

Source code in vimms/Roi.py
339
340
341
342
343
344
345
346
347
348
349
def fragmented(self, rt):
    """
    Sets this SmartROI as having been fragmented
    """
    self.is_fragmented = True
    self.can_fragment = False
    self.last_frag_rt = rt
    self.fragmented_index = len(self.mz_list) - 1
    self.max_at_frag = self.intensity_list[self.fragmented_index]
    self.max_since_last_frag = self.max_at_frag
    self.status = SmartRoi.AFTER_FRAGMENT

get_can_fragment()

Returns the status of whether this SmartROI can be fragmented

Source code in vimms/Roi.py
424
425
426
427
428
def get_can_fragment(self):
    """
    Returns the status of whether this SmartROI can be fragmented
    """
    return self.can_fragment

get_status()

Returns the current status of this SmartROI

Source code in vimms/Roi.py
351
352
353
354
355
356
357
358
359
360
361
362
def get_status(self):
    """
    Returns the current status of this SmartROI
    """
    if self.status == 0:
        return "INITIAL_WAITING"
    elif self.status == 1:
        return "CAN_FRAGMENT"
    elif self.status == 2:
        return "AFTER_FRAGMENT"
    elif self.status == 3:
        return "POST_PEAK"

set_can_fragment(status)

Sets the status of this SmartROI

Parameters:
  • status

    True if this SmartROI can be fragmented again, False otherwise

Returns: None

Source code in vimms/Roi.py
430
431
432
433
434
435
436
437
438
439
440
441
def set_can_fragment(self, status):
    """
    Sets the status of this SmartROI

    Args:
        status: True if this SmartROI can be fragmented again,
                False otherwise

    Returns: None

    """
    self.can_fragment = status

SmartRoiParams

A parameter object that stores various settings required for SmartRoi

Source code in vimms/Roi.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
class SmartRoiParams:
    """
    A parameter object that stores various settings required for SmartRoi
    """

    def __init__(
        self,
        initial_length_seconds=5,
        reset_length_seconds=1e6,
        intensity_increase_factor=10,
        dew=15,
        drop_perc=0.1 / 100,
    ):
        """
        Initialises a SmartRoiParams object

        Args:
            initial_length_seconds: the initial length (in seconds) before
                                    this ROI can be fragmented
            reset_length_seconds: the length (in seconds) before this ROI
                                  can be fragmented again (CAN_FRAGMENT)
            intensity_increase_factor: a factor of which the intensity
                                       should increase from the **minimum** since
                                       last fragmentation before this ROI can be fragmented again
            dew: dynamic exclusion window (DEW) in seconds before this ROI
                 can be fragmented again
            drop_perc: percentage drop in intensity since last fragmentation
                       before this ROI can be fragmented again
        """
        self.initial_length_seconds = initial_length_seconds
        self.reset_length_seconds = reset_length_seconds
        self.intensity_increase_factor = intensity_increase_factor
        self.drop_perc = drop_perc
        self.dew = dew

    def __repr__(self):
        return str(self.__dict__)

__init__(initial_length_seconds=5, reset_length_seconds=1000000.0, intensity_increase_factor=10, dew=15, drop_perc=0.1 / 100)

Initialises a SmartRoiParams object

Parameters:
  • initial_length_seconds

    the initial length (in seconds) before this ROI can be fragmented

  • reset_length_seconds

    the length (in seconds) before this ROI can be fragmented again (CAN_FRAGMENT)

  • intensity_increase_factor

    a factor of which the intensity should increase from the minimum since last fragmentation before this ROI can be fragmented again

  • dew

    dynamic exclusion window (DEW) in seconds before this ROI can be fragmented again

  • drop_perc

    percentage drop in intensity since last fragmentation before this ROI can be fragmented again

Source code in vimms/Roi.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def __init__(
    self,
    initial_length_seconds=5,
    reset_length_seconds=1e6,
    intensity_increase_factor=10,
    dew=15,
    drop_perc=0.1 / 100,
):
    """
    Initialises a SmartRoiParams object

    Args:
        initial_length_seconds: the initial length (in seconds) before
                                this ROI can be fragmented
        reset_length_seconds: the length (in seconds) before this ROI
                              can be fragmented again (CAN_FRAGMENT)
        intensity_increase_factor: a factor of which the intensity
                                   should increase from the **minimum** since
                                   last fragmentation before this ROI can be fragmented again
        dew: dynamic exclusion window (DEW) in seconds before this ROI
             can be fragmented again
        drop_perc: percentage drop in intensity since last fragmentation
                   before this ROI can be fragmented again
    """
    self.initial_length_seconds = initial_length_seconds
    self.reset_length_seconds = reset_length_seconds
    self.intensity_increase_factor = intensity_increase_factor
    self.drop_perc = drop_perc
    self.dew = dew

cosine_score(u, v)

Computes the cosine similarity between two vectors

Parameters:
  • u

    first vector

  • v

    second vector

Returns: the cosine similarity

Source code in vimms/Roi.py
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
def cosine_score(u, v):
    """
    Computes the cosine similarity between two vectors

    Args:
        u: first vector
        v: second vector

    Returns: the cosine similarity

    """
    numerator = (u * v).sum()
    denominator = np.sqrt((u * u).sum()) * np.sqrt((v * v).sum())
    return numerator / denominator

greedy_roi_cluster(roi_list, corr_thresh=0.75, corr_type='cosine')

Performs a greedy clustering of ROIs

Parameters:
  • roi_list

    a list of ROIs to cluster

  • corr_thresh

    the threshold on correlation for clustering

  • corr_type

    correlation type, currently unused

Returns: a list of lists of ROIs, each member list is a cluster.

Source code in vimms/Roi.py
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
def greedy_roi_cluster(roi_list, corr_thresh=0.75, corr_type="cosine"):
    """
    Performs a greedy clustering of ROIs

    Args:
        roi_list: a list of ROIs to cluster
        corr_thresh: the threshold on correlation for clustering
        corr_type: correlation type, currently unused

    Returns: a list of lists of ROIs, each member list is a cluster.

    """
    # sort in descending intensity
    roi_list_copy = [r for r in roi_list]
    roi_list_copy.sort(key=lambda x: max(x.intensity_list), reverse=True)
    roi_clusters = []
    while len(roi_list_copy) > 0:
        roi_clusters.append([roi_list_copy[0]])
        remove_idx = [0]
        if len(roi_list_copy) > 1:
            for i, r in enumerate(roi_list_copy[1:]):
                corr = roi_correlation(roi_list_copy[0], r)
                if corr > corr_thresh:
                    roi_clusters[-1].append(r)
                    remove_idx.append(i + 1)
        remove_idx.sort(reverse=True)
        for r in remove_idx:
            del roi_list_copy[r]

    return roi_clusters

make_roi(input_file, roi_params)

Make ROIs from an input file

Parameters:
  • input_file

    input mzML file

  • roi_params

    a RoiBuilderParams object

the list of good ROI objects that have been filtered according to
  • certain criteria.

Source code in vimms/Roi.py
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
def make_roi(input_file, roi_params):
    """
    Make ROIs from an input file

    Args:
        input_file: input mzML file
        roi_params: a RoiBuilderParams object

    Returns: the list of good ROI objects that have been filtered according to
             certain criteria.

    """

    from vimms.MassSpec import Scan  # import in fn. body to avoid circular import

    run = pymzml.run.Reader(
        input_file,
        MS1_Precision=5e-6,
        extraAccessions=[("MS:1000016", ["value", "unitName"])],
        obo_version="4.0.1",
    )

    scan_id = 0
    roi_builder = RoiBuilder(roi_params)
    for i, spectrum in enumerate(run):
        ms_level = 1
        if spectrum["ms level"] == ms_level:
            current_ms1_scan_rt, units = spectrum.scan_time

            # check that ms1 scan (in seconds) is within bound
            if units == "minute":
                current_ms1_scan_rt *= 60.0
            if current_ms1_scan_rt < roi_params.start_rt:
                continue
            if current_ms1_scan_rt > roi_params.stop_rt:
                break

            # get the raw peak data from spectrum
            mzs, intensities = spectrum_to_arrays(spectrum)

            # update the ROI construction based on the new scan
            scan = Scan(scan_id, mzs, intensities, ms_level, current_ms1_scan_rt)
            roi_builder.update_roi(scan)
            scan_id += 1

    good_roi = roi_builder.get_good_rois()
    return good_roi

plot_roi(roi, statuses=None, log=False)

Plots an ROI

Parameters:
  • roi

    the ROI to plot

  • statuses

    flags for coloring

  • log

    whether to log the intensity (defaults False)

Returns: None

Source code in vimms/Roi.py
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
def plot_roi(roi, statuses=None, log=False):
    """
    Plots an ROI

    Args:
        roi: the ROI to plot
        statuses: flags for coloring
        log: whether to log the intensity (defaults False)

    Returns: None

    """
    if log:
        intensities = np.log(roi.intensity_list)
        plt.ylabel("Log Intensity")
    else:
        intensities = roi.intensity_list
        plt.ylabel("Intensity")
    if statuses is not None:
        colours = []
        for s in statuses:
            if s == "Noise":
                colours.append("red")
            elif s == "Increase":
                colours.append("blue")
            elif s == "Decrease":
                colours.append("yellow")
            else:
                colours.append("green")
        plt.scatter(roi.rt_list, intensities, color=colours)
    else:
        plt.scatter(roi.rt_list, intensities)
    plt.xlabel("RT")
    plt.show()

roi_correlation(roi1, roi2, min_rt_point_overlap=5, method='pearson')

Computes the correlation between two ROI objects

Parameters:
  • roi1

    first ROI

  • roi2

    second ROI

  • min_rt_point_overlap

    minimum points that overlap in RT, currently unused

  • method

    if 'pearson' then Peason's correlation is used, otherwise the cosine score is used

Returns: the correlation between the two ROIs.

Source code in vimms/Roi.py
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
def roi_correlation(roi1, roi2, min_rt_point_overlap=5, method="pearson"):
    """
    Computes the correlation between two ROI objects

    Args:
        roi1: first ROI
        roi2: second ROI
        min_rt_point_overlap: minimum points that overlap in RT,
                              currently unused
        method: if 'pearson' then Peason's correlation is
                used, otherwise the cosine score is used

    Returns: the correlation between the two ROIs.

    """
    # flip around so that roi1 starts earlier (or equal)
    if roi2.rt_list[0] < roi1.rt_list[0]:
        temp = roi2
        roi2 = roi1
        roi1 = temp

    # check that they meet the min_rt_point overlap
    if roi1.rt_list[-1] < roi2.rt_list[0]:
        # no overlap at all
        return 0.0

    # find the position of the first element in roi2 in roi1
    pos = roi1.rt_list.index(roi2.rt_list[0])

    # print roi1.rt_list
    # print roi2.rt_list
    # print pos

    total_length = max([len(roi1.rt_list), len(roi2.rt_list) + pos])
    # print total_length

    r1 = np.zeros((total_length), np.double)
    r2 = np.zeros_like(r1)

    r1[: len(roi1.rt_list)] = roi1.intensity_list
    r2[pos: pos + len(roi2.rt_list)] = roi2.intensity_list

    if method == "pearson":
        r, _ = pearsonr(r1, r2)
    else:
        r = cosine_score(r1, r2)

    return r

spectrum_to_arrays(spectrum)

Converts pymzml spectrum to parallel arrays

Parameters:
  • spectrum

    a pymzml spectrum object

a tuple (mzs, intensities) where mzs and intensities are numpy
  • arrays of m/z and intensity values

Source code in vimms/Roi.py
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
def spectrum_to_arrays(spectrum):
    """
    Converts pymzml spectrum to parallel arrays

    Args:
        spectrum: a pymzml spectrum object

    Returns: a tuple (mzs, intensities) where mzs and intensities are numpy
             arrays of m/z and intensity values

    """
    mzs = []
    intensities = []
    for mz, intensity in spectrum.peaks("raw"):
        mzs.append(mz)
        intensities.append(intensity)
    mzs = np.array(mzs)
    intensities = np.array(intensities)
    return mzs, intensities

update_picked_boxes(picked_boxes, rt_shifts, mz_shifts)

Updates picked boxes ??

Parameters:
  • picked_boxes
  • rt_shifts
  • mz_shifts

Returns: ???

Source code in vimms/Roi.py
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
def update_picked_boxes(picked_boxes, rt_shifts, mz_shifts):
    """
    Updates picked boxes ??

    Args:
        picked_boxes:
        rt_shifts:
        mz_shifts:

    Returns: ???

    """
    if rt_shifts is None and mz_shifts is None:
        return picked_boxes

    new_boxes = copy.deepcopy(picked_boxes)
    for box, sec_shift, mz_shift in zip(new_boxes, rt_shifts, mz_shifts):
        if rt_shifts is not None:
            sec_shift = float(sec_shift)
            min_shift = sec_shift / 60.0

            box.rt += min_shift
            box.rt_in_minutes += min_shift
            box.rt_in_seconds += sec_shift
            box.rt_range = [r + min_shift for r in box.rt_range]
            box.rt_range_in_seconds = [r + sec_shift for r in box.rt_range_in_seconds]

        if mz_shifts is not None:
            mz_shift = float(mz_shift)
            box.mz += mz_shift
            box.mz_range = [r + mz_shift for r in box.mz_range]