Skip to content

Commit

Permalink
first syn run without runtime error
Browse files Browse the repository at this point in the history
  • Loading branch information
TimOliverMaier committed Nov 4, 2023
1 parent 2d7dd35 commit f04c096
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 27 deletions.
11 changes: 11 additions & 0 deletions mscore/src/mz_spectrum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,17 @@ impl std::ops::Add for MzSpectrum {
}
}

impl std::ops::Mul<f64> for MzSpectrum {
type Output = Self;
fn mul(self, scale: f64) -> Self::Output{
let mut scaled_intensities: Vec<f64> = vec![0.0; self.intensity.len()];
for (idx,intensity) in self.intensity.iter().enumerate(){
scaled_intensities[idx] = scale*intensity;
}
Self{ mz: self.mz.clone(), intensity: scaled_intensities}

}
}
/// Represents a mass spectrum with associated m/z indices, m/z values, and intensities
#[derive(Clone)]
pub struct IndexedMzSpectrum {
Expand Down
38 changes: 28 additions & 10 deletions pyims/pyims/data/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,20 @@ def from_jsons(cls, jsons:str) -> MzSpectrum:
json_dict:dict = json.loads(jsons)
mz = json_dict["mz"]
intensity = json_dict["intensity"]
return cls(mz, intensity)
return cls(np.array(mz, dtype=np.float64), np.array(intensity, dtype=np.float64))

@classmethod
def from_spectra_list(cls, spectra_list:List[MzSpectrum], resolution: int, centroided: bool)->MzSpectrum:
pass
def from_mz_spectra_list(cls, spectra_list:List[MzSpectrum], resolution: int)->MzSpectrum:
"""Generates a convoluted mass spectrum by adding all spectra in the given list.
Args:
spectra_list (List[MzSpectrum]): List of mass spectra.
resolution (int): Desired resolution of returned spectrum.
Returns:
MzSpectrum: Convoluted spectrum.
"""
return cls.from_py_mz_spectrum(pims.PyMzSpectrum.from_mzspectra_list([spectrum.__spec_ptr for spectrum in spectra_list], resolution))

def __init__(self, mz: NDArray[np.float64], intensity: NDArray[np.float64]):
"""MzSpectrum class.
Expand Down Expand Up @@ -78,6 +87,18 @@ def from_py_mz_spectrum(cls, spec: pims.PyMzSpectrum):

def __repr__(self):
return f"MzSpectrum(num_peaks={len(self.mz)})"

def __mul__(self, scale) -> MzSpectrum:
"""Overwrite * operator for scaling of spectrum
Args:
scale (float): Scale.
Returns:
MzSpectrum: Scaled spectrum
"""
tmp: pims.PyMzSpectrum = self.__spec_ptr * scale
return self.from_py_mz_spectrum(tmp)

def to_windows(self, window_length: float = 10, overlapping: bool = True, min_num_peaks: int = 5,
min_intensity: float = 1) -> Tuple[NDArray, List[MzSpectrum]]:
Expand Down Expand Up @@ -106,7 +127,7 @@ def to_resolution(self, resolution: int) -> MzSpectrum:
Returns:
MzSpectrum: A new `MzSpectrum` where m/z values are binned according to the given resolution.
"""
return self.__spec_ptr.to_resolution(resolution)
return MzSpectrum.from_py_mz_spectrum(self.__spec_ptr.to_resolution(resolution))

def filter(self, mz_min: float = 0.0, mz_max: float = 2000.0, intensity_min: float = 0.0,
intensity_max: float = 1e9) -> MzSpectrum:
Expand Down Expand Up @@ -140,8 +161,8 @@ def to_jsons(self) -> str:
generates json string representation of MzSpectrum
"""
json_dict = {}
json_dict["mz"] = self.mz().tolist()
json_dict["intensity"] = self.intensity().tolist()
json_dict["mz"] = self.mz.tolist()
json_dict["intensity"] = self.intensity.tolist()

return json.dumps(json_dict)

Expand Down Expand Up @@ -205,7 +226,7 @@ def __repr__(self):
return f"MzSpectrumVectorized(num_values={len(self.values)})"


class TimsSpectrum(AbstractSpectrum):
class TimsSpectrum:
def __init__(self, frame_id: int, scan: int, retention_time: float, mobility: float, ms_type: int,
index: NDArray[np.int32], mz: NDArray[np.float64], intensity: NDArray[np.float64]):
"""TimsSpectrum class.
Expand Down Expand Up @@ -339,6 +360,3 @@ def __repr__(self):
return (f"TimsSpectrum(id={self.frame_id}, retention_time={np.round(self.retention_time, 2)}, "
f"scan={self.scan}, mobility={np.round(self.mobility, 2)}, ms_type={self.ms_type}, "
f"num_peaks={len(self.index)})")

def to_jsons(self) -> str:
return super().to_jsons()
2 changes: 1 addition & 1 deletion pyims/pyims/feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def generate_feature(self, mz: float, charge: int,
frame_list = []

spec = pattern_generator.generate_spectrum(mz, charge, min_intensity=5, centroided=True, k=12)
mz, intensity = spec.mz(), spec.intensity() / np.max(spec.intensity()) * 100
mz, intensity = spec.mz, spec.intensity / np.max(spec.intensity) * 100

for i in range(num_rt):

Expand Down
16 changes: 9 additions & 7 deletions pyims/pyims/isotopes.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def numba_generate_pattern(lower_bound: float,
mzs = np.linspace(lower_bound,upper_bound,size)
intensities = iso(mzs,mass,charge,sigma,amp,k,step_size)

return mzs + MASS_PROTON, intensities.astype(np.int64)
return mzs + MASS_PROTON, intensities

#@numba.jit(nopython= True)
def numba_ion_sampler(mass: float, charge: int, sigma: ArrayLike, k: int, ion_count: int, intensity_per_ion: int ):
Expand Down Expand Up @@ -158,7 +158,7 @@ def _get_component(u: float, weights_cum_sum: ArrayLike = weights) -> int:

mz = ((comps*MASS_NEUTRON) + mass) / charge + MASS_PROTON + devs
i = np.ones_like(mz) * intensity_per_ion
return (mz, i.astype(np.int64))
return (mz, i)

@numba.jit
def create_initial_feature_distribution(num_rt: int, num_im: int,
Expand Down Expand Up @@ -200,8 +200,8 @@ def generate_pattern(self, mass: float, charge: int, k: int = 7,
min_intensity: int = 5) -> Tuple[ArrayLike, ArrayLike]:
pass

def generate_spectrum(self, mass: int, charge: int, k: int = 7,
amp :Optional[float] = None, resolution:float =3, min_intensity: int = 5, centroided: bool = True) -> MzSpectrum:
def generate_spectrum(self, mass: int, charge: int, min_intensity: int = 5, k: int = 7,
amp :Optional[float] = None, resolution:float =3, centroided: bool = True) -> MzSpectrum:
if amp is None:
amp = self.default_abundancy

Expand All @@ -210,6 +210,7 @@ def generate_spectrum(self, mass: int, charge: int, k: int = 7,

mz, i = numba_generate_pattern(lower_bound=lb, upper_bound=ub,
mass=mass, charge=charge, amp=amp, k=k, resolution=resolution)
#Todo implement centroid method

if centroided:
return MzSpectrum(mz, i)\
Expand All @@ -233,8 +234,9 @@ def generate_spectrum_by_sampling(self,
mz, i = numba_ion_sampler(mass, charge, sigma, k, ion_count, intensity_per_ion)

if centroided:
return MzSpectrum(mz,i)\
.to_resolution(resolution).filter(-1,-1,min_intensity)\
.to_centroided(baseline_noise_level=max(min_intensity,1), sigma=1/np.power(10,resolution-1)) #Todo implement centroid method
return ( MzSpectrum(mz,i)
.to_resolution(resolution).filter(-1,-1,min_intensity)
.to_centroided(baseline_noise_level=max(min_intensity,1), sigma=1/np.power(10,resolution-1))
)
return MzSpectrum(mz,i)\
.to_resolution(resolution).filter(-1,-1,min_intensity)
4 changes: 2 additions & 2 deletions pyims/pyims/noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ def baseline_shot_noise(spectrum:MzSpectrum,window_size:float=50,expected_noise_
"""
min_mz = spectrum.mz().min()-0.1
max_mz = spectrum.mz().max()+0.1
min_mz = spectrum.mz.min()-0.1
max_mz = spectrum.mz.max()+0.1
bins,windows = spectrum.windows(window_size,overlapping=False,min_peaks=0,min_intensity=0)
noised_spectrum = spectrum
for b,w in zip(bins,windows):
Expand Down
2 changes: 1 addition & 1 deletion pyims/pyims/proteome.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def make_sql_compatible(column):
if isinstance(column.iloc[0], (RTProfile, ScanProfile, ChargeProfile, TokenSequence)):
return column.apply(lambda x: x.jsons)
elif isinstance(column.iloc[0], MzSpectrum):
return column.apply(lambda x: x.to_jsons(only_spectrum = True))
return column.apply(lambda x: x.to_jsons())
else:
return column

Expand Down
6 changes: 3 additions & 3 deletions pyims/pyims/simulation/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ def _assemble_frame_range(frame_range, scan_id_min, scan_id_max, default_abundan
for (s_id,scan_spectra_list) in frame_dict.items():

if len(scan_spectra_list) > 0:
scan_spectrum = MzSpectrum.from_mzSpectra_list(scan_spectra_list,resolution = resolution, sigma=1/np.power(10,(resolution-1)))
output_dict["mz"].append(scan_spectrum.mz().tolist())
output_dict["intensity"].append(scan_spectrum.intensity().tolist())
scan_spectrum = MzSpectrum.from_mz_spectra_list(scan_spectra_list,resolution = resolution)
output_dict["mz"].append(scan_spectrum.mz.tolist())
output_dict["intensity"].append(scan_spectrum.intensity.tolist())
output_dict["scan_id"].append(s_id)
output_dict["frame_id"].append(f_id)
signal[f_id][s_id] = None
Expand Down
4 changes: 2 additions & 2 deletions pyims/pyims/simulation/hardware_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,6 @@ def simulate(self, sample: ProteomicsExperimentSampleSlice, device: MzSeparation
charges = joined_df["charge"].values
spectra = []
for (m, c) in zip(masses, charges):
spectrum = avg.generate_spectrum(m,c,-1,-1,amp = self.default_abundance, centroided=False)
spectrum = avg.generate_spectrum(m,c,amp = self.default_abundance, centroided=False)
spectra.append(spectrum)
return spectra
return spectra
28 changes: 27 additions & 1 deletion pyims_connector/src/py_mz_spectrum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,41 @@ impl PyMsType {
}

#[pyclass]
#[derive(Clone)]
pub struct PyMzSpectrum {
pub inner: MzSpectrum,
}

#[pymethods]

impl PyMzSpectrum {
#[new]
pub unsafe fn new(mz: &PyArray1<f64>, intensity: &PyArray1<f64>) -> PyResult<Self> {
Ok(PyMzSpectrum {
inner: MzSpectrum {
mz: mz.as_slice()?.to_vec(),
intensity: intensity.as_slice()?.to_vec(),
},
}
})
}
#[staticmethod]
pub unsafe fn from_mzspectra_list(list: Vec<PyMzSpectrum>, resolution: i32) -> PyResult<Self> {
if list.is_empty(){
Ok(PyMzSpectrum {
inner: MzSpectrum {
mz: Vec::new(),
intensity: Vec::new(),
}
})
}
else {
let mut convoluted: MzSpectrum = MzSpectrum { mz: vec![], intensity: vec![] };
for spectrum in list {
convoluted = convoluted + spectrum.inner;
}
Ok(PyMzSpectrum { inner: convoluted.to_resolution(resolution) })
}
}

#[getter]
pub fn mz(&self, py: Python) -> Py<PyArray1<f64>> {
Expand Down Expand Up @@ -86,6 +106,12 @@ impl PyMzSpectrum {
};
Ok(py_filtered)
}
pub fn __add__(&self, other: PyMzSpectrum) -> PyResult<PyMzSpectrum> {
Ok(PyMzSpectrum { inner: (self.inner.clone() + other.inner) })
}
pub fn __mul__(&self, scale: f64) -> PyResult<PyMzSpectrum> {
Ok(PyMzSpectrum { inner: (self.inner.clone() * scale) })
}
}

#[pyclass]
Expand Down

0 comments on commit f04c096

Please sign in to comment.