keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/pyOpenMS/pyTOPP/OpenSwathRTNormalizer.py
.py
3,228
95
import sys import pyopenms """ python pyTOPP/OpenSwathRTNormalizer.py --in ../source/TEST/TOPP/OpenSwathRTNormalizer_1_input.mzML \ --tr ../source/TEST/TOPP/OpenSwathRTNormalizer_1_input.TraML --out OpenSwathRTNormalizer.tmp.out \ && diff OpenSwathRTNormalizer.tmp.out ../source/TEST/TOPP/OpenSwathRTNormalizer_1_output.trafoXML """ def simple_find_best_feature(output, pairs, targeted): f_map = {} for f in output: key = f.getMetaValue("PeptideRef") if f_map.has_key(key): f_map[key].append(f) else: f_map[key] = [f] for v in f_map.values(): bestscore = -10000 for feature in v: score = feature.getMetaValue("main_var_xx_lda_prelim_score") if score > bestscore: best = feature bestscore = score pep = targeted.getPeptideByRef( feature.getMetaValue("PeptideRef") ) pairs.append( [best.getRT(), pep.getRetentionTime() ] ) def algorithm(chromatograms, targeted): # Create empty files as input and finally as output empty_swath = pyopenms.MSExperiment() trafo = pyopenms.TransformationDescription() output = pyopenms.FeatureMap(); # set up featurefinder and run featurefinder = pyopenms.MRMFeatureFinderScoring() # set the correct rt use values scoring_params = pyopenms.MRMFeatureFinderScoring().getDefaults(); scoring_params.setValue("Scores:use_rt_score",'false', '') featurefinder.setParameters(scoring_params); featurefinder.pickExperiment(chromatograms, output, targeted, trafo, empty_swath) # get the pairs pairs=[] simple_find_best_feature(output, pairs, targeted) pairs_corrected = pyopenms.MRMRTNormalizer().rm_outliers( pairs, 0.95, 0.6) pairs_corrected = [ list(p) for p in pairs_corrected] # // store transformation, using a linear model as default trafo_out = pyopenms.TransformationDescription() trafo_out.setDataPoints(pairs_corrected); model_params = pyopenms.Param() model_params.setValue("symmetric_regression", 'false', ''); model_type = "linear"; trafo_out.fitModel(model_type, model_params); return trafo_out def main(options): # load chromatograms chromatograms = pyopenms.MSExperiment() fh = pyopenms.FileHandler() fh.loadExperiment(options.infile, chromatograms) # load TraML file targeted = pyopenms.TargetedExperiment(); tramlfile = pyopenms.TraMLFile(); tramlfile.load(options.traml_in, targeted); trafo_out = algorithm(chromatograms, targeted) pyopenms.TransformationXMLFile().store(options.outfile, trafo_out); def handle_args(): import argparse usage = "" usage += "\nMRMMapper maps measured chromatograms (mzML) and the transitions used (TraML)" parser = argparse.ArgumentParser(description = usage ) parser.add_argument('--in', dest="infile", help = 'An input file containing chromatograms') parser.add_argument("--tr", dest="traml_in", help="TraML input file containt the transitions") parser.add_argument("--out", dest="outfile", help="Output trafoXML file with annotated chromatograms") args = parser.parse_args(sys.argv[1:]) return args if __name__ == '__main__': options = handle_args() main(options)
Python
3D
OpenMS/OpenMS
src/pyOpenMS/pyTOPP/MapAlignerPoseClustering.py
.py
8,985
256
import argparse import pyopenms as pms from common import addDataProcessing, writeParamsIfRequested, updateDefaults def align(in_files, out_files, out_trafos, reference_index, reference_file, params): in_types = set(pms.FileHandler.getType(in_) for in_ in in_files) if in_types <= set((pms.Type.MZML, pms.Type.MZXML, pms.Type.MZDATA)): align_features = False elif in_types == set((pms.Type.FEATUREXML,)): align_features = True else: raise Exception("different kinds of input files") algorithm = pms.MapAlignmentAlgorithmPoseClustering() alignment_params = params.copy("algorithm:", True) algorithm.setParameters(alignment_params) algorithm.setLogType(pms.LogType.CMD) plog = pms.ProgressLogger() plog.setLogType(pms.LogType.CMD) if reference_file: file_ = reference_file elif reference_index > 0: file_ = in_files[reference_index-1] else: sizes = [] if align_features: fh = pms.FeatureXMLFile() plog.startProgress(0, len(in_files), "Determine Reference map") for i, in_f in enumerate(in_files): sizes.append((fh.loadSize(in_f), in_f)) plog.setProgress(i) else: fh = pms.MzMLFile() mse = pms.MSExperiment() plog.startProgress(0, len(in_files), "Determine Reference map") for i, in_f in enumerate(in_files): fh.load(in_f, mse) mse.updateRanges() sizes.append((mse.getSize(), in_f)) plog.setProgress(i) plog.endProgress() __, file_ = max(sizes) f_fmxl = pms.FeatureXMLFile() if not out_files: options = f_fmxl.getOptions() options.setLoadConvexHull(False) options.setLoadSubordinates(False) f_fmxl.setOptions(options) if align_features: map_ref = pms.FeatureMap() f_fxml_tmp = pms.FeatureXMLFile() options = f_fmxl.getOptions() options.setLoadConvexHull(False) options.setLoadSubordinates(False) f_fxml_tmp.setOptions(options) f_fxml_tmp.load(file_, map_ref) algorithm.setReference(map_ref) else: map_ref = pms.MSExperiment() pms.MzMLFile().load(file_, map_ref) algorithm.setReference(map_ref) plog.startProgress(0, len(in_files), "Align input maps") for i, in_file in enumerate(in_files): trafo = pms.TransformationDescription() if align_features: map_ = pms.FeatureMap() f_fxml_tmp = pms.FeatureXMLFile() f_fxml_tmp.setOptions(f_fmxl.getOptions()) f_fxml_tmp.load(in_file, map_) if in_file == file_: trafo.fitModel("identity") else: algorithm.align(map_, trafo) if out_files: pms.MapAlignmentTransformer.transformRetentionTimes(map_, trafo) addDataProcessing(map_, params, pms.DataProcessing.ProcessingAction.ALIGNMENT) f_fxml_tmp.store(out_files[i], map_) else: map_ = pms.MSExperiment() pms.MzMLFile().load(in_file, map_) if in_file == file_: trafo.fitModel("identity") else: algorithm.align(map_, trafo) if out_files: pms.MapAlignmentTransformer.transformRetentionTimes(map_, trafo) addDataProcessing(map_, params, pms.DataProcessing.ProcessingAction.ALIGNMENT) pms.MzMLFile().store(out_files[i], map_) if out_trafos: pms.TransformationXMLFile().store(out_trafos[i], trafo) plog.setProgress(i+1) plog.endProgress() def getModelDefaults(default_model): params = pms.Param() params.setValue("type", default_model, "Type of model") model_types = [ "linear", "interpolated"] if default_model not in model_types: model_types.insert(0, default_model) params.setValidStrings("type", model_types) model_params = pms.Param() pms.TransformationModelLinear.getDefaultParameters(model_params) params.insert("linear:", model_params) params.setSectionDescription("linear", "Parameters for 'linear' model") pms.TransformationModelInterpolated.getDefaultParameters(model_params) entry = model_params.getEntry("interpolation_type") interpolation_types = entry.valid_strings model_params.setValidStrings("interpolation_type", interpolation_types) params.insert("interpolated:", model_params) params.setSectionDescription("interpolated", "Parameters for 'interpolated' model") return params def getDefaultParameters(): model_param = getModelDefaults("linear") algo_param = pms.MapAlignmentAlgorithmPoseClustering().getParameters() default = pms.Param() default.insert("model:", model_param) default.insert("algorithm:", algo_param) return default def main(): parser = argparse.ArgumentParser(description="PeakPickerHiRes") parser.add_argument("-in", action="append", type=str, dest="in_", metavar="input_file", ) parser.add_argument("-seeds", action="store", type=str, metavar="seeds_file", ) parser.add_argument("-out", action="append", type=str, metavar="output_file", ) parser.add_argument("-trafo_out", action="append", type=str, metavar="output_file", ) parser.add_argument("-ini", action="store", type=str, metavar="ini_file", ) parser.add_argument("-dict_ini", action="store", type=str, metavar="python_dict_ini_file", ) parser.add_argument("-write_ini", action="store", type=str, metavar="ini_file", ) parser.add_argument("-write_dict_ini", action="store", type=str, metavar="python_dict_ini_file", ) parser.add_argument("-reference:file", action="store", type=str, metavar="reference_file", dest="reference_file", ) parser.add_argument("-reference:index", action="store", type=int, metavar="reference_index", dest="reference_index", ) args = parser.parse_args() def collect(args): return [f.strip() for arg in args or [] for f in arg.split(",")] in_files = collect(args.in_) out_files = collect(args.out) trafo_out_files = collect(args.trafo_out) run_mode = (in_files and (out_files or trafo_out_files))\ and (args.ini is not None or args.dict_ini is not None) write_mode = args.write_ini is not None or args.write_dict_ini is not None ok = run_mode or write_mode if not ok: parser.error("either specify -in, -(trafo_)out and -(dict)ini for running " "the map aligner\nor -write(dict)ini for creating std " "ini file") defaults = getDefaultParameters() write_requested = writeParamsIfRequested(args, defaults) if not write_requested: updateDefaults(args, defaults) if not out_files and not trafo_out_files: parser.error("need -out or -trafo_out files") if out_files and len(out_files) != len(in_files): parser.error("need as many -out files as -in files") if trafo_out_files and len(trafo_out_files) != len(in_files): parser.error("need as many -trafo_out files as -in files") if args.reference_index is not None and args.reference_file is not None: parser.error("can only handle either reference:index or reference:file") if args.reference_index is not None: if args.reference_index <0 or args.reference_index >= len(in_files): parser.error("reference:index invalid") if args.reference_file is not None: if args.reference_file not in in_files: parser.error("reference_file not in input files") align(in_files, out_files, trafo_out_files, args.reference_index or 0, args.reference_file or "", defaults) if __name__ == "__main__": main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/pyTOPP/CTDsupport.py
.py
3,133
90
import CTDopts import sys import os from CTDopts.CTDopts import CTDModel, parse_cl_directives import pyopenms as pms import tempfile # code related to CTD support def addParamToCTDopts(defaults, model): keys = defaults.keys() for key in keys: ctd_tags = defaults.getTags(key) value = defaults.getValue(key) desc = defaults.getDescription(key) ctd_required = False if "required" in ctd_tags: ctd_required = True ctd_type = None ctd_type_str = '' ctd_list = False if isinstance(value, int): ctd_type = int ctd_type_str = 'int' elif isinstance(value, float): ctd_type = float ctd_type_str = 'float' elif isinstance(value, str): ctd_type = str ctd_type_str = 'str' elif isinstance(value, list): ctd_list = True # we can't determine the type based on an element so we need this helper function value_type = defaults.getValueType(key) if value_type == pms.ValueType.STRING_LIST: ctd_type=str ctd_type_str = 'list of str' elif value_type == pms.ValueType.DOUBLE_LIST: ctd_type=float ctd_type_str = 'list of float' elif value_type == pms.ValueType.INT_LIST: ctd_type=int ctd_type_str = 'list of int' print('Adding parameter: {0} with value: {1} and description: "{2}".'.format(key, value, desc)) print(' required: {0} \t tags: {1} \t type: {2}.'.format(ctd_required, ctd_tags, ctd_type_str)) model.add( key.decode(), required=ctd_required, type=ctd_type, default=value, is_list=ctd_list, description=desc) def parseCTDCommandLine(argv, model, openms_param): # Configure CTDOpt to use OpenMS style on the command line. directives = parse_cl_directives(argv, input_ctd='ini', write_tool_ctd='write_ini', prefix='-') if directives["write_tool_ctd"] is not None: # triggered if -write_ini was provided on CML # if called with -write_ini write CTD model.write_ctd(directives["write_tool_ctd"]) exit(0) elif directives["input_ctd"] is not None: # read ctd/ini file model = CTDModel(from_file=directives["input_ctd"]) # print(model.get_defaults()) param = pms.Param() fh = pms.ParamXMLFile() fh.load(directives["input_ctd"], param) openms_param.update(param, True) return model.get_defaults(), openms_param else: # only command line options provided temp = tempfile.NamedTemporaryFile(suffix='ini') # makes sure we get a writable file tmp_name = temp.name temp.close() # removes the file model.write_ctd(tmp_name) param = pms.Param() fh = pms.ParamXMLFile() fh.load(tmp_name, param) openms_param.update(param) os.remove(tmp_name) return model.parse_cl_args(argv), openms_param
Python
3D
OpenMS/OpenMS
src/pyOpenMS/pyTOPP/OpenSwathChromatogramExtractor.py
.py
3,631
84
import os,sys import pyopenms """ python pyTOPP/OpenSwathChromatogramExtractor.py --in ../source/TEST/TOPP/OpenSwathChromatogramExtractor_input.mzML\ --tr ../source/TEST/TOPP/OpenSwathChromatogramExtractor_input.TraML --out OpenSwathChromatogramExtractor.tmp.out \ && diff OpenSwathChromatogramExtractor.tmp.out ../source/TEST/TOPP/OpenSwathChromatogramExtractor_output.mzML """ def main(options): # load TraML file targeted = pyopenms.TargetedExperiment(); pyopenms.TraMLFile().load(options.traml_in, targeted); # Create empty files as input and finally as output empty_swath = pyopenms.MSExperiment() trafo = pyopenms.TransformationDescription() output = pyopenms.MSExperiment(); # load input for infile in options.infiles: exp = pyopenms.MSExperiment() pyopenms.FileHandler().loadExperiment(infile, exp) transition_exp_used = pyopenms.TargetedExperiment(); do_continue = True if options.is_swath: do_continue = pyopenms.OpenSwathHelper().checkSwathMapAndSelectTransitions(exp, targeted, transition_exp_used, options.min_upper_edge_dist) else: transition_exp_used = targeted if do_continue: # set up extractor and run tmp_out = pyopenms.MSExperiment(); extractor = pyopenms.ChromatogramExtractor() extractor.extractChromatograms(exp, tmp_out, targeted, options.extraction_window, options.ppm, trafo, options.rt_extraction_window, options.extraction_function) # add all chromatograms to the output for chrom in tmp_out.getChromatograms(): output.addChromatogram(chrom) dp = pyopenms.DataProcessing() pa = pyopenms.DataProcessing().ProcessingAction().SMOOTHING dp.setProcessingActions(set([pa])) chromatograms = output.getChromatograms(); for chrom in chromatograms: this_dp = chrom.getDataProcessing() this_dp.append(dp) chrom.setDataProcessing(this_dp) output.setChromatograms(chromatograms); pyopenms.MzMLFile().store(options.outfile, output); def handle_args(): import argparse usage = "" usage += "\nExtract chromatograms (XIC) from a MS2 map file." parser = argparse.ArgumentParser(description = usage ) parser.add_argument('--in', dest="infiles", nargs = '+', help = 'An input file containing spectra') parser.add_argument("--tr", dest="traml_in", help="TraML input file containt the transitions") parser.add_argument("--out", dest="outfile", help="Output chrom.mzML file with chromatograms") parser.add_argument("--extraction_window", dest="extraction_window", default=0.05, help="Extraction window in Th", metavar='0.05', type=float) parser.add_argument("--min_upper_edge_dist", dest="min_upper_edge_dist", default=0.0, help="Minimal distance to the edge to still consider a precursor, in Thomson (for Swath)", metavar='0.0', type=float) parser.add_argument('--ppm', action='store_true', default=False, help="use ppm instead of Th") parser.add_argument('--is_swath', action='store_true', default=False, help="The input file is a SWATH file") parser.add_argument("--rt_extraction_window", dest="rt_extraction_window", default=-1, help="Extraction window in RT", metavar='-1', type=float) parser.add_argument("--extraction_function", dest="extraction_function", default="tophat", help="Extraction function (tophat or bartlett)", metavar="tophat") args = parser.parse_args(sys.argv[1:]) return args if __name__ == '__main__': options = handle_args() main(options)
Python
3D
OpenMS/OpenMS
src/pyOpenMS/converters/__init__.py
.py
789
18
from .special_autowrap_conversionproviders import * from autowrap.ConversionProvider import special_converters def register_converters(): special_converters.append(OpenMSStringConverter()) special_converters.append(StdVectorStringConverter()) special_converters.append(StdSetStringConverter()) special_converters.append(OpenMSIntListConverter()) special_converters.append(OpenMSStringListConverter()) special_converters.append(OpenMSDoubleListConverter()) special_converters.append(CVTermMapConverter()) special_converters.append(OpenMSDataValue()) special_converters.append(OpenMSParamValue()) special_converters.append(OpenMSDPosition1()) special_converters.append(OpenMSDPosition2()) special_converters.append(OpenMSDPosition2Vector())
Python
3D
OpenMS/OpenMS
src/pyOpenMS/converters/special_autowrap_conversionproviders.py
.py
25,091
668
from __future__ import print_function from autowrap.Code import Code from autowrap.ConversionProvider import (TypeConverterBase, mangle, StdMapConverter) class OpenMSDPosition1(TypeConverterBase): """Converter for DPosition1 (1-dimensional position). Accepts a single float/int from Python and converts to C++ DPosition<1>. """ def get_base_types(self): return "DPosition1", def matches(self, cpp_type): return not cpp_type.is_ptr def matching_python_type(self, cpp_type): return "" def matching_python_type_full(self, cpp_type): return "Union[int, float]" def type_check_expression(self, cpp_type, argument_var): return "isinstance(%s, (int, float))" % argument_var def input_conversion(self, cpp_type, argument_var, arg_num): dp = "_dp_%s" % arg_num code = Code().add(""" |cdef _DPosition1 $dp |$dp[0] = <double>$argument_var """, locals()) cleanup = "" if cpp_type.is_ref: cleanup = Code().add(""" |$argument_var = $dp[0] """, locals()) call_as = dp return code, call_as, cleanup def output_conversion(self, cpp_type, input_cpp_var, output_py_var): return Code().add(""" |$output_py_var = $input_cpp_var[0] """, locals()) class OpenMSDPosition2(TypeConverterBase): def get_base_types(self): return "DPosition2", def matches(self, cpp_type): return not cpp_type.is_ptr def matching_python_type(self, cpp_type): return "" def matching_python_type_full(self, cpp_type): return "Union[Sequence[int], Sequence[float]]" def type_check_expression(self, cpp_type, argument_var): return "len(%s) == 2 and isinstance(%s[0], (int, float)) "\ "and isinstance(%s[1], (int, float))"\ % (argument_var, argument_var, argument_var) def input_conversion(self, cpp_type, argument_var, arg_num): dp = "_dp_%s" % arg_num code = Code().add(""" |cdef _DPosition2 $dp |$dp[0] = <float>$argument_var[0] |$dp[1] = <float>$argument_var[1] """, locals()) cleanup = "" if cpp_type.is_ref: cleanup = Code().add(""" |$cpp_type[0] = $dp[0] |$cpp_type[1] = $dp[1] """, locals()) call_as = dp return code, call_as, cleanup def output_conversion(self, cpp_type, input_cpp_var, output_py_var): # this one is slow as it uses construction of python type DataValue for # delegating conversion to this type, which reduces code below: return Code().add(""" |$output_py_var = [$input_cpp_var[0], $input_cpp_var[1]] """, locals()) class OpenMSDPosition2Vector(TypeConverterBase): def get_base_types(self): return "libcpp_vector", def matches(self, cpp_type): inner_t, = cpp_type.template_args return inner_t == "DPosition2" def matching_python_type(self, cpp_type): return "np.ndarray[np.float32_t,ndim=2]" def matching_python_type_full(self, cpp_type): # TODO figure out the best way to do numpy typing. Being able to specify the dimensions would be nice: # might be available soon (without extensions): https://github.com/numpy/numpy/issues/16544 # Note that using those types will need a top-of-file import which we cannot inject to autowrap (yet). # This means we would either need to support injection or import per default in autowraps pyi files. # For now, we add it to all pyi files in a post-processing step of our build system. return "'_np.ndarray[Any, _np.dtype[_np.float32]]'" def type_check_expression(self, cpp_type, argument_var): # TODO in autowrap: More finegrained error reporting. Currently it just reports # if ANY of the input types to a function does not match. Not which, not why.. return "%s.shape[1] == 2" % argument_var def input_conversion(self, cpp_type, argument_var, arg_num): dp = "_dp_%s" % arg_num vec ="_dp_vec_%s" % arg_num ii = "_dp_ii_%s" % arg_num N = "_dp_N_%s" % arg_num code = Code().add(""" |cdef libcpp_vector[_DPosition2] $vec |cdef _DPosition2 $dp |cdef int $ii |cdef int $N = $argument_var.shape[0] |for $ii in range($N): | $dp[0] = $argument_var[$ii,0] | $dp[1] = $argument_var[$ii,1] | $vec.push_back($dp) """, locals()) cleanup = "" if cpp_type.is_ref: it = "_dp_it_%s" % arg_num n = "_dp_n_%s" % arg_num cleanup = Code().add(""" |$n = $vec.size() |$argument_var.resize(($n,2)) |$n = $vec.size() |cdef libcpp_vector[_DPosition2].iterator $it = $vec.begin() |$ii = 0 |while $it != $vec.end(): | $argument_var[$ii, 0] = deref($it)[0] | $argument_var[$ii, 1] = deref($it)[1] | inc($it) | $ii += 1 """, locals()) call_as = vec return code, call_as, cleanup def output_conversion(self, cpp_type, input_cpp_var, output_py_var): # this one is slow as it uses construction of python type DataValue for # delegating conversion to this type, which reduces code below: it = "_out_it_dpos_vec" n = "_out_n_dpos_vec" ii = "_out_ii_dpos_vec" return Code().add(""" |cdef int $n = $input_cpp_var.size() |cdef $output_py_var = np.zeros([$n,2], dtype=np.float32) |cdef libcpp_vector[_DPosition2].iterator $it = $input_cpp_var.begin() |cdef int $ii = 0 |while $it != $input_cpp_var.end(): | $output_py_var[$ii, 0] = deref($it)[0] | $output_py_var[$ii, 1] = deref($it)[1] | inc($it) | $ii += 1 """, locals()) class OpenMSDataValue(TypeConverterBase): def get_base_types(self): return "DataValue", def matches(self, cpp_type): return not cpp_type.is_ptr and not cpp_type.is_ref def matching_python_type(self, cpp_type): return "" def matching_python_type_full(self, cpp_type): return "Union[int, float, bytes, str, List[int], List[float], List[bytes]]" def type_check_expression(self, cpp_type, argument_var): return "isinstance(%s, (int, float, list, bytes, str))" % argument_var def input_conversion(self, cpp_type, argument_var, arg_num): call_as = "deref(DataValue(%s).inst.get())" % argument_var return "", call_as, "" def output_conversion(self, cpp_type, input_cpp_var, output_py_var): # this one is slow as it uses construction of python type DataValue for # delegating conversion to this type, which reduces code below: return Code().add(""" |cdef DataValue _value = DataValue.__new__(DataValue) |_value.inst = shared_ptr[_DataValue](new _DataValue($input_cpp_var)) |cdef int _type = $input_cpp_var.valueType() |cdef object $output_py_var |if _type == DataType.STRING_VALUE: | $output_py_var = _value.toString() |elif _type == DataType.INT_VALUE: | $output_py_var = _value.toInt() |elif _type == DataType.DOUBLE_VALUE: | $output_py_var = _value.toDouble() |elif _type == DataType.INT_LIST: | $output_py_var = _value.toIntList() |elif _type == DataType.DOUBLE_LIST: | $output_py_var = _value.toDoubleList() |elif _type == DataType.STRING_LIST: | $output_py_var = _value.toStringList() |elif _type == DataType.EMPTY_VALUE: | $output_py_var = None |else: | raise Exception("DataValue instance has invalid value type %d" % _type) """, locals()) class OpenMSParamValue(TypeConverterBase): def get_base_types(self): return "ParamValue", def matches(self, cpp_type): return not cpp_type.is_ptr and not cpp_type.is_ref def matching_python_type(self, cpp_type): return "" def matching_python_type_full(self, cpp_type): return "Union[int, float, bytes, str, List[int], List[float], List[bytes]]" def type_check_expression(self, cpp_type, argument_var): return "isinstance(%s, (int, float, list, bytes, str))" % argument_var def input_conversion(self, cpp_type, argument_var, arg_num): call_as = "deref(ParamValue(%s).inst.get())" % argument_var return "", call_as, "" def output_conversion(self, cpp_type, input_cpp_var, output_py_var): # this one is slow as it uses construction of python type ParamValue for # delegating conversion to this type, which reduces code below: return Code().add(""" |cdef ParamValue _value = ParamValue.__new__(ParamValue) |_value.inst = shared_ptr[_ParamValue](new _ParamValue($input_cpp_var)) |cdef int _type = $input_cpp_var.valueType() |cdef object $output_py_var |if _type == ValueType.STRING_VALUE: | $output_py_var = _value.toString() |elif _type == ValueType.INT_VALUE: | $output_py_var = _value.toInt() |elif _type == ValueType.DOUBLE_VALUE: | $output_py_var = _value.toDouble() |elif _type == ValueType.INT_LIST: | $output_py_var = _value.toIntVector() |elif _type == ValueType.DOUBLE_LIST: | $output_py_var = _value.toDoubleVector() |elif _type == ValueType.STRING_LIST: | $output_py_var = _value.toStringVector() |elif _type == ValueType.EMPTY_VALUE: | $output_py_var = None |else: | raise Exception("ParamValue instance has invalid value type %d" % _type) """, locals()) class OpenMSStringConverter(TypeConverterBase): def get_base_types(self): return "String", def matches(self, cpp_type): return not cpp_type.is_ptr def matching_python_type(self, cpp_type): # We allow bytes, unicode, str and String return "" def matching_python_type_full(self, cpp_type): if (cpp_type.is_ptr or cpp_type.is_ref) and not cpp_type.is_const: return "String" else: return "Union[bytes, str, String]" def type_check_expression(self, cpp_type, argument_var): # Need to treat ptr and reference differently as these may be modified # and the results needs to be available in Python if (cpp_type.is_ptr or cpp_type.is_ref) and not cpp_type.is_const: return "isinstance(%s, String)" % (argument_var) # Allow conversion from str, bytes and OpenMS::String return "(isinstance(%s, str) or isinstance(%s, bytes) or isinstance(%s, String))" % ( argument_var,argument_var,argument_var) def input_conversion(self, cpp_type, argument_var, arg_num): # See ./src/pyOpenMS/addons/ADD_TO_FIRST.pyx for declaration of convString call_as = "deref((convString(%s)).get())" % argument_var cleanup = "" code = "" # Need to treat ptr and reference differently as these may be modified # and the results needs to be available in Python if cpp_type.is_ptr and not cpp_type.is_const: call_as = "((<String>%s).inst.get())" % argument_var if cpp_type.is_ref and not cpp_type.is_const: call_as = "deref((<String>%s).inst.get())" % argument_var return code, call_as, cleanup def output_conversion(self, cpp_type, input_cpp_var, output_py_var): # See ./src/pyOpenMS/addons/ADD_TO_FIRST.pyx for declaration of convOutputString return "%s = convOutputString(%s)" % (output_py_var, input_cpp_var) class AbstractOpenMSListConverter(TypeConverterBase): def __init__(self): # mark as abstract: raise NotImplementedError() def get_base_types(self): return self.openms_type, def matches(self, cpp_type): return not cpp_type.is_ptr def matching_python_type(self, cpp_type): return "list" def matching_python_type_full(self, cpp_type): return "List[%s]" % (self.inner_py_type) def type_check_expression(self, cpp_type, argument_var): return\ "isinstance(%s, list) and all(isinstance(li, %s) for li in %s)"\ % (argument_var, self.inner_py_type, argument_var) def input_conversion(self, cpp_type, argument_var, arg_num): temp_var = "v%d" % arg_num t = self.inner_cpp_type ltype = self.openms_type code = Code().add(""" |cdef libcpp_vector[$t] _$temp_var = $argument_var |cdef _$ltype $temp_var = _$ltype(_$temp_var) """, locals()) cleanup = "" if cpp_type.is_ref: cleanup_code = Code().add(""" |replace = [] |cdef int i, n |n = $temp_var.size() |for i in range(n): | replace.append(<$t>$temp_var.at(i)) |$argument_var[:] = replace """, locals()) # here we inject special behavoir for testing if this converter # was called ! call_as = "(%s)" % temp_var return code, call_as, cleanup def output_conversion(self, cpp_type, input_cpp_var, output_py_var): t = self.inner_cpp_type code = Code().add(""" |$output_py_var = [] |cdef int i, n |n = $input_cpp_var.size() |for i in range(n): | $output_py_var.append(<$t>$input_cpp_var.at(i)) """, locals()) return code class OpenMSIntListConverter(AbstractOpenMSListConverter): openms_type = "IntList" inner_py_type = "int" inner_cpp_type = "int" # mark as non abstract: def __init__(self): pass class OpenMSDoubleListConverter(AbstractOpenMSListConverter): openms_type = "DoubleList" inner_py_type = "float" inner_cpp_type = "double" # mark as non abstract: def __init__(self): pass class StdVectorStringConverter(TypeConverterBase): def get_base_types(self): return "libcpp_vector", def matches(self, cpp_type): inner_t, = cpp_type.template_args return inner_t == "String" def matching_python_type(self, cpp_type): return "list" def matching_python_type_full(self, cpp_type): return "List[bytes]" def type_check_expression(self, cpp_type, arg_var): return Code().add(""" |isinstance($arg_var, list) and all(isinstance(i, bytes) for i in + $arg_var) """, locals()).render() def input_conversion(self, cpp_type, argument_var, arg_num): temp_var = "v%d" % arg_num temp_it = "it_%d" % arg_num item = "item%d" % arg_num code = Code().add(""" |cdef libcpp_vector[_String] * $temp_var = new libcpp_vector[_String]() |cdef bytes $item |for $item in $argument_var: | $temp_var.push_back(_String(<char *>$item)) """, locals()) if cpp_type.is_ref: cleanup_code = Code().add(""" |replace = [] |cdef libcpp_vector[_String].iterator $temp_it = $temp_var.begin() |while $temp_it != $temp_var.end(): | replace.append(<char*>deref($temp_it).c_str()) | inc($temp_it) |$argument_var[:] = replace |del $temp_var """, locals()) else: cleanup_code = "del %s" % temp_var return code, "deref(%s)" % temp_var, cleanup_code def call_method(self, res_type, cy_call_str, with_const=False): return "_r = %s" % (cy_call_str) def output_conversion(self, cpp_type, input_cpp_var, output_py_var): if cpp_type.is_ptr: raise AssertionError() it = mangle("it_" + input_cpp_var) item = mangle("item_" + output_py_var) code = Code().add(""" |$output_py_var = [] |cdef libcpp_vector[_String].iterator $it = $input_cpp_var.begin() |while $it != $input_cpp_var.end(): | $output_py_var.append(<char*>deref($it).c_str()) | inc($it) """, locals()) return code class OpenMSStringListConverter(StdVectorStringConverter): """ StringList is now a std::vector<String> so we can directly inherit all methods from StdVectorStringConverter but need to add the matching rules for StringList. """ openms_type = "StringList" inner_py_type = "bytes" inner_cpp_type = "libcpp_string" # mark as non abstract: def __init__(self): pass def get_base_types(self): return self.openms_type, def matches(self, cpp_type): return not cpp_type.is_ptr def matching_python_type(self, cpp_type): return "list" def matching_python_type_full(self, cpp_type): return "List[%s]" % (self.inner_py_type) def type_check_expression(self, cpp_type, argument_var): return\ "isinstance(%s, list) and all(isinstance(li, %s) for li in %s)"\ % (argument_var, self.inner_py_type, argument_var) class StdSetStringConverter(TypeConverterBase): def get_base_types(self): return "libcpp_set", def matches(self, cpp_type): inner_t, = cpp_type.template_args return inner_t == "String" def matching_python_type(self, cpp_type): return "set" def matching_python_type_full(self, cpp_type): return "Set[bytes]" def type_check_expression(self, cpp_type, arg_var): return Code().add(""" |isinstance($arg_var, set) and all(isinstance(i, bytes) for i in + $arg_var) """, locals()).render() def input_conversion(self, cpp_type, argument_var, arg_num): temp_var = "v%d" % arg_num item = "item%d" % arg_num code = Code().add(""" |cdef libcpp_set[_String] * $temp_var = new libcpp_set[_String]() |cdef bytes $item |for $item in $argument_var: | $temp_var.insert(_String(<char *>$item)) """, locals()) if cpp_type.is_ref: cleanup_code = Code().add(""" |cdef replace = set() |cdef libcpp_set[_String].iterator it = $temp_var.begin() |while it != $temp_var.end(): | replace.add(<char*>deref(it).c_str()) | inc(it) |$argument_var.clear() |$argument_var.update(replace) |del $temp_var """, locals()) else: cleanup_code = "del %s" % temp_var return code, "deref(%s)" % temp_var, cleanup_code def call_method(self, res_type, cy_call_str, with_const=False): return "_r = %s" % (cy_call_str) def output_conversion(self, cpp_type, input_cpp_var, output_py_var): if cpp_type.is_ptr: raise AssertionError() it = mangle("it_" + input_cpp_var) item = mangle("item_" + output_py_var) code = Code().add(""" |$output_py_var = set() |cdef libcpp_set[_String].iterator $it = $input_cpp_var.begin() |while $it != $input_cpp_var.end(): | $output_py_var.add(<char*>deref($it).c_str()) | inc($it) """, locals()) return code import time class CVTermMapConverter(TypeConverterBase): def get_base_types(self): return "libcpp_map", def matches(self, cpp_type): # print(str(cpp_type), "Map[String,libcpp_vector[CVTerm]]") return str(cpp_type) == "libcpp_map[String,libcpp_vector[CVTerm]]" \ or str(cpp_type) == "libcpp_map[String,libcpp_vector[CVTerm]] &" def matching_python_type(self, cpp_type): return "dict" def matching_python_type_full(self, cpp_type): return "Dict[bytes,List[CVTerm]]" def type_check_expression(self, cpp_type, arg_var): return Code().add(""" |isinstance($arg_var, dict) + and all(isinstance(k, bytes) for k in $arg_var.keys()) + and all(isinstance(v, list) for v in $arg_var.values()) + and all(isinstance(vi, CVTerm) for v in $arg_var.values() for vi in v) """, locals()).render() def input_conversion(self, cpp_type, argument_var, arg_num): map_name = "_map_%d" % arg_num v_vec = "_v_vec_%d" % arg_num v_ptr = "_v_ptr_%d" % arg_num v_i = "_v_i_%d" % arg_num k_string = "_k_str_%d" % arg_num code = Code().add(""" |cdef libcpp_map[_String, libcpp_vector[_CVTerm]] $map_name |cdef libcpp_vector[_CVTerm] $v_vec |cdef _String $k_string |cdef CVTerm $v_i |for k, v in $argument_var.items(): | $v_vec.clear() | for $v_i in v: | $v_vec.push_back(deref($v_i.inst.get())) | $map_name[_String(<char *>k)] = $v_vec """, locals()) if cpp_type.is_ref: replace = "_replace_%d" % arg_num outer_it = "outer_it_%d" % arg_num inner_it = "inner_it_%d" % arg_num item = "item_%d" % arg_num inner_key = "inner_key_%d" % arg_num inner_values = "inner_values_%d" % arg_num cleanup_code = Code().add(""" |cdef $replace = dict() |cdef libcpp_map[_String, libcpp_vector[_CVTerm]].iterator $outer_it + = $map_name.begin() |cdef libcpp_vector[_CVTerm].iterator $inner_it |cdef CVTerm $item |cdef bytes $inner_key |cdef list $inner_values |while $outer_it != $map_name.end(): | $inner_key = deref($outer_it).first.c_str() | $inner_values = [] | $inner_it = deref($outer_it).second.begin() | while $inner_it != deref($outer_it).second.end(): | $item = CVTerm.__new__(CVTerm) | $item.inst = shared_ptr[_CVTerm](new _CVTerm(deref($inner_it))) | $inner_values.append($item) | inc($inner_it) | $replace[$inner_key] = $inner_values | inc($outer_it) |$argument_var.clear() |$argument_var.update($replace) """, locals()) else: cleanup_code = "" return code, map_name, cleanup_code def call_method(self, res_type, cy_call_str, with_const=False): return "_r = %s" % (cy_call_str) def output_conversion(self, cpp_type, input_cpp_var, output_py_var): rnd = str(id(self))+str(time.time()).split(".")[0] outer_it = "outer_it_%s" % rnd inner_it = "inner_it_%s" % rnd item = "item_%s" % rnd inner_key = "inner_key_%s" % rnd inner_values = "inner_values_%s" % rnd code = Code().add(""" |$output_py_var = dict() |cdef libcpp_map[_String, libcpp_vector[_CVTerm]].iterator $outer_it + = $input_cpp_var.begin() |cdef libcpp_vector[_CVTerm].iterator $inner_it |cdef CVTerm $item |cdef bytes $inner_key |cdef list $inner_values |while $outer_it != $input_cpp_var.end(): | $inner_key = deref($outer_it).first.c_str() | $inner_values = [] | $inner_it = deref($outer_it).second.begin() | while $inner_it != deref($outer_it).second.end(): | $item = CVTerm.__new__(CVTerm) | $item.inst = shared_ptr[_CVTerm](new _CVTerm(deref($inner_it))) | $inner_values.append($item) | inc($inner_it) | $output_py_var[$inner_key] = $inner_values | inc($outer_it) """, locals()) return code
Python
3D
OpenMS/OpenMS
src/pyOpenMS/extra_includes/python_ms_data_consumer.hpp
.hpp
4,796
114
#ifndef __PYTHON_MS_DATA_CONSUMER_HPP__ #define __PYTHON_MS_DATA_CONSUMER_HPP__ #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/METADATA/ExperimentalSettings.h> // see ../pxds/PythonMSDataConsumer.pxd for Cython def class PythonMSDataConsumer : virtual public OpenMS::Interfaces::IMSDataConsumer { typedef OpenMS::PeakMap::SpectrumType SpectrumType; typedef OpenMS::PeakMap::ChromatogramType ChromatogramType; // typedefs for function ptr (helper fxn to convert C++ type to Python object) // see ../addons/MzMLFile.pyx typedef PyObject* (*SpectrumToPythonWrapper) (const SpectrumType &); typedef PyObject* (*ChromatogramToPythonWrapper) (const ChromatogramType &); typedef PyObject* (*ExperimentalSettingsToPythonWrapper) (const OpenMS::ExperimentalSettings &); private: PyObject *py_consumer_; SpectrumToPythonWrapper wrap_spectrum_; ChromatogramToPythonWrapper wrap_chromatogram_; ExperimentalSettingsToPythonWrapper wrap_experimental_settings_; public: /// Constructor PythonMSDataConsumer(PyObject *py_consumer, SpectrumToPythonWrapper wrap_spectrum, ChromatogramToPythonWrapper wrap_chromatogram, ExperimentalSettingsToPythonWrapper wrap_experimental_settings) : py_consumer_(py_consumer), wrap_spectrum_(wrap_spectrum), wrap_chromatogram_(wrap_chromatogram), wrap_experimental_settings_(wrap_experimental_settings) { Py_INCREF(py_consumer_); }; /// Destructor ~PythonMSDataConsumer() { Py_DECREF(py_consumer_); }; /// Consume spectrum (call Python method "consumeSpectrum" of the py_consumer_ object from C++) virtual void consumeSpectrum(SpectrumType & spec) { PyObject * py_spec = wrap_spectrum_(spec); PyObject * method_name = PyUnicode_FromString("consumeSpectrum"); PyObject * r = PyObject_CallMethodObjArgs(py_consumer_, method_name, py_spec, NULL); Py_DECREF(py_spec); Py_DECREF(method_name); // NULL indicates python exception: if (r == NULL) throw "exception"; // not sense needed, as cython evaluates python strack trace Py_DECREF(r); }; /// Consume chromatogram (call Python method "consumeChromatogram" of the py_consumer_ object from C++) virtual void consumeChromatogram(ChromatogramType & chrom) { PyObject * py_chrom = wrap_chromatogram_(chrom); PyObject * method_name = PyUnicode_FromString("consumeChromatogram"); PyObject * r = PyObject_CallMethodObjArgs(py_consumer_, method_name, py_chrom, NULL); Py_DECREF(py_chrom); Py_DECREF(method_name); // NULL indicates python exception: if (r == NULL) throw "exception"; // not sense needed, as cython evaluates python strack trace Py_DECREF(r); }; virtual void setExpectedSize(OpenMS::Size expectedSpectra, OpenMS::Size expectedChromatograms) { PyObject * expected_spectra = PyLong_FromSize_t(expectedSpectra); PyObject * expected_chromatograms = PyLong_FromSize_t(expectedChromatograms); PyObject * method_name = PyUnicode_FromString("setExpectedSize"); PyObject * r = PyObject_CallMethodObjArgs(py_consumer_, method_name, expected_spectra, expected_chromatograms, NULL); Py_DECREF(expected_spectra); Py_DECREF(expected_chromatograms); Py_DECREF(method_name); // NULL indicates python exception: if (r == NULL) throw "exception"; // not sense needed, as cython evaluates python strack trace Py_DECREF(r); }; virtual void setExperimentalSettings(const OpenMS::ExperimentalSettings & exp_settings) { PyObject * py_exp_settings = wrap_experimental_settings_(exp_settings); PyObject * method_name = PyUnicode_FromString("setExperimentalSettings"); PyObject * r = PyObject_CallMethodObjArgs(py_consumer_, method_name, py_exp_settings, NULL); Py_DECREF(py_exp_settings); Py_DECREF(method_name); // NULL indicates python exception: if (r == NULL) throw "exception"; // not sense needed, as cython evaluates python strack trace Py_DECREF(r); }; }; #endif
Unknown
3D
OpenMS/OpenMS
src/pyOpenMS/tests/__init__.py
.py
0
0
null
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/conftest.py
.py
2,785
81
""" Pytest configuration file for pyOpenMS tests. This file provides fixtures and configuration for test data paths, replacing the old env.py import pattern. """ import os # Import pytest only if available (needed for fixtures) try: import pytest _HAS_PYTEST = True except ImportError: _HAS_PYTEST = False def _get_test_data_dir(): """ Get the path to the OpenMS test data directory. This function tries multiple strategies to find the test data: 1. Check the OPENMS_TEST_DATA_PATH environment variable (for custom locations) 2. Use relative path from this file (works for regular source clones) 3. Try to import env.py if available (for CMake builds, backwards compatibility) Returns: str: Path to the test data directory (src/tests/topp) """ # Strategy 1: Check environment variable for override env_path = os.environ.get('OPENMS_TEST_DATA_PATH') if env_path and os.path.isdir(env_path): return env_path # Strategy 2: Use relative path from this conftest.py file # This works for regular clones where the structure is: # src/pyOpenMS/tests/conftest.py (this file) # src/tests/topp/ (test data) tests_dir = os.path.dirname(os.path.abspath(__file__)) relative_path = os.path.join(tests_dir, '..', '..', '..', 'src', 'tests', 'topp') relative_path = os.path.normpath(relative_path) if os.path.isdir(relative_path): return relative_path # Strategy 3: Try to import env.py (backwards compatibility for CMake builds) try: import env if hasattr(env, 'PYOPENMS_SRC_DIR'): env_based_path = os.path.join(env.PYOPENMS_SRC_DIR, "..", "..", "src", "tests", "topp") env_based_path = os.path.normpath(env_based_path) if os.path.isdir(env_based_path): return env_based_path except ImportError: pass # If all strategies fail, raise an error raise RuntimeError( "Could not locate OpenMS test data directory. " "Please set the OPENMS_TEST_DATA_PATH environment variable to point to " "the 'src/tests/topp' directory, or ensure you're running tests from a " "complete OpenMS source tree." ) # Only define pytest fixtures if pytest is available if _HAS_PYTEST: @pytest.fixture(scope='session') def openms_test_data_dir(): """ Pytest fixture providing the path to the OpenMS test data directory. Usage in tests: def test_something(openms_test_data_dir): data_file = os.path.join(openms_test_data_dir, "test_file.mzML") Returns: str: Path to the test data directory """ return _get_test_data_dir()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/integration_tests/test_MRMRTNormalizer.py
.py
3,218
87
import unittest import os import pytest import pyopenms from collections import defaultdict eps = 2 def simple_find_best_feature(output, pairs, targeted): f_map = defaultdict(list) for f in output: key = f.getMetaValue("PeptideRef".encode()) f_map[key].append(f) get_score = lambda f: f.getMetaValue("main_var_xx_lda_prelim_score".encode()) for fl in f_map.values(): scores = [(get_score(fi), fi) for fi in fl] best_score, best_feature = max(scores) __, feature = scores[-1] pep = targeted.getPeptideByRef( feature.getMetaValue("PeptideRef".encode()) ) pairs.append([best_feature.getRT(), pep.getRetentionTime()]) class TestMRMRTNormalizer(unittest.TestCase): """Emulates the behavior of OpenSwathMRMRTNormalizer""" @pytest.fixture(autouse=True) def setup_test_data(self, openms_test_data_dir): """Setup test with test data directory from pytest fixture.""" self.testdirname = openms_test_data_dir # set up files self.chromatograms = os.path.join(self.testdirname, "OpenSwathRTNormalizer_1_input.mzML").encode() self.tramlfile = os.path.join(self.testdirname, "OpenSwathRTNormalizer_1_input.TraML").encode() def test_run_mrmrtnormalizer(self): # load chromatograms chromatograms = pyopenms.MSExperiment() fh = pyopenms.FileHandler() fh.loadExperiment(self.chromatograms, chromatograms) # load TraML file targeted = pyopenms.TargetedExperiment(); tramlfile = pyopenms.TraMLFile(); tramlfile.load(self.tramlfile, targeted); # Create empty files as input and finally as output empty_swath = pyopenms.MSExperiment() trafo = pyopenms.TransformationDescription() output = pyopenms.FeatureMap(); # set up featurefinder and run featurefinder = pyopenms.MRMFeatureFinderScoring() # set the correct rt use values scoring_params = pyopenms.MRMFeatureFinderScoring().getDefaults(); scoring_params.setValue(b"Scores:use_rt_score", b'false', b'') featurefinder.setParameters(scoring_params); featurefinder.pickExperiment(chromatograms, output, targeted, trafo, empty_swath) # get the pairs pairs=[] simple_find_best_feature(output, pairs, targeted) pairs_corrected = pyopenms.MRMRTNormalizer().removeOutliersIterative(pairs, 0.95, 0.6, True, b"iter_jackknife") pairs_corrected = [ list(p) for p in pairs_corrected] expected = [(1497.56884765625, 1881.0), (2045.9776611328125, 2409.0), (2151.4814453125, 2509.0), (1924.0750732421875, 2291.0), (612.9832153320312, 990.0), (1086.2474365234375, 1470.0), (1133.89404296875, 1519.0), (799.5291137695312, 1188.0), (1397.1541748046875, 1765.0)] for exp,res in zip(sorted(expected), sorted(pairs_corrected)): self.assertAlmostEqual(exp[0], res[0], eps) self.assertAlmostEqual(exp[1], res[1], eps) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/memoryleaktests/__init__.py
.py
0
0
null
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/memoryleaktests/testAll.py
.py
7,809
265
from __future__ import print_function import sys import unittest import os import copy import time import contextlib import pyopenms from pyopenms._sysinfo import free_mem import numpy as np def show_mem(label): p = free_mem() p /= 1024.0 * 1024 print((label+" ").ljust(50, "."), ": %8.2f MB" % p) sys.stdout.flush() @contextlib.contextmanager def MemTester(name): mem_at_start = free_mem() print("\n") show_mem("start test '%s' with" % name) yield missing = mem_at_start - free_mem() show_mem("end with") print("\n") assert missing <= 0.1* mem_at_start, "possible mem leak: %s at start, missing %s" % (mem_at_start, missing) if True or int(os.environ.get("WITH_MEMLEAK_TESTS", 0)): class TestAll(unittest.TestCase): def setUp(self): self.mem_at_start = free_mem() print("\n") show_mem("AT THE BEGINNING ") print("\n") dirname = os.path.dirname(os.path.abspath(__file__)) self.testfile = os.path.join(dirname, "../test.mzXML").encode() def tearDown(self): time.sleep(3) print("\n") show_mem("AT THE END ") print("\n") missing = self.mem_at_start - free_mem() assert missing <= 0.1* self.mem_at_start, "possible mem leak: %s at start, missing %s" % (self.mem_at_start, missing) def testAll(self): with MemTester("specs from experiment"): self.run_extractSpetraFromMSExperiment() with MemTester("copy experiment"): self.run_MSExperiment_copy() with MemTester("string_conversions1"): self.run_string_conversions1() with MemTester("string_conversions2"): self.run_string_conversions2() with MemTester("string_lists"): self.run_string_lists() with MemTester("list_conversions"): self.run_list_conversions() with MemTester("set_spec_peaks"): self.set_spec_peaks() with MemTester("set_spec_peaks2"): self.set_spec_peaks2() with MemTester("test io"): self.run_fileformats_io() def run_string_conversions1(self): basestr = 200000*b" " li = [] for i in range(1000): if (i+1)%100 == 0: show_mem("%4d runs" % i) dv = pyopenms.DataValue(basestr) dv = pyopenms.DataValue(basestr) li.append(dv) del li def run_string_conversions2(self): basestr = 200000*b" " li = [] for i in range(1000): if (i+1)%100 == 0: show_mem("%4d runs" % i) sf = pyopenms.SourceFile() sf.setNameOfFile(basestr) sf.setNameOfFile(basestr) li.append(sf) del li def run_string_lists(self): basestr = 10000*b" " li = [] for i in range(100): if (i+1)%100 == 0: show_mem("%4d runs" % i) sl = pyopenms.DataValue([basestr]*30) sl = pyopenms.DataValue([basestr]*30) li.append(sl) del sl del li def run_list_conversions(self): pc = pyopenms.Precursor() allpcs = 500*[pc] li = [] for i in range(500): if (i+1)%100 == 0: show_mem("%4d runs" % i) spec = pyopenms.MSSpectrum() spec.setPrecursors(allpcs) spec.setPrecursors(allpcs) li.append(spec) del spec del li def set_spec_peaks(self): data = np.zeros((10000,2), dtype=np.float32) li = [] for i in range(1000): if (i+1)%100 == 0: show_mem("%4d specs processed" % i) spec = pyopenms.MSSpectrum() spec.set_peaks((data[:,0], data[:,1])) spec.set_peaks((data[:,0], data[:,1])) spec.set_peaks((data[:,0], data[:,1])) li.append(spec) for spec in li: del spec del data def set_spec_peaks2(self): data = np.zeros((10000,2), dtype=np.float32) li = [] for i in range(1000): if (i+1)%100 == 0: show_mem("%4d specs processed" % i) spec = pyopenms.MSSpectrum() spec.set_peaks((data[:,0], data[:,1])) spec.set_peaks((data[:,0], data[:,1])) spec.set_peaks((data[:,0], data[:,1])) spec.set_peaks(spec.get_peaks()) li.append(spec) for spec in li: del spec del data def run_extractSpetraFromMSExperiment(self): p = pyopenms.FileHandler() e = pyopenms.MSExperiment() p.loadExperiment(self.testfile, e) show_mem("data loaded") li = [] print("please be patient :") for k in range(5): sys.stdout.flush() li.append([ e[i] for i in range(e.size()) ]) li.append([ e[i] for i in range(e.size()) ]) print((20*k+20), "%") print("\n") show_mem("spectra list generated") del li show_mem("spectra list deleted") del p del e def run_MSExperiment_copy(self): p = pyopenms.FileHandler() e1 = pyopenms.MSExperiment() p.loadExperiment(self.testfile, e1) show_mem("data loaded") specs = list(e1) for s in specs: for _ in range(10): e1.addSpectrum(s) li = [] print("please be patient :") N = 5 for k in range(N): sys.stdout.flush() for __ in range(400): e2 = copy.copy(e1) li.append(e2) e1 = copy.copy(e2) li.append(e1) print(int(100.0*(k+1)/N), "%") print("\n") show_mem("experiment list generated") del li del e1 del e2 del p show_mem("experiment list deleted") def run_fileformats_io(self): p = pyopenms.FileHandler() e = pyopenms.MSExperiment() p.loadExperiment(self.testfile, e) show_mem("after load mzXML") ct = pyopenms.ChromatogramTools() ct.convertChromatogramsToSpectra(e) p.storeExperiment(self.testfile, e) show_mem("after store mzXML") p.loadExperiment(self.testfile, e) show_mem("after load mzXML") p = pyopenms.FileHandler() ct.convertSpectraToChromatograms(e, True, False) p.storeExperiment("../test.mzML".encode(), e) show_mem("after store mzML") p.loadExperiment("../test.mzML".encode(), e) show_mem("after load mzML") p = pyopenms.FileHandler() ct.convertChromatogramsToSpectra(e) p.storeExperiment("../test.mzData".encode(), e) show_mem("after store mzData") p.loadExperiment("../test.mzData".encode(), e) show_mem("after load mzData") del e del p del ct if __name__ == "__main__": unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_FLASHDeconv.py
.py
40,084
1,185
""" Test suite for FLASHDeconv Python bindings. Tests cover: - FLASHHelperClasses (LogMzPeak, PrecalculatedAveragine, MassFeature, IsobaricQuantities) - PeakGroup - DeconvolvedSpectrum - SpectralDeconvolution - FLASHDeconvAlgorithm - FLASHDeconvSpectrumFile - FLASHDeconvFeatureFile """ import unittest import os import tempfile import pyopenms class TestFLASHHelperClasses(unittest.TestCase): """Test FLASHHelperClasses wrapper class and static functions.""" def test_class_instantiation(self): """Test that FLASHHelperClasses can be instantiated.""" helper = pyopenms.FLASHHelperClasses() self.assertIsNotNone(helper) def test_getLogMz_positive(self): """Test getLogMz for positive ionization mode.""" mz = 1300.0 log_mz = pyopenms.FLASHHelperClasses.getLogMz(mz, True) self.assertAlmostEqual(log_mz, 7.169344415063863, places=4) def test_getLogMz_negative(self): """Test getLogMz for negative ionization mode.""" mz = 1300.0 log_mz = pyopenms.FLASHHelperClasses.getLogMz(mz, False) self.assertAlmostEqual(log_mz, 7.170894071437545, places=4) def test_getLogMz_different_modes(self): """Test that positive and negative modes give different results.""" mz = 1300.0 log_mz_pos = pyopenms.FLASHHelperClasses.getLogMz(mz, True) log_mz_neg = pyopenms.FLASHHelperClasses.getLogMz(mz, False) self.assertNotEqual(log_mz_pos, log_mz_neg) def test_getChargeMass_positive(self): """Test getChargeMass for positive ionization mode.""" charge_mass = pyopenms.FLASHHelperClasses.getChargeMass(True) # Should be approximately proton mass self.assertAlmostEqual(charge_mass, 1.007276, places=4) def test_getChargeMass_negative(self): """Test getChargeMass for negative ionization mode.""" charge_mass = pyopenms.FLASHHelperClasses.getChargeMass(False) # Should be approximately negative proton mass self.assertAlmostEqual(charge_mass, -1.007276, places=4) class TestLogMzPeak(unittest.TestCase): """Test LogMzPeak struct.""" def test_default_constructor(self): """Test default constructor.""" peak = pyopenms.LogMzPeak() self.assertIsNotNone(peak) def test_constructor_from_peak1d_positive(self): """Test constructor from Peak1D in positive mode.""" p = pyopenms.Peak1D() p.setMZ(1125.5118055019082) p.setIntensity(443505.625) log_peak = pyopenms.LogMzPeak(p, True) self.assertAlmostEqual(log_peak.mz, 1125.5118055019082, places=4) self.assertAlmostEqual(log_peak.intensity, 443505.625, places=1) self.assertAlmostEqual(log_peak.logMz, 7.0250977989903145, places=4) self.assertTrue(log_peak.is_positive) self.assertEqual(log_peak.abs_charge, 0) self.assertEqual(log_peak.isotopeIndex, 0) def test_constructor_from_peak1d_negative(self): """Test constructor from Peak1D in negative mode.""" p = pyopenms.Peak1D() p.setMZ(1125.5118055019082) p.setIntensity(443505.625) log_peak_pos = pyopenms.LogMzPeak(p, True) log_peak_neg = pyopenms.LogMzPeak(p, False) self.assertFalse(log_peak_neg.is_positive) # logMz should be different for negative mode self.assertNotEqual(log_peak_neg.logMz, log_peak_pos.logMz) def test_copy_constructor(self): """Test copy constructor.""" p = pyopenms.Peak1D() p.setMZ(1125.5118055019082) p.setIntensity(443505.625) original = pyopenms.LogMzPeak(p, True) copy = pyopenms.LogMzPeak(original) self.assertAlmostEqual(copy.mz, original.mz, places=4) self.assertAlmostEqual(copy.intensity, original.intensity, places=1) self.assertAlmostEqual(copy.logMz, original.logMz, places=6) def test_getUnchargedMass_with_charge(self): """Test getUnchargedMass when charge is set.""" p = pyopenms.Peak1D() p.setMZ(1125.5118055019082) p.setIntensity(443505.625) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 2 mass = log_peak.getUnchargedMass() self.assertAlmostEqual(mass, 2249.0090580702745, places=2) def test_getUnchargedMass_zero_charge(self): """Test getUnchargedMass when charge is 0.""" p = pyopenms.Peak1D() p.setMZ(1125.5118055019082) p.setIntensity(443505.625) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 0 mass = log_peak.getUnchargedMass() self.assertAlmostEqual(mass, 0.0, places=4) def test_getUnchargedMass_preset_mass(self): """Test getUnchargedMass when mass is already set.""" p = pyopenms.Peak1D() p.setMZ(1125.5118055019082) p.setIntensity(443505.625) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 2 log_peak.mass = 5000.0 mass = log_peak.getUnchargedMass() self.assertAlmostEqual(mass, 5000.0, places=4) def test_comparison_operators(self): """Test comparison operators.""" p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(100.0) peak1 = pyopenms.LogMzPeak(p, True) peak2 = pyopenms.LogMzPeak(p, True) peak2.logMz = 8.0 # Make peak2 have larger logMz self.assertLess(peak1, peak2) self.assertTrue(peak2 > peak1) def test_equality_operator(self): """Test equality operator.""" p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(100.0) peak1 = pyopenms.LogMzPeak(p, True) peak2 = pyopenms.LogMzPeak(peak1) self.assertTrue(peak1 == peak2) def test_member_variables(self): """Test that member variables can be accessed and modified.""" peak = pyopenms.LogMzPeak() peak.mz = 500.0 peak.intensity = 1000.0 peak.logMz = 6.0 peak.mass = 2000.0 peak.abs_charge = 3 peak.is_positive = True peak.isotopeIndex = 2 self.assertAlmostEqual(peak.mz, 500.0, places=4) self.assertAlmostEqual(peak.intensity, 1000.0, places=4) self.assertAlmostEqual(peak.logMz, 6.0, places=4) self.assertAlmostEqual(peak.mass, 2000.0, places=4) self.assertEqual(peak.abs_charge, 3) self.assertTrue(peak.is_positive) self.assertEqual(peak.isotopeIndex, 2) class TestPrecalculatedAveragine(unittest.TestCase): """Test PrecalculatedAveragine (PrecalAveragine) class.""" def test_default_constructor(self): """Test default constructor.""" avg = pyopenms.PrecalAveragine() self.assertIsNotNone(avg) def test_constructor_with_generator(self): """Test constructor with CoarseIsotopePatternGenerator.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) apex_idx = avg.getApexIndex(75.0) mass_delta = avg.getAverageMassDelta(75.0) self.assertEqual(apex_idx, 0) self.assertAlmostEqual(mass_delta, 0.04, delta=0.3) def test_constructor_with_decoy_distance(self): """Test constructor with decoy isotope distance.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False, 1.5) iso = avg.get(75.0) self.assertGreater(iso.size(), 0) def test_get_isotope_distribution(self): """Test get method for isotope distribution.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) iso = avg.get(60.0) self.assertIsNotNone(iso) self.assertGreater(iso.size(), 0) def test_max_isotope_index(self): """Test getMaxIsotopeIndex and setMaxIsotopeIndex.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) avg.setMaxIsotopeIndex(4) self.assertEqual(avg.getMaxIsotopeIndex(), 4) def test_left_count_from_apex(self): """Test getLeftCountFromApex.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) left_count = avg.getLeftCountFromApex(75.0) self.assertIsInstance(left_count, int) def test_right_count_from_apex(self): """Test getRightCountFromApex.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) right_count = avg.getRightCountFromApex(75.0) self.assertIsInstance(right_count, int) def test_apex_index(self): """Test getApexIndex.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) apex_idx = avg.getApexIndex(75.0) self.assertEqual(apex_idx, 0) def test_last_index(self): """Test getLastIndex.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) last_idx = avg.getLastIndex(50.0) self.assertEqual(last_idx, 2) def test_average_mass_delta(self): """Test getAverageMassDelta.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) delta = avg.getAverageMassDelta(50.0) self.assertAlmostEqual(delta, 0.025, delta=0.1) def test_most_abundant_mass_delta(self): """Test getMostAbundantMassDelta.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) delta = avg.getMostAbundantMassDelta(1000.0) self.assertAlmostEqual(delta, 0.0, delta=0.1) def test_snr_multiplication_factor(self): """Test getSNRMultiplicationFactor.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) factor = avg.getSNRMultiplicationFactor(75.0) self.assertGreater(factor, 0) def test_copy_constructor(self): """Test copy constructor.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg1 = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) avg1.setMaxIsotopeIndex(4) avg2 = pyopenms.PrecalAveragine(avg1) self.assertEqual(avg2.getApexIndex(75.0), avg1.getApexIndex(75.0)) self.assertEqual(avg2.getMaxIsotopeIndex(), avg1.getMaxIsotopeIndex()) def test_rna_averagine(self): """Test RNA averagine mode.""" generator = pyopenms.CoarseIsotopePatternGenerator() avg_peptide = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, False) avg_rna = pyopenms.PrecalAveragine(50.0, 100.0, 25.0, generator, True) iso_peptide = avg_peptide.get(75.0) iso_rna = avg_rna.get(75.0) self.assertGreater(iso_peptide.size(), 0) self.assertGreater(iso_rna.size(), 0) class TestMassFeature(unittest.TestCase): """Test MassFeature (MassFeature_FDHS) struct.""" def test_default_constructor(self): """Test default constructor.""" mf = pyopenms.MassFeature_FDHS() self.assertIsNotNone(mf) def test_member_variables(self): """Test that all member variables can be accessed and modified.""" mf = pyopenms.MassFeature_FDHS() # Set all member variables mf.index = 42 mf.iso_offset = 1 mf.scan_number = 100 mf.min_scan_number = 90 mf.max_scan_number = 110 mf.rep_charge = 5 mf.avg_mass = 15000.0 mf.min_charge = 3 mf.max_charge = 10 mf.charge_count = 8 mf.isotope_score = 0.95 mf.qscore = 0.88 mf.rep_mz = 1500.5 mf.is_decoy = False mf.ms_level = 1 # Verify all values self.assertEqual(mf.index, 42) self.assertEqual(mf.iso_offset, 1) self.assertEqual(mf.scan_number, 100) self.assertEqual(mf.min_scan_number, 90) self.assertEqual(mf.max_scan_number, 110) self.assertEqual(mf.rep_charge, 5) self.assertAlmostEqual(mf.avg_mass, 15000.0, places=2) self.assertEqual(mf.min_charge, 3) self.assertEqual(mf.max_charge, 10) self.assertEqual(mf.charge_count, 8) self.assertAlmostEqual(mf.isotope_score, 0.95, places=4) self.assertAlmostEqual(mf.qscore, 0.88, places=4) self.assertAlmostEqual(mf.rep_mz, 1500.5, places=2) self.assertFalse(mf.is_decoy) self.assertEqual(mf.ms_level, 1) def test_intensity_vectors(self): """Test per_charge_intensity and per_isotope_intensity vectors.""" mf = pyopenms.MassFeature_FDHS() mf.per_charge_intensity = [100.0, 200.0, 300.0] mf.per_isotope_intensity = [50.0, 100.0, 75.0, 25.0] self.assertEqual(len(mf.per_charge_intensity), 3) self.assertEqual(len(mf.per_isotope_intensity), 4) self.assertAlmostEqual(mf.per_charge_intensity[1], 200.0, places=1) self.assertAlmostEqual(mf.per_isotope_intensity[2], 75.0, places=1) def test_comparison_operators(self): """Test comparison operators.""" mf1 = pyopenms.MassFeature_FDHS() mf2 = pyopenms.MassFeature_FDHS() mf1.avg_mass = 1000.0 mf2.avg_mass = 2000.0 self.assertTrue(mf1 < mf2) self.assertFalse(mf2 < mf1) self.assertTrue(mf2 > mf1) self.assertFalse(mf1 > mf2) def test_equality_operator(self): """Test equality operator.""" mf1 = pyopenms.MassFeature_FDHS() mf2 = pyopenms.MassFeature_FDHS() mf1.avg_mass = 1000.0 mf2.avg_mass = 1000.0 self.assertTrue(mf1 == mf2) mf2.avg_mass = 2000.0 self.assertFalse(mf1 == mf2) class TestIsobaricQuantities(unittest.TestCase): """Test IsobaricQuantities struct.""" def test_default_constructor(self): """Test default constructor.""" iq = pyopenms.IsobaricQuantities() self.assertIsNotNone(iq) def test_empty_method(self): """Test empty() method.""" iq = pyopenms.IsobaricQuantities() # Should be empty initially self.assertTrue(iq.empty()) # Add quantities iq.quantities = [100.0] self.assertFalse(iq.empty()) # Clear quantities iq.quantities = [] self.assertTrue(iq.empty()) def test_member_variables(self): """Test all member variables.""" iq = pyopenms.IsobaricQuantities() iq.scan = 500 iq.rt = 120.5 iq.precursor_mz = 750.25 iq.precursor_mass = 1498.48 iq.quantities = [100.0, 200.0, 150.0, 175.0] iq.merged_quantities = [450.0, 375.0] self.assertEqual(iq.scan, 500) self.assertAlmostEqual(iq.rt, 120.5, places=2) self.assertAlmostEqual(iq.precursor_mz, 750.25, places=2) self.assertAlmostEqual(iq.precursor_mass, 1498.48, places=2) self.assertEqual(len(iq.quantities), 4) self.assertEqual(len(iq.merged_quantities), 2) self.assertAlmostEqual(iq.quantities[0], 100.0, places=2) self.assertAlmostEqual(iq.quantities[3], 175.0, places=2) self.assertAlmostEqual(iq.merged_quantities[0], 450.0, places=2) class TestPeakGroup(unittest.TestCase): """Test PeakGroup class.""" def test_default_constructor(self): """Test default constructor.""" pg = pyopenms.PeakGroup() self.assertIsNotNone(pg) def test_constructor_with_charge_range(self): """Test constructor with charge range parameters.""" pg = pyopenms.PeakGroup(1, 10, True) self.assertIsNotNone(pg) self.assertTrue(pg.isPositive()) def test_copy_constructor(self): """Test copy constructor.""" pg1 = pyopenms.PeakGroup(1, 10, True) pg1.setScanNumber(5) pg1.setQscore(0.9) pg2 = pyopenms.PeakGroup(pg1) self.assertEqual(pg2.getScanNumber(), pg1.getScanNumber()) self.assertAlmostEqual(pg2.getQscore(), pg1.getQscore(), places=4) def test_scan_number(self): """Test getScanNumber and setScanNumber.""" pg = pyopenms.PeakGroup() pg.setScanNumber(42) self.assertEqual(pg.getScanNumber(), 42) def test_monoisotopic_mass(self): """Test getMonoMass and setMonoisotopicMass.""" pg = pyopenms.PeakGroup() pg.setMonoisotopicMass(5000.0) self.assertAlmostEqual(pg.getMonoMass(), 5000.0, places=2) def test_intensity(self): """Test getIntensity.""" pg = pyopenms.PeakGroup() # Intensity is computed from peaks, so test that it returns a float intensity = pg.getIntensity() self.assertIsInstance(intensity, float) def test_qscore(self): """Test getQscore and setQscore.""" pg = pyopenms.PeakGroup() pg.setQscore(0.85) self.assertAlmostEqual(pg.getQscore(), 0.85, places=4) def test_qscore_2d(self): """Test getQscore2D and setQscore2D.""" pg = pyopenms.PeakGroup() pg.setQscore2D(0.75) self.assertAlmostEqual(pg.getQscore2D(), 0.75, places=4) def test_isotope_cosine(self): """Test getIsotopeCosine and setIsotopeCosine.""" pg = pyopenms.PeakGroup() pg.setIsotopeCosine(0.95) self.assertAlmostEqual(pg.getIsotopeCosine(), 0.95, places=4) def test_charge_score(self): """Test getChargeScore and setChargeScore.""" pg = pyopenms.PeakGroup() pg.setChargeScore(0.8) self.assertAlmostEqual(pg.getChargeScore(), 0.8, places=4) def test_snr(self): """Test getSNR and setSNR.""" pg = pyopenms.PeakGroup() pg.setSNR(50.0) self.assertAlmostEqual(pg.getSNR(), 50.0, places=2) def test_rep_abs_charge(self): """Test getRepAbsCharge and setRepAbsCharge.""" pg = pyopenms.PeakGroup() pg.setRepAbsCharge(5) self.assertEqual(pg.getRepAbsCharge(), 5) def test_index(self): """Test getIndex and setIndex.""" pg = pyopenms.PeakGroup() pg.setIndex(10) self.assertEqual(pg.getIndex(), 10) def test_feature_index(self): """Test getFeatureIndex and setFeatureIndex.""" pg = pyopenms.PeakGroup() pg.setFeatureIndex(20) self.assertEqual(pg.getFeatureIndex(), 20) def test_qvalue(self): """Test getQvalue and setQvalue.""" pg = pyopenms.PeakGroup() pg.setQvalue(0.05) self.assertAlmostEqual(pg.getQvalue(), 0.05, places=4) def test_target_decoy_type(self): """Test getTargetDecoyType and setTargetDecoyType.""" pg = pyopenms.PeakGroup() pg.setTargetDecoyType(pyopenms.PeakGroup.TargetDecoyType.target) self.assertEqual(pg.getTargetDecoyType(), pyopenms.PeakGroup.TargetDecoyType.target) pg.setTargetDecoyType(pyopenms.PeakGroup.TargetDecoyType.noise_decoy) self.assertEqual(pg.getTargetDecoyType(), pyopenms.PeakGroup.TargetDecoyType.noise_decoy) def test_is_positive(self): """Test isPositive.""" pg_pos = pyopenms.PeakGroup(1, 10, True) pg_neg = pyopenms.PeakGroup(1, 10, False) self.assertTrue(pg_pos.isPositive()) self.assertFalse(pg_neg.isPositive()) def test_is_targeted(self): """Test isTargeted and setTargeted.""" pg = pyopenms.PeakGroup() self.assertFalse(pg.isTargeted()) pg.setTargeted() self.assertTrue(pg.isTargeted()) def test_avg_ppm_error(self): """Test getAvgPPMError and setAvgPPMError.""" pg = pyopenms.PeakGroup() pg.setAvgPPMError(5.5) self.assertAlmostEqual(pg.getAvgPPMError(), 5.5, places=2) def test_avg_da_error(self): """Test getAvgDaError.""" pg = pyopenms.PeakGroup() error = pg.getAvgDaError() self.assertIsInstance(error, float) def test_isotope_da_distance(self): """Test getIsotopeDaDistance and setIsotopeDaDistance.""" pg = pyopenms.PeakGroup() pg.setIsotopeDaDistance(1.003) self.assertAlmostEqual(pg.getIsotopeDaDistance(), 1.003, places=3) def test_charge_intensity(self): """Test getChargeIntensity.""" pg = pyopenms.PeakGroup(1, 10, True) intensity = pg.getChargeIntensity(5) self.assertIsInstance(intensity, float) def test_charge_snr(self): """Test getChargeSNR and setChargeSNR.""" pg = pyopenms.PeakGroup(1, 10, True) pg.setChargeSNR(5, 10.0) self.assertAlmostEqual(pg.getChargeSNR(5), 10.0, places=2) def test_charge_isotope_cosine(self): """Test getChargeIsotopeCosine and setChargeIsotopeCosine.""" pg = pyopenms.PeakGroup(1, 10, True) pg.setChargeIsotopeCosine(5, 0.9) self.assertAlmostEqual(pg.getChargeIsotopeCosine(5), 0.9, places=2) def test_isotope_intensities(self): """Test getIsotopeIntensities.""" pg = pyopenms.PeakGroup() intensities = pg.getIsotopeIntensities() self.assertIsInstance(intensities, list) def test_mass_errors(self): """Test getMassErrors.""" pg = pyopenms.PeakGroup() errors_ppm = pg.getMassErrors(True) errors_da = pg.getMassErrors(False) self.assertIsInstance(errors_ppm, list) self.assertIsInstance(errors_da, list) def test_container_operations(self): """Test container operations (size, empty, push_back, reserve).""" pg = pyopenms.PeakGroup(1, 10, True) self.assertTrue(pg.empty()) self.assertEqual(pg.size(), 0) # Add a LogMzPeak p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(100.0) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 5 log_peak.isotopeIndex = 0 pg.push_back(log_peak) self.assertFalse(pg.empty()) self.assertEqual(pg.size(), 1) def test_element_access(self): """Test element access via operator[].""" pg = pyopenms.PeakGroup(1, 10, True) p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(100.0) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 5 pg.push_back(log_peak) retrieved = pg[0] self.assertAlmostEqual(retrieved.mz, 1000.0, places=2) def test_iteration(self): """Test iteration over peaks.""" pg = pyopenms.PeakGroup(1, 10, True) for mz in [1000.0, 1001.0, 1002.0]: p = pyopenms.Peak1D() p.setMZ(mz) p.setIntensity(100.0) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 5 pg.push_back(log_peak) mz_values = [peak.mz for peak in pg] self.assertEqual(len(mz_values), 3) self.assertAlmostEqual(mz_values[0], 1000.0, places=2) self.assertAlmostEqual(mz_values[1], 1001.0, places=2) self.assertAlmostEqual(mz_values[2], 1002.0, places=2) def test_comparison_operators(self): """Test comparison operators.""" pg1 = pyopenms.PeakGroup() pg2 = pyopenms.PeakGroup() pg1.setMonoisotopicMass(1000.0) pg2.setMonoisotopicMass(2000.0) self.assertTrue(pg1 < pg2) self.assertTrue(pg2 > pg1) def test_equality_operator(self): """Test equality operator.""" pg1 = pyopenms.PeakGroup() pg2 = pyopenms.PeakGroup(pg1) self.assertTrue(pg1 == pg2) def test_sort(self): """Test sort method.""" pg = pyopenms.PeakGroup(1, 10, True) # Add peaks in reverse order for mz in [1002.0, 1000.0, 1001.0]: p = pyopenms.Peak1D() p.setMZ(mz) p.setIntensity(100.0) log_peak = pyopenms.LogMzPeak(p, True) log_peak.abs_charge = 5 pg.push_back(log_peak) pg.sort() # Verify sorted order mz_values = [peak.mz for peak in pg] self.assertLess(mz_values[0], mz_values[1]) self.assertLess(mz_values[1], mz_values[2]) class TestDeconvolvedSpectrum(unittest.TestCase): """Test DeconvolvedSpectrum class.""" def test_default_constructor(self): """Test default constructor.""" ds = pyopenms.DeconvolvedSpectrum() self.assertIsNotNone(ds) def test_constructor_with_scan_number(self): """Test constructor with scan number.""" ds = pyopenms.DeconvolvedSpectrum(42) self.assertEqual(ds.getScanNumber(), 42) def test_copy_constructor(self): """Test copy constructor.""" ds1 = pyopenms.DeconvolvedSpectrum(10) ds2 = pyopenms.DeconvolvedSpectrum(ds1) self.assertEqual(ds2.getScanNumber(), ds1.getScanNumber()) def test_scan_number(self): """Test getScanNumber.""" ds = pyopenms.DeconvolvedSpectrum(100) self.assertEqual(ds.getScanNumber(), 100) def test_original_spectrum(self): """Test getOriginalSpectrum and setOriginalSpectrum.""" ds = pyopenms.DeconvolvedSpectrum(1) spec = pyopenms.MSSpectrum() p = pyopenms.Peak1D() p.setMZ(500.0) p.setIntensity(1000.0) spec.push_back(p) ds.setOriginalSpectrum(spec) retrieved = ds.getOriginalSpectrum() self.assertEqual(retrieved.size(), 1) def test_precursor(self): """Test getPrecursor and setPrecursor.""" ds = pyopenms.DeconvolvedSpectrum(1) prec = pyopenms.Precursor() prec.setMZ(750.0) prec.setCharge(5) ds.setPrecursor(prec) retrieved = ds.getPrecursor() self.assertAlmostEqual(retrieved.getMZ(), 750.0, places=2) self.assertEqual(retrieved.getCharge(), 5) def test_precursor_charge(self): """Test getPrecursorCharge.""" ds = pyopenms.DeconvolvedSpectrum(1) prec = pyopenms.Precursor() prec.setCharge(7) ds.setPrecursor(prec) self.assertEqual(ds.getPrecursorCharge(), 7) def test_precursor_scan_number(self): """Test getPrecursorScanNumber and setPrecursorScanNumber.""" ds = pyopenms.DeconvolvedSpectrum(1) ds.setPrecursorScanNumber(50) self.assertEqual(ds.getPrecursorScanNumber(), 50) def test_precursor_peak_group(self): """Test getPrecursorPeakGroup and setPrecursorPeakGroup.""" ds = pyopenms.DeconvolvedSpectrum(1) pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(5000.0) ds.setPrecursorPeakGroup(pg) retrieved = ds.getPrecursorPeakGroup() self.assertAlmostEqual(retrieved.getMonoMass(), 5000.0, places=2) def test_current_mass_limits(self): """Test getCurrentMaxMass and getCurrentMinMass.""" ds = pyopenms.DeconvolvedSpectrum(1) max_mass = ds.getCurrentMaxMass(10000.0) min_mass = ds.getCurrentMinMass(500.0) self.assertIsInstance(max_mass, float) self.assertIsInstance(min_mass, float) def test_current_max_abs_charge(self): """Test getCurrentMaxAbsCharge.""" ds = pyopenms.DeconvolvedSpectrum(1) max_charge = ds.getCurrentMaxAbsCharge(20) self.assertIsInstance(max_charge, int) def test_quantities(self): """Test getQuantities and setQuantities.""" ds = pyopenms.DeconvolvedSpectrum(1) iq = pyopenms.IsobaricQuantities() iq.scan = 100 iq.quantities = [100.0, 200.0] ds.setQuantities(iq) retrieved = ds.getQuantities() self.assertEqual(retrieved.scan, 100) def test_is_decoy(self): """Test isDecoy.""" ds = pyopenms.DeconvolvedSpectrum(1) is_decoy = ds.isDecoy() self.assertIsInstance(is_decoy, bool) def test_container_operations(self): """Test container operations (size, empty, clear, reserve, push_back, pop_back).""" ds = pyopenms.DeconvolvedSpectrum(1) self.assertTrue(ds.empty()) self.assertEqual(ds.size(), 0) pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(5000.0) ds.push_back(pg) self.assertFalse(ds.empty()) self.assertEqual(ds.size(), 1) ds.pop_back() self.assertTrue(ds.empty()) self.assertEqual(ds.size(), 0) def test_set_peak_groups(self): """Test setPeakGroups.""" ds = pyopenms.DeconvolvedSpectrum(1) pgs = [] for mass in [1000.0, 2000.0, 3000.0]: pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(mass) pgs.append(pg) ds.setPeakGroups(pgs) self.assertEqual(ds.size(), 3) def test_element_access(self): """Test element access via operator[].""" ds = pyopenms.DeconvolvedSpectrum(1) pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(5000.0) ds.push_back(pg) retrieved = ds[0] self.assertAlmostEqual(retrieved.getMonoMass(), 5000.0, places=2) def test_iteration(self): """Test iteration over peak groups.""" ds = pyopenms.DeconvolvedSpectrum(1) for mass in [1000.0, 2000.0, 3000.0]: pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(mass) ds.push_back(pg) masses = [pg.getMonoMass() for pg in ds] self.assertEqual(len(masses), 3) self.assertAlmostEqual(masses[0], 1000.0, places=2) self.assertAlmostEqual(masses[1], 2000.0, places=2) self.assertAlmostEqual(masses[2], 3000.0, places=2) def test_sort(self): """Test sort method.""" ds = pyopenms.DeconvolvedSpectrum(1) for mass in [3000.0, 1000.0, 2000.0]: pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(mass) ds.push_back(pg) ds.sort() masses = [pg.getMonoMass() for pg in ds] self.assertLess(masses[0], masses[1]) self.assertLess(masses[1], masses[2]) def test_sort_by_qscore(self): """Test sortByQscore method.""" ds = pyopenms.DeconvolvedSpectrum(1) for qscore in [0.5, 0.9, 0.7]: pg = pyopenms.PeakGroup(1, 10, True) pg.setQscore(qscore) ds.push_back(pg) ds.sortByQscore() qscores = [pg.getQscore() for pg in ds] # sortByQscore sorts in descending order self.assertGreaterEqual(qscores[0], qscores[1]) self.assertGreaterEqual(qscores[1], qscores[2]) def test_to_spectrum(self): """Test toSpectrum conversion.""" ds = pyopenms.DeconvolvedSpectrum(1) pg = pyopenms.PeakGroup(1, 10, True) pg.setMonoisotopicMass(5000.0) ds.push_back(pg) # Original spectrum needed for conversion spec = pyopenms.MSSpectrum() spec.setRT(100.0) ds.setOriginalSpectrum(spec) result = ds.toSpectrum(1, 10.0, False) # MSSpectrum may be wrapped as _MSSpectrumDF, check for size method instead self.assertTrue(hasattr(result, 'size')) def test_comparison_operators(self): """Test comparison operators.""" ds1 = pyopenms.DeconvolvedSpectrum(1) ds2 = pyopenms.DeconvolvedSpectrum(2) # Comparison is based on scan number self.assertTrue(ds1 < ds2) self.assertTrue(ds2 > ds1) def test_equality_operator(self): """Test equality operator.""" ds1 = pyopenms.DeconvolvedSpectrum(1) ds2 = pyopenms.DeconvolvedSpectrum(ds1) self.assertTrue(ds1 == ds2) class TestSpectralDeconvolution(unittest.TestCase): """Test SpectralDeconvolution class.""" def test_default_constructor(self): """Test default constructor.""" sd = pyopenms.SpectralDeconvolution() self.assertIsNotNone(sd) def test_copy_constructor(self): """Test copy constructor.""" sd1 = pyopenms.SpectralDeconvolution() sd2 = pyopenms.SpectralDeconvolution(sd1) self.assertIsNotNone(sd2) def test_default_param_handler_interface(self): """Test DefaultParamHandler interface.""" sd = pyopenms.SpectralDeconvolution() # Test that we can get and set parameters params = sd.getParameters() self.assertIsNotNone(params) # Test that default parameters exist defaults = sd.getDefaults() self.assertIsNotNone(defaults) def test_get_nominal_mass(self): """Test static getNominalMass method.""" mass1 = 10000.0 mass2 = 25000.0 nominal1 = pyopenms.SpectralDeconvolution.getNominalMass(mass1) nominal2 = pyopenms.SpectralDeconvolution.getNominalMass(mass2) self.assertEqual(nominal1, 9995) self.assertEqual(nominal2, 24987) def test_calculate_averagine(self): """Test calculateAveragine method.""" sd = pyopenms.SpectralDeconvolution() params = pyopenms.Param() params.setValue("max_mass", 2000.0) params.setValue("min_charge", 1) params.setValue("max_charge", 10) sd.setParameters(params) # Calculate peptide averagine sd.calculateAveragine(False) avg = sd.getAveragine() self.assertIsNotNone(avg) self.assertGreater(avg.getMaxIsotopeIndex(), 0) def test_calculate_rna_averagine(self): """Test calculateAveragine method with RNA mode.""" sd = pyopenms.SpectralDeconvolution() params = pyopenms.Param() params.setValue("max_mass", 2000.0) params.setValue("min_charge", 1) params.setValue("max_charge", 10) sd.setParameters(params) # Calculate RNA averagine sd.calculateAveragine(True) avg = sd.getAveragine() self.assertIsNotNone(avg) self.assertGreater(avg.getMaxIsotopeIndex(), 0) def test_get_set_averagine(self): """Test getAveragine and setAveragine methods.""" sd = pyopenms.SpectralDeconvolution() generator = pyopenms.CoarseIsotopePatternGenerator() avg = pyopenms.PrecalAveragine(50.0, 1000.0, 25.0, generator, False) avg.setMaxIsotopeIndex(10) sd.setAveragine(avg) retrieved = sd.getAveragine() self.assertEqual(retrieved.getMaxIsotopeIndex(), 10) def test_set_tolerance_estimation(self): """Test setToleranceEstimation method.""" sd = pyopenms.SpectralDeconvolution() sd.setToleranceEstimation() # No direct way to verify, just check no exception def test_get_cosine(self): """Test static getCosine method.""" a = [1.0, 2.0, 3.0, 4.0, 5.0] # Create isotope distribution for comparison generator = pyopenms.CoarseIsotopePatternGenerator() formula = pyopenms.EmpiricalFormula("C100H200N50O50") b = generator.run(formula) cosine = pyopenms.SpectralDeconvolution.getCosine(a, 0, 5, b, 0, 2) self.assertIsInstance(cosine, float) self.assertGreaterEqual(cosine, -1.0) self.assertLessEqual(cosine, 1.0) def test_set_target_decoy_type(self): """Test setTargetDecoyType method.""" sd = pyopenms.SpectralDeconvolution() params = pyopenms.Param() params.setValue("max_mass", 2000.0) params.setValue("min_charge", 1) params.setValue("max_charge", 10) sd.setParameters(params) sd.calculateAveragine(False) ds = pyopenms.DeconvolvedSpectrum(1) sd.setTargetDecoyType(pyopenms.PeakGroup.TargetDecoyType.target, ds) class TestFLASHDeconvAlgorithm(unittest.TestCase): """Test FLASHDeconvAlgorithm class.""" def test_default_constructor(self): """Test default constructor.""" algo = pyopenms.FLASHDeconvAlgorithm() self.assertIsNotNone(algo) def test_copy_constructor(self): """Test copy constructor.""" algo1 = pyopenms.FLASHDeconvAlgorithm() algo2 = pyopenms.FLASHDeconvAlgorithm(algo1) self.assertEqual(algo2.getParameters(), algo1.getParameters()) def test_default_param_handler_interface(self): """Test DefaultParamHandler interface.""" algo = pyopenms.FLASHDeconvAlgorithm() params = algo.getParameters() self.assertIsNotNone(params) defaults = algo.getDefaults() self.assertIsNotNone(defaults) def test_progress_logger_interface(self): """Test ProgressLogger interface.""" algo = pyopenms.FLASHDeconvAlgorithm() algo.setLogType(pyopenms.LogType.NONE) self.assertEqual(algo.getLogType(), pyopenms.LogType.NONE) def test_get_tolerances(self): """Test getTolerances method.""" algo = pyopenms.FLASHDeconvAlgorithm() params = pyopenms.Param() params.setValue("SD:tol", [10.0, 5.0]) algo.setParameters(params) tolerances = algo.getTolerances() self.assertEqual(len(tolerances), 2) self.assertAlmostEqual(tolerances[0], 10.0, places=2) self.assertAlmostEqual(tolerances[1], 5.0, places=2) def test_get_scan_number(self): """Test static getScanNumber method.""" exp = pyopenms.MSExperiment() # Add a spectrum with native ID spec = pyopenms.MSSpectrum() spec.setNativeID("scan=42") exp.addSpectrum(spec) scan_num = pyopenms.FLASHDeconvAlgorithm.getScanNumber(exp, 0) self.assertIsInstance(scan_num, int) class TestFLASHDeconvSpectrumFile(unittest.TestCase): """Test FLASHDeconvSpectrumFile class.""" def test_default_constructor(self): """Test default constructor.""" sf = pyopenms.FLASHDeconvSpectrumFile() self.assertIsNotNone(sf) def test_copy_constructor(self): """Test copy constructor.""" sf1 = pyopenms.FLASHDeconvSpectrumFile() sf2 = pyopenms.FLASHDeconvSpectrumFile(sf1) self.assertIsNotNone(sf2) class TestFLASHDeconvFeatureFile(unittest.TestCase): """Test FLASHDeconvFeatureFile class.""" def test_default_constructor(self): """Test default constructor.""" ff = pyopenms.FLASHDeconvFeatureFile() self.assertIsNotNone(ff) def test_copy_constructor(self): """Test copy constructor.""" ff1 = pyopenms.FLASHDeconvFeatureFile() ff2 = pyopenms.FLASHDeconvFeatureFile(ff1) self.assertIsNotNone(ff2) class TestTargetDecoyTypeEnum(unittest.TestCase): """Test TargetDecoyType enum.""" def test_enum_values(self): """Test that all enum values exist.""" # Cython enums are exposed as integers, not Python enum objects self.assertEqual(pyopenms.PeakGroup.TargetDecoyType.target, 0) self.assertEqual(pyopenms.PeakGroup.TargetDecoyType.noise_decoy, 1) self.assertEqual(pyopenms.PeakGroup.TargetDecoyType.signal_decoy, 2) def test_enum_assignment(self): """Test enum assignment to PeakGroup.""" pg = pyopenms.PeakGroup() pg.setTargetDecoyType(pyopenms.PeakGroup.TargetDecoyType.target) self.assertEqual(pg.getTargetDecoyType(), pyopenms.PeakGroup.TargetDecoyType.target) pg.setTargetDecoyType(pyopenms.PeakGroup.TargetDecoyType.noise_decoy) self.assertEqual(pg.getTargetDecoyType(), pyopenms.PeakGroup.TargetDecoyType.noise_decoy) pg.setTargetDecoyType(pyopenms.PeakGroup.TargetDecoyType.signal_decoy) self.assertEqual(pg.getTargetDecoyType(), pyopenms.PeakGroup.TargetDecoyType.signal_decoy) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_StaticMethods.py
.py
31,908
801
""" Tests for static methods converted to @staticmethod decorator pattern. This test file covers the wrapper changes from issue #8559. """ import unittest import os import tempfile import pyopenms def make_peak1d(mz, intensity): """Helper to create Peak1D with mz and intensity.""" p = pyopenms.Peak1D() p.setMZ(mz) p.setIntensity(intensity) return p class TestFileStaticMethods(unittest.TestCase): """Test static methods of the File class.""" def test_exists(self): """Test File.exists static method.""" # Create a temporary file with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name try: self.assertTrue(pyopenms.File.exists(temp_path)) self.assertFalse(pyopenms.File.exists("/nonexistent/path/file.txt")) finally: os.unlink(temp_path) def test_readable(self): """Test File.readable static method.""" with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name try: self.assertTrue(pyopenms.File.readable(temp_path)) self.assertFalse(pyopenms.File.readable("/nonexistent/path/file.txt")) finally: os.unlink(temp_path) def test_writable(self): """Test File.writable static method.""" with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name try: self.assertTrue(pyopenms.File.writable(temp_path)) finally: os.unlink(temp_path) def test_empty(self): """Test File.empty static method.""" # Create an empty file with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name try: self.assertTrue(pyopenms.File.empty(temp_path)) finally: os.unlink(temp_path) # Create a non-empty file with tempfile.NamedTemporaryFile(delete=False, mode='w') as f: f.write("content") temp_path = f.name try: self.assertFalse(pyopenms.File.empty(temp_path)) finally: os.unlink(temp_path) def test_remove(self): """Test File.remove static method.""" with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name self.assertTrue(os.path.exists(temp_path)) result = pyopenms.File.remove(temp_path) self.assertTrue(result) self.assertFalse(os.path.exists(temp_path)) def test_rename(self): """Test File.rename static method.""" with tempfile.NamedTemporaryFile(delete=False) as f: old_path = f.name new_path = old_path + "_renamed" try: result = pyopenms.File.rename(old_path, new_path, True, False) self.assertTrue(result) self.assertFalse(os.path.exists(old_path)) self.assertTrue(os.path.exists(new_path)) finally: if os.path.exists(new_path): os.unlink(new_path) if os.path.exists(old_path): os.unlink(old_path) def test_basename(self): """Test File.basename static method.""" result = pyopenms.File.basename("/path/to/file.txt") self.assertEqual(str(result), "file.txt") def test_path(self): """Test File.path static method.""" result = pyopenms.File.path("/path/to/file.txt") self.assertIn("path", str(result)) def test_absolutePath(self): """Test File.absolutePath static method.""" result = pyopenms.File.absolutePath(".") self.assertGreater(len(str(result)), 0) def test_isDirectory(self): """Test File.isDirectory static method.""" self.assertTrue(pyopenms.File.isDirectory(tempfile.gettempdir())) with tempfile.NamedTemporaryFile(delete=False) as f: temp_path = f.name try: self.assertFalse(pyopenms.File.isDirectory(temp_path)) finally: os.unlink(temp_path) def test_getTempDirectory(self): """Test File.getTempDirectory static method.""" result = pyopenms.File.getTempDirectory() self.assertGreater(len(str(result)), 0) def test_getUserDirectory(self): """Test File.getUserDirectory static method.""" result = pyopenms.File.getUserDirectory() self.assertGreater(len(str(result)), 0) def test_getUniqueName(self): """Test File.getUniqueName static method.""" name1 = pyopenms.File.getUniqueName() name2 = pyopenms.File.getUniqueName() self.assertNotEqual(str(name1), str(name2)) def test_getTemporaryFile(self): """Test File.getTemporaryFile static method.""" result = pyopenms.File.getTemporaryFile("") self.assertGreater(len(str(result)), 0) class TestBuildInfoStaticMethods(unittest.TestCase): """Test static methods of the OpenMSBuildInfo and OpenMSOSInfo classes.""" def test_getOSInfo(self): """Test OpenMSOSInfo.getOSInfo static method.""" # Note: getOSInfo is in OpenMSOSInfo, not OpenMSBuildInfo os_info = pyopenms.OpenMSOSInfo.getOSInfo() self.assertIsNotNone(os_info) # Test that we can get OS info from the returned object os_string = os_info.getOSAsString() self.assertGreater(len(str(os_string)), 0) def test_getBinaryArchitecture(self): """Test OpenMSOSInfo.getBinaryArchitecture static method.""" # Note: getBinaryArchitecture is in OpenMSOSInfo, not OpenMSBuildInfo arch = pyopenms.OpenMSOSInfo.getBinaryArchitecture() self.assertGreater(len(str(arch)), 0) def test_isOpenMPEnabled(self): """Test OpenMSBuildInfo.isOpenMPEnabled static method.""" # Just check it returns a boolean result = pyopenms.OpenMSBuildInfo.isOpenMPEnabled() self.assertIsInstance(result, bool) def test_getBuildType(self): """Test OpenMSBuildInfo.getBuildType static method.""" build_type = pyopenms.OpenMSBuildInfo.getBuildType() self.assertGreater(len(str(build_type)), 0) def test_getOpenMPMaxNumThreads(self): """Test OpenMSBuildInfo.getOpenMPMaxNumThreads static method.""" num_threads = pyopenms.OpenMSBuildInfo.getOpenMPMaxNumThreads() self.assertGreaterEqual(num_threads, 1) class TestVersionInfoStaticMethods(unittest.TestCase): """Test static methods of the VersionInfo class.""" def test_getVersion(self): """Test VersionInfo.getVersion static method.""" version = pyopenms.VersionInfo.getVersion() self.assertGreater(len(str(version)), 0) def test_getRevision(self): """Test VersionInfo.getRevision static method.""" revision = pyopenms.VersionInfo.getRevision() # Revision may be empty in some builds self.assertIsNotNone(revision) def test_getTime(self): """Test VersionInfo.getTime static method.""" time = pyopenms.VersionInfo.getTime() self.assertIsNotNone(time) def test_getBranch(self): """Test VersionInfo.getBranch static method.""" branch = pyopenms.VersionInfo.getBranch() self.assertIsNotNone(branch) class TestDateTimeStaticMethods(unittest.TestCase): """Test static methods of the DateTime class.""" def test_now(self): """Test DateTime.now static method.""" dt = pyopenms.DateTime.now() self.assertIsNotNone(dt) # Check that the returned DateTime has valid date date_str = dt.getDate() self.assertGreater(len(str(date_str)), 0) class TestDeisotoperStaticMethods(unittest.TestCase): """Test static methods of the Deisotoper class.""" def test_deisotopeAndSingleCharge(self): """Test Deisotoper.deisotopeAndSingleCharge static method.""" spectrum = pyopenms.MSSpectrum() # Add peaks that form an isotope pattern (doubly charged) for mz, intensity in [(500.0, 1000.0), (500.5, 800.0), (501.0, 400.0), (501.5, 150.0)]: spectrum.push_back(make_peak1d(mz, intensity)) # Call the static method with all 15 required parameters pyopenms.Deisotoper.deisotopeAndSingleCharge( spectrum, 0.1, # fragment_tolerance False, # fragment_unit_ppm 1, # min_charge 3, # max_charge False, # keep_only_deisotoped 2, # min_isopeaks 10, # max_isopeaks True, # make_single_charged True, # annotate_charge False, # annotate_iso_peak_count True, # use_decreasing_model 2, # start_intensity_check False, # add_up_intensity False # annotate_features ) # Just verify it runs without error - deisotoping should reduce peak count self.assertIsNotNone(spectrum) class TestIMTypesStaticMethods(unittest.TestCase): """Test static methods of IMTypes enums. Note: These methods use the wrap-attach pattern instead of @staticmethod, as they are free functions in the OpenMS namespace. """ def test_toDriftTimeUnit(self): """Test IMTypes.toDriftTimeUnit static method.""" # Use correct string value "ms" (not "millisecond") unit = pyopenms.IMTypes.toDriftTimeUnit("ms") # DriftTimeUnit enum is at module level, not nested under IMTypes self.assertEqual(unit, pyopenms.DriftTimeUnit.MILLISECOND) def test_toIMFormat(self): """Test IMTypes.toIMFormat static method.""" fmt = pyopenms.IMTypes.toIMFormat("concatenated") # IMFormat enum is at module level, not nested under IMTypes self.assertEqual(fmt, pyopenms.IMFormat.CONCATENATED) class TestTransformationModelStaticMethods(unittest.TestCase): """Test static methods of TransformationModel classes.""" def test_TransformationModelLinear_getDefaultParameters(self): """Test TransformationModelLinear.getDefaultParameters static method.""" params = pyopenms.Param() pyopenms.TransformationModelLinear.getDefaultParameters(params) self.assertIsNotNone(params) def test_TransformationModelBSpline_getDefaultParameters(self): """Test TransformationModelBSpline.getDefaultParameters static method.""" params = pyopenms.Param() pyopenms.TransformationModelBSpline.getDefaultParameters(params) self.assertIsNotNone(params) def test_TransformationModelLowess_getDefaultParameters(self): """Test TransformationModelLowess.getDefaultParameters static method.""" params = pyopenms.Param() pyopenms.TransformationModelLowess.getDefaultParameters(params) self.assertIsNotNone(params) class TestMZTrafoModelStaticMethods(unittest.TestCase): """Test static methods of MZTrafoModel class.""" def test_nameToEnum(self): """Test MZTrafoModel.nameToEnum static method.""" enum_val = pyopenms.MZTrafoModel.nameToEnum("linear") self.assertEqual(enum_val, pyopenms.MZTrafoModel.MODELTYPE.LINEAR) def test_enumToName(self): """Test MZTrafoModel.enumToName static method.""" name = pyopenms.MZTrafoModel.enumToName(pyopenms.MZTrafoModel.MODELTYPE.LINEAR) self.assertEqual(name, "linear") class TestSpectrumHelperStaticMethods(unittest.TestCase): """Test static methods of SpectrumHelper class. Note: These methods use the wrap-attach pattern instead of @staticmethod, as they are free template functions in the OpenMS namespace. """ def test_removePeaks_spectrum(self): """Test SpectrumHelper.removePeaks for MSSpectrum. Note: removePeaks(spectrum, min_pos, max_pos) KEEPS peaks in the range, removing those outside. """ spectrum = pyopenms.MSSpectrum() spectrum.push_back(make_peak1d(100.0, 1000.0)) spectrum.push_back(make_peak1d(200.0, 800.0)) spectrum.push_back(make_peak1d(300.0, 600.0)) # Keep only peaks between 150 and 250 (removes peaks outside) pyopenms.SpectrumHelper.removePeaks(spectrum, 150.0, 250.0) # Should have 1 peak left (200.0) self.assertEqual(spectrum.size(), 1) self.assertEqual(spectrum[0].getMZ(), 200.0) def test_subtractMinimumIntensity_spectrum(self): """Test SpectrumHelper.subtractMinimumIntensity for MSSpectrum.""" spectrum = pyopenms.MSSpectrum() spectrum.push_back(make_peak1d(100.0, 1000.0)) spectrum.push_back(make_peak1d(200.0, 500.0)) pyopenms.SpectrumHelper.subtractMinimumIntensity(spectrum) # Minimum (500) should be subtracted - verify first peak has reduced intensity self.assertEqual(spectrum[0].getIntensity(), 500.0) self.assertEqual(spectrum[1].getIntensity(), 0.0) class TestMRMRTNormalizerConstructors(unittest.TestCase): """Test MRMRTNormalizer constructors added in the wrapper changes.""" def test_default_constructor(self): """Test MRMRTNormalizer default constructor.""" normalizer = pyopenms.MRMRTNormalizer() self.assertIsNotNone(normalizer) def test_copy_constructor(self): """Test MRMRTNormalizer copy constructor.""" normalizer1 = pyopenms.MRMRTNormalizer() normalizer2 = pyopenms.MRMRTNormalizer(normalizer1) self.assertIsNotNone(normalizer2) def test_removeOutliersIterative(self): """Test MRMRTNormalizer.removeOutliersIterative static method.""" # Create sample pairs (observed RT, reference RT) - must be lists, not tuples pairs = [ [100.0, 110.0], [200.0, 210.0], [300.0, 310.0], [400.0, 410.0], [500.0, 510.0], ] # Note: outlier_detection_method must be bytes, not str result = pyopenms.MRMRTNormalizer.removeOutliersIterative( pairs, 0.95, 0.6, True, b"iter_jackknife" ) self.assertIsNotNone(result) self.assertGreater(len(result), 0) def test_removeOutliersRANSAC(self): """Test MRMRTNormalizer.removeOutliersRANSAC static method.""" # Signature: pairs, rsq_limit, coverage_limit, max_iterations, max_rt_threshold, sampling_size # Pairs must be lists, not tuples # Note: RANSAC requires at least 30 input peptides pairs = [[float(i * 100), float(i * 100 + 10)] for i in range(1, 35)] result = pyopenms.MRMRTNormalizer.removeOutliersRANSAC( pairs, 0.95, 0.6, 10, 5.0, 5 ) self.assertIsNotNone(result) class TestCalibrationDataStaticMethods(unittest.TestCase): """Test CalibrationData static methods.""" def test_getMetaValues(self): """Test CalibrationData.getMetaValues static method.""" meta_values = pyopenms.CalibrationData.getMetaValues() self.assertIsNotNone(meta_values) # Should return a list of strings self.assertIsInstance(meta_values, list) class TestFileHandlerStaticMethods(unittest.TestCase): """Test FileHandler static methods.""" def test_getTypeByFileName(self): """Test FileHandler.getTypeByFileName static method.""" file_type = pyopenms.FileHandler.getTypeByFileName("test.mzML") self.assertIsNotNone(file_type) def test_hasValidExtension(self): """Test FileHandler.hasValidExtension static method.""" # mzML should have valid extension for MZML type result = pyopenms.FileHandler.hasValidExtension("test.mzML", pyopenms.FileType.MZML) self.assertTrue(result) def test_isSupported(self): """Test FileHandler.isSupported static method.""" # MZML should be supported result = pyopenms.FileHandler.isSupported(pyopenms.FileType.MZML) self.assertTrue(result) class TestCachedmzMLStaticMethods(unittest.TestCase): """Test CachedmzML static methods.""" def test_store_and_load(self): """Test CachedmzML.store and CachedmzML.load static methods.""" # Create a simple MSExperiment exp = pyopenms.MSExperiment() spectrum = pyopenms.MSSpectrum() spectrum.push_back(make_peak1d(100.0, 1000.0)) exp.addSpectrum(spectrum) # Create a temporary file with tempfile.NamedTemporaryFile(suffix=".mzML", delete=False) as f: temp_path = f.name try: # Store using static method pyopenms.CachedmzML.store(temp_path, exp) self.assertTrue(os.path.exists(temp_path)) # Load using static method cached = pyopenms.CachedmzML() pyopenms.CachedmzML.load(temp_path, cached) self.assertIsNotNone(cached) # Delete cached object to release file handles (required for Windows cleanup) del cached finally: # Clean up - remove both the mzML and any cache files if os.path.exists(temp_path): os.unlink(temp_path) cache_path = temp_path + ".cached" if os.path.exists(cache_path): os.unlink(cache_path) class TestExperimentalDesignStaticMethods(unittest.TestCase): """Test ExperimentalDesign static methods.""" def test_fromFeatureMap(self): """Test ExperimentalDesign.fromFeatureMap static method.""" fm = pyopenms.FeatureMap() result = pyopenms.ExperimentalDesign.fromFeatureMap(fm) self.assertIsNotNone(result) def test_fromConsensusMap(self): """Test ExperimentalDesign.fromConsensusMap static method.""" cm = pyopenms.ConsensusMap() result = pyopenms.ExperimentalDesign.fromConsensusMap(cm) self.assertIsNotNone(result) def test_fromIdentifications(self): """Test ExperimentalDesign.fromIdentifications static method.""" proteins = [] result = pyopenms.ExperimentalDesign.fromIdentifications(proteins) self.assertIsNotNone(result) class TestAASequenceStaticMethods(unittest.TestCase): """Test AASequence static methods.""" def test_fromString(self): """Test AASequence.fromString static method (deprecated but still exposed).""" seq = pyopenms.AASequence.fromString("PEPTIDE") self.assertIsNotNone(seq) self.assertIn("PEPTIDE", str(seq.toString())) def test_fromStringPermissive(self): """Test AASequence.fromStringPermissive static method.""" seq = pyopenms.AASequence.fromStringPermissive("PEPTIDE", True) self.assertIsNotNone(seq) self.assertIn("PEPTIDE", str(seq.toString())) class TestNASequenceStaticMethods(unittest.TestCase): """Test NASequence static methods.""" def test_fromString(self): """Test NASequence.fromString static method.""" # Use a simple RNA sequence seq = pyopenms.NASequence.fromString("ACGU") self.assertIsNotNone(seq) class TestFileHandlerAdditionalStaticMethods(unittest.TestCase): """Test additional FileHandler static methods.""" def test_getType(self): """Test FileHandler.getType static method.""" file_type = pyopenms.FileHandler.getType("test.mzML") self.assertIsNotNone(file_type) # Should return an integer (enum value) self.assertIsInstance(file_type, int) def test_getTypeByContent(self): """Test FileHandler.getTypeByContent static method with a real file.""" # Create a minimal mzML file exp = pyopenms.MSExperiment() with tempfile.NamedTemporaryFile(suffix=".mzML", delete=False) as f: temp_path = f.name try: pyopenms.MzMLFile().store(temp_path, exp) file_type = pyopenms.FileHandler.getTypeByContent(temp_path) self.assertIsNotNone(file_type) finally: if os.path.exists(temp_path): os.unlink(temp_path) def test_computeFileHash(self): """Test FileHandler.computeFileHash static method.""" with tempfile.NamedTemporaryFile(delete=False, mode='w') as f: f.write("test content") temp_path = f.name try: hash_val = pyopenms.FileHandler.computeFileHash(temp_path) self.assertIsNotNone(hash_val) self.assertGreater(len(str(hash_val)), 0) finally: os.unlink(temp_path) def test_stripExtension(self): """Test FileHandler.stripExtension static method.""" result = pyopenms.FileHandler.stripExtension("/path/to/file.mzML") self.assertIn("file", str(result)) self.assertNotIn(".mzML", str(result)) def test_swapExtension(self): """Test FileHandler.swapExtension static method.""" result = pyopenms.FileHandler.swapExtension("test.mzML", pyopenms.FileType.FEATUREXML) self.assertIn("featureXML", str(result)) class TestMRMRTNormalizerAdditionalStaticMethods(unittest.TestCase): """Test additional MRMRTNormalizer static methods.""" def test_chauvenet_probability(self): """Test MRMRTNormalizer.chauvenet_probability static method.""" residuals = [0.1, 0.2, 0.15, 0.12, 0.18] prob = pyopenms.MRMRTNormalizer.chauvenet_probability(residuals, 0) self.assertIsNotNone(prob) self.assertIsInstance(prob, float) def test_chauvenet(self): """Test MRMRTNormalizer.chauvenet static method.""" residuals = [0.1, 0.2, 0.15, 0.12, 0.18] result = pyopenms.MRMRTNormalizer.chauvenet(residuals, 0) self.assertIsInstance(result, bool) def test_computeBinnedCoverage(self): """Test MRMRTNormalizer.computeBinnedCoverage static method.""" rt_range = [0.0, 1000.0] pairs = [[100.0, 110.0], [200.0, 210.0], [300.0, 310.0], [400.0, 410.0], [500.0, 510.0]] result = pyopenms.MRMRTNormalizer.computeBinnedCoverage(rt_range, pairs, 5, 1, 3) self.assertIsInstance(result, bool) class TestTransformationDescriptionStaticMethods(unittest.TestCase): """Test TransformationDescription static methods.""" def test_getModelTypes(self): """Test TransformationDescription.getModelTypes static method.""" result = [] pyopenms.TransformationDescription.getModelTypes(result) self.assertIsInstance(result, list) self.assertGreater(len(result), 0) # Should contain known model types like 'linear', 'b_spline', etc. # StringList returns bytes self.assertIn(b"linear", result) class TestFLASHDeconvStaticMethods(unittest.TestCase): """Test FLASHDeconv static methods.""" def test_FLASHDeconvAlgorithm_getScanNumber(self): """Test FLASHDeconvAlgorithm.getScanNumber static method.""" exp = pyopenms.MSExperiment() spectrum = pyopenms.MSSpectrum() # Set native ID with scan number (required for getScanNumber) spectrum.setNativeID("scan=42") exp.addSpectrum(spectrum) scan_num = pyopenms.FLASHDeconvAlgorithm.getScanNumber(exp, 0) self.assertIsInstance(scan_num, int) self.assertEqual(scan_num, 42) def test_FLASHHelperClasses_getLogMz(self): """Test FLASHHelperClasses.getLogMz static method.""" log_mz = pyopenms.FLASHHelperClasses.getLogMz(500.0, True) self.assertIsInstance(log_mz, float) self.assertGreater(log_mz, 0) def test_FLASHHelperClasses_getChargeMass(self): """Test FLASHHelperClasses.getChargeMass static method.""" charge_mass = pyopenms.FLASHHelperClasses.getChargeMass(True) self.assertIsInstance(charge_mass, float) class TestSpectrumMetaDataLookupStaticMethods(unittest.TestCase): """Test SpectrumMetaDataLookup static methods.""" def test_addMissingRTsToPeptideIDs(self): """Test SpectrumMetaDataLookup.addMissingRTsToPeptideIDs static method.""" peptides = pyopenms.PeptideIdentificationList() exp = pyopenms.MSExperiment() result = pyopenms.SpectrumMetaDataLookup.addMissingRTsToPeptideIDs( peptides, exp ) self.assertIsInstance(result, bool) def test_addMissingSpectrumReferences(self): """Test SpectrumMetaDataLookup.addMissingSpectrumReferences static method.""" peptides = pyopenms.PeptideIdentificationList() exp = pyopenms.MSExperiment() # This method has more parameters - skip if signature is complex try: result = pyopenms.SpectrumMetaDataLookup.addMissingSpectrumReferences( peptides, "", exp, False, False, False ) self.assertIsInstance(result, bool) except TypeError: # If signature differs, just verify the method exists self.assertTrue(hasattr(pyopenms.SpectrumMetaDataLookup, 'addMissingSpectrumReferences')) class TestPrecursorEnumStaticMethods(unittest.TestCase): """Test Precursor enum-to-string static methods.""" def test_activationMethodToString(self): """Test Precursor.activationMethodToString static method.""" result = pyopenms.Precursor.activationMethodToString( pyopenms.Precursor.ActivationMethod.CID ) self.assertIsNotNone(result) self.assertIn("Collision-induced dissociation", result) def test_activationMethodToShortString(self): """Test Precursor.activationMethodToShortString static method.""" result = pyopenms.Precursor.activationMethodToShortString( pyopenms.Precursor.ActivationMethod.CID ) self.assertIsNotNone(result) self.assertEqual(result, "CID") def test_toActivationMethod(self): """Test Precursor.toActivationMethod static method.""" # Test with full name result = pyopenms.Precursor.toActivationMethod("Collision-induced dissociation") self.assertEqual(result, pyopenms.Precursor.ActivationMethod.CID) # Test with short name result = pyopenms.Precursor.toActivationMethod("CID") self.assertEqual(result, pyopenms.Precursor.ActivationMethod.CID) def test_activationMethod_roundtrip(self): """Test that conversion to string and back produces the same enum.""" for method in [ pyopenms.Precursor.ActivationMethod.CID, pyopenms.Precursor.ActivationMethod.HCD, pyopenms.Precursor.ActivationMethod.ETD, ]: full_name = pyopenms.Precursor.activationMethodToString(method) short_name = pyopenms.Precursor.activationMethodToShortString(method) self.assertEqual(pyopenms.Precursor.toActivationMethod(full_name), method) self.assertEqual(pyopenms.Precursor.toActivationMethod(short_name), method) class TestIonSourceEnumStaticMethods(unittest.TestCase): """Test IonSource enum-to-string static methods.""" def test_inletTypeToString(self): """Test IonSource.inletTypeToString static method.""" result = pyopenms.IonSource.inletTypeToString( pyopenms.IonSource.InletType.DIRECT ) self.assertIsNotNone(result) self.assertEqual(result, "Direct") def test_toInletType(self): """Test IonSource.toInletType static method.""" result = pyopenms.IonSource.toInletType("Direct") self.assertEqual(result, pyopenms.IonSource.InletType.DIRECT) def test_ionizationMethodToString(self): """Test IonSource.ionizationMethodToString static method.""" result = pyopenms.IonSource.ionizationMethodToString( pyopenms.IonSource.IonizationMethod.ESI ) self.assertIsNotNone(result) self.assertEqual(result, "Electrospray ionisation") def test_toIonizationMethod(self): """Test IonSource.toIonizationMethod static method.""" result = pyopenms.IonSource.toIonizationMethod("Electrospray ionisation") self.assertEqual(result, pyopenms.IonSource.IonizationMethod.ESI) def test_polarityToString(self): """Test IonSource.polarityToString static method.""" result = pyopenms.IonSource.polarityToString( pyopenms.IonSource.Polarity.POSITIVE ) self.assertIsNotNone(result) self.assertEqual(result, "positive") def test_toPolarity(self): """Test IonSource.toPolarity static method.""" result = pyopenms.IonSource.toPolarity("positive") self.assertEqual(result, pyopenms.IonSource.Polarity.POSITIVE) def test_inletType_roundtrip(self): """Test that conversion to string and back produces the same enum.""" for inlet in [ pyopenms.IonSource.InletType.DIRECT, pyopenms.IonSource.InletType.NANOSPRAY, ]: name = pyopenms.IonSource.inletTypeToString(inlet) self.assertEqual(pyopenms.IonSource.toInletType(name), inlet) def test_ionizationMethod_roundtrip(self): """Test that conversion to string and back produces the same enum.""" for method in [ pyopenms.IonSource.IonizationMethod.ESI, pyopenms.IonSource.IonizationMethod.MALDI, ]: name = pyopenms.IonSource.ionizationMethodToString(method) self.assertEqual(pyopenms.IonSource.toIonizationMethod(name), method) def test_polarity_roundtrip(self): """Test that conversion to string and back produces the same enum.""" for polarity in [ pyopenms.IonSource.Polarity.POSITIVE, pyopenms.IonSource.Polarity.NEGATIVE, ]: name = pyopenms.IonSource.polarityToString(polarity) self.assertEqual(pyopenms.IonSource.toPolarity(name), polarity) class TestIonDetectorEnumStaticMethods(unittest.TestCase): """Test IonDetector enum-to-string static methods.""" def test_typeToString(self): """Test IonDetector.typeToString static method.""" result = pyopenms.IonDetector.typeToString( pyopenms.IonDetector.Type.ELECTRONMULTIPLIER ) self.assertIsNotNone(result) self.assertEqual(result, "Electron multiplier") def test_toType(self): """Test IonDetector.toType static method.""" result = pyopenms.IonDetector.toType("Electron multiplier") self.assertEqual(result, pyopenms.IonDetector.Type.ELECTRONMULTIPLIER) def test_acquisitionModeToString(self): """Test IonDetector.acquisitionModeToString static method.""" result = pyopenms.IonDetector.acquisitionModeToString( pyopenms.IonDetector.AcquisitionMode.ADC ) self.assertIsNotNone(result) self.assertEqual(result, "Analog-digital converter") def test_toAcquisitionMode(self): """Test IonDetector.toAcquisitionMode static method.""" result = pyopenms.IonDetector.toAcquisitionMode("Analog-digital converter") self.assertEqual(result, pyopenms.IonDetector.AcquisitionMode.ADC) def test_type_roundtrip(self): """Test that conversion to string and back produces the same enum.""" for detector_type in [ pyopenms.IonDetector.Type.ELECTRONMULTIPLIER, pyopenms.IonDetector.Type.PHOTOMULTIPLIER, ]: name = pyopenms.IonDetector.typeToString(detector_type) self.assertEqual(pyopenms.IonDetector.toType(name), detector_type) def test_acquisitionMode_roundtrip(self): """Test that conversion to string and back produces the same enum.""" for mode in [ pyopenms.IonDetector.AcquisitionMode.ADC, pyopenms.IonDetector.AcquisitionMode.TDC, ]: name = pyopenms.IonDetector.acquisitionModeToString(mode) self.assertEqual(pyopenms.IonDetector.toAcquisitionMode(name), mode) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Utf8StringInput.py
.py
9,768
246
""" Tests for libcpp_utf8_string parameter handling. These tests verify that functions using libcpp_utf8_string accept both Python str and bytes inputs (PR #8602). """ import unittest import pyopenms class TestMRMRTNormalizerStringInput(unittest.TestCase): """Test MRMRTNormalizer accepts str and bytes for outlier_detection_method.""" def setUp(self): """Set up test data.""" self.pairs = [ [100.0, 110.0], [200.0, 210.0], [300.0, 310.0], [400.0, 410.0], [500.0, 510.0], ] def test_removeOutliersIterative_with_str(self): """Test removeOutliersIterative accepts str for outlier_detection_method.""" result = pyopenms.MRMRTNormalizer.removeOutliersIterative( self.pairs, 0.95, 0.6, True, "iter_jackknife" ) self.assertIsNotNone(result) self.assertGreater(len(result), 0) def test_removeOutliersIterative_with_bytes(self): """Test removeOutliersIterative still accepts bytes (backward compatible).""" result = pyopenms.MRMRTNormalizer.removeOutliersIterative( self.pairs, 0.95, 0.6, True, b"iter_jackknife" ) self.assertIsNotNone(result) self.assertGreater(len(result), 0) class TestElementDBStringInput(unittest.TestCase): """Test ElementDB.addElement accepts str and bytes.""" def test_addElement_with_str(self): """Test addElement accepts str for name and symbol.""" db = pyopenms.ElementDB() # Add a test element with str parameters (use unique atomic number) # Use random suffix to avoid conflicts with previous test runs import random suffix = random.randint(1000, 9999) abundance = {900 + suffix % 100: 1.0} mass = {900 + suffix % 100: 900.0 + suffix % 100} db.addElement(f"TestElem{suffix}", f"T{suffix % 100}", 900 + suffix % 100, abundance, mass, False) # Verify it was added elem = db.getElement(f"TestElem{suffix}") self.assertIsNotNone(elem) def test_addElement_with_bytes(self): """Test addElement still accepts bytes (backward compatible).""" db = pyopenms.ElementDB() import random suffix = random.randint(1000, 9999) abundance = {800 + suffix % 100: 1.0} mass = {800 + suffix % 100: 800.0 + suffix % 100} db.addElement(f"TestElemB{suffix}".encode(), f"B{suffix % 100}".encode(), 800 + suffix % 100, abundance, mass, False) elem = db.getElement(f"TestElemB{suffix}".encode()) self.assertIsNotNone(elem) class TestMZTrafoModelStringInput(unittest.TestCase): """Test MZTrafoModel.nameToEnum accepts str and bytes.""" def test_nameToEnum_with_str(self): """Test nameToEnum accepts str.""" enum_val = pyopenms.MZTrafoModel.nameToEnum("linear") self.assertEqual(enum_val, pyopenms.MZTrafoModel.MODELTYPE.LINEAR) def test_nameToEnum_with_bytes(self): """Test nameToEnum still accepts bytes (backward compatible).""" enum_val = pyopenms.MZTrafoModel.nameToEnum(b"linear") self.assertEqual(enum_val, pyopenms.MZTrafoModel.MODELTYPE.LINEAR) def test_enumToName_returns_str(self): """Test enumToName returns str (not bytes).""" name = pyopenms.MZTrafoModel.enumToName(pyopenms.MZTrafoModel.MODELTYPE.LINEAR) self.assertIsInstance(name, str) self.assertEqual(name, "linear") class TestIMTypesStringInput(unittest.TestCase): """Test IMTypes functions accept str and bytes.""" def test_toDriftTimeUnit_with_str(self): """Test toDriftTimeUnit accepts str.""" # Note: DriftTimeUnit uses short strings like "ms", not "millisecond" unit = pyopenms.IMTypes.toDriftTimeUnit("ms") self.assertEqual(unit, pyopenms.DriftTimeUnit.MILLISECOND) def test_toDriftTimeUnit_with_bytes(self): """Test toDriftTimeUnit still accepts bytes (backward compatible).""" unit = pyopenms.IMTypes.toDriftTimeUnit(b"ms") self.assertEqual(unit, pyopenms.DriftTimeUnit.MILLISECOND) def test_driftTimeUnitToString_returns_str(self): """Test IMTypes.driftTimeUnitToString returns str.""" result = pyopenms.IMTypes.driftTimeUnitToString(pyopenms.DriftTimeUnit.MILLISECOND) self.assertIsInstance(result, str) self.assertEqual(result, "ms") def test_toIMFormat_with_str(self): """Test toIMFormat accepts str.""" fmt = pyopenms.IMTypes.toIMFormat("concatenated") self.assertEqual(fmt, pyopenms.IMFormat.CONCATENATED) def test_toIMFormat_with_bytes(self): """Test toIMFormat still accepts bytes (backward compatible).""" fmt = pyopenms.IMTypes.toIMFormat(b"concatenated") self.assertEqual(fmt, pyopenms.IMFormat.CONCATENATED) def test_imFormatToString_returns_str(self): """Test IMTypes.imFormatToString returns str.""" result = pyopenms.IMTypes.imFormatToString(pyopenms.IMFormat.CONCATENATED) self.assertIsInstance(result, str) self.assertEqual(result, "concatenated") class TestRibonucleotideDBStringInput(unittest.TestCase): """Test RibonucleotideDB methods accept str and bytes.""" def test_getRibonucleotide_with_str(self): """Test getRibonucleotide accepts str.""" db = pyopenms.RibonucleotideDB() ribo = db.getRibonucleotide("A") self.assertIsNotNone(ribo) def test_getRibonucleotide_with_bytes(self): """Test getRibonucleotide still accepts bytes (backward compatible).""" db = pyopenms.RibonucleotideDB() ribo = db.getRibonucleotide(b"A") self.assertIsNotNone(ribo) def test_getRibonucleotidePrefix_with_str(self): """Test getRibonucleotidePrefix accepts str.""" db = pyopenms.RibonucleotideDB() ribo = db.getRibonucleotidePrefix("A") self.assertIsNotNone(ribo) class TestIndexedMzMLHandlerStringInput(unittest.TestCase): """Test IndexedMzMLHandler native ID methods accept str and bytes.""" def test_getMSSpectrumByNativeId_method_exists(self): """Test getMSSpectrumByNativeId method exists.""" self.assertTrue(hasattr(pyopenms.IndexedMzMLHandler, 'getMSSpectrumByNativeId')) def test_getMSChromatogramByNativeId_method_exists(self): """Test getMSChromatogramByNativeId method exists.""" self.assertTrue(hasattr(pyopenms.IndexedMzMLHandler, 'getMSChromatogramByNativeId')) class TestLightTargetedExperimentStringInput(unittest.TestCase): """Test LightTargetedExperiment methods accept str and bytes.""" def test_setFragmentType_with_str(self): """Test LightTransition.setFragmentType accepts str.""" transition = pyopenms.LightTransition() transition.setFragmentType("y") self.assertEqual(transition.getFragmentType(), b"y") def test_setFragmentType_with_bytes(self): """Test LightTransition.setFragmentType still accepts bytes.""" transition = pyopenms.LightTransition() transition.setFragmentType(b"b") self.assertEqual(transition.getFragmentType(), b"b") def test_getCompoundByRef_method_exists(self): """Test LightTargetedExperiment.getCompoundByRef method exists.""" # Just verify the method exists - actual lookup can cause issues # if compound not found self.assertTrue(hasattr(pyopenms.LightTargetedExperiment, 'getCompoundByRef')) def test_getPeptideByRef_method_exists(self): """Test LightTargetedExperiment.getPeptideByRef method exists.""" self.assertTrue(hasattr(pyopenms.LightTargetedExperiment, 'getPeptideByRef')) class TestOpenSwathScoringStringInput(unittest.TestCase): """Test OpenSwathScoring.initialize accepts str and bytes.""" def test_initialize_signature_exists(self): """Test OpenSwathScoring.initialize exists with string parameters.""" self.assertTrue(hasattr(pyopenms.OpenSwathScoring, 'initialize')) class TestMSExperimentStringInput(unittest.TestCase): """Test MSExperiment aggregate methods accept str and bytes.""" def test_aggregateFromMatrix_with_str(self): """Test aggregateFromMatrix accepts str for mz_agg.""" exp = pyopenms.MSExperiment() # Add a spectrum with peaks spectrum = pyopenms.MSSpectrum() spectrum.setRT(100.0) peak = pyopenms.Peak1D() peak.setMZ(500.0) peak.setIntensity(1000.0) spectrum.push_back(peak) exp.addSpectrum(spectrum) # Create a ranges matrix using MatrixDouble ranges = pyopenms.MatrixDouble() ranges.resize(1, 4) ranges.setValue(0, 0, 0.0) # rt_min ranges.setValue(0, 1, 200.0) # rt_max ranges.setValue(0, 2, 400.0) # mz_min ranges.setValue(0, 3, 600.0) # mz_max # Call with str parameter result = exp.aggregateFromMatrix(ranges, 1, "sum") self.assertIsNotNone(result) def test_extractXICsFromMatrix_with_str(self): """Test extractXICsFromMatrix accepts str for mz_agg.""" exp = pyopenms.MSExperiment() spectrum = pyopenms.MSSpectrum() spectrum.setRT(100.0) peak = pyopenms.Peak1D() peak.setMZ(500.0) peak.setIntensity(1000.0) spectrum.push_back(peak) exp.addSpectrum(spectrum) ranges = pyopenms.MatrixDouble() ranges.resize(1, 4) ranges.setValue(0, 0, 0.0) ranges.setValue(0, 1, 200.0) ranges.setValue(0, 2, 400.0) ranges.setValue(0, 3, 600.0) result = exp.extractXICsFromMatrix(ranges, 1, "sum") self.assertIsNotNone(result) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_MzXMLConsumer.py
.py
1,171
39
import pyopenms import os.path from .collections_ import Counter def test0(): fh = pyopenms.MzXMLFile() here = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(here, "test2.mzXML").encode() class Consumer(object): def __init__(self): self.speclevels = [] self.rts = [] def consumeSpectrum(self, spec): self.speclevels.append(spec.getMSLevel()) self.rts.append(spec.getRT()) def consumeChromatogram(self, chromo): raise Exception("should never be called as we have no chromoatograms in example file") def setExpectedSize(self, num_specs, num_chromo): assert num_specs == 5, num_specs assert num_chromo == 0, num_chromo def setExperimentalSettings(self, exp): assert isinstance(exp, pyopenms.ExperimentalSettings) consumer = Consumer() fh.transform(path, consumer) cc = Counter(consumer.speclevels) assert set(cc.keys()) == set([1, 2]) assert cc[1] == 2 assert cc[2] == 3 assert abs(min(consumer.rts) - 4200.76) < 0.01 assert abs(max(consumer.rts) - 4202.03) < 0.01
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_MSNumpressCoder.py
.py
6,766
204
import unittest import os import pyopenms class TestMSNumpressCoder(unittest.TestCase): def setUp(self): self.testData = [ 100.0, 200.0, 300.00005, 400.00010, ] def test_encodeNP_SLOF(self): """ String out; MSNumpressCoder::NumpressConfig config; config.np_compression = MSNumpressCoder::SLOF; config.estimate_fixed_point = true; // critical bool zlib_compression = false; MSNumpressCoder().encodeNP(in, out, zlib_compression, config); TEST_EQUAL(out.size(), 24) TEST_EQUAL(out, "QMVagAAAAAAZxX3ivPP8/w==") """ coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.SLOF config.estimate_fixed_point = True out_ = pyopenms.String() coder.encodeNP(self.testData, out_, False, config) out = out_.c_str() self.assertEqual( len(out), 24) self.assertEqual( out, b"QMVagAAAAAAZxX3ivPP8/w==") def test_decodeNP_SLOF(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.SLOF config.estimate_fixed_point = True inData = b"QMVagAAAAAAZxX3ivPP8/w==" out = [] coder.decodeNP(inData, out, False, config) self.assertEqual( len(out), 4) for a,b in zip(self.testData, out): self.assertAlmostEqual( a, b, places=2) def test_encodeNP_PIC(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.PIC config.estimate_fixed_point = True out_ = pyopenms.String() coder.encodeNP(self.testData, out_, False, config) out = out_.c_str() self.assertEqual( len(out), 12) self.assertEqual( out, b"ZGaMXCFQkQ==") def test_decodeNP_PIC(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.PIC config.estimate_fixed_point = True inData = b"ZGaMXCFQkQ==" out = [] coder.decodeNP(inData, out, False, config) self.assertEqual( len(out), 4) for a,b in zip(self.testData, out): self.assertAlmostEqual( a, b, places=2) def test_encodeNP_LINEAR(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.LINEAR config.estimate_fixed_point = True out_ = pyopenms.String() coder.encodeNP(self.testData, out_, False, config) out = out_.c_str() self.assertEqual( len(out), 28) self.assertEqual( out, b"QWR64UAAAADo//8/0P//f1kSgA==") def test_decodeNP_LINEAR(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.LINEAR config.estimate_fixed_point = True inData = b"QWR64UAAAADo//8/0P//f1kSgA==" out = [] coder.decodeNP(inData, out, False, config) self.assertEqual( len(out), 4) for a,b in zip(self.testData, out): self.assertAlmostEqual( a, b, places=7) class TestMSNumpressCoderRaw(unittest.TestCase): def setUp(self): self.testData = [ 100.0, 200.0, 300.00005, 400.00010, ] def test_encodeNP_SLOF(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.SLOF config.estimate_fixed_point = True out_ = pyopenms.String() coder.encodeNPRaw(self.testData, out_, config) out = out_.c_str() self.assertEqual( len(out), 16) self.assertEqual( out, b'@\xc5Z\x80\x00\x00\x00\x00\x19\xc5}\xe2\xbc\xf3\xfc\xff' ) def test_decodeNP_SLOF(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.SLOF config.estimate_fixed_point = True inData = b'@\xc5Z\x80\x00\x00\x00\x00\x19\xc5}\xe2\xbc\xf3\xfc\xff' out = [] coder.decodeNPRaw(inData, out, config) self.assertEqual( len(out), 4) for a,b in zip(self.testData, out): self.assertAlmostEqual( a, b, places=2) def test_encodeNP_PIC(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.PIC config.estimate_fixed_point = True out_ = pyopenms.String() coder.encodeNPRaw(self.testData, out_, config) out = out_.c_str() self.assertEqual( len(out), 7) self.assertEqual( out, b'df\x8c\\!P\x91') def test_decodeNP_PIC(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.PIC config.estimate_fixed_point = True inData = b'df\x8c\\!P\x91' out = [] coder.decodeNPRaw(inData, out, config) self.assertEqual( len(out), 4) for a,b in zip(self.testData, out): self.assertAlmostEqual( a, b, places=2) def test_encodeNP_LINEAR(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.LINEAR config.estimate_fixed_point = True out_ = pyopenms.String() coder.encodeNPRaw(self.testData, out_, config) out = out_.c_str() self.assertEqual( len(out), 19) self.assertEqual( out, b'Adz\xe1@\x00\x00\x00\xe8\xff\xff?\xd0\xff\xff\x7fY\x12\x80') def test_decodeNP_LINEAR(self): coder = pyopenms.MSNumpressCoder() config = pyopenms.NumpressConfig() config.np_compression = pyopenms.MSNumpressCoder.NumpressCompression.LINEAR config.estimate_fixed_point = True inData = b'Adz\xe1@\x00\x00\x00\xe8\xff\xff?\xd0\xff\xff\x7fY\x12\x80' out = [] coder.decodeNPRaw(inData, out, config) self.assertEqual( len(out), 4) for a,b in zip(self.testData, out): self.assertAlmostEqual( a, b, places=7) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_MzMLConsumer.py
.py
1,169
39
import pyopenms import os.path from .collections_ import Counter def test0(): fh = pyopenms.MzMLFile() here = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(here, "test2.mzML").encode() class Consumer(object): def __init__(self): self.speclevels = [] self.rts = [] def consumeSpectrum(self, spec): self.speclevels.append(spec.getMSLevel()) self.rts.append(spec.getRT()) def consumeChromatogram(self, chromo): raise Exception("should never be called as we have no chromoatograms in example file") def setExpectedSize(self, num_specs, num_chromo): assert num_specs == 5, num_specs assert num_chromo == 0, num_chromo def setExperimentalSettings(self, exp): assert isinstance(exp, pyopenms.ExperimentalSettings) consumer = Consumer() fh.transform(path, consumer) cc = Counter(consumer.speclevels) assert set(cc.keys()) == set([1, 2]) assert cc[1] == 2 assert cc[2] == 3 assert abs(min(consumer.rts) - 4200.76) < 0.01 assert abs(max(consumer.rts) - 4202.03) < 0.01
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/testLocale.py
.py
1,478
48
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test that pyOpenMS doesn't affect Python's locale settings. This test ensures that importing pyOpenMS doesn't change the Python locale, which would affect other Python libraries. """ import unittest import locale class TestLocale(unittest.TestCase): """Test that pyOpenMS import doesn't affect Python locale.""" def test_locale_preserved_after_import(self): """Test that locale is preserved after importing pyOpenMS.""" # Get the locale before importing pyOpenMS locale_before = locale.getlocale() # Import pyOpenMS import pyopenms # Get the locale after importing pyOpenMS locale_after = locale.getlocale() # Check that the locale hasn't changed # Note: Some systems might have (None, None) as the default locale, # so we just check that it's the same as before self.assertEqual( locale_before, locale_after, f"Locale changed from {locale_before} to {locale_after} after importing pyOpenMS" ) # Also ensure it's not (None, None) if we started with a valid locale if locale_before != (None, None): self.assertNotEqual( locale_after, (None, None), "Locale was reset to (None, None) after importing pyOpenMS" ) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_FileIO.py
.py
3,943
126
import unittest import os import pyopenms class TestPepXML(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.pep.xml").encode() def test_readfile(self): pepxml_file = pyopenms.PepXMLFile() peps = pyopenms.PeptideIdentificationList() prots = [] pepxml_file.load(self.filename, prots, peps) def test_readfile_content(self): pepxml_file = pyopenms.PepXMLFile() peps = pyopenms.PeptideIdentificationList() prots = [] pepxml_file.load(self.filename, prots, peps) self.assertEqual( len(prots), 3) self.assertEqual( peps.size(), 19) self.assertEqual( peps[0].getHits()[0].getSequence().toString(), ".(Glu->pyro-Glu)ELNKEMAAEKAKAAAG") class TestIdXML(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.idXML").encode() def test_readfile(self): idxml_file = pyopenms.IdXMLFile() peps = pyopenms.PeptideIdentificationList() prots = [] idxml_file.load(self.filename, prots, peps) def test_readfile_content(self): idxml_file = pyopenms.IdXMLFile() peps = pyopenms.PeptideIdentificationList() prots = [] idxml_file.load(self.filename, prots, peps) self.assertEqual( len(prots), 1) self.assertEqual( peps.size(), 3) class TestIndexedMzMLFileLoader(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.indexed.mzML").encode() def test_readfile(self): e = pyopenms.OnDiscMSExperiment() success = pyopenms.IndexedMzMLFileLoader().load(self.filename, e) self.assertTrue(success) def test_readfile_content(self): e = pyopenms.OnDiscMSExperiment() pyopenms.IndexedMzMLFileLoader().load(self.filename, e) self.assertEqual( e.getNrSpectra() , 2) self.assertEqual( e.getNrChromatograms() , 1) s = e.getSpectrum(0) data_mz, data_int = s.get_peaks() self.assertEqual( len(data_mz), 19914) self.assertEqual( len(data_int), 19914) self.assertEqual( len(e.getSpectrum(1).get_peaks()[0]), 19800) self.assertEqual( len(e.getSpectrum(1).get_peaks()[1]), 19800) self.assertEqual( len(e.getChromatogram(0).get_peaks()[0]), 48) self.assertEqual( len(e.getChromatogram(0).get_peaks()[1]), 48) if False: # Currently we don't deal with exceptions properly raised = False try: e.getChromatogram(2).get_peaks() except Exception as e: raised = True self.assertTrue(raised) class TestIndexedMzMLFile(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.indexed.mzML").encode() def test_readfile(self): f = pyopenms.IndexedMzMLHandler() f.openFile(self.filename) self.assertTrue(f.getParsingSuccess()) def test_readfile_content(self): f = pyopenms.IndexedMzMLHandler() f.openFile(self.filename) self.assertEqual( f.getNrSpectra() , 2) self.assertEqual( f.getNrChromatograms() , 1) s = f.getSpectrumById(0) mzdata = s.getMZArray() intdata = s.getIntensityArray() self.assertEqual( len(mzdata), 19914) self.assertEqual( len(intdata), 19914) s = f.getMSSpectrumById(0) self.assertEqual(s.size(), 19914) s = f.getMSSpectrumById(1) self.assertEqual(s.size(), 19800) c = f.getMSChromatogramById(0) self.assertEqual(c.size(), 48) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_DIAScoring.py
.py
2,512
74
import unittest import os import pyopenms class TestDIAScoring(unittest.TestCase): def setUp(self): pass def test_spectrum(self): intensity = [ 100, 100, 100, 100, 100, 100 ] mz = [ #// four of the naked b/y ions #// as well as one of the modified b and y ions ion each 350.17164, #// b 421.20875, #// b 421.20875 + 79.9657, #// b + P 547.26291, #// y 646.33133, #// y 809.39466 + 79.9657 #// y + P ] spectrum = pyopenms.OSSpectrum() spectrum.set_mz_array(mz) spectrum.set_intensity_array(intensity) spectrumList = [ spectrum ] diascoring = pyopenms.DIAScoring() # diascoring.set_dia_parameters(0.05, False, 30, 50, 4, 4) // here we use a large enough window so that none of our peaks falls out p_dia = diascoring.getDefaults(); p_dia.setValue("dia_extraction_window", 0.05); p_dia.setValue("dia_extraction_unit", "Th"); p_dia.setValue("dia_centroided", "false"); p_dia.setValue("dia_byseries_intensity_min", 30.0); p_dia.setValue("dia_byseries_ppm_diff", 50.0); p_dia.setValue("dia_nr_isotopes", 4); p_dia.setValue("dia_nr_charges", 4); diascoring.setParameters(p_dia); a = pyopenms.AASequence.fromString(b"SYVAWDR") bseries_score = 0.0 yseries_score = 0.0 charge = 1 im_range = pyopenms.RangeMobility() bseries_score, yseries_score = diascoring.dia_by_ion_score([spectrum], a, charge, im_range, bseries_score, yseries_score) self.assertAlmostEqual(bseries_score, 2.0) self.assertAlmostEqual(yseries_score, 2.0) # // now add a modification to the sequence a.setModification(1, b"Phospho" ) #; // modify the Y bseries_score = 0 yseries_score = 0 im_range = pyopenms.RangeMobility() bseries_score, yseries_score = diascoring.dia_by_ion_score([spectrum], a, 1, im_range, bseries_score, yseries_score) self.assertAlmostEqual (bseries_score, 1.0) self.assertAlmostEqual (yseries_score, 3.0) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/testCVTermList.py
.py
2,274
88
import pyopenms def testCVTermList(): term = pyopenms.CVTerm() term.setAccession("ACC") assert term.getAccession() == "ACC" term.setName("NAME") assert term.getName() == "NAME" term.setCVIdentifierRef("CVREF") assert term.getCVIdentifierRef() == "CVREF" term.setValue(123) assert term.getValue() == 123 li = pyopenms.CVTermList() li.setCVTerms([term]) (name, (term,)), = li.getCVTerms().items() assert name == b"ACC" assert term.getName() == "NAME" assert term.getCVIdentifierRef() == "CVREF" assert term.getValue() == 123 li.replaceCVTerm(term) (name, (term,)), = li.getCVTerms().items() assert name == b"ACC" assert term.getName() == "NAME" assert term.getCVIdentifierRef() == "CVREF" assert term.getValue() == 123 li.replaceCVTerms([term], "ACC2") dd = li.getCVTerms() assert len(dd) == 2 assert b"ACC" in dd and b"ACC2" in dd term, = dd[b"ACC"] assert term.getName() == "NAME" assert term.getCVIdentifierRef() == "CVREF" assert term.getValue() == 123 term, = dd[b"ACC2"] assert term.getName() == "NAME" assert term.getCVIdentifierRef() == "CVREF" assert term.getValue() == 123 # li.replaceCVTerms(li.getCVTerms()) # dd = li.getCVTerms() # assert len(dd) == 2 # assert b"ACC" in dd and b"ACC2" in dd # term, = dd[b"ACC"] # assert term.getName() == "NAME" # assert term.getCVIdentifierRef() == "CVREF" # assert term.getValue() == 123 # term, = dd[b"ACC2"] # assert term.getName() == "NAME" # assert term.getCVIdentifierRef() == "CVREF" # assert term.getValue() == 123 li.addCVTerm(term) dd = li.getCVTerms() assert len(dd) == 2 assert b"ACC" in dd and b"ACC2" in dd term1, term2, = dd[b"ACC"] assert term1.getName() == "NAME" assert term1.getCVIdentifierRef() == "CVREF" assert term1.getValue() == 123 assert term2.getName() == "NAME" assert term2.getCVIdentifierRef() == "CVREF" assert term2.getValue() == 123 term, = dd[b"ACC2"] assert term.getName() == "NAME" assert term.getCVIdentifierRef() == "CVREF" assert term.getValue() == 123 assert li.hasCVTerm("ACC") assert not li.hasCVTerm("ABC")
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Math.py
.py
2,741
84
import unittest import pyopenms class TestMath(unittest.TestCase): def test_getPPM(self): """Test Math.getPPM function""" # Test basic PPM calculation # If observed m/z is 1000.001 and reference is 1000.0, # PPM = (1000.001 - 1000.0) / 1000.0 * 1e6 = 1.0 mz_obs = 1000.001 mz_ref = 1000.0 ppm = pyopenms.Math.getPPM(mz_obs, mz_ref) self.assertAlmostEqual(ppm, 1.0, places=5) # Test negative PPM (observed < reference) mz_obs = 999.999 mz_ref = 1000.0 ppm = pyopenms.Math.getPPM(mz_obs, mz_ref) self.assertAlmostEqual(ppm, -1.0, places=5) def test_getPPMAbs(self): """Test Math.getPPMAbs function""" # Test absolute PPM calculation mz_obs = 1000.001 mz_ref = 1000.0 ppm_abs = pyopenms.Math.getPPMAbs(mz_obs, mz_ref) self.assertAlmostEqual(ppm_abs, 1.0, places=5) # Test that negative PPM is returned as positive mz_obs = 999.999 mz_ref = 1000.0 ppm_abs = pyopenms.Math.getPPMAbs(mz_obs, mz_ref) self.assertAlmostEqual(ppm_abs, 1.0, places=5) def test_ppmToMass(self): """Test Math.ppmToMass function""" # Test conversion from PPM to mass difference # If PPM = 5.0 and mz_ref = 1000.0, # mass_diff = 5.0 / 1e6 * 1000.0 = 0.005 ppm = 5.0 mz_ref = 1000.0 mass_diff = pyopenms.Math.ppmToMass(ppm, mz_ref) self.assertAlmostEqual(mass_diff, 0.005, places=6) # Test negative PPM ppm = -5.0 mz_ref = 1000.0 mass_diff = pyopenms.Math.ppmToMass(ppm, mz_ref) self.assertAlmostEqual(mass_diff, -0.005, places=6) def test_ppmToMassAbs(self): """Test Math.ppmToMassAbs function""" # Test absolute mass difference ppm = 5.0 mz_ref = 1000.0 mass_diff_abs = pyopenms.Math.ppmToMassAbs(ppm, mz_ref) self.assertAlmostEqual(mass_diff_abs, 0.005, places=6) # Test that negative PPM returns positive mass difference ppm = -5.0 mz_ref = 1000.0 mass_diff_abs = pyopenms.Math.ppmToMassAbs(ppm, mz_ref) self.assertAlmostEqual(mass_diff_abs, 0.005, places=6) def test_roundtrip(self): """Test roundtrip conversion PPM <-> mass""" mz_obs = 1000.005 mz_ref = 1000.0 # Calculate PPM ppm = pyopenms.Math.getPPM(mz_obs, mz_ref) # Convert back to mass difference mass_diff = pyopenms.Math.ppmToMass(ppm, mz_ref) # Should equal the original difference self.assertAlmostEqual(mass_diff, mz_obs - mz_ref, places=6) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/testSpectrumNativeIDParser.py
.py
5,485
87
import pyopenms def testSpectrumNativeIDParser(): """Test the SpectrumNativeIDParser class for parsing spectrum native IDs.""" # Test isNativeID - recognized native ID prefixes assert pyopenms.SpectrumNativeIDParser.isNativeID("scan=123") assert pyopenms.SpectrumNativeIDParser.isNativeID("scanId=456") assert pyopenms.SpectrumNativeIDParser.isNativeID("scanID=456") # both cases supported assert pyopenms.SpectrumNativeIDParser.isNativeID("controllerType=0 controllerNumber=1 scan=100") assert pyopenms.SpectrumNativeIDParser.isNativeID("function=2 process=1 scan=100") assert pyopenms.SpectrumNativeIDParser.isNativeID("sample=1 period=1 cycle=42 experiment=1") assert pyopenms.SpectrumNativeIDParser.isNativeID("index=789") assert pyopenms.SpectrumNativeIDParser.isNativeID("spectrum=101112") assert pyopenms.SpectrumNativeIDParser.isNativeID("file=42") # Test isNativeID - non-native IDs assert not pyopenms.SpectrumNativeIDParser.isNativeID("123") assert not pyopenms.SpectrumNativeIDParser.isNativeID("") assert not pyopenms.SpectrumNativeIDParser.isNativeID("some_random_string") assert not pyopenms.SpectrumNativeIDParser.isNativeID("SCAN=123") # case-sensitive # Test getRegExFromNativeID assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("scan=123") == "scan=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("controllerType=0 scan=100") == "scan=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("function=2 scan=100") == "scan=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("index=456") == "index=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("scanId=789") == "scanId=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("scanID=789") == "scanID=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("spectrum=101") == "spectrum=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("file=42") == "file=(?<GROUP>\\d+)" assert pyopenms.SpectrumNativeIDParser.getRegExFromNativeID("123") == "(?<GROUP>\\d+)" # Test extractScanNumber with CV accession - Thermo format (MS:1000768) assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "MS:1000768") == 42 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=0", "MS:1000768") == 0 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("controllerType=0 controllerNumber=1 scan=123", "MS:1000768") == 123 # Test extractScanNumber - Waters format (MS:1000769) assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "MS:1000769") == 42 # Test extractScanNumber - WIFF format (MS:1000770) - cycle * 1000 + experiment assert pyopenms.SpectrumNativeIDParser.extractScanNumber("sample=1 period=1 cycle=42 experiment=1", "MS:1000770") == 42001 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("sample=1 period=1 cycle=100 experiment=50", "MS:1000770") == 100050 # Test extractScanNumber - Bruker formats assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "MS:1000771") == 42 # Bruker BAF assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "MS:1000772") == 42 # Bruker U2 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("file=42", "MS:1000773") == 42 # Bruker FID assert pyopenms.SpectrumNativeIDParser.extractScanNumber("file=42", "MS:1000775") == 42 # Single peak list assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "MS:1000776") == 42 # Thermo/Bruker TDF # Test extractScanNumber - index format (MS:1000774) - returns index+1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("index=42", "MS:1000774") == 43 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("index=0", "MS:1000774") == 1 # Test extractScanNumber - spectrum format (MS:1000777) assert pyopenms.SpectrumNativeIDParser.extractScanNumber("spectrum=42", "MS:1000777") == 42 # Test extractScanNumber - Agilent MassHunter format (MS:1001508) assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scanId=42", "MS:1001508") == 42 # Test extractScanNumber - mzML unique identifier (MS:1001530) assert pyopenms.SpectrumNativeIDParser.extractScanNumber("42", "MS:1001530") == 42 # Test extractScanNumber - invalid accession returns -1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "MS:9999999") == -1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "invalid") == -1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("scan=42", "") == -1 # Test extractScanNumber - invalid native_id for given accession returns -1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("spectrum=42", "MS:1000768") == -1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("", "MS:1000768") == -1 assert pyopenms.SpectrumNativeIDParser.extractScanNumber("malformed", "MS:1000768") == -1 # Test merged spectra - should return last scan number assert pyopenms.SpectrumNativeIDParser.extractScanNumber( "controllerType=0 controllerNumber=1 scan=100 merged controllerType=0 controllerNumber=1 scan=200", "MS:1000768" ) == 200 print("All SpectrumNativeIDParser tests passed!") if __name__ == "__main__": testSpectrumNativeIDParser()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py
.py
5,211
166
import unittest import os import pyopenms class TestOpenSwathDataStructures(unittest.TestCase): def setUp(self): pass def test_spectrum(self): # Interfaces.Spectrum uses camelCase (no addon file) spectrum = pyopenms.Interfaces.Spectrum() mz_exp = [1,2,3] int_exp = [4,5,6] spectrum.setMZArray(mz_exp) spectrum.setIntensityArray(int_exp) mz = spectrum.getMZArray() intensity = spectrum.getIntensityArray() for m,e in zip(mz, mz_exp): self.assertAlmostEqual(m,e) for i,e in zip(intensity, int_exp): self.assertAlmostEqual(i,e) def test_spectrum_osw(self): spectrum = pyopenms.OSSpectrum() mz_exp = [1,2,3] int_exp = [4,5,6] spectrum.set_mz_array(mz_exp) spectrum.set_intensity_array(int_exp) mz = spectrum.get_mz_array() intensity = spectrum.get_intensity_array() for m,e in zip(mz, mz_exp): self.assertAlmostEqual(m,e) for i,e in zip(intensity, int_exp): self.assertAlmostEqual(i,e) # Now also check drift time, first check that there are 2 arrays and no drift time self.assertEqual( spectrum.get_drift_time_array(), None) self.assertEqual( len(spectrum.get_data_arrays()), 2) drift_exp = [7, 8, 9] da = pyopenms.OSBinaryDataArray() da.data = drift_exp da.description = b"Ion Mobility" arrays = spectrum.get_data_arrays() arrays.append(da) spectrum.set_data_arrays(arrays) self.assertEqual( len(spectrum.get_data_arrays()), 3) drift = spectrum.get_drift_time_array() for i,e in zip(drift, drift_exp): self.assertAlmostEqual(i,e) da = pyopenms.OSBinaryDataArray() da.data = [5, 6.88] da.description = b"test" arrays = spectrum.get_data_arrays() arrays.append(da) spectrum.set_data_arrays(arrays) self.assertEqual( len(spectrum.get_data_arrays()), 4) da = spectrum.get_data_arrays() data = da[3].get_data() self.assertEqual( len(data), 2) self.assertAlmostEqual(data[0], 5) self.assertAlmostEqual(data[1], 6.88) def test_spectrum_osw_memview(self): spectrum = pyopenms.OSSpectrum() mz_exp = [1,2,3] int_exp = [4,5,6] spectrum.set_mz_array(mz_exp) spectrum.set_intensity_array(int_exp) mz = spectrum.get_mz_array() self.assertAlmostEqual(mz[0], 1) mz_view = spectrum.get_mz_array_mv() self.assertAlmostEqual(mz_view[0], 1) # change a copy, nothing happens mz[0] = 100 self.assertAlmostEqual(spectrum.get_mz_array()[0], 1) self.assertAlmostEqual(mz[0], 100) # change a memview, it changes the underlying data mz_view[0] = 200 self.assertAlmostEqual(spectrum.get_mz_array()[0], 200) self.assertAlmostEqual(mz[0], 100) dataarr = spectrum.get_data_arrays() mz = dataarr[0].get_data() mz_view = dataarr[0].get_data_mv() self.assertAlmostEqual(mz[0], 200) self.assertAlmostEqual(mz_view[0], 200) # change a memview, it changes the underlying data mz[0] = 300 mz_view[0] = 400 self.assertAlmostEqual(spectrum.get_mz_array()[0], 400) self.assertAlmostEqual(mz[0], 300) def test_chromatogram_osw(self): chromatogram = pyopenms.OSChromatogram() rt_exp = [1,2,3] int_exp = [4,5,6] chromatogram.set_time_array(rt_exp) chromatogram.set_intensity_array(int_exp) time = chromatogram.get_time_array() intensity = chromatogram.get_intensity_array() for m,e in zip(time, rt_exp): self.assertAlmostEqual(m,e) for i,e in zip(intensity, int_exp): self.assertAlmostEqual(i,e) # Now also check that we can add a data array, first check that there are 2 arrays and no drift time self.assertEqual( len(chromatogram.get_data_arrays()), 2) da = pyopenms.OSBinaryDataArray() da.data = [5, 6.88] da.description = b"test" arrays = chromatogram.get_data_arrays() arrays.append(da) chromatogram.set_data_arrays(arrays) self.assertEqual( len(chromatogram.get_data_arrays()), 3) da = chromatogram.get_data_arrays() data = da[2].get_data() self.assertEqual( len(data), 2) self.assertAlmostEqual(data[0], 5) self.assertAlmostEqual(data[1], 6.88) def test_chromatogram(self): # Interfaces.Chromatogram uses camelCase (no addon file) chromatogram = pyopenms.Interfaces.Chromatogram() rt_exp = [1,2,3] int_exp = [4,5,6] chromatogram.setTimeArray(rt_exp) chromatogram.setIntensityArray(int_exp) time = chromatogram.getTimeArray() intensity = chromatogram.getIntensityArray() for m,e in zip(time, rt_exp): self.assertAlmostEqual(m,e) for i,e in zip(intensity, int_exp): self.assertAlmostEqual(i,e) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_SpectraFilter.py
.py
6,421
171
import unittest import os import pyopenms class TestSpectraFilter(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() self.exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, self.exp) def test_map_NLargest(self): thisfilter = pyopenms.NLargest(); old_firstspec = self.exp[0] thisfilter.filterPeakMap(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_spectrum_NLargest(self): thisfilter = pyopenms.NLargest(); new_firstspec = self.exp[0] thisfilter.filterSpectrum(new_firstspec) self.assertNotEqual(new_firstspec.size(), 0) self.assertNotEqual(new_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(new_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(new_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_map_Normalizer(self): thisfilter = pyopenms.Normalizer(); old_firstspec = self.exp[0] thisfilter.filterPeakMap(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) self.assertEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_spectrum_Normalizer(self): thisfilter = pyopenms.Normalizer(); new_firstspec = self.exp[0] thisfilter.filterSpectrum(new_firstspec) self.assertNotEqual(new_firstspec.size(), 0) self.assertNotEqual(new_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertEqual(new_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(new_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_map_Scaler(self): thisfilter = pyopenms.RankScaler(); old_firstspec = self.exp[0] thisfilter.filterPeakMap(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_spectrum_Scaler(self): thisfilter = pyopenms.RankScaler(); new_firstspec = self.exp[0] thisfilter.filterSpectrum(new_firstspec) self.assertNotEqual(new_firstspec.size(), 0) self.assertNotEqual(new_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(new_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(new_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_map_SqrtScaler(self): thisfilter = pyopenms.SqrtScaler(); old_firstspec = self.exp[0] thisfilter.filterPeakMap(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_spectrum_SqrtScaler(self): thisfilter = pyopenms.SqrtScaler(); new_firstspec = self.exp[0] thisfilter.filterSpectrum(new_firstspec) self.assertNotEqual(new_firstspec.size(), 0) self.assertNotEqual(new_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertEqual(new_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(new_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_map_ThresholdMower(self): thisfilter = pyopenms.ThresholdMower(); old_firstspec = self.exp[0] thisfilter.filterPeakMap(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_spectrum_ThresholdMower(self): thisfilter = pyopenms.ThresholdMower(); new_firstspec = self.exp[0] thisfilter.filterSpectrum(new_firstspec) self.assertNotEqual(new_firstspec.size(), 0) self.assertNotEqual(new_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(new_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(new_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_map_WindowMower(self): thisfilter = pyopenms.WindowMower(); old_firstspec = self.exp[0] thisfilter.filterPeakMap(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) def test_spectrum_WindowMower(self): thisfilter = pyopenms.WindowMower(); new_firstspec = self.exp[0] thisfilter.filterPeakSpectrumForTopNInSlidingWindow(new_firstspec) self.assertNotEqual(new_firstspec.size(), 0) self.assertNotEqual(new_firstspec, self.exp[0]) # in most cases, a different spectrum is returned self.assertNotEqual(new_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(new_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_ProteaseDigestion.py
.py
1,981
64
#!/usr/bin/env python # -*- coding: utf-8 -*- ## ---------------------------------------------------------------------------- ## $Maintainer: $ ## $Authors: Hendrik Weisser, Hannes Roest, Stephan Aiche, ## Jeremi Maciejewski $ ## ---------------------------------------------------------------------------- import pyopenms from functools import wraps def report(f): @wraps(f) def wrapper(*a, **kw): print("run ", f.__name__) f(*a, **kw) return wrapper @report def testProteaseDigestion(): """ @tests: ProteaseDigestion ProteaseDigestion.__init__ ProteaseDigestion.setEnzyme() ProteaseDigestion.digest() ProteaseDigestion.peptideCount() ProteaseDigestion.isValidProduct() ProteaseDigestion.getMissedCleavages() ProteaseDigestion.setMissedCleavages() """ ff = pyopenms.ProteaseDigestion() assert pyopenms.ProteaseDigestion().setEnzyme is not None ff.setEnzyme("Trypsin/P") assert ff.getEnzymeName() == "Trypsin/P" assert pyopenms.ProteaseDigestion().digest is not None seq = pyopenms.AASequence.fromString("MHARLVP") output = [] ff.digest(seq, output) # MHAR, LVP assert len(output) == 2 ff.setSpecificity(1) # Semi-specific output = [] ff.digest(seq, output) # MHAR, LVP, HAR, LV, AR, L, R, MHA, VP, MH, P, M assert len(output) == 12 assert pyopenms.ProteaseDigestion().peptideCount is not None ff.setSpecificity(2) assert ff.peptideCount(seq) == 2 assert pyopenms.ProteaseDigestion().isValidProduct is not None assert ff.isValidProduct(seq, 0, 4, True, False) assert not ff.isValidProduct(seq, 3, 4, True, False) ff.setSpecificity(1) assert ff.isValidProduct(seq, 1, 3, True, False) assert pyopenms.ProteaseDigestion().getMissedCleavages is not None assert pyopenms.ProteaseDigestion().setMissedCleavages is not None ff.setMissedCleavages(5) assert ff.getMissedCleavages() == 5
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_AcquisitionInfo.py
.py
2,033
69
import unittest import os import pyopenms class TestAcquisitionInfo(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename_mzml = os.path.join(dirname, "test.mzML").encode() def test_acquisitioninfomemberaccess(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename_mzml, exp) # Basically test that the output is non-zero (e.g. the data is # correctly relayed to python) # The functionality is not tested here! # starting point self.assertEqual(exp[0].getAcquisitionInfo().size(), 1) self.assertNotEqual(exp[0].getAcquisitionInfo().size(), 0) # metainfo exp[0].getAcquisitionInfo().size() # is 1 self.assertEqual(exp[0].getAcquisitionInfo()[0].isMetaEmpty(), True) # is True spectra = exp.getSpectra() aqis = spectra[0].getAcquisitionInfo() aqi = aqis[0] # get a copy aqi.setMetaValue('key', 420) # modify it aqis[0] = aqi # and set entry spectra[0].setAcquisitionInfo(aqis) exp.setSpectra(spectra) self.assertEqual(exp[0].getAcquisitionInfo()[0].getMetaValue('key'), 420) # should be 420 acin = pyopenms.Acquisition() acin.setMetaValue('key', 42) self.assertEqual(acin.getMetaValue('key'), 42) # is 42 self.assertEqual(acin.isMetaEmpty(), False) # is False # list/vector assignment magicnumber = 3 neac = pyopenms.AcquisitionInfo() for i in range(0,magicnumber): neac.push_back(acin) self.assertEqual(neac.size(), magicnumber) # is magicnumber # iteration for i in neac: self.assertEqual(i.isMetaEmpty(), False) # always is False # accession already tested in 2nd section tmp = exp.getSpectra() tmp[0].setAcquisitionInfo(neac) exp.setSpectra(tmp) self.assertEqual(exp[0].getAcquisitionInfo().size(), magicnumber) # should be magicnumber for i in exp[0].getAcquisitionInfo(): self.assertEqual(i.isMetaEmpty(), False) # should always be False # resize neac.resize(0) self.assertEqual(neac.size(), 0) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test000.py
.py
205,282
6,958
#!/usr/bin/env python # -*- coding: utf-8 -*- ## ---------------------------------------------------------------------------- ## $Maintainer: $ ## $Authors: Hannes Roest, Timo Sachsenberg, axelwalter, ## Samuel Wein, Uwe Schmitt, Joshua Charkow, ## Nikos Patikas, Chris Bielow, Julianus Pfeuffer, ## Oliver Alka, Stephan Aiche $ ## ---------------------------------------------------------------------------- from __future__ import print_function import pyopenms import copy import os import logging from pyopenms import String as s import numpy as np import pandas as pd print("IMPORTED ", pyopenms.__file__) try: long except NameError: long = int from functools import wraps import sys def _testStrOutput(input_str): if sys.version_info[0] < 3: assert isinstance(input_str, unicode) else: assert isinstance( input_str, str) def report(f): @wraps(f) def wrapper(*a, **kw): print("run ", f.__name__) f(*a, **kw) return wrapper @report def _testMetaInfoInterface(what): #void getKeys(libcpp_vector[String] & keys) #void getKeys(libcpp_vector[unsigned int] & keys) #DataValue getMetaValue(unsigned int) except + nogil #DataValue getMetaValue(String) except + nogil #void setMetaValue(unsigned int, DataValue) except + nogil #void setMetaValue(String, DataValue) except + nogil #bool metaValueExists(String) except + nogil #bool metaValueExists(unsigned int) except + nogil #void removeMetaValue(String) except + nogil #void removeMetaValue(unsigned int) except + nogil # Store essential meta values (like rank for PeptideHit) before testing essential_keys = [b"rank"] preserved_values = {} for key in essential_keys: if what.metaValueExists(key): preserved_values[key] = what.getMetaValue(key) what.setMetaValue("key", 42) what.setMetaValue("key2", 42) keys = [] what.getKeys(keys) assert len(keys) and all(isinstance(k, bytes) for k in keys) # Check that our set keys exist and have correct values (keys are unordered) assert b"key" in keys assert b"key2" in keys assert what.getMetaValue(b"key") == 42 assert what.getMetaValue(b"key2") == 42 assert what.metaValueExists("key") what.removeMetaValue("key") keys = [] what.getKeys(keys) assert b"key2" in keys assert what.getMetaValue(b"key2") == 42 what.clearMetaInfo() # Restore essential meta values after clearMetaInfo for key, value in preserved_values.items(): what.setMetaValue(key, value) keys = [] what.getKeys(keys) # Check that only essential keys remain (if any were preserved) expected_len = len(preserved_values) assert len(keys) == expected_len @report def _testUniqueIdInterface(what): assert what.hasInvalidUniqueId() assert not what.hasValidUniqueId() assert what.ensureUniqueId() assert isinstance(what.getUniqueId(), (int, long)) assert what.getUniqueId() > 0 assert not what.hasInvalidUniqueId() assert what.hasValidUniqueId() what.clearUniqueId() assert what.getUniqueId() == 0 assert what.hasInvalidUniqueId() assert not what.hasValidUniqueId() assert what.ensureUniqueId() assert isinstance(what.getUniqueId(), (int, long)) assert what.getUniqueId() > 0 assert not what.hasInvalidUniqueId() assert what.hasValidUniqueId() what.setUniqueId(1234) assert what.getUniqueId() == 1234 def _testProgressLogger(ff): """ @tests: ProgressLogger ProgressLogger.__init__ ProgressLogger.endProgress ProgressLogger.getLogType ProgressLogger.setLogType ProgressLogger.setProgress ProgressLogger.startProgress """ ff.setLogType(pyopenms.LogType.NONE) assert ff.getLogType() == pyopenms.LogType.NONE ff.startProgress(0, 3, "label") ff.setProgress(0) ff.setProgress(1) ff.setProgress(2) ff.setProgress(3) ff.endProgress() @report def testSpectrumAlignment(): """ @tests: SpectrumAlignment SpectrumAlignment.__init__ SpectrumAlignment.getSpectrumAlignment """ # test existence of some methods pyopenms.SpectrumAlignment pyopenms.SpectrumAlignment.__init__ pyopenms.SpectrumAlignment.getDefaults pyopenms.SpectrumAlignment.getParameters pyopenms.SpectrumAlignment.setParameters spec = pyopenms.MSSpectrum() p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(200.0) spec.push_back(p) p.setMZ(2000.0) p.setIntensity(200.0) spec.push_back(p) rich_spec = pyopenms.MSSpectrum() p = pyopenms.Peak1D() p.setMZ(1000.001) p.setIntensity(200.0) rich_spec.push_back(p) p.setMZ(2000.001) p.setIntensity(200.0) rich_spec.push_back(p) p.setMZ(3000.001) p.setIntensity(200.0) rich_spec.push_back(p) aligner = pyopenms.SpectrumAlignment() result = [] aligner.getSpectrumAlignment(result, spec, spec) assert result == [ (0,0), (1,1) ], result aligner.getSpectrumAlignment(result, rich_spec, spec) assert result == [ (0,0), (1,1) ], result aligner.getSpectrumAlignment(result, spec, rich_spec) assert result == [ (0,0), (1,1) ], result aligner.getSpectrumAlignment(result, rich_spec, rich_spec) assert result == [ (0,0), (1,1), (2,2) ], result aligner = pyopenms.SpectrumAlignmentScore() assert isinstance(aligner(spec), float) assert isinstance(aligner(rich_spec), float) assert isinstance(aligner(spec, rich_spec), float) assert isinstance(aligner(rich_spec, spec), float) assert isinstance(aligner(spec, spec), float) assert isinstance(aligner(rich_spec, rich_spec), float) @report def testAASequence(): """ @tests: AASequence AASequence.__init__ AASequence.__add__ AASequence.__radd__ AASequence.__iadd__ AASequence.getCTerminalModificationName AASequence.getNTerminalModificationName AASequence.setCTerminalModification AASequence.setModification AASequence.setNTerminalModification AASequence.toString AASequence.toUnmodifiedString AASequence.getAAFrequencies """ aas = pyopenms.AASequence() aas + aas aas += aas aas.__doc__ aas = pyopenms.AASequence.fromString("DFPIANGER") assert aas.getCTerminalModificationName() == "" assert aas.getNTerminalModificationName() == "" aas.setCTerminalModification("") aas.setNTerminalModification("") assert aas.toString() == "DFPIANGER" assert aas.toUnmodifiedString() == "DFPIANGER" aas = pyopenms.AASequence.fromStringPermissive("DFPIANGER", True) assert aas.toString() == "DFPIANGER" assert aas.toUnmodifiedString() == "DFPIANGER" # constructor from C string using the static method seq = pyopenms.AASequence.fromString("PEPTIDESEKUEM(Oxidation)CER") assert seq.toString() == "PEPTIDESEKUEM(Oxidation)CER" assert seq.toUnmodifiedString() == "PEPTIDESEKUEMCER" assert seq.toBracketString() == "PEPTIDESEKUEM[147]CER" assert seq.toBracketString(True) == "PEPTIDESEKUEM[147]CER" # constructor from String seq2 = pyopenms.AASequence("PEPTIDESEKUEM(Oxidation)CER") assert seq2.toString() == "PEPTIDESEKUEM(Oxidation)CER" assert seq2.toUnmodifiedString() == "PEPTIDESEKUEMCER" assert seq == seq2 assert seq2.toBracketString() == "PEPTIDESEKUEM[147]CER" assert seq2.toBracketString(True) == "PEPTIDESEKUEM[147]CER" # constructor from String (Permissive) seq3 = pyopenms.AASequence("PEPTIDE#SEKUEM(Oxidation)CER", True) assert seq3.toString() == "PEPTIDEXSEKUEM(Oxidation)CER" assert seq3.toUnmodifiedString() == "PEPTIDEXSEKUEMCER" assert seq3.toBracketString() == "PEPTIDEXSEKUEM[147]CER" assert seq3.toBracketString(True) == "PEPTIDEXSEKUEM[147]CER" assert seq.toBracketString(False) == "PEPTIDESEKUEM[147.03540001709996]CER" or \ seq.toBracketString(False) == "PEPTIDESEKUEM[147.035400017100017]CER" assert seq.toBracketString(False) == "PEPTIDESEKUEM[147.03540001709996]CER" or \ seq.toBracketString(False) == "PEPTIDESEKUEM[147.035400017100017]CER" assert seq.toUniModString() == "PEPTIDESEKUEM(UniMod:35)CER" assert seq.isModified() assert not seq.hasCTerminalModification() assert not seq.hasNTerminalModification() assert not seq.empty() # has selenocysteine assert seq.getResidue(1) is not None assert seq.size() == 16 # test exception forwarding from C++ to python # classes derived from std::runtime_exception can be caught in python try: seq.getResidue(1000) # does not exist except RuntimeError: print("Exception successfully triggered.") else: print("Error: Exception not triggered.") assert False assert seq.getFormula(pyopenms.Residue.ResidueType.Full, 0) == pyopenms.EmpiricalFormula("C75H122N20O32S2Se1") assert abs(seq.getMonoWeight(pyopenms.Residue.ResidueType.Full, 0) - 1958.7140766518) < 1e-5 # assert seq.has(pyopenms.ResidueDB.getResidue("P")) # Test __repr__ and __str__ methods aas_repr = pyopenms.AASequence.fromString("PEPTM(Oxidation)IDE") repr_str = repr(aas_repr) assert "AASequence(" in repr_str assert "sequence=" in repr_str assert "PEPTM(Oxidation)IDE" in repr_str assert "length=" in repr_str assert "mono_mass=" in repr_str assert "modified=True" in repr_str str_str = str(aas_repr) assert str_str == repr_str # Test unmodified sequence aas_unmod = pyopenms.AASequence.fromString("PEPTIDE") repr_unmod = repr(aas_unmod) assert "modified=True" not in repr_unmod # Test getAAFrequencies - matching C++ test case aas_freq = pyopenms.AASequence.fromString("THREEAAAWITHYYY") freq_table = {} aas_freq.getAAFrequencies(freq_table) assert freq_table[b"T"] == 2 assert freq_table[b"H"] == 2 assert freq_table[b"R"] == 1 assert freq_table[b"E"] == 2 assert freq_table[b"A"] == 3 assert freq_table[b"W"] == 1 assert freq_table[b"I"] == 1 assert freq_table[b"Y"] == 3 assert len(freq_table) == 8 @report def testElement(): """ @tests: Element Element.__init__ Element.setAtomicNumber Element.getAtomicNumber Element.setAverageWeight Element.getAverageWeight Element.setMonoWeight Element.getMonoWeight Element.setIsotopeDistribution Element.getIsotopeDistribution Element.setName Element.getName Element.setSymbol Element.getSymbol """ ins = pyopenms.Element() ins.setAtomicNumber(6) ins.getAtomicNumber() ins.setAverageWeight(12.011) ins.getAverageWeight() ins.setMonoWeight(12) ins.getMonoWeight() iso = pyopenms.IsotopeDistribution() ins.setIsotopeDistribution(iso) ins.getIsotopeDistribution() ins.setName("Carbon") ins.getName() ins.setSymbol("C") ins.getSymbol() e = pyopenms.Element() e.setSymbol("blah") e.setSymbol("blah") e.setSymbol(u"blah") e.setSymbol(str("blah")) oms_string = s("blu") e.setSymbol(oms_string) assert oms_string assert oms_string.toString() == "blu" evil = u"blü" evil8 = evil.encode("utf8") evil1 = evil.encode("latin1") e.setSymbol(evil.encode("utf8")) assert e.getSymbol() == u"blü" e.setSymbol(evil.encode("latin1")) assert e.getSymbol().decode("latin1") == u"blü" # If we get the raw symbols, we get bytes (which we would need to decode first) e.setSymbol(evil8.decode("utf8")) # assert e.getSymbol() == 'bl\xc3\xbc', e.getSymbol() assert e.getSymbol() == u"blü" #.encode("utf8") # OpenMS strings, however, understand the decoding assert s(e.getSymbol()) == s(u"blü") assert s(e.getSymbol()).toString() == u"blü" # What if you use the wrong decoding ? e.setSymbol(evil1) assert e.getSymbol().decode("latin1") == u"blü" e.setSymbol(evil8) assert e.getSymbol() == u"blü" @report def testResidue(): """ @tests: Residue Residue.__init__ """ ins = pyopenms.Residue() pyopenms.Residue.ResidueType.Full pyopenms.Residue.ResidueType.Internal pyopenms.Residue.ResidueType.NTerminal pyopenms.Residue.ResidueType.CTerminal pyopenms.Residue.ResidueType.AIon pyopenms.Residue.ResidueType.BIon pyopenms.Residue.ResidueType.CIon pyopenms.Residue.ResidueType.XIon pyopenms.Residue.ResidueType.YIon pyopenms.Residue.ResidueType.ZIon pyopenms.Residue.ResidueType.SizeOfResidueType @report def testResidueRepr(): """ @tests: Residue.__repr__ """ # Get a residue from the database rdb = pyopenms.ResidueDB() glycine = rdb.getResidue(s("Glycine")) # Test __repr__ method repr_str = repr(glycine) assert "Residue(" in repr_str assert "name=" in repr_str assert "Glycine" in repr_str assert "one_letter=" in repr_str assert "'G'" in repr_str assert "three_letter=" in repr_str assert "'Gly'" in repr_str assert "formula=" in repr_str assert "mono_mass=" in repr_str # Test __str__ method for unmodified residue str_str = str(glycine) assert str_str == "G" # Test with modified residue - get oxidized methionine methionine = rdb.getResidue(s("Methionine")) str_str = str(methionine) assert str_str == "M" repr_str = repr(methionine) assert "Residue(" in repr_str assert "'M'" in repr_str assert "'Met'" in repr_str @report def testResidueModificationRepr(): """ @tests: ResidueModification.__repr__ """ # Get a modification from the database mdb = pyopenms.ModificationsDB() mod = mdb.getModification("Oxidation", "M", pyopenms.ResidueModification.TermSpecificity.ANYWHERE) # Test __repr__ and __str__ methods repr_str = repr(mod) assert "ResidueModification(" in repr_str str_str = str(mod) assert str_str == repr_str @report def testMobilityPeak1DRepr(): """ @tests: MobilityPeak1D.__repr__ """ p = pyopenms.MobilityPeak1D() p.setMobility(1.234) p.setIntensity(10000.0) # Test __repr__ and __str__ methods repr_str = repr(p) assert "MobilityPeak1D(" in repr_str assert "mobility=" in repr_str assert "intensity=" in repr_str str_str = str(p) assert str_str == repr_str @report def testIsotopeDistribution(): """ @tests: IsotopeDistribution IsotopeDistribution.__init__ """ ins = pyopenms.IsotopeDistribution() ins.getMax() ins.getMin() ins.size() ins.clear() ins.renormalize() ins.trimLeft(6.0) ins.trimRight(8.0) ins.clear() ins.insert(1, 2) ins.insert(6, 5) assert ins.size() == 2 for p in ins: print(p) # Test __repr__ and __str__ methods iso_repr = pyopenms.IsotopeDistribution() iso_repr.insert(100.0, 0.9) iso_repr.insert(101.0, 0.08) iso_repr.insert(102.0, 0.02) repr_str = repr(iso_repr) assert "IsotopeDistribution(" in repr_str assert "num_isotopes=" in repr_str assert "mass_range=" in repr_str str_str = str(iso_repr) assert str_str == repr_str @report def testFineIsotopePatternGenerator(): """ @tests: FineIsotopePatternGenerator """ iso = pyopenms.FineIsotopePatternGenerator() iso.setThreshold(1e-5) iso.setAbsolute(True) assert iso.getAbsolute() methanol = pyopenms.EmpiricalFormula("CH3OH") water = pyopenms.EmpiricalFormula("H2O") mw = methanol + water iso_dist = mw.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-20, False, False)) assert len(iso_dist.getContainer()) == 56 iso_dist = mw.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-200, False, False)) assert len(iso_dist.getContainer()) == 84 c100 = pyopenms.EmpiricalFormula("C100") iso_dist = c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-200, False, False)) assert len(iso_dist.getContainer()) == 101 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-2, False, False)).size() == 6 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-2, False, True)).size() == 5 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-2, True, False)).size() == 5 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-2, True, True)).size() == 5 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-10, False, False)).size() == 14 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-10, False, True)).size() == 13 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-10, True, False)).size() == 10 assert c100.getIsotopeDistribution(pyopenms.FineIsotopePatternGenerator(1e-10, True, True)).size() == 10 iso = pyopenms.FineIsotopePatternGenerator(1e-5, False, False) isod = iso.run(methanol) assert len(isod.getContainer()) == 6 assert abs(isod.getContainer()[0].getMZ() - 32.0262151276) < 1e-5 assert isod.getContainer()[0].getIntensity() - 0.986442089081 < 1e-5 @report def testCoarseIsotopePatternGenerator(): """ @tests: CoarseIsotopePatternGenerator CoarseIsotopePatternGenerator.__init__ CoarseIsotopePatternGenerator.getMaxIsotope() CoarseIsotopePatternGenerator.setMaxIsotope() CoarseIsotopePatternGenerator.estimateFromPeptideWeight() """ iso = pyopenms.CoarseIsotopePatternGenerator() iso.setMaxIsotope(5) assert iso.getMaxIsotope() == 5 res = iso.estimateFromPeptideWeight(500) methanol = pyopenms.EmpiricalFormula("CH3OH") water = pyopenms.EmpiricalFormula("H2O") mw = methanol + water iso_dist = mw.getIsotopeDistribution(pyopenms.CoarseIsotopePatternGenerator(3)) assert len(iso_dist.getContainer()) == 3, len(iso_dist.getContainer()) iso_dist = mw.getIsotopeDistribution(pyopenms.CoarseIsotopePatternGenerator(0)) assert len(iso_dist.getContainer()) == 18, len(iso_dist.getContainer()) iso = pyopenms.CoarseIsotopePatternGenerator(10) isod = iso.run(methanol) assert len(isod.getContainer()) == 10, len(isod.getContainer()) assert abs(isod.getContainer()[0].getMZ() - 32.0262151276) < 1e-5 assert isod.getContainer()[0].getIntensity() - 0.986442089081 < 1e-5 @report def testEmpiricalFormula(): """ @tests: EmpiricalFormula EmpiricalFormula.__init__ EmpiricalFormula.getMonoWeight EmpiricalFormula.getAverageWeight EmpiricalFormula.getIsotopeDistribution EmpiricalFormula.getNumberOfAtoms EmpiricalFormula.setCharge EmpiricalFormula.getCharge EmpiricalFormula.toString EmpiricalFormula.isEmpty EmpiricalFormula.isCharged EmpiricalFormula.hasElement EmpiricalFormula.hasElement """ ins = pyopenms.EmpiricalFormula() ins.getMonoWeight() ins.getAverageWeight() ins.getIsotopeDistribution(pyopenms.CoarseIsotopePatternGenerator(0)) # ins.getNumberOf(0) # ins.getNumberOf("test") ins.getNumberOfAtoms() ins.setCharge(2) ins.getCharge() ins.toString() ins.isEmpty() ins.isCharged() ins.hasElement( pyopenms.Element() ) ef = pyopenms.EmpiricalFormula("C2H5") s = ef.toString() assert s == "C2H5" m = ef.getElementalComposition() assert m[b"C"] == 2 assert m[b"H"] == 5 assert ef.getNumberOfAtoms() == 7 # Test __repr__ and __str__ methods ef_repr = pyopenms.EmpiricalFormula("C6H12O6") repr_str = repr(ef_repr) assert "EmpiricalFormula(" in repr_str assert "formula=" in repr_str assert "C6H12O6" in repr_str assert "mono_mass=" in repr_str str_str = str(ef_repr) # __str__ returns just the formula, __repr__ returns detailed info assert str_str == "C6H12O6" assert str_str != repr_str @report def testModificationDefinitionsSet(): """ @tests: ModificationDefinitionsSet ModificationDefinitionsSet.__init__ """ empty = pyopenms.ModificationDefinitionsSet() fixed = [b"Carbamidomethyl"] variable = [b"Oxidation"] full = pyopenms.ModificationDefinitionsSet(fixed, variable) @report def test_AcquisitionInfo(): """ @tests: AcquisitionInfo AcquisitionInfo.__init__ AcquisitionInfo.__eq__ AcquisitionInfo.__ge__ AcquisitionInfo.__gt__ AcquisitionInfo.__le__ AcquisitionInfo.__lt__ AcquisitionInfo.__ne__ AcquisitionInfo.getMethodOfCombination AcquisitionInfo.setMethodOfCombination """ ai = pyopenms.AcquisitionInfo() ai.__doc__ assert ai == ai assert not ai != ai ai.setMethodOfCombination("ABC") assert ai.getMethodOfCombination() == "ABC" @report def test_BaseFeature(): """ @tests: BaseFeature BaseFeature.__init__ BaseFeature.clearUniqueId BaseFeature.ensureUniqueId BaseFeature.getCharge BaseFeature.getKeys BaseFeature.getMetaValue BaseFeature.getQuality BaseFeature.getUniqueId BaseFeature.getWidth BaseFeature.hasInvalidUniqueId BaseFeature.hasValidUniqueId BaseFeature.metaValueExists BaseFeature.removeMetaValue BaseFeature.setCharge BaseFeature.setMetaValue BaseFeature.setQuality BaseFeature.setWidth BaseFeature.clearMetaInfo BaseFeature.setUniqueId """ bf = pyopenms.BaseFeature() _testMetaInfoInterface(bf) _testUniqueIdInterface(bf) bf.clearUniqueId() assert bf.ensureUniqueId() assert bf.getCharge() == 0 assert isinstance(bf.getQuality(), float) assert isinstance(bf.getUniqueId(), (long, int)) assert isinstance(bf.getWidth(), float) assert not bf.hasInvalidUniqueId() assert bf.hasValidUniqueId() _testMetaInfoInterface(bf) bf.setCharge(1) bf.setQuality(0.0) bf.setWidth(1.0) @report def test_AnnotationState(): """ @tests: AnnotationState AnnotationState.__init__ """ state = pyopenms.AnnotationState() assert state.FEATURE_ID_NONE is not None assert state.FEATURE_ID_SINGLE is not None assert state.FEATURE_ID_MULTIPLE_SAME is not None assert state.FEATURE_ID_MULTIPLE_DIVERGENT is not None assert state.SIZE_OF_ANNOTATIONSTATE is not None @report def testChecksumType(): """ @tests: ChecksumType ChecksumType.MD5 ChecksumType.SHA1 ChecksumType.SIZE_OF_CHECKSUMTYPE ChecksumType.UNKNOWN_CHECKSUM """ assert isinstance(pyopenms.SourceFile.ChecksumType.MD5, int) assert isinstance(pyopenms.SourceFile.ChecksumType.SHA1, int) assert isinstance(pyopenms.SourceFile.ChecksumType.SIZE_OF_CHECKSUMTYPE, int) assert isinstance(pyopenms.SourceFile.ChecksumType.UNKNOWN_CHECKSUM, int) @report def testChromatogramPeak(): """ @tests: ChromatogramPeak ChromatogramPeak.__init__ ChromatogramPeak.__eq__ ChromatogramPeak.__ge__ ChromatogramPeak.__gt__ ChromatogramPeak.__le__ ChromatogramPeak.__lt__ ChromatogramPeak.__ne__ ChromatogramPeak.getIntensity ChromatogramPeak.getRT ChromatogramPeak.setIntensity ChromatogramPeak.setRT """ p = pyopenms.ChromatogramPeak() assert p == p assert not p != p p.setIntensity(12.0) p.setRT(34.0) assert p.getIntensity() == 12.0 assert p.getRT() == 34.0 # Test __repr__ and __str__ methods repr_str = repr(p) assert "ChromatogramPeak(" in repr_str assert "rt=" in repr_str assert "intensity=" in repr_str str_str = str(p) assert str_str == repr_str # Test constructor with RT and intensity p2 = pyopenms.ChromatogramPeak(100.5, 5000.0) assert p2.getRT() == 100.5 assert p2.getIntensity() == 5000.0 # Test constructor with int RT (DPosition1 converter accepts int/float) p3 = pyopenms.ChromatogramPeak(200, 10000.0) assert p3.getRT() == 200.0 assert p3.getIntensity() == 10000.0 # Test getPosition returns float pos = p2.getPosition() assert isinstance(pos, float) assert pos == 100.5 # Test setPosition with float p2.setPosition(300.0) assert p2.getRT() == 300.0 assert p2.getPosition() == 300.0 # Test setPosition with int (DPosition1 converter accepts int/float) p2.setPosition(400) assert p2.getRT() == 400.0 @report def testChromatogramToosl(): """ @tests: ChromatogramTools ChromatogramTools.__init__ ChromatogramTools.convertChromatogramsToSpectra ChromatogramTools.convertSpectraToChromatograms """ pyopenms.ChromatogramTools() pyopenms.ChromatogramTools.convertChromatogramsToSpectra pyopenms.ChromatogramTools.convertSpectraToChromatograms @report def testConsensusFeature(): """ @tests: ConsensusFeature ConsensusFeature.__eq__ ConsensusFeature.__ge__ ConsensusFeature.__gt__ ConsensusFeature.__le__ ConsensusFeature.__lt__ ConsensusFeature.__ne__ ConsensusFeature.__init__ ConsensusFeature.clearUniqueId ConsensusFeature.computeConsensus ConsensusFeature.computeDechargeConsensus ConsensusFeature.computeMonoisotopicConsensus ConsensusFeature.ensureUniqueId ConsensusFeature.getCharge ConsensusFeature.getKeys ConsensusFeature.getMetaValue ConsensusFeature.getQuality ConsensusFeature.getUniqueId ConsensusFeature.getWidth ConsensusFeature.hasInvalidUniqueId ConsensusFeature.hasValidUniqueId ConsensusFeature.insert ConsensusFeature.metaValueExists ConsensusFeature.removeMetaValue ConsensusFeature.setCharge ConsensusFeature.setMetaValue ConsensusFeature.setQuality ConsensusFeature.setWidth ConsensusFeature.clearMetaInfo ConsensusFeature.setUniqueId ConsensusFeature.size ConsensusFeature.getPeptideIdentifications ConsensusFeature.setPeptideIdentifications """ f = pyopenms.ConsensusFeature() f_ = copy.copy(f) assert f_ == f f_ = copy.deepcopy(f) assert f_ == f f_ = pyopenms.ConsensusFeature(f) assert f_ == f _testUniqueIdInterface(f) _testMetaInfoInterface(f) f.setCharge(1) f.setQuality(2.0) f.setWidth(4.0) assert f.getCharge() == 1 assert f.getQuality() == 2.0 assert f.getWidth() == 4.0 f.insert(0, pyopenms.Peak2D(), 1) f.insert(1, pyopenms.BaseFeature()) f.insert(2, pyopenms.ConsensusFeature()) f.computeConsensus() f.computeDechargeConsensus f.computeMonoisotopicConsensus() assert f.size() >= 0 p = f.getPeptideIdentifications() f.setPeptideIdentifications(p) # Test __repr__ and __str__ methods cf_repr = pyopenms.ConsensusFeature() cf_repr.setRT(1234.5) cf_repr.setMZ(445.678) cf_repr.setIntensity(100000.0) cf_repr.setCharge(2) cf_repr.insert(0, pyopenms.Peak2D(), 1) cf_repr.insert(1, pyopenms.BaseFeature()) repr_str = repr(cf_repr) assert "ConsensusFeature(" in repr_str assert "rt=" in repr_str assert "mz=" in repr_str assert "intensity=" in repr_str assert "num_features=" in repr_str str_str = str(cf_repr) assert str_str == repr_str @report def testConsensusMap(): """ @tests: ConsensusMap ConsensusMap.__eq__ ConsensusMap.__ge__ ConsensusMap.__gt__ ConsensusMap.__init__ ConsensusMap.__iter__ ConsensusMap.__le__ ConsensusMap.__len__ ConsensusMap.__lt__ ConsensusMap.__ne__ ConsensusMap.append ConsensusMap.clear ConsensusMap.clearUniqueId ConsensusMap.ensureUniqueId ConsensusMap.extend ConsensusMap.getDataProcessing ConsensusMap.getColumnHeaders ConsensusMap.getProteinIdentifications ConsensusMap.getUnassignedPeptideIdentifications ConsensusMap.getUniqueId ConsensusMap.hasInvalidUniqueId ConsensusMap.hasValidUniqueId ConsensusMap.setDataProcessing ConsensusMap.setColumnHeaders ConsensusMap.setProteinIdentifications ConsensusMap.setUnassignedPeptideIdentifications ConsensusMap.setUniqueId ConsensusMap.setUniqueIds ConsensusMap.size ConsensusMap.sortByIntensity ConsensusMap.sortByMZ ConsensusMap.sortByMaps ConsensusMap.sortByPosition ConsensusMap.sortByQuality ConsensusMap.sortByRT ConsensusMap.sortBySize ConsensusMap.updateRanges """ m = pyopenms.ConsensusMap() m_ = copy.copy(m) assert m_ == m m_ = copy.deepcopy(m) assert m_ == m m_ = pyopenms.ConsensusMap(m) assert m_ == m m.clear() m.clearUniqueId() m.ensureUniqueId() m.getDataProcessing() m.getColumnHeaders() m.getProteinIdentifications() m.getUnassignedPeptideIdentifications() m.getUniqueId() m.hasInvalidUniqueId() m.hasValidUniqueId() m.setDataProcessing m.setColumnHeaders m.setProteinIdentifications m.setUnassignedPeptideIdentifications m.setUniqueId m.setUniqueIds m.size() m.sortByIntensity() m.sortByMZ() m.sortByMaps() m.sortByPosition() m.sortByQuality() m.sortByRT() m.sortBySize() # We need to add a feature to the map before calling updateRanges otherwise the getMin and getMax throw an error. f = pyopenms.ConsensusFeature() f.setCharge(1) f.setQuality(2.0) f.setWidth(4.0) m.push_back(f) m.push_back(f) m.updateRanges() assert isinstance(m.getMinRT(), float) assert isinstance(m.getMinRT(), float) assert isinstance(m.getMaxMZ(), float) assert isinstance(m.getMaxMZ(), float) assert isinstance(m.getMinIntensity(), float) assert isinstance(m.getMaxIntensity(), float) m.getIdentifier() m.getLoadedFileType() m.getLoadedFilePath() intydf = m.get_intensity_df() metadf = m.get_metadata_df() assert intydf.shape[0] == 2 assert metadf.shape[0] == 2 assert m == m assert not m != m # Test __repr__ and __str__ methods cm_repr = pyopenms.ConsensusMap() cf1 = pyopenms.ConsensusFeature() cf1.setRT(100.0) cf1.setMZ(500.0) cf2 = pyopenms.ConsensusFeature() cf2.setRT(200.0) cf2.setMZ(600.0) cm_repr.push_back(cf1) cm_repr.push_back(cf2) cm_repr.setExperimentType("label-free") repr_str = repr(cm_repr) assert "ConsensusMap(" in repr_str assert "num_consensus_features=" in repr_str # Test __len__, append, and extend methods cm_len = pyopenms.ConsensusMap() assert len(cm_len) == 0 assert len(cm_len) == cm_len.size() cf_test1 = pyopenms.ConsensusFeature() cf_test1.setRT(100.0) cf_test1.setMZ(500.0) cf_test2 = pyopenms.ConsensusFeature() cf_test2.setRT(200.0) cf_test2.setMZ(600.0) cf_test3 = pyopenms.ConsensusFeature() cf_test3.setRT(300.0) cf_test3.setMZ(700.0) # Test append (single item) cm_len.append(cf_test1) assert len(cm_len) == 1 assert len(cm_len) == cm_len.size() # Test extend with list cm_len.extend([cf_test2, cf_test3]) assert len(cm_len) == 3 assert len(cm_len) == cm_len.size() # Verify the features were added correctly assert cm_len[0].getRT() == 100.0 assert cm_len[1].getRT() == 200.0 assert cm_len[2].getRT() == 300.0 # Test extend with another ConsensusMap cm_source = pyopenms.ConsensusMap() cf_test4 = pyopenms.ConsensusFeature() cf_test4.setRT(400.0) cf_test4.setMZ(800.0) cm_source.push_back(cf_test4) cm_len.extend(cm_source) assert len(cm_len) == 4 assert cm_len[3].getRT() == 400.0 @report def testConsensusXMLFile(): """ @tests: ConsensusXMLFile ConsensusXMLFile.__init__ ConsensusXMLFile.getOptions ConsensusXMLFile.load ConsensusXMLFile.store """ f = pyopenms.ConsensusXMLFile() f.getOptions() assert f.load is not None assert f.store is not None @report def testXTandemXMLFile(): """ @tests: XTandemXMLFile XTandemXMLFile.__init__ XTandemXMLFile.load XTandemXMLFile.setModificationDefinitionsSet """ f = pyopenms.XTandemXMLFile() assert f.load is not None @report def testXTandemInfile(): """ """ f = pyopenms.XTandemInfile() f.setFragmentMassTolerance is not None f.getFragmentMassTolerance is not None f.setPrecursorMassTolerancePlus is not None f.getPrecursorMassTolerancePlus is not None f.setPrecursorMassToleranceMinus is not None f.getPrecursorMassToleranceMinus is not None f.setPrecursorErrorType is not None f.getPrecursorErrorType is not None f.setFragmentMassErrorUnit is not None f.getFragmentMassErrorUnit is not None f.setPrecursorMassErrorUnit is not None f.getPrecursorMassErrorUnit is not None f.setNumberOfThreads is not None f.getNumberOfThreads is not None f.setModifications is not None f.getModifications is not None f.setOutputFilename is not None f.getOutputFilename is not None f.setInputFilename is not None f.getInputFilename is not None f.setTaxonomyFilename is not None f.getTaxonomyFilename is not None f.setDefaultParametersFilename is not None f.getDefaultParametersFilename is not None f.setTaxon("testTaxon") assert f.getTaxon() == "testTaxon" assert f.setMaxPrecursorCharge is not None assert f.getMaxPrecursorCharge is not None assert f.setNumberOfMissedCleavages is not None assert f.getNumberOfMissedCleavages is not None assert f.setMaxValidEValue is not None assert f.getMaxValidEValue is not None assert f.setSemiCleavage is not None assert f.setAllowIsotopeError is not None assert f.write is not None assert f.setCleavageSite is not None assert f.getCleavageSite is not None @report def testSignalToNoiseEstimatorMedian(): """ @tests: SignalToNoiseEstimatorMedian SignalToNoiseEstimatorMedian.__init__ """ f = pyopenms.SignalToNoiseEstimatorMedian() assert f.init is not None assert f.getSignalToNoise is not None @report def testSignalToNoiseEstimatorMedianChrom(): """ @tests: SignalToNoiseEstimatorMedianChrom SignalToNoiseEstimatorMedianChrom.__init__ """ f = pyopenms.SignalToNoiseEstimatorMedianChrom() assert f.init is not None assert f.getSignalToNoise is not None @report def testConvexHull2D(): """ @tests: ConvexHull2D ConvexHull2D.__eq__ ConvexHull2D.__ge__ ConvexHull2D.__gt__ ConvexHull2D.__init__ ConvexHull2D.__le__ ConvexHull2D.__lt__ ConvexHull2D.__ne__ ConvexHull2D.clear """ ch = pyopenms.ConvexHull2D() ch.clear() assert ch == ch # Test __repr__ and __str__ methods ch_repr = pyopenms.ConvexHull2D() ch_repr.addPointXY(100.0, 400.0) ch_repr.addPointXY(110.0, 400.0) ch_repr.addPointXY(110.0, 410.0) ch_repr.addPointXY(100.0, 410.0) repr_str = repr(ch_repr) assert "ConvexHull2D(" in repr_str assert "num_points=" in repr_str @report def testDataProcessing(dp=pyopenms.DataProcessing()): """ @tests: DataProcessing DataProcessing.__init__ DataProcessing.getKeys DataProcessing.getMetaValue DataProcessing.getProcessingActions DataProcessing.getSoftware DataProcessing.isMetaEmpty DataProcessing.metaValueExists DataProcessing.removeMetaValue DataProcessing.setCompletionTime DataProcessing.setMetaValue DataProcessing.setProcessingActions DataProcessing.setSoftware DataProcessing.__eq__ DataProcessing.__ge__ DataProcessing.__gt__ DataProcessing.__le__ DataProcessing.__lt__ DataProcessing.__ne__ DataProcessing.clearMetaInfo DataProcessing.getCompletionTime """ _testMetaInfoInterface(dp) assert dp == dp assert not dp != dp # assert isinstance(dp.getCompletionTime().getDate(), bytes) # assert isinstance(dp.getCompletionTime().getTime(), bytes) dp.clearMetaInfo() k = [] dp.getKeys(k) assert k == [] dp.getMetaValue ac = dp.getProcessingActions() assert ac == set(()) ac = set([ pyopenms.DataProcessing.ProcessingAction.PEAK_PICKING, pyopenms.DataProcessing.ProcessingAction.BASELINE_REDUCTION]) dp.setProcessingActions(ac) assert len(dp.getProcessingActions() ) == 2 _testStrOutput(dp.getSoftware().getName()) _testStrOutput(dp.getSoftware().getVersion()) dp.isMetaEmpty() dp.metaValueExists dp.removeMetaValue # dp.setCompletionTime(pyopenms.DateTime.now()) s = dp.getSoftware() s.setName("pyopenms") dp.setSoftware(s) assert dp.getSoftware().getName() == "pyopenms" # Test getAllNamesOf method action_names = pyopenms.DataProcessing.getAllNamesOfProcessingAction() assert len(action_names) == pyopenms.DataProcessing.ProcessingAction.SIZE_OF_PROCESSINGACTION assert action_names[pyopenms.DataProcessing.ProcessingAction.PEAK_PICKING].decode() == "Peak picking" assert action_names[pyopenms.DataProcessing.ProcessingAction.SMOOTHING].decode() == "Smoothing" @report def testDataType(): """ @tests: DataType DataType.DOUBLE_LIST DataType.DOUBLE_VALUE DataType.EMPTY_VALUE DataType.INT_LIST DataType.INT_VALUE DataType.STRING_LIST DataType.STRING_VALUE """ assert isinstance(pyopenms.DataType.DOUBLE_LIST, int) assert isinstance(pyopenms.DataType.DOUBLE_VALUE, int) assert isinstance(pyopenms.DataType.EMPTY_VALUE, int) assert isinstance(pyopenms.DataType.INT_LIST, int) assert isinstance(pyopenms.DataType.INT_VALUE, int) assert isinstance(pyopenms.DataType.STRING_LIST, int) assert isinstance(pyopenms.DataType.STRING_VALUE, int) @report def testDataValue(): """ @tests: DataValue DataValue.__init__ DataValue.isEmpty DataValue.toDoubleList DataValue.toDouble DataValue.toInt DataValue.toIntList DataValue.toString DataValue.toStringList DataValue.valueType """ a = pyopenms.DataValue() assert a.isEmpty() a = pyopenms.DataValue(1) assert not a.isEmpty() assert a.toInt() == 1 assert a.valueType() == pyopenms.DataType.INT_VALUE a = pyopenms.DataValue(1.0) assert not a.isEmpty() assert a.toDouble() == 1.0 assert a.valueType() == pyopenms.DataType.DOUBLE_VALUE a = pyopenms.DataValue("1") assert not a.isEmpty() assert a.toString() == "1" assert a.valueType() == pyopenms.DataType.STRING_VALUE a = pyopenms.DataValue([1]) assert not a.isEmpty() assert a.toIntList() == [1] assert a.valueType() == pyopenms.DataType.INT_LIST a = pyopenms.DataValue([1.0]) assert not a.isEmpty() assert a.toDoubleList() == [1.0] assert a.valueType() == pyopenms.DataType.DOUBLE_LIST a = pyopenms.DataValue([b"1.0"]) assert not a.isEmpty() assert a.toStringList() == [b"1.0"] assert a.valueType() == pyopenms.DataType.STRING_LIST assert pyopenms.MSSpectrum().getMetaValue("nonexisingkey") is None @report def testAdduct(): """ @tests: Adduct Adduct.__init__ """ a = pyopenms.Adduct() @report def testGaussFitter(): """ @tests: GaussFitter GaussFitter.__init__ """ ins = pyopenms.GaussFitter() @report def testGaussFitResult(): """ @tests: GaussFitResult GaussFitResult.__init__ """ ins = pyopenms.GaussFitResult(0.0, 0.0, 0.0) ins.A = 5.0 ins.x0 = 5.0 ins.sigma = 5.0 @report def testChargePair(): """ @tests: ChargePair ChargePair.__init__ """ a = pyopenms.ChargePair() @report def testCompomer(): """ @tests: Compomer Compomer.__init__ """ a = pyopenms.Compomer() @report def testCVMappings(): """ @tests: CVMappings CVMappings.__init__ """ val = pyopenms.CVMappings() @report def testCVMappingFile(): """ @tests: CVMappingFile CVMappingFile.__init__ """ val = pyopenms.CVMappingFile() assert pyopenms.CVMappingFile().load @report def testControlledVocabulary(): """ @tests: ControlledVocabulary ControlledVocabulary.__init__ """ val = pyopenms.ControlledVocabulary() assert pyopenms.ControlledVocabulary().loadFromOBO @report def testSemanticValidator(): """ @tests: SemanticValidator SemanticValidator.__init__ """ m = pyopenms.CVMappings() cv = pyopenms.ControlledVocabulary() val = pyopenms.SemanticValidator(m, cv) assert val.validate is not None assert val.setCheckTermValueTypes is not None assert val.setCheckUnits is not None # @report # def testDateTime(): # """ # @tests: DateTime # DateTime.__init__ # DateTime.getDate # DateTime.getTime # DateTime.now # """ # d = pyopenms.DateTime() # assert isinstance( d.getDate(), bytes) # assert isinstance( d.getTime(), bytes) # d = pyopenms.DateTime.now() # assert isinstance( d.getDate(), bytes) # assert isinstance( d.getTime(), bytes) # # d.clear() # d.set("01.01.2001 11:11:11") # assert d.get() == "2001-01-01 11:11:11" @report def testFeature(): """ @tests: Feature Feature.__init__ Feature.clearUniqueId Feature.ensureUniqueId Feature.getCharge Feature.getIntensity Feature.getKeys Feature.getMZ Feature.getMetaValue Feature.getQuality Feature.getRT Feature.getUniqueId Feature.getWidth Feature.hasInvalidUniqueId Feature.hasValidUniqueId Feature.metaValueExists Feature.removeMetaValue Feature.setCharge Feature.setIntensity Feature.setMZ Feature.setMetaValue Feature.setQuality Feature.setRT Feature.setWidth Feature.__eq__ Feature.__ge__ Feature.__gt__ Feature.__le__ Feature.__lt__ Feature.__ne__ Feature.clearMetaInfo Feature.getConvexHulls Feature.getSubordinates Feature.setConvexHulls Feature.setSubordinates Feature.setUniqueId Feature.getPeptideIdentifications Feature.setPeptideIdentifications """ f = pyopenms.Feature() _testMetaInfoInterface(f) _testUniqueIdInterface(f) f.setConvexHulls(f.getConvexHulls()) f.setSubordinates(f.getSubordinates()) f.setUniqueId(12345) assert f == f assert not f != f f.setCharge(-1) assert f.getCharge() == -1 f.setIntensity(10.0) assert f.getIntensity() == 10.0 f.setQuality(0, 20.0) assert f.getQuality(0) == 20.0 f.setRT(30.0) assert f.getRT() == 30.0 f.setWidth(40.0) assert f.getWidth() == 40.0 p = f.getPeptideIdentifications() f.setPeptideIdentifications(p) # Test __repr__ and __str__ methods f_repr = pyopenms.Feature() f_repr.setRT(1234.5) f_repr.setMZ(445.678) f_repr.setIntensity(100000.0) f_repr.setCharge(2) f_repr.setOverallQuality(0.95) repr_str = repr(f_repr) assert "Feature(" in repr_str assert "rt=" in repr_str assert "mz=" in repr_str assert "intensity=" in repr_str assert "charge=" in repr_str assert "quality=" in repr_str # Test str method str_str = str(f_repr) assert str_str == repr_str @report def testFeatureFileOptions(): """ @tests: FeatureFileOptions FeatureFileOptions.__init__ FeatureFileOptions.getLoadConvexHull FeatureFileOptions.getLoadSubordinates FeatureFileOptions.getMetadataOnly FeatureFileOptions.getSizeOnly FeatureFileOptions.setLoadConvexHull FeatureFileOptions.setLoadSubordinates FeatureFileOptions.setMetadataOnly FeatureFileOptions.setSizeOnly """ fo = pyopenms.FeatureFileOptions() fo.getLoadConvexHull() fo.getLoadSubordinates() fo.getSizeOnly() assert fo.setLoadConvexHull is not None assert fo.setLoadSubordinates is not None assert fo.setMetadataOnly is not None assert fo.setSizeOnly is not None @report def _testParam(p): """ @tests: Param Param.__init__ Param.addTag Param.addTags Param.asDict Param.clearTags Param.copy Param.exists Param.get Param.getDescription Param.getEntry Param.getSectionDescription Param.getTags Param.getValue Param.hasTag Param.insert Param.setMaxFloat Param.setMaxInt Param.setMinFloat Param.setMinInt Param.setSectionDescription Param.setValidStrings Param.getValidStrings Param.setValue Param.size Param.update Param.__eq__ Param.__ge__ Param.__gt__ Param.__le__ Param.__lt__ Param.__ne__ ParamEntry.__init__ ParamEntry.description ParamEntry.isValid ParamEntry.max_float ParamEntry.max_int ParamEntry.min_float ParamEntry.min_int ParamEntry.name ParamEntry.tags ParamEntry.valid_strings ParamEntry.value ParamEntry.__eq__ ParamEntry.__ge__ ParamEntry.__gt__ ParamEntry.__le__ ParamEntry.__lt__ ParamEntry.__ne__ """ assert p == p dd = p.asDict() assert len(dd) == p.size() assert isinstance(dd, dict) for k in p.keys(): #value = p.getValue(k) value = p[k] p[k] = value p.update(p) p.update(p.asDict()) assert p[k] == value desc = p.getDescription(k) tags = p.getTags(k) p.setValue(k, value, desc, tags) p.setValue(k, value, desc) assert p.exists(k) # only set the section description if there are actually two or more sections if len(k.split(b":")) < 2: continue f = k.split(b":")[0] p.setSectionDescription(f, k) # TODO: keys inside maps are not yet properly decoded assert p.getSectionDescription(f) == k.decode() assert p.get(k) is not None assert len(p.values()) == len([p[k] for k in p.keys()]) assert sorted(p.items()) == sorted((k, p[k]) for k in p.keys()) assert not p.exists("asdflkj01231321321v") p.addTag(k, "a") p.addTags(k, [b"", b"c"]) assert sorted(p.getTags(k)) == [b"", b"a", b"c"] p.clearTags(k) assert p.getTags(k) == [] pn = pyopenms.Param() pn.insert("master:", p) assert pn.exists(b"master:"+k) p1 = pn.copy("master:", True) assert p1 == p p1.update(p) p1.update(p,0) p1.update(p,1) p1.update(dd) p.setValidStrings p.getValidStrings p.setMinFloat p.setMaxFloat p.setMinInt p.setMaxInt ph = pyopenms.ParamXMLFile() ph.store("test.ini", p) p1 = pyopenms.Param() ph.load("test.ini", p1) assert p == p1 e1 = p1.getEntry(k) for f in ["name", "description", "value", "tags", "valid_strings", "min_float", "max_float", "min_int", "max_int"]: assert getattr(e1, f) is not None assert e1 == e1 assert p1.get(b"abcde", 7) == 7 @report def testParamPythonicInterface(): """ @tests: Param Param.from_dict Param.to_dict Param.__iter__ Param.__len__ Param.__contains__ """ # Test from_dict() class method d = {b"param1": 42, b"param2": 3.14, b"param3": "hello"} p = pyopenms.Param.from_dict(d) assert p.size() == 3 assert p[b"param1"] == 42 assert abs(p[b"param2"] - 3.14) < 0.001 assert p[b"param3"] == "hello" # Test from_dict() with string keys d_str = {"str_param1": 100, "str_param2": 2.718} p2 = pyopenms.Param.from_dict(d_str) assert p2.size() == 2 assert p2["str_param1"] == 100 assert p2[b"str_param1"] == 100 # bytes key also works # Test to_dict() returns string keys d_out = p.to_dict() assert isinstance(d_out, dict) assert len(d_out) == 3 assert "param1" in d_out # String key, not bytes assert d_out["param1"] == 42 # Test asDict() still returns bytes keys (backward compatibility) d_bytes = p.asDict() assert b"param1" in d_bytes assert d_bytes[b"param1"] == 42 # Verify to_dict() and asDict() have same values but different key types assert len(p.to_dict()) == len(p.asDict()) for str_key, value in p.to_dict().items(): assert isinstance(str_key, str) assert p.asDict()[str_key.encode('utf-8')] == value # Test __len__() assert len(p) == 3 assert len(p) == p.size() # Test __iter__() keys_from_iter = list(p) keys_from_method = p.keys() assert keys_from_iter == keys_from_method assert len(keys_from_iter) == 3 # Test iteration in for loop count = 0 for key in p: assert p[key] is not None count += 1 assert count == 3 # Test __contains__() with bytes key assert b"param1" in p assert b"nonexistent" not in p # Test __contains__() with string key assert "param1" in p assert "nonexistent" not in p # Test __getitem__() with string key assert p["param1"] == 42 assert p["param2"] == p[b"param2"] # Test __setitem__() with string key p["new_param"] = 999 assert p["new_param"] == 999 assert p[b"new_param"] == 999 # Test get() with string key assert p.get("param1") == 42 assert p.get("nonexistent") is None assert p.get("nonexistent", "default") == "default" # Test get() with bytes key (backward compatibility) assert p.get(b"param1") == 42 assert p.get(b"nonexistent") is None assert p.get(b"nonexistent", 123) == 123 # Test round-trip: dict -> Param -> dict (now with string keys!) original = {"a": 1, "b": 2.5, "c": "test"} p3 = pyopenms.Param.from_dict(original) result = p3.to_dict() # Keys come back as strings, so direct comparison works assert len(result) == len(original) assert result == original # Direct equality now works! # Test round-trip workflow: fetch, modify, write back p4 = pyopenms.Param.from_dict({"threshold": 0.5, "iterations": 10}) d = p4.to_dict() d["threshold"] = 0.75 # Modify with string key d["new_key"] = "added" # Add new key p4.update(d) assert p4["threshold"] == 0.75 assert p4["iterations"] == 10 assert p4["new_key"] == "added" # Test empty Param p_empty = pyopenms.Param() assert len(p_empty) == 0 assert list(p_empty) == [] assert "anything" not in p_empty assert p_empty.to_dict() == {} # Test from_dict() with empty dict p_from_empty = pyopenms.Param.from_dict({}) assert len(p_from_empty) == 0 @report def testFeatureFinderAlgorithmPicked(): """ @tests: FeatureFinderAlgorithmPicked FeatureFinderAlgorithmPicked.__init__ FeatureFinderAlgorithmPicked.getDefaults FeatureFinderAlgorithmPicked.getName FeatureFinderAlgorithmPicked.getParameters FeatureFinderAlgorithmPicked.getProductName FeatureFinderAlgorithmPicked.setName FeatureFinderAlgorithmPicked.setParameters """ ff = pyopenms.FeatureFinderAlgorithmPicked() p = ff.getDefaults() _testParam(p) _testParam(ff.getParameters()) assert ff.getName() == "FeatureFinderAlgorithmPicked" ff.setParameters(pyopenms.Param()) ff.setName("test") assert ff.getName() == "test" @report def testExperimentalSettings(): """ @tests: ExperimentalSettings ExperimentalSettings.__init__ """ ff = pyopenms.ExperimentalSettings() @report def testFeatureDeconvolution(): """ @tests: FeatureDeconvolution FeatureDeconvolution.__init__ """ ff = pyopenms.FeatureDeconvolution() p = ff.getDefaults() _testParam(p) assert pyopenms.FeatureDeconvolution().compute is not None @report def testInternalCalibration(): """ @tests: InternalCalibration InternalCalibration.__init__ """ ff = pyopenms.InternalCalibration() p = ff.getDefaults() _testParam(p) # TODO # assert pyopenms.InternalCalibration().compute is not None @report def testItraqConstants(): """ @tests: testItraqConstants """ constants = pyopenms.ItraqConstants() assert pyopenms.ITRAQ_TYPES.FOURPLEX is not None assert pyopenms.ITRAQ_TYPES.EIGHTPLEX is not None assert pyopenms.ITRAQ_TYPES.TMT_SIXPLEX is not None assert constants.getIsotopeMatrixAsStringList is not None assert constants.updateIsotopeMatrixFromStringList is not None assert constants.translateIsotopeMatrix is not None @report def testLinearResampler(): """ @tests: LinearResampler LinearResampler.__init__ """ ff = pyopenms.LinearResampler() p = ff.getDefaults() _testParam(p) assert pyopenms.LinearResampler().raster is not None assert pyopenms.LinearResampler().rasterExperiment is not None @report def testPeptideAndProteinQuant(): """ @tests: PeptideAndProteinQuant PeptideAndProteinQuant.__init__ """ ff = pyopenms.PeptideAndProteinQuant() p = ff.getDefaults() _testParam(p) assert pyopenms.PeptideAndProteinQuant().quantifyPeptides is not None assert pyopenms.PeptideAndProteinQuant().quantifyProteins is not None @report def testSeedListGenerator(): """ @tests: SeedListGenerator SeedListGenerator.__init__ """ ff = pyopenms.SeedListGenerator() p = ff.getDefaults() _testParam(p) # TODO # assert pyopenms.SeedListGenerator().compute is not None # TODO: re-enable as soon as ConsensusIDAlgorithm classes are wrapped # @report # def testConsensusID(): # """ # @tests: ConsensusID # ConsensusID.__init__ # """ # ff = pyopenms.ConsensusID() # p = ff.getDefaults() # _testParam(p) # assert pyopenms.ConsensusID().apply is not None @report def testFalseDiscoveryRate(): """ @tests: FalseDiscoveryRate FalseDiscoveryRate.__init__ """ ff = pyopenms.FalseDiscoveryRate() p = ff.getDefaults() _testParam(p) assert pyopenms.FalseDiscoveryRate().apply is not None @report def testIDFilter(): """ @tests: IDFilter IDFilter.__init__ """ ff = pyopenms.IDFilter() # assert pyopenms.IDFilter().apply is not None @report def testPosteriorErrorProbabilityModel(): """ @tests: PosteriorErrorProbabilityModel PosteriorErrorProbabilityModel.__init__ """ model = pyopenms.PosteriorErrorProbabilityModel() p = model.getDefaults() _testParam(p) assert pyopenms.PosteriorErrorProbabilityModel().fit is not None assert pyopenms.PosteriorErrorProbabilityModel().computeProbability is not None scores = [float(i) for i in range(10)] model.fit(scores, "none") model.fit(scores, scores, "none") model.fillLogDensities(scores, scores, scores) assert model.computeLogLikelihood is not None assert model.pos_neg_mean_weighted_posteriors is not None GaussFitResult = model.getCorrectlyAssignedFitResult() GaussFitResult = model.getIncorrectlyAssignedFitResult() model.getNegativePrior() model.computeProbability(5.0) # model.InitPlots target = [float(i) for i in range(10)] model.getGumbelGnuplotFormula(GaussFitResult) model.getGaussGnuplotFormula(GaussFitResult) model.getBothGnuplotFormula(GaussFitResult, GaussFitResult) model.plotTargetDecoyEstimation(target, target) model.getSmallestScore() @report def testSeedListGenerator(): """ @tests: SeedListGenerator SeedListGenerator.__init__ """ ff = pyopenms.SeedListGenerator() # TODO # assert pyopenms.SeedListGenerator().generateSeedList is not None @report def testConsensusMapNormalizerAlgorithmMedian(): """ @tests: ConsensusMapNormalizerAlgorithmMedian ConsensusMapNormalizerAlgorithmMedian.__init__ """ ff = pyopenms.ConsensusMapNormalizerAlgorithmMedian() assert pyopenms.ConsensusMapNormalizerAlgorithmMedian().normalizeMaps is not None @report def testConsensusMapNormalizerAlgorithmQuantile(): """ @tests: ConsensusMapNormalizerAlgorithmQuantile ConsensusMapNormalizerAlgorithmQuantile.__init__ """ ff = pyopenms.ConsensusMapNormalizerAlgorithmQuantile() assert pyopenms.ConsensusMapNormalizerAlgorithmQuantile().normalizeMaps is not None @report def testConsensusMapNormalizerAlgorithmThreshold(): """ @tests: ConsensusMapNormalizerAlgorithmThreshold ConsensusMapNormalizerAlgorithmThreshold.__init__ """ ff = pyopenms.ConsensusMapNormalizerAlgorithmThreshold() assert pyopenms.ConsensusMapNormalizerAlgorithmThreshold().computeCorrelation is not None assert pyopenms.ConsensusMapNormalizerAlgorithmThreshold().normalizeMaps is not None @report def testAScore(): """ @tests: AScore AScore.__init__ """ ff = pyopenms.AScore() hit = pyopenms.PeptideHit() spectrum = pyopenms.MSSpectrum() ff.compute(hit, spectrum) # ff.computeCumulativeScore(1,1,0.5) @report def testIDRipper(): """ @tests: IDRipper IDRipper.__init__ IDRipper.rip """ ff = pyopenms.IDRipper() assert pyopenms.IDRipper().rip is not None @report def testFASTAFile(): """ @tests: FASTAFile FASTAFile.__init__ FASTAFile.load FASTAFile.store """ ff = pyopenms.FASTAFile() assert pyopenms.FASTAFile().load is not None assert pyopenms.FASTAFile().store is not None @report def testFASTAEntry(): """ @tests: FASTAEntry FASTAEntry.__init__ """ ff = pyopenms.FASTAEntry() @report def testInternalCalibration(): """ @tests: InternalCalibration InternalCalibration.__init__ InternalCalibration.calibrateMapGlobally InternalCalibration.calibrateMapSpectrumwise """ ff = pyopenms.InternalCalibration() assert pyopenms.InternalCalibration().fillCalibrants is not None assert pyopenms.InternalCalibration().getCalibrationPoints is not None assert pyopenms.InternalCalibration().calibrate is not None @report def testTransitionTSVFile(): """ @tests: TransitionTSVFile.__init__ TransitionTSVFile.calibrateMapGlobally TransitionTSVFile.calibrateMapSpectrumwise """ ff = pyopenms.TransitionTSVFile() assert pyopenms.TransitionTSVFile().convertTargetedExperimentToTSV is not None assert pyopenms.TransitionTSVFile().convertTSVToTargetedExperiment is not None assert pyopenms.TransitionTSVFile().validateTargetedExperiment is not None @report def testIDDecoyProbability(): """ @tests: IDDecoyProbability IDDecoyProbability.__init__ """ ff = pyopenms.IDDecoyProbability() assert pyopenms.IDDecoyProbability().apply is not None @report def testFeatureGrouping(): """ @tests: FeatureGroupingAlgorithmQT FeatureGroupingAlgorithmQT.getDefaults FeatureGroupingAlgorithmQT.getName FeatureGroupingAlgorithmQT.getParameters FeatureGroupingAlgorithmQT.setName FeatureGroupingAlgorithmQT.setParameters FeatureGroupingAlgorithmQT.transferSubelements FeatureGroupingAlgorithmQT.__init__ FeatureGroupingAlgorithmQT.getDefaults FeatureGroupingAlgorithmQT.getName FeatureGroupingAlgorithmQT.getParameters FeatureGroupingAlgorithmQT.group FeatureGroupingAlgorithmQT.setName FeatureGroupingAlgorithmQT.setParameters FeatureGroupingAlgorithmQT.transferSubelements """ assert pyopenms.FeatureGroupingAlgorithmQT.getDefaults is not None assert pyopenms.FeatureGroupingAlgorithmQT.getName is not None assert pyopenms.FeatureGroupingAlgorithmQT.getParameters is not None assert pyopenms.FeatureGroupingAlgorithmQT.setName is not None assert pyopenms.FeatureGroupingAlgorithmQT.setParameters is not None assert pyopenms.FeatureGroupingAlgorithmQT.transferSubelements is not None qt = pyopenms.FeatureGroupingAlgorithmQT() qt.getDefaults() qt.getParameters() qt.getName() assert qt.group is not None assert qt.setName is not None assert qt.setParameters is not None assert qt.transferSubelements is not None @report def testFeatureMap(): """ @tests: FeatureMap FeatureMap.__init__ FeatureMap.__add__ FeatureMap.__iadd__ FeatureMap.__radd__ FeatureMap.__getitem__ FeatureMap.__iter__ FeatureMap.__len__ FeatureMap.append FeatureMap.clear FeatureMap.clearUniqueId FeatureMap.ensureUniqueId FeatureMap.extend FeatureMap.getDataProcessing FeatureMap.getProteinIdentifications FeatureMap.getUnassignedPeptideIdentifications FeatureMap.getUniqueId FeatureMap.setUniqueId FeatureMap.hasInvalidUniqueId FeatureMap.hasValidUniqueId FeatureMap.push_back FeatureMap.setDataProcessing FeatureMap.setProteinIdentifications FeatureMap.setUnassignedPeptideIdentifications FeatureMap.setUniqueIds FeatureMap.size FeatureMap.sortByIntensity FeatureMap.sortByMZ FeatureMap.sortByOverallQuality FeatureMap.sortByPosition FeatureMap.sortByRT FeatureMap.swap FeatureMap.updateRanges """ fm = pyopenms.FeatureMap() fm_ = copy.copy(fm) assert fm_ == fm fm_ = copy.deepcopy(fm) assert fm_ == fm fm_ = pyopenms.FeatureMap(fm) assert fm_ == fm _testUniqueIdInterface(fm) fm.clear() fm.clearUniqueId() fm.getIdentifier() fm.getLoadedFileType() fm.getLoadedFilePath() f = pyopenms.Feature() fm.push_back(f) assert len(list(fm)) == 1 assert fm.size() == 1 assert fm[0] == f fm.sortByIntensity() assert fm.size() == 1 assert fm[0] == f fm.sortByIntensity(False) assert fm.size() == 1 assert fm[0] == f fm.sortByPosition() assert fm.size() == 1 assert fm[0] == f fm.sortByRT() assert fm.size() == 1 assert fm[0] == f fm.sortByMZ() assert fm.size() == 1 assert fm[0] == f fm.sortByOverallQuality() assert fm.size() == 1 assert fm[0] == f fm2 = pyopenms.FeatureMap() fm.swap(fm2) assert fm2.size() == 1 assert fm2[0] == f assert fm.size() == 0 fm2.updateRanges() assert isinstance(fm2.getMinRT(), float) assert isinstance(fm2.getMinRT(), float) assert isinstance(fm2.getMaxMZ(), float) assert isinstance(fm2.getMaxMZ(), float) assert isinstance(fm2.getMinIntensity(), float) assert isinstance(fm2.getMaxIntensity(), float) assert fm2.getProteinIdentifications() == [] fm2.setProteinIdentifications([]) assert fm2.getUnassignedPeptideIdentifications().empty() fm2.setUnassignedPeptideIdentifications(pyopenms.PeptideIdentificationList()) fm2.clear() assert fm2.size() == 0 dp = pyopenms.DataProcessing() fm2.setDataProcessing([dp]) assert fm2.getDataProcessing() == [dp] testDataProcessing(dp) fm2.setUniqueIds() fm += fm assert fm + fm2 != fm # Test __repr__ and __str__ methods fm_repr = pyopenms.FeatureMap() f1 = pyopenms.Feature() f1.setRT(100.0) f1.setMZ(500.0) f1.setIntensity(1000.0) f2 = pyopenms.Feature() f2.setRT(200.0) f2.setMZ(600.0) f2.setIntensity(2000.0) fm_repr.push_back(f1) fm_repr.push_back(f2) repr_str = repr(fm_repr) assert "FeatureMap(" in repr_str assert "num_features=" in repr_str # Test __len__, append, and extend methods fm_len = pyopenms.FeatureMap() assert len(fm_len) == 0 assert len(fm_len) == fm_len.size() f_test1 = pyopenms.Feature() f_test1.setRT(100.0) f_test1.setMZ(500.0) f_test2 = pyopenms.Feature() f_test2.setRT(200.0) f_test2.setMZ(600.0) f_test3 = pyopenms.Feature() f_test3.setRT(300.0) f_test3.setMZ(700.0) # Test append (single item) fm_len.append(f_test1) assert len(fm_len) == 1 assert len(fm_len) == fm_len.size() # Test extend with list fm_len.extend([f_test2, f_test3]) assert len(fm_len) == 3 assert len(fm_len) == fm_len.size() # Verify the features were added correctly assert fm_len[0].getRT() == 100.0 assert fm_len[1].getRT() == 200.0 assert fm_len[2].getRT() == 300.0 # Test extend with another FeatureMap fm_source = pyopenms.FeatureMap() f_test4 = pyopenms.Feature() f_test4.setRT(400.0) f_test4.setMZ(800.0) fm_source.push_back(f_test4) fm_len.extend(fm_source) assert len(fm_len) == 4 assert fm_len[3].getRT() == 400.0 @report def testFeatureXMLFile(): """ @tests: FeatureXMLFile FeatureXMLFile.__init__ FeatureXMLFile.load FeatureXMLFile.store FeatureXMLFile.getOptions FeatureXMLFile.setOptions FeatureXMLFile.loadSize FileHandler.__init__ FileHandler.loadFeature """ fm = pyopenms.FeatureMap() fm.setUniqueIds() f = pyopenms.Feature() f.setMZ(200) f.setCharge(1) f.setRT(10) f.setIntensity(10000) f.setOverallQuality(10) ch = pyopenms.ConvexHull2D() ch.setHullPoints(np.asarray([[8,199],[12,201]], dtype='f')) f.setConvexHulls([ch]) f.setMetaValue(b'mv1', 1) f.setMetaValue(b'mv2', 2) f.setMetaValue('spectrum_native_id', 'spectrum=123') pep_id = pyopenms.PeptideIdentification() pep_id.insertHit(pyopenms.PeptideHit()) peplist = pyopenms.PeptideIdentificationList() peplist.push_back(pep_id) f.setPeptideIdentifications(peplist) fm.push_back(f) f.setMetaValue('spectrum_native_id', 'spectrum=124') fm.push_back(f) assert fm.get_assigned_peptide_identifications().size() == 2 assert fm.get_df(meta_values='all').shape == (2, 16) assert fm.get_df(meta_values='all', export_peptide_identifications=False).shape == (2, 12) assert pd.merge(fm.get_df(), pyopenms.peptide_identifications_to_df(fm.get_assigned_peptide_identifications()), on = ['feature_id', 'ID_native_id', 'ID_filename']).shape == (2,24) fm = pyopenms.FeatureMap() pyopenms.FeatureXMLFile().load(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1_idmapped.featureXML'), fm) assert pd.merge(fm.get_df(), pyopenms.peptide_identifications_to_df(fm.get_assigned_peptide_identifications()), on = ['feature_id', 'ID_native_id', 'ID_filename']).shape == (15,26) fh = pyopenms.FeatureXMLFile() fh.store("test.featureXML", fm) fh.load("test.featureXML", fm) fh = pyopenms.FileHandler() fh.loadFeatures("test.featureXML", fm) @report def testFileDescription(): """ @tests: ColumnHeader ColumnHeader.__init__ ColumnHeader.filename ColumnHeader.label ColumnHeader.size ColumnHeader.unique_id """ fd = pyopenms.ColumnHeader() _testStrOutput(fd.filename) _testStrOutput(fd.label) assert isinstance(fd.size, int) # assert isinstance(fd.unique_id, (long, int, bytes)) @report def testFileHandler(): """ @tests: FileHandler FileHandler.__init__ FileHandler.getType FileHandler.loadExperiment FileHandler.storeExperiment """ mse = pyopenms.MSExperiment() fh = pyopenms.FileHandler() fh.storeExperiment("test1.mzML", mse) fh.loadExperiment("test1.mzML", mse) fh.storeExperiment("test1.mzXML", mse) fh.loadExperiment("test1.mzXML", mse) fh.storeExperiment("test1.mzData", mse) fh.loadExperiment("test1.mzData", mse) @report def testCachedMzML(): """ """ mse = pyopenms.MSExperiment() s = pyopenms.MSSpectrum() mse.addSpectrum(s) # First load data and cache to disk pyopenms.CachedmzML.store("myCache.mzML", mse) # Now load data cfile = pyopenms.CachedmzML() pyopenms.CachedmzML.load("myCache.mzML", cfile) meta_data = cfile.getMetaData() assert cfile.getNrChromatograms() ==0 assert cfile.getNrSpectra() == 1 @report def testIndexedMzMLFile(): """ """ mse = pyopenms.MSExperiment() s = pyopenms.MSSpectrum() mse.addSpectrum(s) # First load data and cache to disk pyopenms.MzMLFile().store("tfile_idx.mzML", mse) # Now load data ih = pyopenms.IndexedMzMLHandler("tfile_idx.mzML") assert ih.getNrChromatograms() ==0 assert ih.getNrSpectra() == 1 s = ih.getMSSpectrumById(0) s2 = ih.getSpectrumById(0) @report def testIDMapper(): """ @tests: IDMapper IDMapper.__init__ IDMapper.annotate IDMapper.getDefaults IDMapper.getName IDMapper.getParameters IDMapper.setName IDMapper.setParameters """ idm = pyopenms.IDMapper() assert idm.annotate is not None idm.getDefaults() idm.setName("x") assert idm.getName() == "x" idm.setParameters(idm.getParameters()) @report def testIdXMLFile(): """ @tests: IdXMLFile IdXMLFile.__init__ IdXMLFile.load IdXMLFile.store """ assert pyopenms.IdXMLFile().load is not None assert pyopenms.IdXMLFile().store is not None @report def test_peptide_identifications_to_df(): # convert to dataframe peps = pyopenms.PeptideIdentificationList() p = pyopenms.PeptideIdentification() p.setRT(1243.56) p.setMZ(440.0) p.setScoreType("ScoreType") p.setHigherScoreBetter(False) p.setIdentifier("IdentificationRun1") h = pyopenms.PeptideHit() h.setScore(1.0) h.setCharge(2) h.setMetaValue("StringMetaValue", "Value") h.setMetaValue("IntMetaValue", 2) e1 = pyopenms.PeptideEvidence() e1.setProteinAccession("sp|Accession1") e1.setStart(123) e1.setEnd(141) e2 = pyopenms.PeptideEvidence() e2.setProteinAccession("sp|Accession2") e2.setStart(12) e2.setEnd(24) h.setPeptideEvidences([e1, e2]) p.insertHit(h) peps.push_back(p) p1 = pyopenms.PeptideIdentification() p1.setRT(1243.56) p1.setMZ(240.0) p1.setScoreType("ScoreType") p1.setHigherScoreBetter(False) p1.setIdentifier("IdentificationRun2") peps.push_back(p1) assert pyopenms.peptide_identifications_to_df(peps).shape == (2,12) assert pyopenms.peptide_identifications_to_df(peps, decode_ontology=False).shape == (2,12) assert pyopenms.peptide_identifications_to_df(peps)['protein_accession'][0] == 'sp|Accession1,sp|Accession2' assert pyopenms.peptide_identifications_to_df(peps, export_unidentified=False).shape == (1,12) # update from dataframe df = pyopenms.peptide_identifications_to_df(peps) df.loc[0, "ScoreType"] = 10.0 peps = pyopenms.update_scores_from_df(peps, df, "ScoreType") assert peps[0].getHits()[0].getScore() == 10.0 @report def testPepXMLFile(): """ @tests: PepXMLFile PepXMLFile.__init__ PepXMLFile.load PepXMLFile.store """ f = pyopenms.PepXMLFile() assert pyopenms.PepXMLFile().load is not None assert pyopenms.PepXMLFile().store is not None @report def testProtXMLFile(): """ @tests: ProtXMLFile ProtXMLFile.__init__ ProtXMLFile.load ProtXMLFile.store """ f = pyopenms.ProtXMLFile() assert pyopenms.ProtXMLFile().load is not None assert pyopenms.ProtXMLFile().store is not None @report def testDTA2DFile(): """ @tests: DTA2DFile DTA2DFile.__init__ DTA2DFile.load DTA2DFile.store """ f = pyopenms.DTA2DFile() assert pyopenms.DTA2DFile().load is not None assert pyopenms.DTA2DFile().store is not None @report def testDTAFile(): """ @tests: DTAFile DTAFile.__init__ DTAFile.load DTAFile.store """ f = pyopenms.DTAFile() assert pyopenms.DTAFile().load is not None assert pyopenms.DTAFile().store is not None @report def testEDTAFile(): """ @tests: EDTAFile EDTAFile.__init__ EDTAFile.load EDTAFile.store """ f = pyopenms.EDTAFile() assert pyopenms.EDTAFile().load is not None assert pyopenms.EDTAFile().store is not None @report def testKroenikFile(): """ @tests: KroenikFile KroenikFile.__init__ KroenikFile.load KroenikFile.store """ f = pyopenms.KroenikFile() assert pyopenms.KroenikFile().load is not None assert pyopenms.KroenikFile().store is not None @report def testMSPFile(): """ @tests: MSPFile MSPFile.__init__ """ f = pyopenms.MSPFile() # assert pyopenms.KroenikFile().load is not None # assert pyopenms.KroenikFile().store is not None @report def testMzIdentMLFile(): """ @tests: MzIdentMLFile MzIdentMLFile.__init__ """ f = pyopenms.MzIdentMLFile() assert pyopenms.MzIdentMLFile().load is not None assert pyopenms.MzIdentMLFile().store is not None assert pyopenms.MzIdentMLFile().isSemanticallyValid is not None @report def testMzTabFile(): """ @tests: MzTabFile MzTabFile.__init__ """ f = pyopenms.MzTabFile() # assert pyopenms.MzTabFile().store is not None @report def testMzTab(): """ @tests: MzTab MzTab.__init__ """ # f = pyopenms.MzTab() @report def testInstrumentSettings(): """ @tests: InstrumentSettings InstrumentSettings.__init__ InstrumentSettings.clearMetaInfo InstrumentSettings.getKeys InstrumentSettings.getMetaValue InstrumentSettings.getPolarity InstrumentSettings.isMetaEmpty InstrumentSettings.metaValueExists InstrumentSettings.removeMetaValue InstrumentSettings.setMetaValue InstrumentSettings.setPolarity InstrumentSettings.__eq__ InstrumentSettings.__ge__ InstrumentSettings.__gt__ InstrumentSettings.__le__ InstrumentSettings.__lt__ InstrumentSettings.__ne__ """ ins = pyopenms.InstrumentSettings() _testMetaInfoInterface(ins) ins.setPolarity(pyopenms.IonSource.Polarity.NEGATIVE) assert ins.getPolarity() == pyopenms.IonSource.Polarity.NEGATIVE assert ins == ins assert not ins != ins # Test getAllNamesOf method scan_mode_names = pyopenms.InstrumentSettings.getAllNamesOfScanMode() assert len(scan_mode_names) == pyopenms.InstrumentSettings.ScanMode.SIZE_OF_SCANMODE assert scan_mode_names[pyopenms.InstrumentSettings.ScanMode.MS1SPECTRUM].decode() == "MS1Spectrum" @report def testContactPerson(): """ @tests: ContactPerson ContactPerson.__init__ ContactPerson.getFirstName ContactPerson.setFirstName ContactPerson.getLastName ContactPerson.setLastName ContactPerson.setName ContactPerson.getInstitution ContactPerson.setInstitution ContactPerson.getEmail ContactPerson.setEmail ContactPerson.getURL ContactPerson.setURL ContactPerson.getAddress ContactPerson.setAddress ContactPerson.getContactInfo ContactPerson.setContactInfo """ ins = pyopenms.ContactPerson() ins.getFirstName() ins.setFirstName("test") ins.getLastName() ins.setLastName("test") ins.setName("Testy Test") ins.getInstitution() ins.setInstitution("test") ins.getEmail() ins.setEmail("test") ins.getURL() ins.setURL("test") ins.getAddress() ins.setAddress("test") ins.getContactInfo() ins.setContactInfo("test") @report def testDocumentIdentifier(): """ @tests: DocumentIdentifier DocumentIdentifier.__init__ DocumentIdentifier.setIdentifier DocumentIdentifier.getIdentifier DocumentIdentifier.setLoadedFilePath DocumentIdentifier.getLoadedFilePath DocumentIdentifier.setLoadedFileType DocumentIdentifier.getLoadedFileType """ ins = pyopenms.DocumentIdentifier() ins.setIdentifier("test") ins.getIdentifier() # ins.setLoadedFilePath("Test") ins.getLoadedFilePath() # ins.setLoadedFileType("test") ins.getLoadedFileType() @report def testGradient(): """ @tests: Gradient Gradient.__init__ Gradient.addEluent Gradient.addEluent Gradient.clearEluents Gradient.getEluents Gradient.addTimepoint Gradient.clearTimepoints Gradient.getTimepoints Gradient.getPercentage Gradient.setPercentage Gradient.clearPercentages Gradient.isValid """ ins = pyopenms.Gradient() ins.addEluent("test") ins.clearEluents() assert len(ins.getEluents() ) == 0 ins.addEluent("test") assert len(ins.getEluents() ) == 1 ins.clearTimepoints() ins.addTimepoint(5) ins.getTimepoints() ins.setPercentage("test", 5, 20) ins.getPercentage("test", 5) ins.clearPercentages() ins.isValid() @report def testHPLC(): """ @tests: HPLC HPLC.__init__ HPLC.getInstrument HPLC.setInstrument HPLC.getColumn HPLC.setColumn HPLC.getTemperature HPLC.setTemperature HPLC.getPressure HPLC.setPressure HPLC.getFlux HPLC.setFlux HPLC.setComment HPLC.getComment HPLC.setGradient HPLC.getGradient """ ins = pyopenms.HPLC() ins.setInstrument("test") ins.getInstrument() ins.setColumn("test") ins.getColumn() ins.setTemperature(6) ins.getTemperature() ins.setPressure(6) ins.getPressure() ins.setFlux(8) ins.getFlux() ins.setComment("test") ins.getComment() g = pyopenms.Gradient() ins.setGradient(g) ins.getGradient() @report def testInstrument(): """ @tests: Instrument Instrument.__init__ Instrument.setName Instrument.getName Instrument.setVendor Instrument.getVendor Instrument.setModel Instrument.getModel Instrument.setCustomizations Instrument.getCustomizations Instrument.setIonSources Instrument.getIonSources Instrument.setMassAnalyzers Instrument.getMassAnalyzers Instrument.setIonDetectors Instrument.getIonDetectors Instrument.setSoftware Instrument.getSoftware """ ins = pyopenms.Instrument() ins.setName("test") ins.getName() ins.setVendor("test") ins.getVendor() ins.setModel("test") ins.getModel() ins.setCustomizations("test") ins.getCustomizations() ion_sources = [ pyopenms.IonSource() for i in range(5)] ins.setIonSources(ion_sources) ins.getIonSources() mass_analyzers = [ pyopenms.MassAnalyzer() for i in range(5)] ins.setMassAnalyzers(mass_analyzers) ins.getMassAnalyzers() ion_detectors = [ pyopenms.IonDetector() for i in range(5)] ins.setIonDetectors(ion_detectors) ins.getIonDetectors() s = pyopenms.Software() ins.setSoftware(s) ins.getSoftware() # Test getAllNamesOf method ion_optics_names = pyopenms.Instrument.getAllNamesOfIonOpticsType() assert len(ion_optics_names) == pyopenms.Instrument.IonOpticsType.SIZE_OF_IONOPTICSTYPE assert ion_optics_names[pyopenms.Instrument.IonOpticsType.REFLECTRON].decode() == "reflectron" @report def testIonDetector(): """ @tests: IonDetector IonDetector.__init__ IonDetector.setAcquisitionMode IonDetector.getAcquisitionMode IonDetector.setResolution IonDetector.getResolution IonDetector.setADCSamplingFrequency IonDetector.getADCSamplingFrequency IonDetector.setOrder IonDetector.getOrder IonDetector.getAllNamesOfType IonDetector.getAllNamesOfAcquisitionMode """ ins = pyopenms.IonDetector() m = pyopenms.IonDetector.AcquisitionMode.ACQMODENULL ins.setAcquisitionMode(m) ins.getAcquisitionMode() ins.setResolution(8.0) ins.getResolution() ins.setADCSamplingFrequency(8.0) ins.getADCSamplingFrequency() ins.setOrder(8) ins.getOrder() # Test getAllNamesOf methods type_names = pyopenms.IonDetector.getAllNamesOfType() assert len(type_names) == pyopenms.IonDetector.Type.SIZE_OF_TYPE assert type_names[pyopenms.IonDetector.Type.ELECTRONMULTIPLIER].decode() == "Electron multiplier" acq_mode_names = pyopenms.IonDetector.getAllNamesOfAcquisitionMode() assert len(acq_mode_names) == pyopenms.IonDetector.AcquisitionMode.SIZE_OF_ACQUISITIONMODE assert acq_mode_names[pyopenms.IonDetector.AcquisitionMode.PULSECOUNTING].decode() == "Pulse counting" @report def testIonSource(): """ @tests: IonSource IonSource.__init__ IonSource.setPolarity IonSource.getPolarity IonSource.setInletType IonSource.getInletType IonSource.setIonizationMethod IonSource.getIonizationMethod IonSource.setOrder IonSource.getOrder IonSource.getAllNamesOfInletType IonSource.getAllNamesOfIonizationMethod IonSource.getAllNamesOfPolarity """ ins = pyopenms.IonSource() p = pyopenms.IonSource.Polarity.POSITIVE ins.setPolarity(p) ins.getPolarity() i = pyopenms.IonSource.InletType.INLETNULL ins.setInletType(i) ins.getInletType() i = pyopenms.IonSource.IonizationMethod.ESI ins.setIonizationMethod(i) ins.getIonizationMethod() ins.setOrder(5) ins.getOrder() # Test getAllNamesOf methods inlet_names = pyopenms.IonSource.getAllNamesOfInletType() assert len(inlet_names) == pyopenms.IonSource.InletType.SIZE_OF_INLETTYPE assert inlet_names[pyopenms.IonSource.InletType.INLETNULL].decode() == "Unknown" assert inlet_names[pyopenms.IonSource.InletType.DIRECT].decode() == "Direct" assert inlet_names[pyopenms.IonSource.InletType.NANOSPRAY].decode() == "Nanospray inlet" ionization_names = pyopenms.IonSource.getAllNamesOfIonizationMethod() assert len(ionization_names) == pyopenms.IonSource.IonizationMethod.SIZE_OF_IONIZATIONMETHOD assert ionization_names[pyopenms.IonSource.IonizationMethod.IONMETHODNULL].decode() == "Unknown" assert ionization_names[pyopenms.IonSource.IonizationMethod.ESI].decode() == "Electrospray ionisation" assert ionization_names[pyopenms.IonSource.IonizationMethod.MALDI].decode() == "Matrix-assisted laser desorption ionization" polarity_names = pyopenms.IonSource.getAllNamesOfPolarity() assert len(polarity_names) == pyopenms.IonSource.Polarity.SIZE_OF_POLARITY assert polarity_names[pyopenms.IonSource.Polarity.POLNULL].decode() == "unknown" assert polarity_names[pyopenms.IonSource.Polarity.POSITIVE].decode() == "positive" assert polarity_names[pyopenms.IonSource.Polarity.NEGATIVE].decode() == "negative" @report def testMassAnalyzer(): """ @tests: MassAnalyzer MassAnalyzer.__init__ MassAnalyzer.setType MassAnalyzer.getType MassAnalyzer.setResolutionMethod MassAnalyzer.getResolutionMethod MassAnalyzer.setResolutionType MassAnalyzer.getResolutionType MassAnalyzer.setScanDirection MassAnalyzer.getScanDirection MassAnalyzer.setScanLaw MassAnalyzer.getScanLaw MassAnalyzer.setReflectronState MassAnalyzer.getReflectronState MassAnalyzer.setResolution MassAnalyzer.getResolution MassAnalyzer.setAccuracy MassAnalyzer.getAccuracy MassAnalyzer.setScanRate MassAnalyzer.getScanRate MassAnalyzer.setScanTime MassAnalyzer.getScanTime MassAnalyzer.setTOFTotalPathLength MassAnalyzer.getTOFTotalPathLength MassAnalyzer.setIsolationWidth MassAnalyzer.getIsolationWidth MassAnalyzer.setFinalMSExponent MassAnalyzer.getFinalMSExponent MassAnalyzer.setMagneticFieldStrength MassAnalyzer.getMagneticFieldStrength MassAnalyzer.setOrder MassAnalyzer.getOrder MassAnalyzer.getAllNamesOfAnalyzerType MassAnalyzer.getAllNamesOfResolutionMethod MassAnalyzer.getAllNamesOfResolutionType MassAnalyzer.getAllNamesOfScanDirection MassAnalyzer.getAllNamesOfScanLaw MassAnalyzer.getAllNamesOfReflectronState """ ins = pyopenms.MassAnalyzer() ma = pyopenms.MassAnalyzer.AnalyzerType.QUADRUPOLE ins.setType(ma) ins.getType() res = pyopenms.MassAnalyzer.ResolutionMethod.FWHM ins.setResolutionMethod(res) ins.getResolutionMethod() res = pyopenms.MassAnalyzer.ResolutionType.CONSTANT ins.setResolutionType(res) ins.getResolutionType() res = pyopenms.MassAnalyzer.ScanDirection.UP ins.setScanDirection(res) ins.getScanDirection() res = pyopenms.MassAnalyzer.ScanLaw.LINEAR ins.setScanLaw(res) ins.getScanLaw() res = pyopenms.MassAnalyzer.ReflectronState.ON ins.setReflectronState(res) ins.getReflectronState() ins.setResolution(5.0) ins.getResolution() ins.setAccuracy(5.0) ins.getAccuracy() ins.setScanRate(5.0) ins.getScanRate() ins.setScanTime(5.0) ins.getScanTime() ins.setTOFTotalPathLength(5.0) ins.getTOFTotalPathLength() ins.setIsolationWidth(5.0) ins.getIsolationWidth() ins.setFinalMSExponent(5) ins.getFinalMSExponent() ins.setMagneticFieldStrength(5.0) ins.getMagneticFieldStrength() ins.setOrder(5) ins.getOrder() # Test getAllNamesOf methods analyzer_names = pyopenms.MassAnalyzer.getAllNamesOfAnalyzerType() assert len(analyzer_names) == pyopenms.MassAnalyzer.AnalyzerType.SIZE_OF_ANALYZERTYPE assert analyzer_names[pyopenms.MassAnalyzer.AnalyzerType.QUADRUPOLE].decode() == "Quadrupole" assert analyzer_names[pyopenms.MassAnalyzer.AnalyzerType.ORBITRAP].decode() == "Orbitrap" res_method_names = pyopenms.MassAnalyzer.getAllNamesOfResolutionMethod() assert len(res_method_names) == pyopenms.MassAnalyzer.ResolutionMethod.SIZE_OF_RESOLUTIONMETHOD assert res_method_names[pyopenms.MassAnalyzer.ResolutionMethod.FWHM].decode() == "Full width at half max" res_type_names = pyopenms.MassAnalyzer.getAllNamesOfResolutionType() assert len(res_type_names) == pyopenms.MassAnalyzer.ResolutionType.SIZE_OF_RESOLUTIONTYPE assert res_type_names[pyopenms.MassAnalyzer.ResolutionType.CONSTANT].decode() == "Constant" scan_dir_names = pyopenms.MassAnalyzer.getAllNamesOfScanDirection() assert len(scan_dir_names) == pyopenms.MassAnalyzer.ScanDirection.SIZE_OF_SCANDIRECTION assert scan_dir_names[pyopenms.MassAnalyzer.ScanDirection.UP].decode() == "Up" scan_law_names = pyopenms.MassAnalyzer.getAllNamesOfScanLaw() assert len(scan_law_names) == pyopenms.MassAnalyzer.ScanLaw.SIZE_OF_SCANLAW assert scan_law_names[pyopenms.MassAnalyzer.ScanLaw.LINEAR].decode() == "Linar" # Note: typo in source reflectron_names = pyopenms.MassAnalyzer.getAllNamesOfReflectronState() assert len(reflectron_names) == pyopenms.MassAnalyzer.ReflectronState.SIZE_OF_REFLECTRONSTATE assert reflectron_names[pyopenms.MassAnalyzer.ReflectronState.ON].decode() == "On" @report def testSample(): """ @tests: Sample Sample.__init__ Sample.setName Sample.getName Sample.setOrganism Sample.getOrganism Sample.setNumber Sample.getNumber Sample.setComment Sample.getComment Sample.setState Sample.getState Sample.setMass Sample.getMass Sample.setVolume Sample.getVolume Sample.setConcentration Sample.getConcentration Sample.getSubsamples Sample.setSubsamples """ ins = pyopenms.Sample() ins.setName("test") ins.getName() ins.setOrganism("test") ins.getOrganism() ins.setNumber("test") ins.getNumber() ins.setComment("test") ins.getComment() state = pyopenms.Sample.SampleState.LIQUID ins.setState(state) ins.getState() ins.setMass(42.0) ins.getMass() ins.setVolume(42.0) ins.getVolume() ins.setConcentration(42.0) ins.getConcentration() a = ins.getSubsamples() ins.setSubsamples(a) has_exception = False try: ins.removeTreatment(0) except Exception: has_exception = True assert has_exception # Test getAllNamesOf method state_names = pyopenms.Sample.getAllNamesOfSampleState() assert len(state_names) == pyopenms.Sample.SampleState.SIZE_OF_SAMPLESTATE assert state_names[pyopenms.Sample.SampleState.LIQUID].decode() == "liquid" assert state_names[pyopenms.Sample.SampleState.SOLID].decode() == "solid" @report def testLogType(): """ @tests: LogType LogType.CMD LogType.GUI LogType.NONE """ assert isinstance(pyopenms.LogType.CMD, int) assert isinstance(pyopenms.LogType.GUI, int) assert isinstance(pyopenms.LogType.NONE, int) # performance measurement helper for XIC and peak extraction import time import random from typing import Tuple, List def generate_random_ranges(exp: pyopenms.MSExperiment, n_ranges: int, rt_width: float, mz_width: float) -> np.ndarray: """ Generate random ranges within the experiment bounds. Args: exp: MSExperiment object n_ranges: Number of ranges to generate rt_width: Width of RT window mz_width: Width of m/z window Returns: numpy array of shape (n_ranges, 4) with [mz_min, mz_max, rt_min, rt_max] """ # Set the seed np.random.seed(4711) min_mz = exp.getMinMZ() max_mz = exp.getMaxMZ() min_rt = exp.getMinRT() max_rt = exp.getMaxRT() print(f"spectra min_mz: {min_mz}, max_mz: {max_mz}, min_rt: {min_rt}, max_rt: {max_rt}") # Generate random centers mz_centers = np.random.uniform(min_mz + mz_width/2, max_mz - mz_width/2, n_ranges) rt_centers = np.random.uniform(min_rt + rt_width/2, max_rt - rt_width/2, n_ranges) # Create ranges array ranges = np.zeros((n_ranges, 4)) ranges[:, 0] = mz_centers - mz_width/2 # mz_min ranges[:, 1] = mz_centers + mz_width/2 # mz_max ranges[:, 2] = rt_centers - rt_width/2 # rt_min ranges[:, 3] = rt_centers + rt_width/2 # rt_max return ranges def extraction_performance_test(exp: pyopenms.MSExperiment, ms_level: int) -> Tuple[float, float]: """ Run performance test for both aggregateFromMatrix and extractXICsFromMatrix Args: exp: MSExperiment object Returns: Tuple of (aggregate_time, xic_time) """ # Generate 1_000,000 random ranges print("\nGenerating random ranges...") ranges = generate_random_ranges(exp, n_ranges=1_000_000, rt_width=60.0, mz_width=0.01) # Convert to MatrixDouble ranges_matrix = pyopenms.MatrixDouble.fromNdArray(ranges) # Time aggregateFromMatrix print("Running aggregateFromMatrix...") start_time = time.time() _ = exp.aggregateFromMatrix(ranges_matrix, ms_level, b"sum") aggregate_time = time.time() - start_time # Time extractXICsFromMatrix print("Running extractXICsFromMatrix...") start_time = time.time() _ = exp.extractXICsFromMatrix(ranges_matrix, ms_level, b"sum") xic_time = time.time() - start_time return aggregate_time, xic_time @report def testMSExperiment(): """ @tests: MSExperiment MSExperiment.__init__ MSExperiment.getLoadedFilePath MSExperiment.getMaxMZ MSExperiment.getMaxRT MSExperiment.getMetaValue MSExperiment.getMinMZ MSExperiment.getMinRT MSExperiment.push_back MSExperiment.setLoadedFilePath MSExperiment.setMetaValue MSExperiment.size MSExperiment.sortSpectra MSExperiment.updateRanges MSExperiment.__eq__ MSExperiment.__ge__ MSExperiment.__getitem__ MSExperiment.__gt__ MSExperiment.__iter__ MSExperiment.__le__ MSExperiment.__lt__ MSExperiment.__ne__ MSExperiment.clearMetaInfo MSExperiment.getKeys MSExperiment.isMetaEmpty MSExperiment.metaValueExists MSExperiment.removeMetaValue MSExperiment.getSize MSExperiment.isSorted MSExperiment.get2DPeakDataLong MSExperiment.get_df MSExperiment.get_massql_df """ mse = pyopenms.MSExperiment() mse_ = copy.copy(mse) assert mse_ == mse mse_ = copy.deepcopy(mse) assert mse_ == mse mse_ = pyopenms.MSExperiment(mse) assert mse_ == mse _testMetaInfoInterface(mse) mse.setLoadedFilePath("") assert mse.size() == 0 mse.getIdentifier() mse.getLoadedFileType() mse.getLoadedFilePath() # We need to add a feature to the map before updateRanges otherwise the getMin and getMax throw an error. spec = pyopenms.MSSpectrum() data_mz = np.array( [5.0, 8.0] ).astype(np.float64) data_i = np.array( [50.0, 80.0] ).astype(np.float32) spec.set_peaks( [data_mz,data_i] ) mse.addSpectrum(spec) assert mse.size() == 1 mse.updateRanges() mse.sortSpectra(True) assert isinstance(mse.getMaxRT(), float) assert isinstance(mse.getMinRT(), float) assert isinstance(mse.getMaxMZ(), float) assert isinstance(mse.getMinMZ(), float) _testStrOutput(mse.getLoadedFilePath()) assert isinstance(mse.getMinIntensity(), float) assert isinstance(mse.getMaxIntensity(), float) assert mse[0] is not None mse.updateRanges() rt, mz, inty = mse.get2DPeakDataLong(mse.getMinRT(), mse.getMaxRT(), mse.getMinMZ(), mse.getMaxMZ(), 1) assert rt.shape[0] == 2 assert mz.shape[0] == 2 assert inty.shape[0] == 2 assert isinstance(list(mse), list) assert mse == mse assert not mse != mse assert mse.getSize() >= 0 assert int(mse.isSorted()) in (0,1) mse2 = copy.copy(mse) assert mse.getSize() == mse2.getSize() assert mse2 == mse exp = pyopenms.MSExperiment() for i in range(5): s = pyopenms.MSSpectrum() s.setRT(i) s.setMSLevel(1 if i % 2 == 0 else 2) for mz in (500, 600): p = pyopenms.Peak1D() p.setMZ(mz + i) p.setIntensity(i + 10) s.push_back(p) exp.addSpectrum(s) assert exp.get_df().shape == (5, 4) assert exp.get_df(ms_levels=[1]).shape == (3, 4) assert exp.get_df(ms_levels=[2]).shape == (2, 4) assert exp.get_df(long_format=True).shape == (10, 4) assert exp.get_df(long_format=True, ms_levels=[1]).shape == (6, 4) assert exp.get_df(long_format=True, ms_levels=[2]).shape == (4, 4) pyopenms.MzMLFile().load(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1.mzML'), exp) ms1_df, ms2_df = exp.get_massql_df() assert ms1_df.shape == (140055, 7) assert np.allclose(ms2_df.head(), pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1_MS2_MassQL.tsv'), sep='\t')) pyopenms.MzMLFile().load(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1_ION.mzML'), exp) df = exp.get_ion_df() assert np.allclose(df.head(), pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1_MS1_ION.tsv'), sep='\t')) ms1_df, ms2_df = exp.get_massql_df(ion_mobility=True) assert ms1_df.shape == (332620, 8) assert np.allclose(ms1_df.head(), pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1_MS1_MassQL_ION.tsv'), sep='\t')) ##################################################################################### # test fast aggregation and XIC extraction using ranges pyopenms.MzMLFile().load(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'BSA1_F1.mzML'), exp) exp.updateRanges() ############################################################################ # Uncomment to run performance tests # print("\nStarting performance tests MS1...") # aggregate_time, xic_time = extraction_performance_test(exp, 1) # Run performance tests on MS level 1 # print("\nPerformance Results:") # print(f"aggregateFromMatrix time for 1M ranges: {aggregate_time:.2f} seconds") # print(f"extractXICsFromMatrix time for 1M ranges: {xic_time:.2f} seconds") # print(f"Ratio (XIC/aggregate): {xic_time/aggregate_time:.2f}") # print("\nStarting performance tests MS2...") # aggregate_time, xic_time = extraction_performance_test(exp, 2) # Run performance tests on MS level 1 # print("\nPerformance Results:") # print(f"aggregateFromMatrix time for 1M ranges: {aggregate_time:.2f} seconds") # print(f"extractXICsFromMatrix time for 1M ranges: {xic_time:.2f} seconds") # print(f"Ratio (XIC/aggregate): {xic_time/aggregate_time:.2f}") # assert false # needed to output the results # eluting peptide feature at these coordinates rt_min = 1730.0 rt_max = 1770.0 iso1_mz = 443.711 # monoisotopic peak iso2_mz = 444.212 # first isotopic peak iso3_mz = 444.713 # second isotopic peak no_iso1_mz = 444.000 # no peaks in this area no_iso2_mz = 444.403 # some noise peaks in this area # Create ranges matrix with structure: # [[mz_min, mz_max, rt_min, rt_max], ...] ranges_matrix = pyopenms.MatrixDouble.fromNdArray( np.array([ # Expected isotope peaks [iso1_mz - 0.1, iso1_mz + 0.1, rt_min, rt_max], [iso2_mz - 0.1, iso2_mz + 0.1, rt_min, rt_max], [iso3_mz - 0.1, iso3_mz + 0.1, rt_min, rt_max], # Regions where we don't expect peaks [no_iso1_mz - 0.1, no_iso1_mz + 0.1, rt_min, rt_max], [no_iso2_mz - 0.1, no_iso2_mz + 0.1, rt_min, rt_max] ]) ) # Print ranges matrix for verification print("Ranges Matrix:") print (ranges_matrix.get_matrix()) agg_result = exp.aggregateFromMatrix(ranges_matrix, 1, b"sum") agg_result_array = np.array(agg_result) # Convert result to numpy array for easier testing print("\nAggregation Results:") print(agg_result) # Basic shape checks assert len(agg_result_array) == ranges_matrix.rows(), f"Expected {ranges_matrix.rows()} results, got {len(agg_result_array)}" # Check that regions with expected peaks have higher values isotope_intensities = agg_result_array[:3] # First three rows are isotope peaks no_peak_intensities = agg_result_array[3:] # Last two rows are regions without peaks print(isotope_intensities) print(no_peak_intensities) print("\nIsotope Peak Arrays and Their Sums:") isotope_sums = [] for i, intensity_array in enumerate(isotope_intensities): array_sum = np.sum(intensity_array) isotope_sums.append(array_sum) print(f"Isotope {i+1} array: {intensity_array}") print(f"Isotope {i+1} sum: {array_sum}") print("\nNo-Peak Region Arrays and Their Sums:") no_peak_sums = [] for i, intensity_array in enumerate(no_peak_intensities): array_sum = np.sum(intensity_array) no_peak_sums.append(array_sum) print(f"No-peak region {i+1} array: {intensity_array}") print(f"No-peak region {i+1} sum: {array_sum}") EXPECTED_ISO_SUMS = [24680058.50, 11043987.94, 3141677.76] EXPECTED_NO_PEAK_SUMS = [0.0, 12322.06] # Test each isotope array sum for i, (actual_sum, expected_sum) in enumerate(zip(isotope_sums, EXPECTED_ISO_SUMS)): assert np.isclose(actual_sum, expected_sum, rtol=1e-5), \ f"Expected isotope {i+1} sum {expected_sum}, got {actual_sum}" # Test each no-peak array sum for i, (actual_sum, expected_sum) in enumerate(zip(no_peak_sums, EXPECTED_NO_PEAK_SUMS)): assert np.isclose(actual_sum, expected_sum, rtol=1e-5), \ f"Expected no-peak region {i+1} sum {expected_sum}, got {actual_sum}" xic_result = exp.extractXICsFromMatrix(ranges_matrix, 1, b"sum") print("\nXIC Results:") for chrom in xic_result: print(f"m/z: {chrom.getProduct().getMZ()}") print(f"Size: {chrom.size()}") xic_details = [] for i, chrom in enumerate(xic_result): # Get basic XIC information mz = chrom.getProduct().getMZ() size = chrom.size() # Get intensity values from the chromatogram intensities = [point.getIntensity() for point in chrom] rt_values = [point.getRT() for point in chrom] total_intensity = sum(intensities) details = { 'mz': mz, 'size': size, 'total_intensity': total_intensity, 'rt_range': (min(rt_values), max(rt_values)) if rt_values else (None, None) } xic_details.append(details) print(f"\nXIC {i+1}:") print(f"m/z: {mz}") print(f"Number of points: {size}") print(f"Total intensity: {total_intensity}") print(f"RT range: {details['rt_range']}") # XIC expectations EXPECTED_XIC_SIZES = [24, 24, 24, 24, 24] # Expected number of points in each XIC EXPECTED_XIC_TOTAL_INTENSITIES = [24680058.50, 11043987.94, 3141677.76, 0.0, 12322.06] # Expected total intensity for each XIC # Test XIC results for i, (details, exp_size, exp_total) in enumerate(zip( xic_details, EXPECTED_XIC_SIZES, EXPECTED_XIC_TOTAL_INTENSITIES)): assert details['size'] == exp_size, \ f"XIC {i+1}: Expected {exp_size} points, got {details['size']}" assert np.isclose(details['total_intensity'], exp_total, rtol=1e-5), \ f"XIC {i+1}: Expected total intensity {exp_total}, got {details['total_intensity']}" # Verify RT range falls within expected bounds if details['rt_range'][0] is not None: assert rt_min <= details['rt_range'][0] <= rt_max, \ f"XIC {i+1}: Start RT {details['rt_range'][0]} outside expected range [{rt_min}, {rt_max}]" assert rt_min <= details['rt_range'][1] <= rt_max, \ f"XIC {i+1}: End RT {details['rt_range'][1]} outside expected range [{rt_min}, {rt_max}]" # Test __repr__ and __str__ methods for MSExperiment exp_repr = pyopenms.MSExperiment() s1 = pyopenms.MSSpectrum() s1.setRT(100.0) s1.setMSLevel(1) s1.set_peaks(([100.0, 200.0], [1000.0, 2000.0])) s2 = pyopenms.MSSpectrum() s2.setRT(200.0) s2.setMSLevel(2) s2.set_peaks(([150.0, 250.0], [500.0, 1500.0])) exp_repr.addSpectrum(s1) exp_repr.addSpectrum(s2) exp_repr.updateRanges() repr_str = repr(exp_repr) assert "MSExperiment(" in repr_str assert "num_spectra=" in repr_str assert "num_chromatograms=" in repr_str str_str = str(exp_repr) assert str_str == repr_str @report def testMSSpectrum(): """ @tests: MSSpectrum MSSpectrum.__init__ MSSpectrum.clear MSSpectrum.clearMetaInfo MSSpectrum.findNearest MSSpectrum.getAcquisitionInfo MSSpectrum.getComment MSSpectrum.getDataProcessing MSSpectrum.getInstrumentSettings MSSpectrum.getKeys MSSpectrum.getMSLevel MSSpectrum.getMetaValue MSSpectrum.getName MSSpectrum.getNativeID MSSpectrum.getPrecursors MSSpectrum.getProducts MSSpectrum.getRT MSSpectrum.getSourceFile MSSpectrum.getType MSSpectrum.get_peaks MSSpectrum.intensityInRange MSSpectrum.isMetaEmpty MSSpectrum.isSorted MSSpectrum.metaValueExists MSSpectrum.push_back MSSpectrum.removeMetaValue MSSpectrum.setAcquisitionInfo MSSpectrum.setComment MSSpectrum.setDataProcessing MSSpectrum.setInstrumentSettings MSSpectrum.setMSLevel MSSpectrum.setMetaValue MSSpectrum.setName MSSpectrum.setNativeID MSSpectrum.setPeptideIdentifications MSSpectrum.setPrecursors MSSpectrum.setProducts MSSpectrum.setRT MSSpectrum.setSourceFile MSSpectrum.setType MSSpectrum.set_peaks MSSpectrum.size MSSpectrum.unify MSSpectrum.updateRanges MSSpectrum.__eq__ MSSpectrum.__ge__ MSSpectrum.__getitem__ MSSpectrum.__gt__ MSSpectrum.__le__ MSSpectrum.__lt__ MSSpectrum.__ne__ """ spec = pyopenms.MSSpectrum() spec_ = copy.copy(spec) assert spec_ == spec spec_ = copy.deepcopy(spec) assert spec_ == spec spec_ = pyopenms.MSSpectrum(spec) assert spec_ == spec _testMetaInfoInterface(spec) testSpectrumSetting(spec) spec.setRT(3.0) assert spec.getRT() == 3.0 spec.setMSLevel(2) assert spec.getMSLevel() == 2 spec.setName("spec") assert spec.getName() == "spec" p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(200.0) spec.push_back(p) assert spec.size() == 1 assert spec[0] == p spec.updateRanges() assert isinstance(spec.findNearest(0.0), int) assert isinstance(spec.getMinMZ(), float) assert isinstance(spec.getMaxMZ(), float) assert isinstance(spec.getMinIntensity(), float) assert isinstance(spec.getMaxIntensity(), float) assert spec == spec assert not spec != spec mz, ii = spec.get_peaks() assert len(mz) == len(ii) assert len(mz) == 1 spec.set_peaks((mz, ii)) mz0, ii0 = spec.get_peaks() assert mz0 == mz assert ii0 == ii assert int(spec.isSorted()) in (0,1) spec.clear(False) p = pyopenms.Peak1D() p.setMZ(1000.0) p.setIntensity(200.0) spec.push_back(p) p = pyopenms.Peak1D() p.setMZ(2000.0) p.setIntensity(400.0) spec.push_back(p) mz, ii = spec.get_peaks() assert spec[0].getMZ() == 1000.0 assert spec[1].getMZ() == 2000.0 assert spec[0].getIntensity() == 200.0 assert spec[1].getIntensity() == 400.0 assert mz[0] == 1000.0 assert mz[1] == 2000.0 assert ii[0] == 200.0 assert ii[1] == 400.0 spec.setMSLevel(2) spec.setNativeID('scan=1') prec = pyopenms.Precursor() prec.setMZ(100.0) prec.setCharge(1) spec.setPrecursors([prec]) spec.setMetaValue('total ion current', 600) data = np.array( [5, 8] ).astype(np.float32) f_da = [ pyopenms.FloatDataArray() ] f_da[0].set_data(data) f_da[0].setName("Ion Mobility") spec.setFloatDataArrays( f_da ) spec.setDriftTimeUnit( pyopenms.DriftTimeUnit.MILLISECOND ) s_da = pyopenms.StringDataArray() for s in ['b3+', 'y4+']: s_da.push_back(s) s_da.setName("IonNames") spec.setStringDataArrays([s_da]) df = spec.get_df() assert df.shape == (2, 11) assert df.loc[0, 'mz'] == 1000.0 assert df.loc[0, 'intensity'] == 200.0 assert df.loc[0, 'ion_mobility'] == 5.0 assert df.loc[0, 'ion_mobility_unit'] == 'ms' assert df.loc[0, 'ms_level'] == 2 assert df.loc[0, 'precursor_mz'] == 100.0 assert df.loc[0, 'precursor_charge'] == 1 assert df.loc[0, 'native_id'] == 'scan=1' assert df.loc[0, 'ion_annotation'] == 'b3+' assert df.loc[0, 'total ion current'] == 600 spec.clear(False) data_mz = np.array( [5.0, 8.0] ).astype(np.float64) data_i = np.array( [50.0, 80.0] ).astype(np.float32) spec.set_peaks( [data_mz,data_i] ) mz, ii = spec.get_peaks() assert spec[0].getMZ() == 5.0 assert spec[1].getMZ() == 8.0 assert spec[0].getIntensity() == 50.0 assert spec[1].getIntensity() == 80.0 assert mz[0] == 5.0 assert mz[1] == 8.0 assert ii[0] == 50.0 assert ii[1] == 80.0 # Fast spec.clear(False) data_mz = np.array( [5.0, 8.0] ).astype(np.float64) data_i = np.array( [50.0, 80.0] ).astype(np.float64) spec.set_peaks( [data_mz,data_i] ) mz, ii = spec.get_peaks() assert spec[0].getMZ() == 5.0 assert spec[1].getMZ() == 8.0 assert spec[0].getIntensity() == 50.0 assert spec[1].getIntensity() == 80.0 assert mz[0] == 5.0 assert mz[1] == 8.0 assert ii[0] == 50.0 assert ii[1] == 80.0 # Slow spec.clear(False) data_mz = np.array( [5.0, 8.0] ).astype(np.float32) data_i = np.array( [50.0, 80.0] ).astype(np.float32) spec.set_peaks( [data_mz,data_i] ) mz, ii = spec.get_peaks() assert spec[0].getMZ() == 5.0 assert spec[1].getMZ() == 8.0 assert spec[0].getIntensity() == 50.0 assert spec[1].getIntensity() == 80.0 assert mz[0] == 5.0 assert mz[1] == 8.0 assert ii[0] == 50.0 assert ii[1] == 80.0 ################################### # get data arrays ################################### assert len(spec.getStringDataArrays()) == 0 string_da = [ pyopenms.StringDataArray() ] string_da[0].push_back("hello") string_da[0].push_back("world") string_da[0].setName("greetings") string_da.append( pyopenms.StringDataArray() ) string_da[1].push_back("other") spec.setStringDataArrays( string_da ) assert len(spec.getStringDataArrays()) == 2 assert spec.getStringDataArrays()[0][0] == b"hello" assert spec.getStringDataArrays()[1][0] == b"other" assert spec.getStringDataArrays()[0] == spec.getStringDataArrays()[0] # test __eq__ assert spec.getStringDataArrays()[0] != spec.getStringDataArrays()[1] # test __ne__ spec = pyopenms.MSSpectrum() assert len(spec.getIntegerDataArrays()) == 0 int_da = [ pyopenms.IntegerDataArray() ] int_da[0].push_back(5) int_da[0].push_back(6) int_da[0].setName("test") int_da.append( pyopenms.IntegerDataArray() ) int_da[1].push_back(8) spec.setIntegerDataArrays( int_da ) assert len(spec.getIntegerDataArrays()) == 2 assert spec.getIntegerDataArrays()[0][0] == 5 assert spec.getIntegerDataArrays()[1][0] == 8 assert spec.getIntegerDataArrays()[0] == spec.getIntegerDataArrays()[0] # test __eq__ assert spec.getIntegerDataArrays()[0] != spec.getIntegerDataArrays()[1] # test __ne__ spec = pyopenms.MSSpectrum() data = np.array( [5, 8, 42] ).astype(np.intc) int_da = [ pyopenms.IntegerDataArray() ] int_da[0].set_data(data) spec.setIntegerDataArrays( int_da ) assert len(spec.getIntegerDataArrays()) == 1 assert spec.getIntegerDataArrays()[0][0] == 5 assert spec.getIntegerDataArrays()[0][2] == 42 assert len(int_da[0].get_data() ) == 3 spec = pyopenms.MSSpectrum() assert len(spec.getFloatDataArrays()) == 0 f_da = [ pyopenms.FloatDataArray() ] f_da[0].push_back(5.0) f_da[0].push_back(6.0) f_da[0].setName("test") f_da.append( pyopenms.FloatDataArray() ) f_da[1].push_back(8.0) spec.setFloatDataArrays( f_da ) assert len(spec.getFloatDataArrays()) == 2.0 assert spec.getFloatDataArrays()[0][0] == 5.0 assert spec.getFloatDataArrays()[1][0] == 8.0 assert spec.getFloatDataArrays()[0] == spec.getFloatDataArrays()[0] # test __eq__ assert spec.getFloatDataArrays()[0] != spec.getFloatDataArrays()[1] # test __ne__ spec = pyopenms.MSSpectrum() data = np.array( [5, 8, 42] ).astype(np.float32) f_da = [ pyopenms.FloatDataArray() ] f_da[0].set_data(data) spec.setFloatDataArrays( f_da ) assert len(spec.getFloatDataArrays()) == 1 assert spec.getFloatDataArrays()[0][0] == 5.0 assert spec.getFloatDataArrays()[0][2] == 42.0 assert len(f_da[0].get_data() ) == 3 spec = pyopenms.MSSpectrum() dfunit = spec.getDriftTimeUnit() assert pyopenms.DriftTimeUnit().getMapping()[dfunit] == "NONE" assert dfunit == pyopenms.DriftTimeUnit.NONE assert spec.getDriftTimeUnitAsString() == '<NONE>' spec.setDriftTimeUnit( pyopenms.DriftTimeUnit.MILLISECOND ) dfunit = spec.getDriftTimeUnit() assert dfunit == pyopenms.DriftTimeUnit.MILLISECOND assert pyopenms.DriftTimeUnit().getMapping()[dfunit] == "MILLISECOND" assert spec.getDriftTimeUnitAsString() == 'ms' spec = pyopenms.MSSpectrum() spec.setDriftTime(6.0) assert spec.getDriftTime() == 6.0 spec = pyopenms.MSSpectrum() assert not spec.containsIMData() data = np.array( [5, 8, 42] ).astype(np.float32) f_da = [ pyopenms.FloatDataArray() ] f_da[0].set_data(data) f_da[0].setName("Ion Mobility") spec.setFloatDataArrays( f_da ) assert spec.containsIMData() assert spec.getIMData()[0] == 0 f_da = [ pyopenms.FloatDataArray(), pyopenms.FloatDataArray() ] f_da[0].setName("test") f_da[0].set_data(data) f_da[1].set_data(data) f_da[1].setName("Ion Mobility") spec.setFloatDataArrays( f_da ) assert spec.containsIMData() assert spec.getIMData()[0] == 1 # Ensure that "set_peaks()" doesnt clear the float data arrays spec = pyopenms.MSSpectrum() data_mz = np.array( [5.0, 8.0] ).astype(np.float64) data_i = np.array( [50.0, 80.0] ).astype(np.float32) f_da = [ pyopenms.FloatDataArray() ] f_da[0].set_data(data) f_da[0].setName("Ion Mobility") spec.setFloatDataArrays( f_da ) spec.set_peaks( [data_mz,data_i] ) assert spec.containsIMData() assert spec.getIMData()[0] == 0 assert len(spec.getFloatDataArrays()) == 1 f = spec.getFloatDataArrays()[0] assert len(f.get_data()) == 3 assert f.get_data()[0] == 5 assert spec.size() == len(data_mz) assert spec.size() == len(data_i) # Test __repr__ and __str__ methods spec_repr = pyopenms.MSSpectrum() spec_repr.setRT(1234.5) spec_repr.setMSLevel(2) spec_repr.set_peaks(([100.0, 200.0, 300.0], [1000.0, 2000.0, 500.0])) repr_str = repr(spec_repr) assert "MSSpectrum(" in repr_str assert "ms_level=" in repr_str assert "rt=" in repr_str assert "num_peaks=" in repr_str str_str = str(spec_repr) assert str_str == repr_str @report def testStringDataArray(): """ @tests: StringDataArray """ da = pyopenms.StringDataArray() assert da.size() == 0 da.push_back("hello") da.push_back("world") assert da.size() == 2 assert da[0] == b"hello" assert da[1] == b"world" da[1] = b"hello world" assert da[1] == b"hello world", da[1] da.clear() assert da.size() == 0 da.push_back("hello") assert da.size() == 1 da.resize(3) da[0] = b"hello" da[1] = b"" da[2] = b"world" assert da.size() == 3 # Test __repr__ method sda_repr = pyopenms.StringDataArray() sda_repr.setName("annotation") sda_repr.push_back("test1") sda_repr.push_back("test2") repr_str = repr(sda_repr) assert "StringDataArray(" in repr_str assert "name='annotation'" in repr_str assert "size=2" in repr_str @report def testIntegerDataArray(): """ @tests: IntegerDataArray """ da = pyopenms.IntegerDataArray() assert da.size() == 0 da.push_back(1) da.push_back(4) assert da.size() == 2 assert da[0] == 1 assert da[1] == 4 da[1] = 7 assert da[1] == 7 da.clear() assert da.size() == 0 da.push_back(1) assert da.size() == 1 da.resize(3) da[0] = 1 da[1] = 2 da[2] = 3 assert da.size() == 3 q = da.get_data() q = np.append(q, 4).astype(np.intc) da.set_data(q) assert da.size() == 4 # Test __repr__ method ida_repr = pyopenms.IntegerDataArray() ida_repr.setName("charge_state") ida_repr.push_back(1) ida_repr.push_back(2) ida_repr.push_back(3) repr_str = repr(ida_repr) assert "IntegerDataArray(" in repr_str assert "name='charge_state'" in repr_str assert "size=3" in repr_str @report def testFloatDataArray(): """ @tests: FloatDataArray """ da = pyopenms.FloatDataArray() assert da.size() == 0 da.push_back(1.0) da.push_back(4.0) assert da.size() == 2 assert da[0] == 1.0 assert da[1] == 4.0 da[1] = 7.0 assert da[1] == 7.0 da.clear() assert da.size() == 0 da.push_back(1.0) assert da.size() == 1 da.resize(3) da[0] = 1.0 da[1] = 2.0 da[2] = 3.0 assert da.size() == 3 q = da.get_data() q = np.append(q, 4.0).astype(np.float32) da.set_data(q) assert da.size() == 4 # Test __repr__ method fda_repr = pyopenms.FloatDataArray() fda_repr.setName("ion_mobility") fda_repr.push_back(1.5) fda_repr.push_back(2.5) repr_str = repr(fda_repr) assert "FloatDataArray(" in repr_str assert "name='ion_mobility'" in repr_str assert "size=2" in repr_str @report def testMSChromatogram(): """ @tests: MSChromatogram MSChromatogram.__init__ MSChromatogram.__copy__ """ chrom = pyopenms.MSChromatogram() chrom_ = copy.copy(chrom) assert chrom_ == chrom chrom_ = copy.deepcopy(chrom) assert chrom_ == chrom chrom_ = pyopenms.MSChromatogram(chrom) assert chrom_ == chrom _testMetaInfoInterface(chrom) chrom.setName("chrom") assert chrom.getName() == "chrom" p = pyopenms.ChromatogramPeak() p.setRT(1000.0) p.setIntensity(200.0) chrom.push_back(p) assert chrom.size() == 1 assert chrom[0] == p chrom.updateRanges() assert isinstance(chrom.findNearest(0.0), int) assert isinstance(chrom.getMinRT(), float) assert isinstance(chrom.getMaxRT(), float) assert isinstance(chrom.getMinIntensity(), float) assert isinstance(chrom.getMaxIntensity(), float) assert chrom == chrom assert not chrom != chrom mz, ii = chrom.get_peaks() assert len(mz) == len(ii) assert len(mz) == 1 chrom.set_peaks((mz, ii)) mz0, ii0 = chrom.get_peaks() assert mz0 == mz assert ii0 == ii assert int(chrom.isSorted()) in (0,1) chrom.clear(False) p = pyopenms.ChromatogramPeak() p.setRT(1000.0) p.setIntensity(200.0) chrom.push_back(p) p = pyopenms.ChromatogramPeak() p.setRT(2000.0) p.setIntensity(400.0) chrom.push_back(p) mz, ii = chrom.get_peaks() assert chrom[0].getRT() == 1000.0 assert chrom[1].getRT() == 2000.0 assert chrom[0].getIntensity() == 200.0 assert chrom[1].getIntensity() == 400.0 assert mz[0] == 1000.0 assert mz[1] == 2000.0 assert ii[0] == 200.0 assert ii[1] == 400.0 chrom.setNativeID('chrom_0') chrom.setMetaValue('FWHM', 5.0) prec = pyopenms.Precursor() prec.setMZ(100.0) prec.setCharge(1) chrom.setPrecursor(prec) prod = pyopenms.Product() prod.setMZ(50.0) chrom.setProduct(prod) chrom.setComment('comment') df = chrom.get_df() # Default columns: rt, intensity, precursor_mz, precursor_charge, product_mz, native_id, FWHM # chromatogram_type and comment are NOT included by default assert df.shape == (2, 7) assert df.loc[0, 'rt'] == 1000.0 assert df.loc[1, 'intensity'] == 400 assert df.loc[1, 'precursor_mz'] == 100.0 assert df.loc[0, 'precursor_charge'] == 1 assert df.loc[1, 'product_mz'] == 50.0 assert df.loc[1, 'native_id'] == 'chrom_0' assert df.loc[0, 'FWHM'] == 5 # Test non-default columns (chromatogram_type, comment) via explicit selection df_all = chrom.get_df(columns=['rt', 'intensity', 'chromatogram_type', 'comment']) assert df_all.shape == (2, 4) assert df_all.loc[0, 'chromatogram_type'] == 'MASS_CHROMATOGRAM' assert df_all.loc[0, 'comment'] == 'comment' chrom.clear(False) data_mz = np.array( [5.0, 8.0] ).astype(np.float64) data_i = np.array( [50.0, 80.0] ).astype(np.float32) chrom.set_peaks( [data_mz,data_i] ) mz, ii = chrom.get_peaks() assert chrom[0].getRT() == 5.0 assert chrom[1].getRT() == 8.0 assert chrom[0].getIntensity() == 50.0 assert chrom[1].getIntensity() == 80.0 assert mz[0] == 5.0 assert mz[1] == 8.0 assert ii[0] == 50.0 assert ii[1] == 80.0 # Fast chrom.clear(False) data_mz = np.array( [5.0, 8.0] ).astype(np.float64) data_i = np.array( [50.0, 80.0] ).astype(np.float64) chrom.set_peaks( [data_mz,data_i] ) mz, ii = chrom.get_peaks() assert chrom[0].getRT() == 5.0 assert chrom[1].getRT() == 8.0 assert chrom[0].getIntensity() == 50.0 assert chrom[1].getIntensity() == 80.0 assert mz[0] == 5.0 assert mz[1] == 8.0 assert ii[0] == 50.0 assert ii[1] == 80.0 # Slow chrom.clear(False) data_mz = np.array( [5.0, 8.0] ).astype(np.float32) data_i = np.array( [50.0, 80.0] ).astype(np.float32) chrom.set_peaks( [data_mz,data_i] ) mz, ii = chrom.get_peaks() assert chrom[0].getRT() == 5.0 assert chrom[1].getRT() == 8.0 assert chrom[0].getIntensity() == 50.0 assert chrom[1].getIntensity() == 80.0 assert mz[0] == 5.0 assert mz[1] == 8.0 assert ii[0] == 50.0 assert ii[1] == 80.0 # test float data chrom = pyopenms.MSChromatogram() data = np.array( [5, 8, 42] ).astype(np.float32) f_da = [ pyopenms.FloatDataArray() ] f_da[0].set_data(data) f_da[0].setName("Test Data") chrom.setFloatDataArrays( f_da ) assert len(chrom.getFloatDataArrays()) == 1 f = chrom.getFloatDataArrays()[0] assert f.get_data()[0] == 5 assert f.getName() == "Test Data" # Ensure that "set_peaks()" doesnt clear the float data arrays chrom = pyopenms.MSChromatogram() chrom.setFloatDataArrays( f_da ) chrom.set_peaks( [data_mz,data_i] ) assert len(chrom.getFloatDataArrays()) == 1 f = chrom.getFloatDataArrays()[0] assert len(f.get_data()) == 3 assert f.get_data()[0] == 5 assert chrom.size() == len(data_mz) assert chrom.size() == len(data_i) # Test __repr__ and __str__ methods chrom_repr = pyopenms.MSChromatogram() chrom_repr.setName("test_chromatogram") chrom_repr.set_peaks(([100.0, 200.0, 300.0], [1000.0, 2000.0, 500.0])) repr_str = repr(chrom_repr) assert "MSChromatogram(" in repr_str assert "num_peaks=" in repr_str str_str = str(chrom_repr) assert str_str == repr_str @report def testMRMFeature(): """ @tests: MRMFeature MRMFeature.__init__ MRMFeature.addScore MRMFeature.getScore """ mrmfeature = pyopenms.MRMFeature() f = pyopenms.Feature() fs = mrmfeature.getFeatures() assert len(fs) == 0 mrmfeature.addFeature(f, "myFeature") fs = mrmfeature.getFeatures() assert len(fs) == 1 assert mrmfeature.getFeature("myFeature") is not None slist = [] mrmfeature.getFeatureIDs(slist) assert len(slist) == 1 mrmfeature.addPrecursorFeature(f, "myFeature_Pr0") slist = [] mrmfeature.getPrecursorFeatureIDs(slist) assert len(slist) == 1 assert mrmfeature.getPrecursorFeature("myFeature_Pr0") is not None s = mrmfeature.getScores() assert abs(s.yseries_score - 0.0) < 1e-4 s.yseries_score = 4.0 mrmfeature.setScores(s) s2 = mrmfeature.getScores() assert abs(s2.yseries_score - 4.0) < 1e-4 # Test __repr__ and __str__ methods mrm_repr = pyopenms.MRMFeature() mrm_repr.setRT(1234.5) mrm_repr.setMZ(445.678) mrm_repr.setIntensity(100000.0) mrm_repr.setCharge(2) f1 = pyopenms.Feature() f2 = pyopenms.Feature() mrm_repr.addFeature(f1, "trans1") mrm_repr.addFeature(f2, "trans2") repr_str = repr(mrm_repr) assert "MRMFeature(" in repr_str assert "rt=" in repr_str assert "mz=" in repr_str assert "intensity=" in repr_str assert "num_transitions=" in repr_str str_str = str(mrm_repr) assert str_str == repr_str @report def testConfidenceScoring(): """ @tests: ConfidenceScoring ConfidenceScoring.__init__ """ scoring = pyopenms.ConfidenceScoring() @report def testMRMDecoy(): """ @tests: MRMDecoy MRMDecoy.__init__ """ mrmdecoy = pyopenms.MRMDecoy() assert mrmdecoy is not None assert pyopenms.MRMDecoy().generateDecoys is not None @report def testMRMTransitionGroup(): """ @tests: MRMTransitionGroup """ mrmgroup = pyopenms.MRMTransitionGroupCP() assert mrmgroup is not None mrmgroup.setTransitionGroupID("this_id") assert mrmgroup.getTransitionGroupID() == "this_id" assert len(mrmgroup.getTransitions()) == 0 mrmgroup.addTransition(pyopenms.ReactionMonitoringTransition(), "tr1") assert len(mrmgroup.getTransitions()) == 1 # add data for testing df output ## test chromatogram df rt, intensity = [[1.0], [5]] chrom = pyopenms.MSChromatogram() chrom.set_peaks([rt, intensity]) chrom.setNativeID("tr1") mrmgroup.addChromatogram(chrom, 'tr1') df = mrmgroup.get_chromatogram_df() # Default columns: rt, intensity, precursor_mz, precursor_charge, product_mz, native_id # chromatogram_type and comment are NOT included by default assert df.shape == (1, 6) assert df.loc[0, 'rt'] == 1.0 assert df.loc[0, 'intensity'] == 5 assert df.loc[0, 'native_id'] == 'tr1' # Test non-default columns (chromatogram_type, comment) via explicit selection df_all = mrmgroup.get_chromatogram_df(columns=['rt', 'intensity', 'chromatogram_type', 'comment']) assert df_all.shape == (1, 4) assert df_all.loc[0, 'chromatogram_type'] == 'MASS_CHROMATOGRAM' ## feature 1 f1 = pyopenms.MRMFeature() f1.setRT(1.0) f1.setMetaValue(b'leftWidth', 0.5) f1.setMetaValue(b'rightWidth', 1.5) f1.setMetaValue(b'peak_apices_sum', 10.0) f1.setOverallQuality(0.5) f1.setUniqueId(1) f1.setIntensity(20.0) mrmgroup.addFeature(f1) # feature 2 f2 = pyopenms.MRMFeature() f2.setRT(2.0) f2.setMetaValue(b'peak_apices_sum', 20.0) f2.setOverallQuality(1.0) f2.setUniqueId(2) f2.setIntensity(40.0) mrmgroup.addFeature(f2) df = mrmgroup.get_feature_df(meta_values=[b'leftWidth', b'rightWidth', b'peak_apices_sum']) assert df.shape == (2, 6) assert df.loc[1, 'leftWidth'] == 0.5 assert df.loc[1, 'rightWidth'] == 1.5 assert df.loc[1, 'peak_apices_sum'] == 10.0 assert df.loc[1, 'intensity'] == 20.0 assert df.loc[1, 'quality'] == 0.5 assert df.loc[1, 'rt'] == 1.0 assert np.isnan(df.loc[2, 'leftWidth']) assert np.isnan(df.loc[2, 'rightWidth']) assert df.loc[2, 'peak_apices_sum'] == 20.0 assert df.loc[2, 'intensity'] == 40.0 assert df.loc[2, 'quality'] == 1.0 assert df.loc[2, 'rt'] == 2.0 # If get "all" meta values should get the same result df = mrmgroup.get_feature_df(meta_values='all') assert df.shape == (2, 6) assert df.loc[1, 'leftWidth'] == 0.5 assert df.loc[1, 'rightWidth'] == 1.5 assert df.loc[1, 'peak_apices_sum'] == 10.0 assert df.loc[1, 'intensity'] == 20.0 assert df.loc[1, 'quality'] == 0.5 assert df.loc[1, 'rt'] == 1.0 assert np.isnan(df.loc[2, 'leftWidth']) assert np.isnan(df.loc[2, 'rightWidth']) assert df.loc[2, 'peak_apices_sum'] == 20.0 assert df.loc[2, 'intensity'] == 40.0 assert df.loc[2, 'quality'] == 1.0 assert df.loc[2, 'rt'] == 2.0 @report def testReactionMonitoringTransition(): """ @tests: ReactionMonitoringTransition ReactionMonitoringTransition.__init__ ReactionMonitoringTransition.__eq__ ReactionMonitoringTransition.__ne__ ReactionMonitoringTransition.getName ReactionMonitoringTransition.setName ReactionMonitoringTransition.getNativeID ReactionMonitoringTransition.setNativeID ReactionMonitoringTransition.getPeptideRef ReactionMonitoringTransition.setPeptideRef ReactionMonitoringTransition.getCompoundRef ReactionMonitoringTransition.setCompoundRef ReactionMonitoringTransition.getProductMZ ReactionMonitoringTransition.setProductMZ ReactionMonitoringTransition.getPrecursorMZ ReactionMonitoringTransition.setPrecursorMZ ReactionMonitoringTransition.getLibraryIntensity ReactionMonitoringTransition.setLibraryIntensity ReactionMonitoringTransition.isDetectingTransition ReactionMonitoringTransition.setDetectingTransition ReactionMonitoringTransition.isIdentifyingTransition ReactionMonitoringTransition.setIdentifyingTransition ReactionMonitoringTransition.isQuantifyingTransition ReactionMonitoringTransition.setQuantifyingTransition ReactionMonitoringTransition.getDecoyTransitionType ReactionMonitoringTransition.setDecoyTransitionType ReactionMonitoringTransition.hasPrecursorCVTerms ReactionMonitoringTransition.setPrecursorCVTermList ReactionMonitoringTransition.addPrecursorCVTerm ReactionMonitoringTransition.getPrecursorCVTermList ReactionMonitoringTransition.addProductCVTerm ReactionMonitoringTransition.getIntermediateProducts ReactionMonitoringTransition.addIntermediateProduct ReactionMonitoringTransition.setIntermediateProducts ReactionMonitoringTransition.setProduct ReactionMonitoringTransition.getProduct ReactionMonitoringTransition.getProductChargeState ReactionMonitoringTransition.isProductChargeStateSet ReactionMonitoringTransition.setRetentionTime ReactionMonitoringTransition.getRetentionTime ReactionMonitoringTransition.setPrediction ReactionMonitoringTransition.addPredictionTerm ReactionMonitoringTransition.hasPrediction ReactionMonitoringTransition.getPrediction """ # Test constructor and equality operators tr = pyopenms.ReactionMonitoringTransition() tr2 = pyopenms.ReactionMonitoringTransition() assert tr == tr # test __eq__ with self assert tr == tr2 # test __eq__ with another default instance assert not tr != tr # test __ne__ # Test copy constructor tr_copy = pyopenms.ReactionMonitoringTransition(tr) assert tr == tr_copy # Test name methods tr.setName("transition1") assert tr.getName() == "transition1" # Test native ID methods tr.setNativeID("tr1") assert tr.getNativeID() == "tr1" # Test peptide reference methods tr.setPeptideRef("peptide1") assert tr.getPeptideRef() == "peptide1" # Test compound reference methods tr.setCompoundRef("compound1") assert tr.getCompoundRef() == "compound1" # Test product m/z methods tr.setProductMZ(200.5) assert abs(tr.getProductMZ() - 200.5) < 1e-10 # Test precursor m/z methods tr.setPrecursorMZ(500.25) assert abs(tr.getPrecursorMZ() - 500.25) < 1e-10 # Test library intensity methods tr.setLibraryIntensity(1000.0) assert abs(tr.getLibraryIntensity() - 1000.0) < 1e-10 # Test transition type flags tr.setDetectingTransition(True) assert tr.isDetectingTransition() == True tr.setDetectingTransition(False) assert tr.isDetectingTransition() == False tr.setIdentifyingTransition(True) assert tr.isIdentifyingTransition() == True tr.setIdentifyingTransition(False) assert tr.isIdentifyingTransition() == False tr.setQuantifyingTransition(True) assert tr.isQuantifyingTransition() == True tr.setQuantifyingTransition(False) assert tr.isQuantifyingTransition() == False # Test decoy transition type decoy_type = pyopenms.DecoyTransitionType().TARGET tr.setDecoyTransitionType(decoy_type) assert tr.getDecoyTransitionType() == decoy_type decoy_type = pyopenms.DecoyTransitionType().DECOY tr.setDecoyTransitionType(decoy_type) assert tr.getDecoyTransitionType() == decoy_type # Test CV Terms for precursor assert tr.hasPrecursorCVTerms() == False or tr.hasPrecursorCVTerms() == True # should not crash # Create and add CV terms cv_term = pyopenms.CVTerm() cv_term.setCVIdentifierRef("MS") cv_term.setAccession("MS:1000827") cv_term.setName("isolation window target m/z") cv_term.setValue(500.25) tr.addPrecursorCVTerm(cv_term) # Test getting CV term list cv_list = tr.getPrecursorCVTermList() assert len(cv_list.getCVTerms()) > 0 # Test setting CV term list new_cv_list = pyopenms.CVTermList() new_cv_list.addCVTerm(cv_term) tr.setPrecursorCVTermList(new_cv_list) # Test adding product CV term product_cv_term = pyopenms.CVTerm() product_cv_term.setCVIdentifierRef("MS") product_cv_term.setAccession("MS:1000041") product_cv_term.setName("charge state") product_cv_term.setValue(2) tr.addProductCVTerm(product_cv_term) # Test intermediate products intermediate_products = tr.getIntermediateProducts() assert isinstance(intermediate_products, list) # Create and add intermediate product intermediate_product = pyopenms.TraMLProduct() intermediate_product.setMZ(150.0) tr.addIntermediateProduct(intermediate_product) # Test setting intermediate products list products_list = [intermediate_product] tr.setIntermediateProducts(products_list) updated_products = tr.getIntermediateProducts() assert len(updated_products) == 1 # Test product methods product = pyopenms.TraMLProduct() product.setMZ(200.5) product.setChargeState(2) tr.setProduct(product) retrieved_product = tr.getProduct() assert abs(retrieved_product.getMZ() - 200.5) < 1e-10 assert retrieved_product.getChargeState() == 2 # Test charge state methods assert tr.getProductChargeState() == 2 assert tr.isProductChargeStateSet() == True # Test retention time methods rt = pyopenms.RetentionTime() rt.setRT(1500.0) tr.setRetentionTime(rt) retrieved_rt = tr.getRetentionTime() assert abs(retrieved_rt.getRT() - 1500.0) < 1e-10 # Test prediction methods assert tr.hasPrediction() == False or tr.hasPrediction() == True # should not crash prediction = pyopenms.Prediction() tr.setPrediction(prediction) # Test adding prediction term pred_cv_term = pyopenms.CVTerm() pred_cv_term.setCVIdentifierRef("MS") pred_cv_term.setAccession("MS:1000042") pred_cv_term.setName("peak intensity") pred_cv_term.setValue(1000.0) tr.addPredictionTerm(pred_cv_term) # Test getting prediction retrieved_prediction = tr.getPrediction() assert retrieved_prediction is not None # Test inequality after modifications tr_different = pyopenms.ReactionMonitoringTransition() tr_different.setName("different_transition") assert tr != tr_different assert not tr == tr_different # Test __repr__ and __str__ methods tr_repr = pyopenms.ReactionMonitoringTransition() tr_repr.setNativeID("tr_001") tr_repr.setPrecursorMZ(500.25) tr_repr.setProductMZ(300.15) tr_repr.setPeptideRef("PEPTIDER") tr_repr.setLibraryIntensity(10000.0) repr_str = repr(tr_repr) assert "ReactionMonitoringTransition(" in repr_str assert "precursor_mz=" in repr_str assert "product_mz=" in repr_str str_str = str(tr_repr) assert str_str == repr_str @report def testTargetedExperiment(): """ @tests: TargetedExperiment """ m = pyopenms.TargetedExperiment() m_ = copy.copy(m) assert m_ == m m_ = copy.deepcopy(m) assert m_ == m m_ = pyopenms.TargetedExperiment(m) assert m_ == m m.clear(True) m.setCVs(m.getCVs()) targeted = m targeted.setCVs(targeted.getCVs()) targeted.setTargetCVTerms(targeted.getTargetCVTerms()) targeted.setPeptides(targeted.getPeptides()) targeted.setProteins(targeted.getProteins()) targeted.setTransitions(targeted.getTransitions()) assert m == m assert not m != m @report def testTargetedExperimentHelper(): """ @tests: TargetedExperimentHelper """ rtu = pyopenms.RetentionTime.RTUnit() rtu = pyopenms.RetentionTime.RTUnit.SECOND rtu = pyopenms.RetentionTime.RTUnit.MINUTE rtt = pyopenms.RetentionTime.RTType() rtt = pyopenms.RetentionTime.RTType.LOCAL rtt = pyopenms.RetentionTime.RTType.NORMALIZED rtt = pyopenms.RetentionTime.RTType.IRT rt = pyopenms.RetentionTime() assert rt.software_ref is not None assert not rt.isRTset() rt.setRT(5.0) rt.retention_time_unit = pyopenms.RetentionTime.RTUnit.SECOND rt.retention_time_type = pyopenms.RetentionTime.RTType.NORMALIZED assert rt.isRTset() assert rt.getRT() == 5.0 p = pyopenms.Peptide() assert p.rts is not None assert p.id is not None assert p.protein_refs is not None assert p.evidence is not None assert p.sequence is not None assert p.mods is not None assert not p.hasCharge() p.setChargeState(5) assert p.hasCharge() assert p.getChargeState() == 5 assert not p.hasRetentionTime() p.rts = [rt] assert p.hasRetentionTime() assert p.getRetentionTime() == 5.0 assert p.getRetentionTimeUnit() == pyopenms.RetentionTime.RTUnit.SECOND assert p.getRetentionTimeType() == pyopenms.RetentionTime.RTType.NORMALIZED c = pyopenms.Compound() assert c.rts is not None assert c.id is not None assert c.molecular_formula is not None assert c.smiles_string is not None assert c.theoretical_mass is not None assert not c.hasCharge() c.setChargeState(5) assert c.hasCharge() assert c.getChargeState() == 5 assert not c.hasRetentionTime() c.rts = [rt] assert c.hasRetentionTime() assert c.getRetentionTime() == 5.0 assert c.getRetentionTimeUnit() == pyopenms.RetentionTime.RTUnit.SECOND assert c.getRetentionTimeType() == pyopenms.RetentionTime.RTType.NORMALIZED @report def testMapAlignment(): """ @tests: MapAlignmentAlgorithmPoseClustering MapAlignmentAlgorithmPoseClustering.__init__ MapAlignmentAlgorithmPoseClustering.getDefaults MapAlignmentAlgorithmPoseClustering.getName MapAlignmentAlgorithmPoseClustering.getParameters MapAlignmentAlgorithmPoseClustering.setName MapAlignmentAlgorithmPoseClustering.setParameters MapAlignmentAlgorithmPoseClustering.setReference MapAlignmentAlgorithmPoseClustering.align MapAlignmentAlgorithmPoseClustering.endProgress MapAlignmentAlgorithmPoseClustering.getLogType MapAlignmentAlgorithmPoseClustering.setLogType MapAlignmentAlgorithmPoseClustering.setProgress MapAlignmentAlgorithmPoseClustering.startProgress MapAlignmentTransformer.transformRetentionTimes """ ma = pyopenms.MapAlignmentAlgorithmPoseClustering() assert isinstance(ma.getDefaults(), pyopenms.Param) assert isinstance(ma.getParameters(), pyopenms.Param) _testStrOutput(ma.getName()) ma.setName(ma.getName()) ma.getDefaults() ma.getParameters() ma.setParameters(ma.getDefaults()) ma.setReference ma.align pyopenms.MapAlignmentTransformer.transformRetentionTimes @report def testMatrixDouble(): """ @tests: MatrixDouble MapAlignmentAlgorithmIdentification.__init__ """ m = pyopenms.MatrixDouble(3, 2, 0.0) for i in range(3): for j in range(2): m.setValue(i, j, i * 10.0 + j) print(m) mv = m.get_matrix_as_view() print(mv) mc = m.get_matrix() print(mc) mat = m.get_matrix_as_view() N = 90 m = pyopenms.MatrixDouble(N-1, N+2, 5.0) assert m.rows() == 89 assert m.cols() == 92 rows = N-1 cols = N+2 test = [] for i in range(int(rows)): for j in range(int(cols)): test.append( m.getValue(i,j) ) testm = np.asarray(test) testm = testm.reshape(rows, cols) assert sum(sum(testm)) == 40940.0 assert sum(sum(testm)) == (N-1)*(N+2)*5 matrix = m.get_matrix() assert sum(sum(matrix)) == 40940.0 assert sum(sum(matrix)) == (N-1)*(N+2)*5 matrix_view = m.get_matrix_as_view() assert sum(sum(matrix_view)) == 40940.0 assert sum(sum(matrix_view)) == (N-1)*(N+2)*5 # Column = 1 / Row = 2 ## Now change a value: assert m.getValue(1, 2) == 5.0 m.setValue(1, 2, 8.0) assert m.getValue(1, 2) == 8.0 print(m) mat = m.get_matrix_as_view() print(mat) assert mat[1, 2] == 8.0 mat = m.get_matrix() assert m.getValue(1, 2) == 8.0 assert mat[1, 2] == 8.0 # Whatever we change here gets changed in the raw data as well matrix_view = m.get_matrix_as_view() matrix_view[1, 6] = 11.0 assert m.getValue(1, 6) == 11.0 assert matrix_view[1, 6] == 11.0 m = pyopenms.MatrixDouble() assert m.rows() == 0 assert m.cols() == 0 mat[3, 6] = 9.0 m.set_matrix(mat) assert m.getValue(1, 2) == 8.0 assert m.getValue(3, 6) == 9.0 # Create a test matrix with known values test_matrix = pyopenms.MatrixDouble(3, 4, 0.0) test_matrix.setValue(2, 3, 120.7) # Test getValue retrieves correct values assert test_matrix.getValue(2, 3) == 120.7 @report def testMatrixDoubleColumnMajorOrdering(): """ @tests: MatrixDouble Verify Matrix preserves row/column ordering through Python<->C++ round-trip. This test catches column-major vs row-major issues that could cause data transposition when passing matrices between numpy and C++. """ # Test 1: Non-square matrix with unique values at each position # Using 3x4 matrix where value[i,j] = i*10 + j makes each element unique # and any transposition immediately detectable original = np.array([[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]], dtype=np.float64) # 3 rows x 4 cols m = pyopenms.MatrixDouble() m.set_matrix(original) # Verify shape preserved (not transposed) assert m.rows() == 3, f"Expected 3 rows, got {m.rows()}" assert m.cols() == 4, f"Expected 4 cols, got {m.cols()}" # Verify each element via getValue matches numpy indexing for i in range(3): for j in range(4): expected = original[i, j] actual = m.getValue(i, j) assert actual == expected, \ f"getValue mismatch at ({i},{j}): C++={actual}, numpy={expected}" # Test 2: Round-trip preservation (numpy -> C++ -> numpy) result = m.get_matrix() assert result.shape == original.shape, \ f"Shape mismatch after round-trip: {result.shape} vs {original.shape}" assert np.array_equal(original, result), \ f"Data mismatch after round-trip:\nOriginal:\n{original}\nResult:\n{result}" # Test 3: Verify view indexing matches getValue for all elements view = m.get_matrix_as_view() assert view.shape == (3, 4), f"View shape mismatch: {view.shape}" for i in range(3): for j in range(4): assert view[i, j] == m.getValue(i, j), \ f"View mismatch at ({i},{j}): view={view[i,j]}, getValue={m.getValue(i,j)}" # Test 4: Verify modifications through view are reflected in C++ object view[2, 3] = 99.0 assert m.getValue(2, 3) == 99.0, "View modification not reflected in C++ object" # Test 5: Test with transposed-like access pattern to catch subtle bugs # Create matrix where row index and col index have very different values m2 = pyopenms.MatrixDouble(2, 5, 0.0) # 2 rows, 5 cols - very non-square for i in range(2): for j in range(5): m2.setValue(i, j, i * 100 + j) view2 = m2.get_matrix_as_view() assert view2.shape == (2, 5), f"Non-square view shape wrong: {view2.shape}" # Check corners and middle to ensure no transposition assert view2[0, 0] == 0, f"[0,0] = {view2[0,0]}, expected 0" assert view2[0, 4] == 4, f"[0,4] = {view2[0,4]}, expected 4" assert view2[1, 0] == 100, f"[1,0] = {view2[1,0]}, expected 100" assert view2[1, 4] == 104, f"[1,4] = {view2[1,4]}, expected 104" @report def testMapAlignmentIdentification(): """ @tests: MapAlignmentAlgorithmIdentification MapAlignmentAlgorithmIdentification.__init__ """ ma = pyopenms.MapAlignmentAlgorithmIdentification() assert pyopenms.MapAlignmentAlgorithmIdentification().align is not None assert pyopenms.MapAlignmentAlgorithmIdentification().setReference is not None @report def testMapAlignmentTransformer(): """ @tests: MapAlignmentTransformer MapAlignmentTransformer.__init__ """ ma = pyopenms.MapAlignmentTransformer() assert pyopenms.MapAlignmentTransformer().transformRetentionTimes is not None @report def testMxxxFile(): """ @tests: MzDataFile MzDataFile.__init__ MzDataFile.endProgress MzDataFile.getLogType MzDataFile.load MzDataFile.setLogType MzDataFile.setProgress MzDataFile.startProgress MzDataFile.store MzDataFile.getOptions MzDataFile.setOptions MzMLFile.__init__ MzMLFile.endProgress MzMLFile.getLogType MzMLFile.load MzMLFile.setLogType MzMLFile.setProgress MzMLFile.startProgress MzMLFile.store MzMLFile.getOptions MzMLFile.setOptions MzXMLFile.getOptions MzXMLFile.setOptions MzXMLFile.__init__ MzXMLFile.endProgress MzXMLFile.getLogType MzXMLFile.load MzXMLFile.setLogType MzXMLFile.setProgress MzXMLFile.startProgress MzXMLFile.store """ mse = pyopenms.MSExperiment() s = pyopenms.MSSpectrum() mse.addSpectrum(s) fh = pyopenms.MzDataFile() _testProgressLogger(fh) fh.store("test.mzData", mse) fh.load("test.mzData", mse) fh.setOptions(fh.getOptions()) fh = pyopenms.MzMLFile() _testProgressLogger(fh) fh.store("test.mzML", mse) fh.load("test.mzML", mse) fh.setOptions(fh.getOptions()) myStr = pyopenms.String() fh.storeBuffer(myStr, mse) assert len(myStr.toString()) == 5269 mse2 = pyopenms.MSExperiment() fh.loadBuffer(bytes(myStr), mse2) assert mse2 == mse assert mse2.size() == 1 fh = pyopenms.MzXMLFile() _testProgressLogger(fh) fh.store("test.mzXML", mse) fh.load("test.mzXML", mse) fh.setOptions(fh.getOptions()) @report def testParamXMLFile(): """ @tests: ParamXMLFile ParamXMLFile.__init__ ParamXMLFile.load ParamXMLFile.store """ fh = pyopenms.ParamXMLFile() p = pyopenms.Param() fh.store("test.ini", p) fh.load("test.ini", p) @report def testPeak(): """ @tests: Peak1D Peak1D.__init__ Peak1D.getIntensity Peak1D.getMZ Peak1D.setIntensity Peak1D.setMZ Peak1D.__eq__ Peak1D.__ge__ Peak1D.__gt__ Peak1D.__le__ Peak1D.__lt__ Peak1D.__ne__ Peak2D.__init__ Peak2D.getIntensity Peak2D.getMZ Peak2D.getRT Peak2D.setIntensity Peak2D.setMZ Peak2D.setRT Peak2D.__eq__ Peak2D.__ge__ Peak2D.__gt__ Peak2D.__le__ Peak2D.__lt__ Peak2D.__ne__ """ p1 = pyopenms.Peak1D() p1.setIntensity(12.0) assert p1.getIntensity() == 12.0 p1.setMZ(13.0) assert p1.getMZ() == 13.0 assert p1 == p1 assert not p1 != p1 p2 = pyopenms.Peak2D() assert p2 == p2 assert not p2 != p2 p2.setIntensity(22.0) assert p2.getIntensity() == 22.0 p2.setMZ(23.0) assert p2.getMZ() == 23.0 p2.setRT(45.0) assert p2.getRT() == 45.0 # Test __repr__ and __str__ methods for Peak1D repr_str = repr(p1) assert "Peak1D(" in repr_str assert "mz=" in repr_str assert "intensity=" in repr_str str_str = str(p1) assert str_str == repr_str # Test __repr__ and __str__ methods for Peak2D repr_str = repr(p2) assert "Peak2D(" in repr_str assert "rt=" in repr_str assert "mz=" in repr_str assert "intensity=" in repr_str str_str = str(p2) assert str_str == repr_str @report def testNumpressCoder(): """ """ np = pyopenms.MSNumpressCoder() nc = pyopenms.NumpressConfig() nc.np_compression = np.NumpressCompression.LINEAR nc.estimate_fixed_point = True tmp = pyopenms.String() out = [] inp = [1.0, 2.0, 3.0] np.encodeNP(inp, tmp, True, nc) res = tmp.toString() assert len(res) != 0, len(res) assert res != "", res np.decodeNP(res, out, True, nc) assert len(out) == 3, (out, res) assert out == inp, out # Now try to use a simple Python string as input -> this will fail as we # cannot pass this by reference in C++ res = "" try: np.encodeNP(inp, res, True, nc) has_error = False except AssertionError: has_error = True assert has_error @report def testNumpressConfig(): """ """ n = pyopenms.MSNumpressCoder() np = pyopenms.NumpressConfig() np.np_compression = n.NumpressCompression.LINEAR assert np.np_compression == n.NumpressCompression.LINEAR np.numpressFixedPoint = 4.2 np.numpressErrorTolerance = 4.2 np.estimate_fixed_point = True np.linear_fp_mass_acc = 4.2 np.setCompression("linear") @report def testBase64(): """ """ b = pyopenms.Base64() out = pyopenms.String() inp = [1.0, 2.0, 3.0] b.encode64(inp, b.ByteOrder.BYTEORDER_LITTLEENDIAN, out, False) res = out.toString() assert len(res) != 0 assert res != "" convBack = [] b.decode64(res, b.ByteOrder.BYTEORDER_LITTLEENDIAN, convBack, False) assert convBack == inp, convBack # For 32 bit out = pyopenms.String() b.encode32(inp, b.ByteOrder.BYTEORDER_LITTLEENDIAN, out, False) res = out.toString() assert len(res) != 0 assert res != "" convBack = [] b.decode32(res, b.ByteOrder.BYTEORDER_LITTLEENDIAN, convBack, False) assert convBack == inp, convBack @report def testPeakFileOptions(): """ @tests: PeakFileOptions PeakFileOptions.__init__ PeakFileOptions.addMSLevel PeakFileOptions.clearMSLevels PeakFileOptions.containsMSLevel PeakFileOptions.getCompression PeakFileOptions.getMSLevels PeakFileOptions.getMetadataOnly PeakFileOptions.getWriteSupplementalData PeakFileOptions.hasMSLevels PeakFileOptions.setCompression PeakFileOptions.setMSLevels PeakFileOptions.setMetadataOnly PeakFileOptions.setWriteSupplementalData """ pfo = pyopenms.PeakFileOptions() pfo.addMSLevel pfo.clearMSLevels() pfo.containsMSLevel(1) pfo.getCompression() pfo.getMSLevels() pfo.getMetadataOnly() pfo.getWriteSupplementalData() pfo.hasMSLevels() pfo.setCompression pfo.setMSLevels pfo.setMetadataOnly pfo.setWriteSupplementalData @report def testMRMMapping(): """ @tests: MRMMapping MRMMapping.__init__ MRMMapping.map """ p = pyopenms.MRMMapping() assert p.mapExperiment is not None e = pyopenms.MSExperiment() c = pyopenms.MSChromatogram() e.addChromatogram(c) assert e.getNrChromatograms() == 1 o = pyopenms.MSExperiment() t = pyopenms.TargetedExperiment() p.mapExperiment(e, t, o) assert o.getNrChromatograms() == 0 # not so easy to test @report def testPeakPickerChromatogram(): """ @tests: PeakPickerChromatogram PeakPickerChromatogram.__init__ PeakPickerChromatogram.pickChromatogram """ p = pyopenms.PeakPickerChromatogram() assert p.pickChromatogram is not None @report def testPeakPickerHiRes(): """ @tests: PeakPickerHiRes PeakPickerHiRes.__init__ PeakPickerHiRes.endProgress PeakPickerHiRes.getDefaults PeakPickerHiRes.getLogType PeakPickerHiRes.getName PeakPickerHiRes.getParameters PeakPickerHiRes.pick PeakPickerHiRes.pickExperiment PeakPickerHiRes.setLogType PeakPickerHiRes.setName PeakPickerHiRes.setParameters PeakPickerHiRes.setProgress PeakPickerHiRes.startProgress """ p = pyopenms.PeakPickerHiRes() assert p.pick is not None assert p.pickExperiment is not None @report def testPeakTypeEstimator(): """ @tests: PeakTypeEstimator PeakTypeEstimator.__init__ PeakTypeEstimator.estimateType """ pyopenms.PeakTypeEstimator().estimateType(pyopenms.MSSpectrum()) @report def testPeptideHit(): """ @tests: PeptideHit PeptideHit.__init__ PeptideHit.addProteinAccession PeptideHit.clearMetaInfo PeptideHit.getAAAfter PeptideHit.getAABefore PeptideHit.getKeys PeptideHit.getMetaValue PeptideHit.getProteinAccessions PeptideHit.getRank PeptideHit.getScore PeptideHit.getSequence PeptideHit.isMetaEmpty PeptideHit.metaValueExists PeptideHit.removeMetaValue PeptideHit.setAAAfter PeptideHit.setAABefore PeptideHit.setCharge PeptideHit.setMetaValue PeptideHit.setProteinAccessions PeptideHit.setRank PeptideHit.setScore PeptideHit.setSequence PeptideHit.__eq__ PeptideHit.__ge__ PeptideHit.__gt__ PeptideHit.__le__ PeptideHit.__lt__ PeptideHit.__ne__ """ ph = pyopenms.PeptideHit() assert ph == ph assert not ph != ph ph = pyopenms.PeptideHit(1.0, 1, 0, pyopenms.AASequence.fromString("A")) _testMetaInfoInterface(ph) assert len(ph.getPeptideEvidences()) == 0 assert ph.getPeptideEvidences() == [] pe = pyopenms.PeptideEvidence() pe.setProteinAccession('B_id') ph.addPeptideEvidence(pe) assert len(ph.getPeptideEvidences()) == 1 assert ph.getPeptideEvidences()[0].getProteinAccession() == 'B_id' ph.setPeptideEvidences([pe,pe]) assert len(ph.getPeptideEvidences()) == 2 assert ph.getPeptideEvidences()[0].getProteinAccession() == 'B_id' assert ph.getScore() == 1.0 assert ph.getRank() == 1 assert ph.getSequence().toString() == "A" ph.setScore(2.0) assert ph.getScore() == 2.0 ph.setRank(30) assert ph.getRank() == 30 ph.setSequence(pyopenms.AASequence.fromString("AAA")) assert ph.getSequence().toString() == "AAA" assert ph == ph assert not ph != ph # Test __repr__ and __str__ methods ph_repr = pyopenms.PeptideHit() ph_repr.setScore(18.1) ph_repr.setRank(1) ph_repr.setCharge(2) ph_repr.setSequence(pyopenms.AASequence.fromString("PEPTIDER")) # Basic repr test repr_str = repr(ph_repr) assert "PeptideHit(" in repr_str assert "score=" in repr_str assert "sequence=" in repr_str assert "charge=" in repr_str # Test with protein evidences pe1 = pyopenms.PeptideEvidence() pe1.setProteinAccession('PH_6057') pe1.setStart(71) pe1.setEnd(80) pe1.setAABefore(b'R') pe1.setAAAfter(b'N') ph_repr.addPeptideEvidence(pe1) repr_str = repr(ph_repr) assert "evidences=" in repr_str assert "PH_6057" in repr_str assert "PeptideEvidence(" in repr_str # Test str method str_str = str(ph_repr) assert str_str == repr_str @report def testPeptideEvidence(): """ @tests: PeptideEvidence PeptideEvidence.__init__ """ pe = pyopenms.PeptideEvidence() assert pe == pe assert not pe != pe pe.setProteinAccession('B_id') assert pe.getProteinAccession() == "B_id" pe.setAABefore(b'A') assert pe.getAABefore() == 'A' pe.setAAAfter(b'C') assert pe.getAAAfter() == 'C' pe.setStart(5) assert pe.getStart() == 5 pe.setEnd(9) assert pe.getEnd() == 9 assert pe == pe assert not pe != pe # Test __repr__ and __str__ methods pe_repr = pyopenms.PeptideEvidence() pe_repr.setProteinAccession('PH_6057') pe_repr.setStart(71) pe_repr.setEnd(80) pe_repr.setAABefore(b'R') pe_repr.setAAAfter(b'N') repr_str = repr(pe_repr) assert "PeptideEvidence(" in repr_str assert "protein=" in repr_str assert "PH_6057" in repr_str assert "start=" in repr_str assert "end=" in repr_str assert "aa_before=" in repr_str assert "aa_after=" in repr_str # Test str method str_str = str(pe_repr) assert str_str == repr_str @report def testPeptideIdentification(): """ @tests: PeptideIdentification PeptideIdentification.__init__ PeptideIdentification.clearMetaInfo PeptideIdentification.empty PeptideIdentification.getHits PeptideIdentification.getIdentifier PeptideIdentification.getKeys PeptideIdentification.getMetaValue PeptideIdentification.getNonReferencingHits PeptideIdentification.getReferencingHits PeptideIdentification.getScoreType PeptideIdentification.getSignificanceThreshold PeptideIdentification.insertHit PeptideIdentification.isHigherScoreBetter PeptideIdentification.isMetaEmpty PeptideIdentification.metaValueExists PeptideIdentification.removeMetaValue PeptideIdentification.setHigherScoreBetter PeptideIdentification.setHits PeptideIdentification.setIdentifier PeptideIdentification.setMetaValue PeptideIdentification.setScoreType PeptideIdentification.sort PeptideIdentification.__eq__ PeptideIdentification.__ge__ PeptideIdentification.__gt__ PeptideIdentification.__le__ PeptideIdentification.__lt__ PeptideIdentification.__ne__ PeptideIdentification.setSignificanceThreshold """ pi = pyopenms.PeptideIdentification() _testMetaInfoInterface(pi) assert pi == pi assert not pi != pi pe = pyopenms.PeptideEvidence() pe.setProteinAccession('B_id') ph = pyopenms.PeptideHit(1.0, 1, 0, pyopenms.AASequence.fromString("A")) ph.addPeptideEvidence(pe) pi.insertHit(ph) phx, = pi.getHits() assert phx == ph pi.setHits([ph]) phx, = pi.getHits() assert phx == ph rv = set([]) peptide_hits = pi.getReferencingHits(pi.getHits(), rv) assert rv == set([]) # assert len(peptide_hits) == 1 assert isinstance(pi.getSignificanceThreshold(), float) _testStrOutput(pi.getScoreType()) pi.setScoreType("A") assert isinstance(pi.isHigherScoreBetter(), int) _testStrOutput(pi.getIdentifier()) pi.setIdentifier("id") pi.sort() assert not pi.empty() pi.setSignificanceThreshold(6.0) # Test __repr__ and __str__ methods pi_repr = pyopenms.PeptideIdentification() pi_repr.setRT(1234.5) pi_repr.setMZ(445.678) pi_repr.setScoreType("XTandem") hit = pyopenms.PeptideHit() hit.setScore(50.5) hit.setRank(1) hit.setSequence(pyopenms.AASequence.fromString("PEPTIDE")) hit.setCharge(2) pi_repr.insertHit(hit) repr_str = repr(pi_repr) assert "PeptideIdentification(" in repr_str assert "rt=" in repr_str assert "mz=" in repr_str assert "score_type=" in repr_str assert "num_hits=" in repr_str assert "top_hit=" in repr_str assert "PEPTIDE" in repr_str # Test str method str_str = str(pi_repr) assert str_str == repr_str @report def testPeptideIdentificationList(): """ @tests: PeptideIdentificationList PeptideIdentificationList.__init__ PeptideIdentificationList.__getitem__ PeptideIdentificationList.__iter__ PeptideIdentificationList.__len__ PeptideIdentificationList.append PeptideIdentificationList.clear PeptideIdentificationList.empty PeptideIdentificationList.extend PeptideIdentificationList.push_back PeptideIdentificationList.size """ import pyopenms # Test default constructor pil = pyopenms.PeptideIdentificationList() assert pil.empty() assert pil.size() == 0 # Create some PeptideIdentification objects for testing pi1 = pyopenms.PeptideIdentification() pi1.setRT(100.0) pi1.setMZ(200.0) pi1.setIdentifier("test1") pi2 = pyopenms.PeptideIdentification() pi2.setRT(150.0) pi2.setMZ(250.0) pi2.setIdentifier("test2") # Test push_back pil.push_back(pi1) assert not pil.empty() assert pil.size() == 1 pil.push_back(pi2) assert pil.size() == 2 # Test element access first = pil[0] assert first.getRT() == 100.0 assert first.getMZ() == 200.0 assert first.getIdentifier() == "test1" second = pil[1] assert second.getRT() == 150.0 assert second.getMZ() == 250.0 assert second.getIdentifier() == "test2" # Test iteration count = 0 for pi in pil: assert isinstance(pi, pyopenms.PeptideIdentification) count += 1 assert count == 2 # Test constructor from vector import pyopenms pil2 = pyopenms.PeptideIdentificationList() pil2.push_back(pi1) pil2.push_back(pi2) assert pil2.size() == 2 assert pil2[0].getIdentifier() == "test1" assert pil2[1].getIdentifier() == "test2" # Test clear pil.clear() assert pil.empty() assert pil.size() == 0 # Test __len__, append, and extend methods pil_len = pyopenms.PeptideIdentificationList() assert len(pil_len) == 0 assert len(pil_len) == pil_len.size() pi_test1 = pyopenms.PeptideIdentification() pi_test1.setRT(100.0) pi_test1.setMZ(500.0) pi_test1.setIdentifier("test_append_1") pi_test2 = pyopenms.PeptideIdentification() pi_test2.setRT(200.0) pi_test2.setMZ(600.0) pi_test2.setIdentifier("test_append_2") pi_test3 = pyopenms.PeptideIdentification() pi_test3.setRT(300.0) pi_test3.setMZ(700.0) pi_test3.setIdentifier("test_append_3") # Test append (single item) pil_len.append(pi_test1) assert len(pil_len) == 1 assert len(pil_len) == pil_len.size() # Test extend with list pil_len.extend([pi_test2, pi_test3]) assert len(pil_len) == 3 assert len(pil_len) == pil_len.size() # Verify the peptide identifications were added correctly assert pil_len[0].getRT() == 100.0 assert pil_len[0].getIdentifier() == "test_append_1" assert pil_len[1].getRT() == 200.0 assert pil_len[1].getIdentifier() == "test_append_2" assert pil_len[2].getRT() == 300.0 assert pil_len[2].getIdentifier() == "test_append_3" # Test extend with another PeptideIdentificationList pil_source = pyopenms.PeptideIdentificationList() pi_test4 = pyopenms.PeptideIdentification() pi_test4.setRT(400.0) pi_test4.setMZ(800.0) pi_test4.setIdentifier("test_append_4") pil_source.push_back(pi_test4) pil_len.extend(pil_source) assert len(pil_len) == 4 assert pil_len[3].getRT() == 400.0 assert pil_len[3].getIdentifier() == "test_append_4" @report def testPolarity(): """ @tests: Polarity Polarity.NEGATIVE Polarity.POLNULL Polarity.POSITIVE Polarity.SIZE_OF_POLARITY """ assert isinstance(pyopenms.IonSource.Polarity.NEGATIVE, int) assert isinstance(pyopenms.IonSource.Polarity.POLNULL, int) assert isinstance(pyopenms.IonSource.Polarity.POSITIVE, int) @report def testPrecursor(): """ @tests: Precursor Precursor.__init__ Precursor.getActivationMethods Precursor.setActivationMethods Precursor.getActivationEnergy Precursor.setActivationEnergy Precursor.getIsolationWindowLowerOffset Precursor.setIsolationWindowLowerOffset Precursor.getDriftTime Precursor.setDriftTime Precursor.getIsolationWindowUpperOffset Precursor.setIsolationWindowUpperOffset Precursor.getDriftTimeWindowLowerOffset Precursor.setDriftTimeWindowLowerOffset Precursor.getDriftTimeWindowUpperOffset Precursor.setDriftTimeWindowUpperOffset Precursor.getCharge Precursor.setCharge Precursor.getPossibleChargeStates Precursor.setPossibleChargeStates Precursor.getUnchargedMass Precursor.__eq__ Precursor.__ne__ """ # Test constructors prec = pyopenms.Precursor() prec2 = pyopenms.Precursor(prec) assert prec == prec2 assert not prec != prec2 # Test activation methods methods = set([pyopenms.Precursor.ActivationMethod.CID, pyopenms.Precursor.ActivationMethod.HCD]) methods_short = ["CID", "HCD"] methods_long = ["Collision-induced dissociation", "beam-type collision-induced dissociation"] prec.setActivationMethods(methods) assert prec.getActivationMethods() == methods # Test activation energy prec.setActivationEnergy(25.0) assert abs(prec.getActivationEnergy() - 25.0) < 1e-5 # Test activation methods as strings short_strings = prec.getActivationMethodsAsShortString() assert sorted([s.decode() for s in short_strings]) == sorted(methods_short) long_strings = prec.getActivationMethodsAsString() assert sorted([s.decode() for s in long_strings]) == sorted(methods_long) # Test static methods for all activation methods all_names = pyopenms.Precursor.getAllNamesOfActivationMethods() assert len(all_names) == pyopenms.Precursor.ActivationMethod.SIZE_OF_ACTIVATIONMETHOD assert all_names[pyopenms.Precursor.ActivationMethod.CID].decode() == "Collision-induced dissociation" all_short_names = pyopenms.Precursor.getAllShortNamesOfActivationMethods() assert len(all_short_names) == pyopenms.Precursor.ActivationMethod.SIZE_OF_ACTIVATIONMETHOD assert all_short_names[pyopenms.Precursor.ActivationMethod.CID].decode() == "CID" # Test isolation window prec.setIsolationWindowLowerOffset(0.5) assert abs(prec.getIsolationWindowLowerOffset() - 0.5) < 1e-5 prec.setIsolationWindowUpperOffset(1.5) assert abs(prec.getIsolationWindowUpperOffset() - 1.5) < 1e-5 # Test drift time prec.setDriftTime(5.0) assert abs(prec.getDriftTime() - 5.0) < 1e-5 # Test drift time window prec.setDriftTimeWindowLowerOffset(0.2) assert abs(prec.getDriftTimeWindowLowerOffset() - 0.2) < 1e-5 prec.setDriftTimeWindowUpperOffset(0.8) assert abs(prec.getDriftTimeWindowUpperOffset() - 0.8) < 1e-5 # Test charge prec.setCharge(2) assert prec.getCharge() == 2 # Test possible charge states charges = [2,3,4] prec.setPossibleChargeStates(charges) assert list(prec.getPossibleChargeStates()) == charges # Test uncharged mass calculation mz = 200.0 prec.setMZ(mz) charge = 2 prec.setCharge(charge) expected_mass = mz * charge - charge * 1.007276466879 # mass of proton assert abs(prec.getUnchargedMass() - expected_mass) < 1e-5 @report def testProcessingAction(): """ @tests: ProcessingAction ProcessingAction.ALIGNMENT ProcessingAction.BASELINE_REDUCTION ProcessingAction.CALIBRATION ProcessingAction.CHARGE_CALCULATION ProcessingAction.CHARGE_DECONVOLUTION ProcessingAction.CONVERSION_DTA ProcessingAction.CONVERSION_MZDATA ProcessingAction.CONVERSION_MZML ProcessingAction.CONVERSION_MZXML ProcessingAction.DATA_PROCESSING ProcessingAction.DEISOTOPING ProcessingAction.FEATURE_GROUPING ProcessingAction.FILTERING ProcessingAction.FORMAT_CONVERSION ProcessingAction.IDENTIFICATION ProcessingAction.IDENTIFICATION_MAPPING ProcessingAction.NORMALIZATION ProcessingAction.PEAK_PICKING ProcessingAction.PRECURSOR_RECALCULATION ProcessingAction.QUANTITATION ProcessingAction.SIZE_OF_PROCESSINGACTION ProcessingAction.SMOOTHING """ assert isinstance(pyopenms.DataProcessing.ProcessingAction.ALIGNMENT, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.BASELINE_REDUCTION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CALIBRATION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CHARGE_CALCULATION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CHARGE_DECONVOLUTION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CONVERSION_DTA, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CONVERSION_MZDATA, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CONVERSION_MZML, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.CONVERSION_MZXML, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.DATA_PROCESSING, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.DEISOTOPING, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.FEATURE_GROUPING, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.FILTERING, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.FORMAT_CONVERSION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.IDENTIFICATION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.IDENTIFICATION_MAPPING, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.NORMALIZATION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.PEAK_PICKING, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.PRECURSOR_RECALCULATION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.QUANTITATION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.SIZE_OF_PROCESSINGACTION, int) assert isinstance(pyopenms.DataProcessing.ProcessingAction.SMOOTHING, int) @report def testProduct(): """ @tests: Product Product.__init__ Product.getIsolationWindowLowerOffset Product.getIsolationWindowUpperOffset Product.getMZ Product.setIsolationWindowLowerOffset Product.setIsolationWindowUpperOffset Product.setMZ Product.__eq__ Product.__ge__ Product.__gt__ Product.__le__ Product.__lt__ Product.__ne__ """ p = pyopenms.Product() p.setMZ(12.0) p.setIsolationWindowLowerOffset(10.0) p.setIsolationWindowUpperOffset(15.0) assert p.getMZ() == 12.0 assert p.getIsolationWindowLowerOffset() == 10.0 assert p.getIsolationWindowUpperOffset() == 15.0 assert p == p assert not p != p @report def testProteinHit(): """ @tests: ProteinHit ProteinHit.__init__ ProteinHit.clearMetaInfo ProteinHit.getAccession ProteinHit.getCoverage ProteinHit.getKeys ProteinHit.getMetaValue ProteinHit.setMetaValue ProteinHit.getRank ProteinHit.__eq__ ProteinHit.__ge__ ProteinHit.__gt__ ProteinHit.__le__ ProteinHit.__lt__ ProteinHit.__ne__ ProteinHit.getScore ProteinHit.getSequence ProteinHit.isMetaEmpty ProteinHit.metaValueExists ProteinHit.removeMetaValue ProteinHit.setAccession ProteinHit.setCoverage ProteinHit.setRank ProteinHit.setScore ProteinHit.setSequence """ ph = pyopenms.ProteinHit() assert ph == ph assert not ph != ph _testMetaInfoInterface(ph) ph.setAccession("A") ph.setCoverage(0.5) ph.setRank(2) ph.setScore(1.5) ph.setSequence("ABA") assert ph.getAccession() == ("A") assert ph.getCoverage() == (0.5) assert ph.getRank() == (2) assert ph.getScore() == (1.5) assert ph.getSequence() == ("ABA") # Test __repr__ and __str__ methods ph_repr = pyopenms.ProteinHit() ph_repr.setAccession("P12345") ph_repr.setScore(150.5) ph_repr.setRank(1) ph_repr.setCoverage(45.2) ph_repr.setDescription("Example protein") repr_str = repr(ph_repr) assert "ProteinHit(" in repr_str assert "accession=" in repr_str assert "P12345" in repr_str assert "score=" in repr_str assert "coverage=" in repr_str # Test str method str_str = str(ph_repr) assert str_str == repr_str @report def testProteinIdentification(): """ @tests: ProteinIdentification ProteinIdentification.PeakMassType ProteinIdentification.__init__ ProteinIdentification.clearMetaInfo ProteinIdentification.getHits ProteinIdentification.getKeys ProteinIdentification.getMetaValue ProteinIdentification.insertHit ProteinIdentification.isMetaEmpty ProteinIdentification.metaValueExists ProteinIdentification.removeMetaValue ProteinIdentification.setHits ProteinIdentification.setMetaValue ProteinIdentification.__eq__ ProteinIdentification.__ge__ ProteinIdentification.__gt__ ProteinIdentification.__le__ ProteinIdentification.__lt__ ProteinIdentification.__ne__ """ pi = pyopenms.ProteinIdentification() _testMetaInfoInterface(pi) assert pi == pi assert not pi != pi assert pi.getHits() == [] ph = pyopenms.ProteinHit() pi.insertHit(ph) ph2, = pi.getHits() assert ph2 == ph pi.setHits([ph]) ph2, = pi.getHits() assert ph2 == ph assert isinstance(pyopenms.ProteinIdentification.PeakMassType.MONOISOTOPIC, int) assert isinstance(pyopenms.ProteinIdentification.PeakMassType.AVERAGE, int) # Test getAllNamesOf method peak_mass_names = pyopenms.ProteinIdentification.getAllNamesOfPeakMassType() assert len(peak_mass_names) == pyopenms.ProteinIdentification.PeakMassType.SIZE_OF_PEAKMASSTYPE assert peak_mass_names[pyopenms.ProteinIdentification.PeakMassType.MONOISOTOPIC].decode() == "Monoisotopic" assert peak_mass_names[pyopenms.ProteinIdentification.PeakMassType.AVERAGE].decode() == "Average" @report def testRichPeak(): """ @tests: RichPeak1D RichPeak1D.__init__ RichPeak1D.getIntensity RichPeak1D.getKeys RichPeak1D.getMZ RichPeak1D.__eq__ RichPeak1D.__ge__ RichPeak1D.__gt__ RichPeak1D.__le__ RichPeak1D.__lt__ RichPeak1D.__ne__ RichPeak1D.getMetaValue RichPeak1D.clearMetaInfo RichPeak1D.isMetaEmpty RichPeak1D.metaValueExists RichPeak1D.removeMetaValue RichPeak1D.setIntensity RichPeak1D.setMZ RichPeak1D.setMetaValue RichPeak2D.__init__ RichPeak2D.clearUniqueId RichPeak2D.clearMetaInfo RichPeak2D.isMetaEmpty RichPeak2D.ensureUniqueId RichPeak2D.getIntensity RichPeak2D.getKeys RichPeak2D.getMZ RichPeak2D.getMetaValue RichPeak2D.getRT RichPeak2D.getUniqueId RichPeak2D.hasInvalidUniqueId RichPeak2D.hasValidUniqueId RichPeak2D.metaValueExists RichPeak2D.removeMetaValue RichPeak2D.setIntensity RichPeak2D.setMZ RichPeak2D.setMetaValue RichPeak2D.setUniqueId RichPeak2D.setRT RichPeak2D.__eq__ RichPeak2D.__ge__ RichPeak2D.__gt__ RichPeak2D.__le__ RichPeak2D.__lt__ RichPeak2D.__ne__ """ p2 = pyopenms.RichPeak2D() _testMetaInfoInterface(p2) _testUniqueIdInterface(p2) assert p2 == p2 assert not p2 != p2 p2.setMZ(22.0) p2.setIntensity(23.0) p2.setRT(43.0) assert p2.getMZ() == (22.0) assert p2.getIntensity() == (23.0) assert p2.getRT() == (43.0) @report def testSoftware(): """ @tests: Software Software.__init__ Software.getName Software.getVersion Software.setName Software.setVersion """ sw = pyopenms.Software() sw.setName("name") sw.setVersion("1.0.0") assert sw.getName() == "name" assert sw.getVersion() == "1.0.0" @report def testSourceFile(): """ @tests: SourceFile SourceFile.__init__ SourceFile.getChecksum SourceFile.getChecksumType SourceFile.getFileSize SourceFile.getFileType SourceFile.getNameOfFile SourceFile.getNativeIDType SourceFile.getPathToFile SourceFile.setChecksum SourceFile.setFileSize SourceFile.setFileType SourceFile.setNameOfFile SourceFile.setNativeIDType SourceFile.setPathToFile """ sf = pyopenms.SourceFile() sf.setNameOfFile("file.txt") assert sf.getNameOfFile() == "file.txt" sf.setPathToFile("file.txt") assert sf.getPathToFile() == "file.txt" sf.setFileType(".txt") assert sf.getFileType() == ".txt" sf.setChecksum("abcde000", pyopenms.SourceFile.ChecksumType.UNKNOWN_CHECKSUM) assert sf.getChecksum() == "abcde000" assert sf.getChecksumType() in (pyopenms.SourceFile.ChecksumType.UNKNOWN_CHECKSUM, pyopenms.SourceFile.ChecksumType.SHA1, pyopenms.SourceFile.ChecksumType.MD5) # Test getAllNamesOf method checksum_names = pyopenms.SourceFile.getAllNamesOfChecksumType() assert len(checksum_names) == pyopenms.SourceFile.ChecksumType.SIZE_OF_CHECKSUMTYPE assert checksum_names[pyopenms.SourceFile.ChecksumType.SHA1].decode() == "SHA-1" assert checksum_names[pyopenms.SourceFile.ChecksumType.MD5].decode() == "MD5" @report def testSpectrumSetting(s=pyopenms.SpectrumSettings()): """ @tests: SpectrumSettings SpectrumSettings.SpectrumType SpectrumSettings.__init__ SpectrumSettings.getAcquisitionInfo SpectrumSettings.getComment SpectrumSettings.getDataProcessing SpectrumSettings.getInstrumentSettings SpectrumSettings.getNativeID SpectrumSettings.getPrecursors SpectrumSettings.getProducts SpectrumSettings.getSourceFile SpectrumSettings.getType SpectrumSettings.setAcquisitionInfo SpectrumSettings.setComment SpectrumSettings.setDataProcessing SpectrumSettings.setInstrumentSettings SpectrumSettings.setNativeID SpectrumSettings.setPrecursors SpectrumSettings.setProducts SpectrumSettings.setSourceFile SpectrumSettings.setType SpectrumSettings.unify """ assert s.getType() in [ pyopenms.SpectrumSettings.SpectrumType.UNKNOWN, pyopenms.SpectrumSettings.SpectrumType.CENTROID, pyopenms.SpectrumSettings.SpectrumType.PROFILE] assert isinstance(s.getAcquisitionInfo(), pyopenms.AcquisitionInfo) assert isinstance(s.getInstrumentSettings(), pyopenms.InstrumentSettings) assert isinstance(s.getSourceFile(), pyopenms.SourceFile) assert isinstance(s.getDataProcessing(), list) s.setAcquisitionInfo(s.getAcquisitionInfo()) s.setInstrumentSettings(s.getInstrumentSettings()) s.setSourceFile(s.getSourceFile()) s.setDataProcessing(s.getDataProcessing()) s.setComment(s.getComment()) s.setPrecursors(s.getPrecursors()) s.setProducts(s.getProducts()) s.setType(s.getType()) s.setNativeID(s.getNativeID()) s.setType(s.getType()) if isinstance(s, pyopenms.SpectrumSettings): s.unify(s) # Test getAllNamesOf method spectrum_type_names = pyopenms.SpectrumSettings.getAllNamesOfSpectrumType() assert len(spectrum_type_names) == pyopenms.SpectrumSettings.SpectrumType.SIZE_OF_SPECTRUMTYPE assert spectrum_type_names[pyopenms.SpectrumSettings.SpectrumType.CENTROID].decode() == "Centroid" assert spectrum_type_names[pyopenms.SpectrumSettings.SpectrumType.PROFILE].decode() == "Profile" @report def testTransformationDescription(): """ @tests: TransformationDescription TransformationDescription.__init__ TransformationDescription.apply TransformationDescription.getDataPoints TransformationDescription.fitModel TransformationDescription.getModelParameters TransformationDescription.getModelType TransformationDescription.invert """ td = pyopenms.TransformationDescription() assert td.getDataPoints() == [] assert isinstance(td.apply(0.0), float) td.fitModel p = td.getModelParameters() td.getModelType() td.invert @report def testTransformationModels(): """ @tests: TransformationModelInterpolated TransformationModelInterpolated.getDefaultParameters TransformationModelInterpolated.getParameters TransformationModelLinear.getDefaultParameters TransformationModelLinear.getParameters TransformationModelBSpline.getDefaultParameters TransformationModelBSpline.getParameters TransformationModelLowess.getDefaultParameters TransformationModelLowess.getParameters NB: THIS TEST STOPS AFTER THE FIRST FAILURE """ for clz in [pyopenms.TransformationModelLinear, pyopenms.TransformationModelBSpline, pyopenms.TransformationModelInterpolated, pyopenms.TransformationModelLowess]: p = pyopenms.Param() data = [ pyopenms.TM_DataPoint(9.0, 8.9), pyopenms.TM_DataPoint(5.0, 6.0), pyopenms.TM_DataPoint(8.0, 8.0) ] mod = clz(data, p) mod.evaluate(7.0) mod.getDefaultParameters(p) @report def testTransformationXMLFile(): """ @tests: TransformationXMLFile TransformationXMLFile.__init__ TransformationXMLFile.load TransformationXMLFile.store """ fh = pyopenms.TransformationXMLFile() td = pyopenms.TransformationDescription() fh.store("test.transformationXML", td) fh.load("test.transformationXML", td, True) assert td.getDataPoints() == [] @report def testIBSpectraFile(): """ @tests: IBSpectraFile IBSpectraFile.__init__ IBSpectraFile.store """ fh = pyopenms.IBSpectraFile() cmap = pyopenms.ConsensusMap() correctError = False try: fh.store( pyopenms.String("test.ibspectra.file"), cmap) assert False except RuntimeError: correctError = True assert correctError @report def testSwathFile(): """ @tests: SwathFile SwathFile.__init__ SwathFile.store """ fh = pyopenms.SwathFile() @report def testType(): """ @tests: Type Type.CONSENSUSXML Type.DTA Type.DTA2D Type.EDTA Type.FASTA Type.FEATUREXML Type.GELML Type.HARDKLOER Type.IDXML Type.INI Type.KROENIK Type.MASCOTXML Type.MGF Type.MS2 Type.MSP Type.MZDATA Type.MZIDENTML Type.MZML Type.MZXML Type.OMSSAXML Type.PEPLIST Type.PEPXML Type.PNG Type.PROTXML Type.SIZE_OF_TYPE Type.TOPPAS Type.TRAML Type.TRANSFORMATIONXML Type.TSV Type.UNKNOWN Type.XMASS """ for ti in [ pyopenms.FileType.CONSENSUSXML ,pyopenms.FileType.DTA ,pyopenms.FileType.DTA2D ,pyopenms.FileType.EDTA ,pyopenms.FileType.FASTA ,pyopenms.FileType.FEATUREXML ,pyopenms.FileType.GELML ,pyopenms.FileType.HARDKLOER ,pyopenms.FileType.IDXML ,pyopenms.FileType.INI ,pyopenms.FileType.KROENIK ,pyopenms.FileType.MASCOTXML ,pyopenms.FileType.MGF ,pyopenms.FileType.MS2 ,pyopenms.FileType.MSP ,pyopenms.FileType.MZDATA ,pyopenms.FileType.MZIDENTML ,pyopenms.FileType.MZML ,pyopenms.FileType.MZXML ,pyopenms.FileType.OMSSAXML ,pyopenms.FileType.PEPLIST ,pyopenms.FileType.PEPXML ,pyopenms.FileType.PNG ,pyopenms.FileType.PROTXML ,pyopenms.FileType.SIZE_OF_TYPE ,pyopenms.FileType.TOPPAS ,pyopenms.FileType.TRAML ,pyopenms.FileType.TRANSFORMATIONXML ,pyopenms.FileType.TSV ,pyopenms.FileType.UNKNOWN ,pyopenms.FileType.XMASS]: assert isinstance(ti, int) @report def testVersion(): """ @tests: VersionDetails VersionDetails.__init__ VersionDetails.create VersionDetails.version_major VersionDetails.version_minor VersionDetails.version_patch VersionDetails.__eq__ VersionDetails.__ge__ VersionDetails.__gt__ VersionDetails.__le__ VersionDetails.__lt__ VersionDetails.__ne__ VersionInfo.getRevision VersionInfo.getTime VersionInfo.getVersion __version__ """ _testStrOutput(pyopenms.VersionInfo.getVersion()) _testStrOutput(pyopenms.VersionInfo.getRevision()) _testStrOutput(pyopenms.VersionInfo.getTime()) vd = pyopenms.VersionDetails.create("19.2.1") assert vd.version_major == 19 assert vd.version_minor == 2 assert vd.version_patch == 1 vd = pyopenms.VersionDetails.create("19.2.1-alpha") assert vd.version_major == 19 assert vd.version_minor == 2 assert vd.version_patch == 1 assert vd.pre_release_identifier == "alpha" assert vd == vd assert not vd < vd assert not vd > vd assert isinstance(pyopenms.__version__, str) @report def testInspectInfile(): """ @tests: InspectInfile InspectInfile.__init__ """ inst = pyopenms.InspectInfile() assert inst.getModifications is not None mods = inst.getModifications() assert len(mods) == 0 @report def testAttachment(): """ @tests: Attachment Attachment.__init__ """ inst = pyopenms.Attachment() assert inst.name is not None assert inst.value is not None assert inst.cvRef is not None assert inst.cvAcc is not None assert inst.unitRef is not None assert inst.unitAcc is not None assert inst.binary is not None assert inst.qualityRef is not None assert inst.colTypes is not None assert inst.tableRows is not None assert inst.toXMLString is not None assert inst.toCSVString is not None inst.name = "test" inst.value = "test" inst.cvRef = "test" inst.cvAcc = "test" inst.unitRef = "test" inst.unitAcc = "test" inst.binary = "test" inst.qualityRef = "test" inst.colTypes = [ b"test", b"test2"] inst.tableRows = [ [b"test", b"test2"], [b"otherTest"] ] assert inst.tableRows[1][0] == b"otherTest" @report def testKernelMassTrace(): trace = pyopenms.Kernel_MassTrace() assert trace.getSize is not None assert trace.getLabel is not None assert trace.setLabel is not None assert trace.getCentroidMZ is not None assert trace.getCentroidRT is not None assert trace.getCentroidSD is not None assert trace.getFWHM is not None assert trace.getTraceLength is not None assert trace.getFWHMborders is not None assert trace.getSmoothedIntensities is not None assert trace.getAverageMS1CycleTime is not None assert trace.computeSmoothedPeakArea is not None assert trace.computePeakArea is not None assert trace.findMaxByIntPeak is not None assert trace.estimateFWHM is not None assert trace.computeFwhmArea is not None assert trace.computeFwhmAreaSmooth is not None # assert trace.computeFwhmAreaRobust is not None # assert trace.computeFwhmAreaSmoothRobust is not None assert trace.getIntensity is not None assert trace.getMaxIntensity is not None assert trace.getConvexhull is not None assert trace.setCentroidSD is not None assert trace.setSmoothedIntensities is not None assert trace.updateSmoothedMaxRT is not None assert trace.updateWeightedMeanRT is not None assert trace.updateSmoothedWeightedMeanRT is not None assert trace.updateMedianRT is not None assert trace.updateMedianMZ is not None assert trace.updateMeanMZ is not None assert trace.updateWeightedMeanMZ is not None assert trace.updateWeightedMZsd is not None s = trace.getSize() @report def testElutionPeakDetection(): detection = pyopenms.ElutionPeakDetection() assert detection.detectPeaks is not None assert detection.filterByPeakWidth is not None assert detection.computeMassTraceNoise is not None assert detection.computeMassTraceSNR is not None assert detection.computeApexSNR is not None assert detection.findLocalExtrema is not None assert detection.smoothData is not None trace = pyopenms.Kernel_MassTrace() detection.smoothData(trace, 4) @report def testIndexedMzMLDecoder(): decoder = pyopenms.IndexedMzMLDecoder() try: pos = decoder.findIndexListOffset("abcde", 100) raise Exception("Should raise an error") except RuntimeError: pass def test_MapConversion(): feature = pyopenms.Feature() feature.setRT(99) cmap = pyopenms.ConsensusMap() fmap = pyopenms.FeatureMap() fmap.push_back(feature) pyopenms.MapConversion().convert(0, fmap, cmap, 1) assert(cmap.size() == 1) assert(cmap[0].getRT() == 99.0) fmap = pyopenms.FeatureMap() pyopenms.MapConversion().convert(cmap, True, fmap) assert(fmap.size() == 1) assert(fmap[0].getRT() == 99.0) exp = pyopenms.MSExperiment() sp = pyopenms.MSSpectrum() peak = pyopenms.Peak1D() peak.setIntensity(10) peak.setMZ(20) sp.push_back(peak) exp.addSpectrum(sp) exp.addSpectrum(sp) cmap = pyopenms.ConsensusMap() pyopenms.MapConversion().convert(0, exp, cmap, 2) assert(cmap.size() == 2) assert(cmap[0].getIntensity() == 10.0) assert(cmap[0].getMZ() == 20.0) def test_BSpline2d(): x = [1.0, 6.0, 8.0, 10.0, 15.0] y = [2.0, 5.0, 6.0, 12.0, 13.0] spline = pyopenms.BSpline2d(x,y,0, pyopenms.BoundaryCondition.BC_ZERO_ENDPOINTS, 0) assert spline.ok() assert abs(spline.eval(6.0) - 5.0 < 0.01) assert abs(spline.derivative(6.0) - 5.0 < 0.01) y_new = [4.0, 5.0, 6.0, 12.0, 13.0] spline.solve(y_new) assert spline.ok() assert abs(spline.eval(6.0) - 5.0 < 0.01) @report def testConsensusIDAlgorithmAverage(): algo = pyopenms.ConsensusIDAlgorithmAverage() assert algo.apply @report def testConsensusIDAlgorithmBest(): algo = pyopenms.ConsensusIDAlgorithmBest() assert algo.apply @report def testConsensusIDAlgorithmPEPIons(): algo = pyopenms.ConsensusIDAlgorithmPEPIons() assert algo.apply @report def testConsensusIDAlgorithmPEPMatrix(): algo = pyopenms.ConsensusIDAlgorithmPEPMatrix() assert algo.apply @report def testConsensusIDAlgorithmRanks(): algo = pyopenms.ConsensusIDAlgorithmRanks() assert algo.apply @report def testConsensusIDAlgorithmWorst(): algo = pyopenms.ConsensusIDAlgorithmWorst() assert algo.apply @report def testDigestionEnzymeProtein(): f = pyopenms.EmpiricalFormula() regex_description = "" psi_id = "" xtandem_id = "" comet_id = 0 omssa_id = 0 e = pyopenms.DigestionEnzymeProtein("testEnzyme", "K", set([]), regex_description, f, f, psi_id, xtandem_id, comet_id, omssa_id) @report def testMRMAssay(): e = pyopenms.MRMAssay() assert e @report def testMRMIonSeries(): e = pyopenms.MRMIonSeries() assert e @report def testPeptideIndexing(): e = pyopenms.PeptideIndexing() assert e @report def testPeptideProteinResolution(): e = pyopenms.PeptideProteinResolution(False) assert e @report def testPercolatorOutfile(): e = pyopenms.PercolatorOutfile() assert e @report def testProteaseDB(): edb = pyopenms.ProteaseDB() f = pyopenms.EmpiricalFormula() synonyms = set(["dummy", "other"]) assert edb.hasEnzyme(pyopenms.String("Trypsin")) trypsin = edb.getEnzyme(pyopenms.String("Trypsin")) names = [] edb.getAllNames(names) assert b"Trypsin" in names @report def testElementDB(): edb = pyopenms.ElementDB() del edb # create a second instance of ElementDB without anything bad happening edb = pyopenms.ElementDB() assert edb.hasElement(16) edb.hasElement(pyopenms.String("O")) e = edb.getElement(16) assert e.getName() == "Sulfur" assert e.getSymbol() == "S" assert e.getIsotopeDistribution() e2 = edb.getElement(pyopenms.String("O")) assert e2.getName() == "Oxygen" assert e2.getSymbol() == "O" assert e2.getIsotopeDistribution() # assume we discovered a new element e2 = edb.addElement(b"NewElement", b"NE", 300, {400 : 1.0}, {400 : 400.1}, False) e2 = edb.getElement(pyopenms.String("NE")) assert e2.getName() == "NewElement" # changing existing elements in tests might have side effects so we define a new element # add first new element e2 = edb.addElement(b"Kryptonite", b"@", 500, {999 : 0.7, 1000 : 0.3}, {999 : 999.01, 1000 : 1000.01}, False) e2 = edb.getElement(pyopenms.String("@")) assert e2.getName() == "Kryptonite" assert e2.getIsotopeDistribution() assert len(e2.getIsotopeDistribution().getContainer()) == 2 assert abs(e2.getIsotopeDistribution().getContainer()[1].getIntensity() - 0.3) < 1e-5 # replace element e2 = edb.addElement(b"Kryptonite", b"@", 500, {9999 : 1.0}, {9999 : 9999.1}, True) e2 = edb.getElement(pyopenms.String("@")) assert e2.getName() == "Kryptonite" assert e2.getIsotopeDistribution() assert len(e2.getIsotopeDistribution().getContainer()) == 1 assert abs(e2.getIsotopeDistribution().getContainer()[0].getIntensity() - 1.0) < 1e-5 # assert e == e2 # not yet implemented # # const Map[ String, Element * ] getNames() except + nogil # const Map[ String, Element * ] getSymbols() except + nogil # const Map[unsigned int, Element * ] getAtomicNumbers() except + nogil @report def testDPosition(): dp = pyopenms.DPosition1() dp = pyopenms.DPosition1(1.0) assert dp[0] == 1.0 dp = pyopenms.DPosition2() dp = pyopenms.DPosition2(1.0, 2.0) assert dp[0] == 1.0 assert dp[1] == 2.0 # Test __repr__ method for DPosition1 dp1_repr = pyopenms.DPosition1(123.456) repr_str = repr(dp1_repr) assert "DPosition1(" in repr_str assert "x=" in repr_str # Test __repr__ method for DPosition2 dp2_repr = pyopenms.DPosition2(100.0, 200.0) repr_str = repr(dp2_repr) assert "DPosition2(" in repr_str assert "x=" in repr_str assert "y=" in repr_str @report def testResidueDB(): rdb = pyopenms.ResidueDB() del rdb # create a second instance of ResidueDB without anything bad happening rdb = pyopenms.ResidueDB() assert rdb.getNumberOfResidues() >= 20 assert len(rdb.getResidueSets() ) >= 1 el = rdb.getResidues(pyopenms.String(rdb.getResidueSets().pop())) assert len(el) >= 1 assert rdb.hasResidue(s("Glycine")) glycine = rdb.getResidue(s("Glycine")) nrr = rdb.getNumberOfResidues() @report def testModificationsDB(): mdb = pyopenms.ModificationsDB() del mdb # create a second instance of ModificationsDB without anything bad happening mdb = pyopenms.ModificationsDB() assert mdb.getNumberOfModifications() > 1 m = mdb.getModification(1) assert mdb.getNumberOfModifications() > 1 m = mdb.getModification(1) assert m is not None mods = set([]) mdb.searchModifications(mods, s("Phosphorylation"), s("T"), pyopenms.ResidueModification.TermSpecificity.ANYWHERE) assert len(mods) == 1 mods = set([]) mdb.searchModifications(mods, s("NIC"), s("T"), pyopenms.ResidueModification.TermSpecificity.N_TERM) assert len(mods) == 1 mods = set([]) mdb.searchModifications(mods, s("NIC"), s("T"), pyopenms.ResidueModification.TermSpecificity.N_TERM) assert len(mods) == 1 mods = set([]) mdb.searchModifications(mods, s("Acetyl"), s("T"), pyopenms.ResidueModification.TermSpecificity.N_TERM) assert len(mods) == 1 assert list(mods)[0].getFullId() == "Acetyl (N-term)" m = mdb.getModification(s("Carboxymethyl (C)"), "", pyopenms.ResidueModification.TermSpecificity.NUMBER_OF_TERM_SPECIFICITY) assert m.getFullId() == "Carboxymethyl (C)" m = mdb.getModification( s("Phosphorylation"), s("S"), pyopenms.ResidueModification.TermSpecificity.ANYWHERE) assert m.getId() == "Phospho" # get out all mods (there should be many, some known ones as well!) mods = [] m = mdb.getAllSearchModifications(mods) assert len(mods) > 100 assert b"Phospho (S)" in mods assert b"Sulfo (S)" in mods assert not (b"Phospho" in mods) # search for specific modifications by mass m = mdb.getBestModificationByDiffMonoMass( 80.0, 1.0, "T", pyopenms.ResidueModification.TermSpecificity.ANYWHERE) assert m is not None assert m.getId() == "Phospho" assert m.getFullName() == "Phosphorylation" assert m.getUniModAccession() == "UniMod:21" m = mdb.getBestModificationByDiffMonoMass(80, 100, "T", pyopenms.ResidueModification.TermSpecificity.ANYWHERE) assert m is not None assert m.getId() == "Phospho" assert m.getFullName() == "Phosphorylation" assert m.getUniModAccession() == "UniMod:21" m = mdb.getBestModificationByDiffMonoMass(16, 1.0, "M", pyopenms.ResidueModification.TermSpecificity.ANYWHERE) assert m is not None assert m.getId() == "Oxidation", m.getId() assert m.getFullName() == "Oxidation or Hydroxylation", m.getFullName() assert m.getUniModAccession() == "UniMod:35" @report def testRNaseDB(): """ @tests: RNaseDB const DigestionEnzymeRNA* getEnzyme(const String& name) except + nogil const DigestionEnzymeRNA* getEnzymeByRegEx(const String& cleavage_regex) except + nogil void getAllNames(libcpp_vector[ String ]& all_names) except + nogil bool hasEnzyme(const String& name) except + nogil bool hasRegEx(const String& cleavage_regex) except + nogil """ db = pyopenms.RNaseDB() names = [] db.getAllNames(names) e = db.getEnzyme("RNase_T1") assert e.getThreePrimeGain() == u'p' assert db.hasEnzyme("RNase_T1") @report def testRibonucleotideDB(): """ @tests: RibonucleotideDB """ r = pyopenms.RibonucleotideDB() uridine = r.getRibonucleotide(b"U") assert uridine.getName() == u'uridine' assert uridine.getCode() == u'U' assert uridine.getFormula().toString() == u'C9H12N2O6' assert uridine.isModified() == False @report def testRibonucleotide(): """ @tests: Ribonucleotide """ r = pyopenms.Ribonucleotide() assert not r.isModified() r.setHTMLCode("test") assert r.getHTMLCode() == "test" r.setOrigin(b"A") assert r.getOrigin() == "A" r.setNewCode(b"A") assert r.getNewCode() == "A" @report def testRNaseDigestion(): """ @tests: RNaseDigestion """ dig = pyopenms.RNaseDigestion() dig.setEnzyme("RNase_T1") assert dig.getEnzymeName() == "RNase_T1" oligo = pyopenms.NASequence.fromString("pAUGUCGCAG"); result = [] dig.digest(oligo, result) assert len(result) == 3 @report def testNASequence(): """ @tests: NASequence """ oligo = pyopenms.NASequence.fromString("pAUGUCGCAG"); assert oligo.size() == 9 seq_formula = oligo.getFormula() seq_formula.toString() == u'C86H108N35O64P9' oligo_mod = pyopenms.NASequence.fromString("A[m1A][Gm]A") seq_formula = oligo_mod.getFormula() seq_formula.toString() == u'C42H53N20O23P3' for r in oligo: pass assert oligo_mod[1].isModified() charge = 2 oligo_mod.getMonoWeight(pyopenms.NASequence.NASFragmentType.WIon, charge) oligo_mod.getFormula(pyopenms.NASequence.NASFragmentType.WIon, charge) # Test __repr__ and __str__ methods # Test __repr__ method na_repr = pyopenms.NASequence.fromString("ACGU") repr_str = repr(na_repr) assert "NASequence(" in repr_str assert "sequence=" in repr_str assert "length=" in repr_str assert "mono_mass=" in repr_str # Test __str__ method returns the sequence string str_str = str(na_repr) assert str_str == "ACGU" # Test __len__ method assert len(na_repr) == 4 @report def testExperimentalDesign(): """ @tests: ExperimentalDesign ExperimentalDesign.__init__ ExperimentalDesign.getNumberOfSamples() == 8 ExperimentalDesign.getNumberOfFractions() == 3 ExperimentalDesign.getNumberOfLabels() == 4 ExperimentalDesign.getNumberOfMSFiles() == 6 ExperimentalDesign.getNumberOfFractionGroups() == 2 ExperimentalDesign.getSample(1, 1) == 0 ExperimentalDesign.getSample(2, 4) == 7 ExperimentalDesign.isFractionated() ExperimentalDesign.sameNrOfMSFilesPerFraction() ExperimentalDesignFile.__init__ ExperimentalDesignFile.load """ f = pyopenms.ExperimentalDesignFile() fourplex_fractionated_design = pyopenms.ExperimentalDesign() ed_dirname = os.path.dirname(os.path.abspath(__file__)) ed_filename = os.path.join(ed_dirname, "ExperimentalDesign_input_2.tsv").encode() fourplex_fractionated_design = pyopenms.ExperimentalDesignFile.load(ed_filename, False) assert fourplex_fractionated_design.getNumberOfSamples() == 8 assert fourplex_fractionated_design.getNumberOfFractions() == 3 assert fourplex_fractionated_design.getNumberOfLabels() == 4 assert fourplex_fractionated_design.getNumberOfMSFiles() == 6 assert fourplex_fractionated_design.getNumberOfFractionGroups() == 2 assert fourplex_fractionated_design.getSample(1, 1) == 0 assert fourplex_fractionated_design.getSample(2, 4) == 7 assert fourplex_fractionated_design.isFractionated() assert fourplex_fractionated_design.sameNrOfMSFilesPerFraction() @report def testString(): pystr = pyopenms.String() pystr = pyopenms.String("blah") assert (pystr.toString() == "blah") pystr = pyopenms.String("blah") assert (pystr.toString() == "blah") pystr = pyopenms.String(u"blah") assert (pystr.toString() == "blah") pystr = pyopenms.String(pystr) assert (pystr.toString() == "blah") assert (len(pystr.toString()) == 4) cstr = pystr.c_str() # Printing should work ... print(cstr) print(pystr) print(pystr.toString()) assert (pystr.toString() == "blah") pystr = pyopenms.String("bläh") assert (pystr.toString() == u"bläh") pystr = pyopenms.String("bläh") pystr = pyopenms.String(u"bläh") assert (pystr.toString() == u"bläh") pystr = pyopenms.String(pystr) assert (pystr.toString() == u"bläh") cstr = pystr.c_str() # Printing should work ... print(cstr) print(pystr) print(pystr.toString().encode("utf8")) assert len(pystr.toString()) == 4 assert len(pystr.c_str()) == 5 # C does not know about Unicode, so be careful with c_str print(pystr) # this prints the C string, due to Py 2/3 compatibility print(pystr.toString().encode("utf8")) # this prints the correct String pystr1 = pyopenms.String("bläh") pystr2 = pyopenms.String("bläh") assert(pystr1 == pystr2) pystr1 = pyopenms.String(u"bläh") pystr2 = pyopenms.String(u"bläh") assert(pystr1 == pystr2) # Handling of different Unicode Strings: # - unicode is natively stored in OpenMS::String # - encoded bytesequences for utf8, utf16 and iso8859 can be stored as # char arrays in OpenMS::String (and be accessed using c_str()) # - encoded bytesequences for anything other than utf8 cannot use # "toString()" as this function expects utf8 ustr = u"bläh" pystr = pyopenms.String(ustr) assert (pystr.toString() == u"bläh") pystr = pyopenms.String(ustr.encode("utf8")) assert (pystr.toString() == u"bläh") pystr = pyopenms.String(ustr.encode("iso8859_15")) assert (pystr.c_str().decode("iso8859_15") == u"bläh") pystr = pyopenms.String(ustr.encode("utf16")) assert (pystr.c_str().decode("utf16") == u"bläh") # toString will throw as its not UTF8 pystr = pyopenms.String(ustr.encode("iso8859_15")) didThrow = False try: pystr.toString() except UnicodeDecodeError: didThrow = True assert didThrow # toString will throw as its not UTF8 pystr = pyopenms.String(ustr.encode("utf16")) didThrow = False try: pystr.toString() except UnicodeDecodeError: didThrow = True assert didThrow # Handling of automatic conversions of String return values # -- return a native str when utf8 is used # -- return a OpenMS::String object when encoding with utf8 is not possible ustr = u"bläh" s = pyopenms.MSSpectrum() s.setNativeID(ustr) r = s.getNativeID() # assert( isinstance(r, str) ) # native, returns str assert(r == u"bläh") s.setNativeID(ustr.encode("utf8")) r = s.getNativeID() # assert( isinstance(r, str) ) assert(r == u"bläh") s.setNativeID(ustr.encode("utf16")) r = s.getNativeID() # assert( isinstance(r, bytes) ) # assert(r.c_str().decode("utf16") == u"bläh") s.setNativeID(ustr.encode("iso8859_15")) r = s.getNativeID() # assert( isinstance(r, bytes) ) assert(r.decode("iso8859_15") == u"bläh") @report def testGNPSExport(): cm = pyopenms.ConsensusMap() for mz, rt, ion, linked_groups in [(222.08, 62.0, "[M+H]+", ["1","2","3"]), (244.08, 62.0, "[M+Na]+", ["1","2"]), (204.08, 62.0, "[M-H-O]+", ["3"]), (294.1, 62.0, "[M+H]+", ["4","5"])]: f = pyopenms.ConsensusFeature() f.setMZ(mz) f.setRT(rt) f.setCharge(1) f.setQuality(2.0) f.setMetaValue("best ion", ion) f.setMetaValue("LinkedGroups", linked_groups) cm.push_back(f) cm.setUniqueIds() pyopenms.IonIdentityMolecularNetworking.annotateConsensusMap(cm) pyopenms.IonIdentityMolecularNetworking.writeSupplementaryPairTable(cm, "SupplementaryPairsTable.csv") with open("SupplementaryPairsTable.csv", "r") as f: assert f.read() == """ID1,ID2,EdgeType,Score,Annotation 1,2,MS1 annotation,1,[M+H]+ [M+Na]+ dm/z=22.0 1,3,MS1 annotation,1,[M+H]+ [M-H-O]+ dm/z=18.0 """ os.remove("SupplementaryPairsTable.csv") pyopenms.GNPSQuantificationFile().store(cm, "FeatureQuantificationTable.txt") with open("FeatureQuantificationTable.txt", "r") as f: assert f.read() == """#MAP id filename label size #CONSENSUS rt_cf mz_cf intensity_cf charge_cf width_cf quality_cf row ID best ion partners annotation network number CONSENSUS 62.0 222.080000000000013 0.0 1 0.0 2.0 1 [M+H]+ 2;3 1 CONSENSUS 62.0 244.080000000000013 0.0 1 0.0 2.0 2 [M+Na]+ 1 1 CONSENSUS 62.0 204.080000000000013 0.0 1 0.0 2.0 3 [M-H-O]+ 1 1 CONSENSUS 62.0 294.100000000000023 0.0 1 0.0 2.0 4 [M+H]+ 2 """ os.remove("FeatureQuantificationTable.txt") # add mandatory file descriptions file_descriptions = {} for i, filename in enumerate(["1.mzML", "2.mzML"]): file_description = pyopenms.ColumnHeader() file_description.filename = filename file_descriptions[i] = file_description cm.setColumnHeaders(file_descriptions) pyopenms.GNPSMetaValueFile().store(cm, "MetaValueTable.tsv") with open("MetaValueTable.tsv", "r") as f: assert f.read() == """ filename ATTRIBUTE_MAPID 0 1.mzML MAP0 1 2.mzML MAP1 """ os.remove("MetaValueTable.tsv")
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Smoothing.py
.py
2,387
75
import unittest import os import pyopenms class TestGaussFilter(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() self.exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, self.exp) def test_init(self): thisfilter = pyopenms.GaussFilter(); def test_run(self): thisfilter = pyopenms.GaussFilter(); old_firstspec = self.exp[0] thisfilter.filterExperiment(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # MZ should not change, Intensity should self.assertEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) class TestSavitzkyGolayFilter(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() self.exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, self.exp) def test_init(self): thisfilter = pyopenms.SavitzkyGolayFilter(); def test_run(self): thisfilter = pyopenms.SavitzkyGolayFilter(); old_firstspec = self.exp[0] thisfilter.filterExperiment(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # MZ should not change, Intensity should self.assertEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) class TestLowessSmoothing(unittest.TestCase): def setUp(self): pass def test_init(self): thisfilter = pyopenms.LowessSmoothing(); def test_init(self): thisfilter = pyopenms.LowessSmoothing(); x = [1.0,2.0,3.0,4.0] y = [10.0,11.0,12.0,13.0] y_smoothed = [0.0] thisfilter.smoothData(x,y,y_smoothed) self.assertNotEqual( len(y_smoothed), 0) # The smoothed data should be different from the input data self.assertNotEqual( y_smoothed, y) self.assertNotEqual( y_smoothed[0], y[0]) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_ChromatogramExtractor.py
.py
2,311
55
import unittest import os import pyopenms class TestChromatogramExtractor(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.TraML").encode() self.filename_mzml = os.path.join(dirname, "test2.mzML").encode() def test_extractor(self): targeted = pyopenms.TargetedExperiment() tramlfile = pyopenms.TraMLFile() tramlfile.load(self.filename, targeted) exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename_mzml, exp) trafo = pyopenms.TransformationDescription() # Prepare extraction coordinates output_chromatograms = [] extraction_coordinates = [] pyopenms.ChromatogramExtractor.prepare_coordinates(output_chromatograms, extraction_coordinates, targeted, -1, # rt_extraction_window False, # ms1 0) # ms1_isotopes # Create input map input_map = pyopenms.SpectrumAccessOpenMS(exp) # Extract chromatograms extractor = pyopenms.ChromatogramExtractor() # extract full RT range (-1) extractor.extractChromatograms(input_map, output_chromatograms, extraction_coordinates, 10, False, -1, b"tophat") # Basically test that the output is non-zero (e.g. the data is # correctly relayed to python) # The functionality is not tested here! self.assertEqual(len(output_chromatograms), len(targeted.getTransitions())) self.assertNotEqual(len(output_chromatograms), 0) self.assertNotEqual(len(output_chromatograms[0].get_intensity_array()), 0) self.assertNotEqual(len(output_chromatograms[0].get_time_array()), 0) # one chromatogram per transition; one chromatographic peak for each spectrum self.assertEqual(len(output_chromatograms[0].get_intensity_array()), exp.size()) self.assertEqual(len(output_chromatograms[0].get_time_array()), exp.size()) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_ISpectrumAccess.py
.py
3,852
120
import unittest import os import pyopenms class TestSpectrumAccessOpenMS(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() def test_readfile_content(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, exp) saccess = pyopenms.SpectrumAccessOpenMS(exp) spectrum = saccess.getSpectrumById(0) mz = spectrum.get_mz_array() intensity = spectrum.get_intensity_array() self.assertAlmostEqual(mz[0], 350.0000305) self.assertAlmostEqual(intensity[0], 0.0) self.assertAlmostEqual(mz[10], 358.075134277) self.assertAlmostEqual(intensity[10], 9210.931640625) class TestSpectrumAccessOpenMSInMemory(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() def test_readfile_content(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, exp) # Create in memory access saccess_ = pyopenms.SpectrumAccessOpenMS(exp) saccess = pyopenms.SpectrumAccessOpenMSInMemory(saccess_) spectrum = saccess.getSpectrumById(0) mz = spectrum.get_mz_array() intensity = spectrum.get_intensity_array() self.assertAlmostEqual(mz[0], 350.0000305) self.assertAlmostEqual(intensity[0], 0.0) self.assertAlmostEqual(mz[10], 358.075134277) self.assertAlmostEqual(intensity[10], 9210.931640625) class TestSpectrumAccessSwathMap(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() def test_swathmap_openms(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, exp) saccess = pyopenms.SpectrumAccessOpenMS(exp) swmap = pyopenms.SwathMap() swmap.lower = 400 swmap.center = 412.5 swmap.upper = 425 swmap.ms1 = False data = swmap.getSpectrumPtr() assert data is None # Now we should have data in there swmap.setSpectrumPtr(saccess) data = swmap.getSpectrumPtr() assert data is not None swmap.setSpectrumPtr(saccess) data = swmap.getSpectrumPtr() assert data is not None spectrum = data.getSpectrumById(0) mz = spectrum.get_mz_array() intensity = spectrum.get_intensity_array() self.assertAlmostEqual(mz[0], 350.0000305) self.assertAlmostEqual(intensity[0], 0.0) self.assertAlmostEqual(mz[10], 358.075134277) self.assertAlmostEqual(intensity[10], 9210.931640625) def test_readfile_contentInMemory(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, exp) # Create in memory access saccess_ = pyopenms.SpectrumAccessOpenMS(exp) saccess = pyopenms.SpectrumAccessOpenMSInMemory(saccess_) swmap = pyopenms.SwathMap() swmap.lower = 400 swmap.center = 412.5 swmap.upper = 425 swmap.ms1 = False data = swmap.getSpectrumPtr() assert data is None swmap.setSpectrumPtr(saccess_) data = swmap.getSpectrumPtr() assert data is not None spectrum = data.getSpectrumById(0) mz = spectrum.get_mz_array() intensity = spectrum.get_intensity_array() self.assertAlmostEqual(mz[0], 350.0000305) self.assertAlmostEqual(intensity[0], 0.0) self.assertAlmostEqual(mz[10], 358.075134277) self.assertAlmostEqual(intensity[10], 9210.931640625) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_DRange.py
.py
4,204
144
""" Tests for DRange1 Python wrapper """ import unittest import pyopenms class TestDRange1(unittest.TestCase): """Test DRange1 class""" def test_default_constructor(self): """Test default constructor creates empty range""" r = pyopenms.DRange1() self.assertTrue(r.isEmpty()) def test_copy_constructor(self): """Test copy constructor""" r1 = pyopenms.DRange1(10.0, 20.0) r2 = pyopenms.DRange1(r1) self.assertEqual(r1.minX(), r2.minX()) self.assertEqual(r1.maxX(), r2.maxX()) def test_two_float_constructor(self): """Test constructor with two floats""" r = pyopenms.DRange1(10.0, 20.0) self.assertFalse(r.isEmpty()) self.assertEqual(r.minX(), 10.0) self.assertEqual(r.maxX(), 20.0) def test_two_int_constructor(self): """Test constructor accepts ints and converts to floats""" r = pyopenms.DRange1(5, 15) self.assertEqual(r.minX(), 5.0) self.assertEqual(r.maxX(), 15.0) def test_setMinX_setMaxX(self): """Test setMinX and setMaxX methods""" r = pyopenms.DRange1() r.setMinX(100.0) r.setMaxX(200.0) self.assertEqual(r.minX(), 100.0) self.assertEqual(r.maxX(), 200.0) def test_encloses(self): """Test encloses method with float values""" r = pyopenms.DRange1(10.0, 20.0) # Below min - not enclosed self.assertFalse(r.encloses(5.0)) # At min - enclosed (inclusive) self.assertTrue(r.encloses(10.0)) # Inside range - enclosed self.assertTrue(r.encloses(15.0)) # At max - not enclosed (exclusive) self.assertFalse(r.encloses(20.0)) # Above max - not enclosed self.assertFalse(r.encloses(25.0)) def test_united(self): """Test united method""" r1 = pyopenms.DRange1(5.0, 15.0) r2 = pyopenms.DRange1(12.0, 25.0) r3 = r1.united(r2) self.assertEqual(r3.minX(), 5.0) self.assertEqual(r3.maxX(), 25.0) def test_isIntersected(self): """Test isIntersected method""" r1 = pyopenms.DRange1(5.0, 15.0) r2 = pyopenms.DRange1(12.0, 25.0) r3 = pyopenms.DRange1(20.0, 30.0) # Overlapping ranges self.assertTrue(r1.isIntersected(r2)) # Non-overlapping ranges self.assertFalse(r1.isIntersected(r3)) def test_repr_str(self): """Test __repr__ and __str__ methods""" r = pyopenms.DRange1(10.0, 20.0) self.assertIn("DRange1", repr(r)) self.assertIn("10.0", repr(r)) self.assertIn("20.0", repr(r)) self.assertEqual(str(r), repr(r)) class TestPeakFileOptionsWithDRange1(unittest.TestCase): """Test PeakFileOptions methods that use DRange1""" def test_rt_range(self): """Test setRTRange/getRTRange/hasRTRange""" pfo = pyopenms.PeakFileOptions() self.assertFalse(pfo.hasRTRange()) rt_range = pyopenms.DRange1(100.0, 500.0) pfo.setRTRange(rt_range) self.assertTrue(pfo.hasRTRange()) rt_back = pfo.getRTRange() self.assertEqual(rt_back.minX(), 100.0) self.assertEqual(rt_back.maxX(), 500.0) def test_mz_range(self): """Test setMZRange/getMZRange/hasMZRange""" pfo = pyopenms.PeakFileOptions() self.assertFalse(pfo.hasMZRange()) mz_range = pyopenms.DRange1(200.0, 1000.0) pfo.setMZRange(mz_range) self.assertTrue(pfo.hasMZRange()) mz_back = pfo.getMZRange() self.assertEqual(mz_back.minX(), 200.0) self.assertEqual(mz_back.maxX(), 1000.0) def test_intensity_range(self): """Test setIntensityRange/getIntensityRange/hasIntensityRange""" pfo = pyopenms.PeakFileOptions() self.assertFalse(pfo.hasIntensityRange()) int_range = pyopenms.DRange1(1000.0, 1e6) pfo.setIntensityRange(int_range) self.assertTrue(pfo.hasIntensityRange()) int_back = pfo.getIntensityRange() self.assertEqual(int_back.minX(), 1000.0) self.assertEqual(int_back.maxX(), 1e6) if __name__ == "__main__": unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/testSpecialCases.py
.py
1,718
63
import pyopenms import numpy def _test_container(c, i, append_method="push_back"): # did raise segfault because of missing index check in __getitem__ # should be resolved by implementing a proper iterator: s = c() assert list(s) == [] try: s[0] except IndexError: pass else: assert False, "no exception risen" exec("s.%s(i())" % append_method) (item,) = s # test iterator s[0] # test getattr try: s[1] except IndexError: pass else: assert False, "no exception risen" def testContainers(): _test_container(pyopenms.MSSpectrum, pyopenms.Peak1D) _test_container(pyopenms.MSExperiment, pyopenms.MSSpectrum, "addSpectrum") _test_container(pyopenms.FeatureMap, pyopenms.Feature) def testConvexHull2D(): h = pyopenms.ConvexHull2D() points = numpy.arange(10.0, dtype=numpy.float32).reshape(-1, 2) h.setHullPoints(points) p = h.getHullPoints() assert numpy.linalg.norm(p - points) < 1e-6 h.expandToBoundingBox() hullp = h.getHullPoints() assert set(hullp[:,0]) == set((0.0, 8.0)) assert set(hullp[:,1]) == set((1.0, 9.0)) box = h.getBoundingBox() assert box.minPosition() == [ 0.0, 1.0] assert box.maxPosition() == [ 8.0, 9.0] h.addPoint([-10.0, -10.0]) box = h.getBoundingBox() assert box.minPosition() == [ -10.0, -10.0] assert box.maxPosition() == [ 8.0, 9.0] h.expandToBoundingBox() hullp = h.getHullPoints() assert set(hullp[:,0]) == set((-10.0, 8.0)) assert set(hullp[:,1]) == set((-10.0, 9.0)) box = h.getBoundingBox() assert box.minPosition() == [ -10.0, -10.0] assert box.maxPosition() == [ 8.0, 9.0]
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/__init__.py
.py
0
0
null
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_dataframe_columns.py
.py
31,472
886
""" Tests for DataFrame column selection feature in MSSpectrum and MSChromatogram. Tests cover: - get_df_columns() discovery method - Column selection via get_df(columns=[...]) - Default behavior (backward compatibility) - Non-default columns (ion_mobility_unit, chromatogram_type, comment) - Meta value handling with column selection - Edge cases (empty spectra, missing data) """ import pytest import numpy as np import pyopenms class TestMSSpectrumColumnSelection: """Tests for MSSpectrum.get_df() column selection.""" @pytest.fixture def spectrum_with_data(self): """Create a spectrum with peaks, precursor, IM data, and meta values.""" spec = pyopenms.MSSpectrum() spec.setMSLevel(2) spec.setRT(123.45) spec.setNativeID('scan=100') spec.setMetaValue('total_ion_current', 1000.0) spec.setMetaValue('base_peak_mz', 500.0) # Set peaks mzs = np.array([100.0, 200.0, 300.0], dtype=np.float64) ints = np.array([10.0, 20.0, 30.0], dtype=np.float32) spec.set_peaks([mzs, ints]) # Set precursor precursor = pyopenms.Precursor() precursor.setMZ(500.0) precursor.setCharge(2) spec.setPrecursors([precursor]) # Set ion mobility data using FloatDataArray fda = pyopenms.FloatDataArray() fda.setName('Ion Mobility') for val in [1.5, 2.0, 2.5]: fda.push_back(val) spec.setFloatDataArrays([fda]) spec.setDriftTime(2.0) # Set drift time for containsIMData() # Set ion annotations sda = pyopenms.StringDataArray() for ann in ['b2+', 'y3+', 'b4+']: sda.push_back(ann) sda.setName('IonNames') spec.setStringDataArrays([sda]) return spec @pytest.fixture def simple_spectrum(self): """Create a simple MS1 spectrum without precursor or IM data.""" spec = pyopenms.MSSpectrum() spec.setMSLevel(1) spec.setRT(50.0) spec.setNativeID('scan=50') mzs = np.array([100.0, 200.0], dtype=np.float64) ints = np.array([10.0, 20.0], dtype=np.float32) spec.set_peaks([mzs, ints]) return spec def test_get_df_columns_full_spectrum(self, spectrum_with_data): """Test get_df_columns() returns all expected columns for full spectrum.""" cols = spectrum_with_data.get_df_columns() # Should have core columns assert 'mz' in cols assert 'intensity' in cols assert 'rt' in cols assert 'ms_level' in cols assert 'native_id' in cols # Should have IM column (data present) assert 'ion_mobility' in cols # Should have precursor columns (MS2) assert 'precursor_mz' in cols assert 'precursor_charge' in cols # Should have annotation column assert 'ion_annotation' in cols # Should have meta values assert 'total_ion_current' in cols assert 'base_peak_mz' in cols # Should NOT have non-default columns assert 'ion_mobility_unit' not in cols def test_get_df_columns_simple_spectrum(self, simple_spectrum): """Test get_df_columns() for simple MS1 spectrum.""" cols = simple_spectrum.get_df_columns() # Should have core columns assert 'mz' in cols assert 'intensity' in cols assert 'rt' in cols # Should NOT have precursor columns (MS1) assert 'precursor_mz' not in cols assert 'precursor_charge' not in cols # Should NOT have IM columns (no IM data) assert 'ion_mobility' not in cols def test_get_df_columns_no_meta_values(self, spectrum_with_data): """Test get_df_columns() with export_meta_values=False.""" cols = spectrum_with_data.get_df_columns(export_meta_values=False) assert 'mz' in cols assert 'total_ion_current' not in cols assert 'base_peak_mz' not in cols def test_get_df_default(self, spectrum_with_data): """Test get_df() default behavior returns all expected columns.""" df = spectrum_with_data.get_df() # Check core columns present assert 'mz' in df.columns assert 'intensity' in df.columns assert 'rt' in df.columns assert 'ms_level' in df.columns assert 'native_id' in df.columns # Check data values assert len(df) == 3 # 3 peaks assert df.loc[0, 'mz'] == 100.0 assert df.loc[0, 'rt'] == 123.45 assert df.loc[0, 'ms_level'] == 2 # Check meta values present assert 'total_ion_current' in df.columns def test_get_df_minimal_columns(self, spectrum_with_data): """Test get_df() with minimal column selection.""" df = spectrum_with_data.get_df(columns=['mz', 'intensity']) assert list(df.columns) == ['mz', 'intensity'] assert len(df) == 3 assert df.loc[0, 'mz'] == 100.0 assert df.loc[0, 'intensity'] == 10.0 def test_get_df_custom_columns(self, spectrum_with_data): """Test get_df() with custom column selection.""" df = spectrum_with_data.get_df(columns=['mz', 'intensity', 'rt', 'precursor_mz']) assert set(df.columns) == {'mz', 'intensity', 'rt', 'precursor_mz'} assert df.loc[0, 'precursor_mz'] == 500.0 def test_get_df_with_ion_mobility(self, spectrum_with_data): """Test get_df() including ion mobility column.""" df = spectrum_with_data.get_df(columns=['mz', 'intensity', 'ion_mobility']) assert 'ion_mobility' in df.columns assert df.loc[0, 'ion_mobility'] == 1.5 assert df.loc[1, 'ion_mobility'] == 2.0 def test_get_df_with_ion_mobility_unit(self, spectrum_with_data): """Test get_df() with non-default ion_mobility_unit column.""" df = spectrum_with_data.get_df(columns=['mz', 'intensity', 'ion_mobility_unit']) assert 'ion_mobility_unit' in df.columns def test_get_df_with_ion_annotation(self, spectrum_with_data): """Test get_df() including ion annotation column.""" df = spectrum_with_data.get_df(columns=['mz', 'intensity', 'ion_annotation']) assert 'ion_annotation' in df.columns assert df.loc[0, 'ion_annotation'] == 'b2+' assert df.loc[1, 'ion_annotation'] == 'y3+' def test_get_df_with_meta_value(self, spectrum_with_data): """Test get_df() with specific meta value column.""" df = spectrum_with_data.get_df(columns=['mz', 'intensity', 'total_ion_current']) assert 'total_ion_current' in df.columns assert df.loc[0, 'total_ion_current'] == 1000.0 def test_get_df_all_columns(self, spectrum_with_data): """Test get_df() requesting all available columns including non-defaults.""" # Get all default columns cols = spectrum_with_data.get_df_columns() # Add non-default columns cols.append('ion_mobility_unit') df = spectrum_with_data.get_df(columns=cols) # Should have all columns assert 'mz' in df.columns assert 'ion_mobility_unit' in df.columns assert 'total_ion_current' in df.columns def test_get_df_missing_precursor(self, simple_spectrum): """Test get_df() requesting precursor columns when no precursor present.""" df = simple_spectrum.get_df(columns=['mz', 'intensity', 'precursor_mz']) assert 'precursor_mz' in df.columns assert np.isnan(df.loc[0, 'precursor_mz']) def test_get_df_empty_spectrum(self): """Test get_df() with empty spectrum.""" spec = pyopenms.MSSpectrum() df = spec.get_df() assert len(df) == 0 def test_get_df_columns_empty_spectrum(self): """Test get_df_columns() with empty spectrum.""" spec = pyopenms.MSSpectrum() cols = spec.get_df_columns() # Should still have core columns assert 'mz' in cols assert 'intensity' in cols class TestMSChromatogramColumnSelection: """Tests for MSChromatogram.get_df() column selection.""" @pytest.fixture def chromatogram_with_data(self): """Create a chromatogram with peaks and meta values.""" chrom = pyopenms.MSChromatogram() chrom.setNativeID('chrom_1') chrom.setMetaValue('FWHM', 5.0) chrom.setMetaValue('peak_apex', 100.5) # Set precursor precursor = pyopenms.Precursor() precursor.setMZ(500.0) precursor.setCharge(2) chrom.setPrecursor(precursor) # Set product product = pyopenms.Product() product.setMZ(300.0) chrom.setProduct(product) # Set peaks rts = np.array([10.0, 20.0, 30.0], dtype=np.float64) ints = np.array([100.0, 200.0, 150.0], dtype=np.float32) chrom.set_peaks([rts, ints]) return chrom def test_get_df_columns(self, chromatogram_with_data): """Test get_df_columns() returns expected columns.""" cols = chromatogram_with_data.get_df_columns() # Default columns assert 'rt' in cols assert 'intensity' in cols assert 'precursor_mz' in cols assert 'precursor_charge' in cols assert 'product_mz' in cols assert 'native_id' in cols # Meta values assert 'FWHM' in cols assert 'peak_apex' in cols # Non-default columns should NOT be present assert 'chromatogram_type' not in cols assert 'comment' not in cols def test_get_df_columns_all(self, chromatogram_with_data): """Test get_df_columns('all') returns all columns including non-defaults.""" cols = chromatogram_with_data.get_df_columns('all') # Default columns should be present assert 'rt' in cols assert 'intensity' in cols assert 'precursor_mz' in cols # Non-default columns SHOULD be present with 'all' assert 'chromatogram_type' in cols assert 'comment' in cols # Meta values still present assert 'FWHM' in cols def test_get_df_default(self, chromatogram_with_data): """Test get_df() default behavior.""" df = chromatogram_with_data.get_df() assert 'rt' in df.columns assert 'intensity' in df.columns assert 'precursor_mz' in df.columns assert 'native_id' in df.columns assert 'FWHM' in df.columns # Non-default should NOT be present assert 'chromatogram_type' not in df.columns assert 'comment' not in df.columns assert len(df) == 3 assert df.loc[0, 'rt'] == 10.0 def test_get_df_minimal_columns(self, chromatogram_with_data): """Test get_df() with minimal columns.""" df = chromatogram_with_data.get_df(columns=['rt', 'intensity']) assert list(df.columns) == ['rt', 'intensity'] assert len(df) == 3 def test_get_df_with_non_default_columns(self, chromatogram_with_data): """Test get_df() with non-default columns.""" df = chromatogram_with_data.get_df(columns=['rt', 'intensity', 'chromatogram_type', 'comment']) assert 'chromatogram_type' in df.columns assert 'comment' in df.columns def test_get_df_with_meta_value(self, chromatogram_with_data): """Test get_df() with specific meta value.""" df = chromatogram_with_data.get_df(columns=['rt', 'intensity', 'FWHM']) assert 'FWHM' in df.columns assert df.loc[0, 'FWHM'] == 5.0 def test_get_df_all_columns(self, chromatogram_with_data): """Test get_df() with all columns including non-defaults using 'all' parameter.""" # Use the cleaner API with 'all' parameter cols = chromatogram_with_data.get_df_columns('all') df = chromatogram_with_data.get_df(columns=cols) # Should have all columns assert 'rt' in df.columns assert 'chromatogram_type' in df.columns assert 'comment' in df.columns assert 'FWHM' in df.columns class TestMobilogramColumnSelection: """Tests for Mobilogram.get_df() column selection.""" @pytest.fixture def mobilogram_with_data(self): """Create a mobilogram with peaks.""" mob = pyopenms.Mobilogram() mob.setRT(100.0) # Set peaks mobilities = np.array([0.8, 0.9, 1.0], dtype=np.float64) ints = np.array([100.0, 200.0, 150.0], dtype=np.float32) mob.set_peaks([mobilities, ints]) return mob def test_get_df_columns(self, mobilogram_with_data): """Test get_df_columns() returns expected columns.""" cols = mobilogram_with_data.get_df_columns() assert 'mobility' in cols assert 'intensity' in cols assert 'rt' in cols assert 'drift_time_unit' in cols def test_get_df_default(self, mobilogram_with_data): """Test get_df() default behavior.""" df = mobilogram_with_data.get_df() assert 'mobility' in df.columns assert 'intensity' in df.columns assert 'rt' in df.columns assert len(df) == 3 assert df.loc[0, 'mobility'] == 0.8 assert df.loc[0, 'rt'] == 100.0 def test_get_df_minimal_columns(self, mobilogram_with_data): """Test get_df() with minimal columns.""" df = mobilogram_with_data.get_df(columns=['mobility', 'intensity']) assert list(df.columns) == ['mobility', 'intensity'] assert len(df) == 3 class TestPeptideIdentificationListGetDF: """Tests for PeptideIdentificationList.get_df() method.""" @pytest.fixture def peptide_id_list(self): """Create a PeptideIdentificationList with test data.""" pep_list = pyopenms.PeptideIdentificationList() # Create first PeptideIdentification with a hit pep1 = pyopenms.PeptideIdentification() pep1.setRT(100.0) pep1.setMZ(500.25) pep1.setScoreType('Mascot') pep1.setIdentifier('test_id_1') hit1 = pyopenms.PeptideHit() hit1.setScore(50.0) hit1.setCharge(2) hit1.setSequence(pyopenms.AASequence.fromString('PEPTIDE')) hit1.setMetaValue('target_decoy', 'target') pep1.setHits([hit1]) pep_list.append(pep1) # Create second PeptideIdentification with a hit pep2 = pyopenms.PeptideIdentification() pep2.setRT(200.0) pep2.setMZ(600.30) pep2.setScoreType('Mascot') pep2.setIdentifier('test_id_2') hit2 = pyopenms.PeptideHit() hit2.setScore(75.0) hit2.setCharge(3) hit2.setSequence(pyopenms.AASequence.fromString('ANOTHER')) hit2.setMetaValue('target_decoy', 'decoy') pep2.setHits([hit2]) pep_list.append(pep2) return pep_list @pytest.fixture def empty_peptide_id_list(self): """Create an empty PeptideIdentificationList.""" return pyopenms.PeptideIdentificationList() @pytest.fixture def peptide_id_list_with_unidentified(self): """Create a PeptideIdentificationList with unidentified entries.""" pep_list = pyopenms.PeptideIdentificationList() # Create identified entry pep1 = pyopenms.PeptideIdentification() pep1.setRT(100.0) pep1.setMZ(500.25) pep1.setScoreType('Mascot') pep1.setIdentifier('test_id_1') hit1 = pyopenms.PeptideHit() hit1.setScore(50.0) hit1.setCharge(2) hit1.setSequence(pyopenms.AASequence.fromString('PEPTIDE')) pep1.setHits([hit1]) pep_list.append(pep1) # Create unidentified entry (no hits) pep2 = pyopenms.PeptideIdentification() pep2.setRT(200.0) pep2.setMZ(600.30) pep2.setIdentifier('test_id_2') # No hits set pep_list.append(pep2) return pep_list def test_get_df_basic(self, peptide_id_list): """Test get_df() returns expected DataFrame structure.""" df = peptide_id_list.get_df() assert len(df) == 2 assert 'rt' in df.columns assert 'mz' in df.columns assert 'charge' in df.columns assert 'P_ID' in df.columns assert 'PSM_ID' in df.columns def test_get_df_values(self, peptide_id_list): """Test get_df() returns correct values.""" df = peptide_id_list.get_df() assert df.loc[0, 'rt'] == pytest.approx(100.0, rel=1e-3) assert df.loc[0, 'mz'] == pytest.approx(500.25, rel=1e-3) assert df.loc[0, 'charge'] == 2 assert df.loc[1, 'rt'] == pytest.approx(200.0, rel=1e-3) assert df.loc[1, 'mz'] == pytest.approx(600.30, rel=1e-3) assert df.loc[1, 'charge'] == 3 def test_get_df_empty_list(self, empty_peptide_id_list): """Test get_df() with empty list.""" df = empty_peptide_id_list.get_df() assert len(df) == 0 def test_get_df_export_unidentified_true(self, peptide_id_list_with_unidentified): """Test get_df() exports unidentified entries when export_unidentified=True.""" df = peptide_id_list_with_unidentified.get_df(export_unidentified=True) assert len(df) == 2 def test_get_df_export_unidentified_false(self, peptide_id_list_with_unidentified): """Test get_df() skips unidentified entries when export_unidentified=False.""" df = peptide_id_list_with_unidentified.get_df(export_unidentified=False) assert len(df) == 1 def test_get_df_decode_ontology_false(self, peptide_id_list): """Test get_df() with decode_ontology=False.""" df = peptide_id_list.get_df(decode_ontology=False) assert len(df) == 2 def test_get_df_custom_missing_values(self, peptide_id_list_with_unidentified): """Test get_df() with custom default_missing_values.""" custom_missing = {bool: False, int: 0, float: 0.0, str: 'N/A'} df = peptide_id_list_with_unidentified.get_df( default_missing_values=custom_missing, export_unidentified=True ) assert len(df) == 2 def test_update_scores_from_df(self, peptide_id_list): """Test update_scores_from_df() method.""" df = peptide_id_list.get_df() # Modify scores in DataFrame df['new_score'] = [100.0, 200.0] # Update scores peptide_id_list.update_scores_from_df(df, 'new_score') # Verify scores were updated assert peptide_id_list[0].getHits()[0].getScore() == 100.0 assert peptide_id_list[1].getHits()[0].getScore() == 200.0 # Verify score type was set assert peptide_id_list[0].getScoreType() == 'new_score' class TestBackwardsCompatibleFunctions: """Tests for backwards-compatible wrapper functions in _dataframes module.""" @pytest.fixture def peptide_id_list(self): """Create a PeptideIdentificationList with test data.""" pep_list = pyopenms.PeptideIdentificationList() pep1 = pyopenms.PeptideIdentification() pep1.setRT(100.0) pep1.setMZ(500.25) pep1.setScoreType('Mascot') pep1.setIdentifier('test_id_1') hit1 = pyopenms.PeptideHit() hit1.setScore(50.0) hit1.setCharge(2) hit1.setSequence(pyopenms.AASequence.fromString('PEPTIDE')) pep1.setHits([hit1]) pep_list.append(pep1) return pep_list def test_peptide_identifications_to_df_wrapper(self, peptide_id_list): """Test that the wrapper function calls get_df() correctly.""" # Call the wrapper function df = pyopenms.peptide_identifications_to_df(peptide_id_list) assert len(df) == 1 assert 'rt' in df.columns assert 'mz' in df.columns def test_update_scores_from_df_wrapper(self, peptide_id_list): """Test that the wrapper function calls update_scores_from_df() correctly.""" df = pyopenms.peptide_identifications_to_df(peptide_id_list) df['new_score'] = [100.0] # Call the wrapper function result = pyopenms.update_scores_from_df(peptide_id_list, df, 'new_score') assert result[0].getHits()[0].getScore() == 100.0 class TestBackwardCompatibility: """Tests to ensure backward compatibility with existing code.""" def test_spectrum_get_df_no_args(self): """Test MSSpectrum.get_df() works without arguments.""" spec = pyopenms.MSSpectrum() spec.setMSLevel(1) mzs = np.array([100.0, 200.0], dtype=np.float64) ints = np.array([10.0, 20.0], dtype=np.float32) spec.set_peaks([mzs, ints]) df = spec.get_df() # No arguments - should work assert 'mz' in df.columns assert 'intensity' in df.columns def test_spectrum_get_df_export_meta_values_only(self): """Test MSSpectrum.get_df(export_meta_values=...) works.""" spec = pyopenms.MSSpectrum() spec.setMSLevel(1) spec.setMetaValue('test', 123) mzs = np.array([100.0], dtype=np.float64) ints = np.array([10.0], dtype=np.float32) spec.set_peaks([mzs, ints]) df_with = spec.get_df(export_meta_values=True) df_without = spec.get_df(export_meta_values=False) assert 'test' in df_with.columns assert 'test' not in df_without.columns def test_chromatogram_get_df_no_args(self): """Test MSChromatogram.get_df() works without arguments.""" chrom = pyopenms.MSChromatogram() rts = np.array([10.0, 20.0], dtype=np.float64) ints = np.array([100.0, 200.0], dtype=np.float32) chrom.set_peaks([rts, ints]) df = chrom.get_df() # No arguments - should work assert 'rt' in df.columns assert 'intensity' in df.columns class TestToArrowMethods: """Tests for to_arrow() methods that export to Apache Arrow Tables.""" def test_spectrum_to_arrow(self): """Test MSSpectrum.to_arrow() returns valid Arrow Table.""" pytest.importorskip('pyarrow') import pyarrow as pa spec = pyopenms.MSSpectrum() spec.setMSLevel(2) spec.setRT(123.45) mzs = np.array([100.0, 200.0, 300.0], dtype=np.float64) ints = np.array([10.0, 20.0, 30.0], dtype=np.float32) spec.set_peaks([mzs, ints]) table = spec.to_arrow() assert isinstance(table, pa.Table) assert table.num_rows == 3 assert 'mz' in table.column_names assert 'intensity' in table.column_names def test_spectrum_to_arrow_column_selection(self): """Test MSSpectrum.to_arrow() with column selection.""" pytest.importorskip('pyarrow') import pyarrow as pa spec = pyopenms.MSSpectrum() mzs = np.array([100.0, 200.0], dtype=np.float64) ints = np.array([10.0, 20.0], dtype=np.float32) spec.set_peaks([mzs, ints]) table = spec.to_arrow(columns=['mz', 'intensity']) assert table.num_columns == 2 assert 'mz' in table.column_names assert 'intensity' in table.column_names assert 'rt' not in table.column_names def test_chromatogram_to_arrow(self): """Test MSChromatogram.to_arrow() returns valid Arrow Table.""" pytest.importorskip('pyarrow') import pyarrow as pa chrom = pyopenms.MSChromatogram() rts = np.array([10.0, 20.0, 30.0], dtype=np.float64) ints = np.array([100.0, 200.0, 150.0], dtype=np.float32) chrom.set_peaks([rts, ints]) table = chrom.to_arrow() assert isinstance(table, pa.Table) assert table.num_rows == 3 assert 'rt' in table.column_names assert 'intensity' in table.column_names def test_mobilogram_to_arrow(self): """Test Mobilogram.to_arrow() returns valid Arrow Table.""" pytest.importorskip('pyarrow') import pyarrow as pa mob = pyopenms.Mobilogram() mobilities = np.array([1.0, 2.0, 3.0], dtype=np.float64) ints = np.array([100.0, 200.0, 150.0], dtype=np.float32) mob.set_peaks([mobilities, ints]) table = mob.to_arrow() assert isinstance(table, pa.Table) assert table.num_rows == 3 assert 'mobility' in table.column_names assert 'intensity' in table.column_names def test_experiment_to_arrow_long_format(self): """Test MSExperiment.to_arrow() with long_format=True.""" pytest.importorskip('pyarrow') import pyarrow as pa exp = pyopenms.MSExperiment() spec = pyopenms.MSSpectrum() spec.setMSLevel(1) mzs = np.array([100.0, 200.0], dtype=np.float64) ints = np.array([10.0, 20.0], dtype=np.float32) spec.set_peaks([mzs, ints]) exp.addSpectrum(spec) table = exp.to_arrow(long_format=True) assert isinstance(table, pa.Table) assert 'mz' in table.column_names assert 'intensity' in table.column_names assert 'ms_level' in table.column_names def test_feature_map_to_arrow(self): """Test FeatureMap.to_arrow() returns valid Arrow Table.""" pytest.importorskip('pyarrow') import pyarrow as pa fmap = pyopenms.FeatureMap() f = pyopenms.Feature() f.setRT(100.0) f.setMZ(500.0) f.setIntensity(1000.0) fmap.push_back(f) table = fmap.to_arrow() assert isinstance(table, pa.Table) assert table.num_rows == 1 def test_to_arrow_to_pandas_roundtrip(self): """Test that to_arrow().to_pandas() produces same result as get_df().""" pytest.importorskip('pyarrow') spec = pyopenms.MSSpectrum() spec.setMSLevel(1) mzs = np.array([100.0, 200.0, 300.0], dtype=np.float64) ints = np.array([10.0, 20.0, 30.0], dtype=np.float32) spec.set_peaks([mzs, ints]) df_direct = spec.get_df(columns=['mz', 'intensity']) df_via_arrow = spec.to_arrow(columns=['mz', 'intensity']).to_pandas() assert list(df_direct['mz']) == list(df_via_arrow['mz']) assert list(df_direct['intensity']) == list(df_via_arrow['intensity']) class TestBugFixes: """Tests for specific bug fixes.""" def test_peptide_id_missing_metavalue_no_error(self): """Test that missing metavalues don't cause UnboundLocalError. Regression test for bug where accessing default_missing_values[type(val)] would fail if val was never assigned (metavalue didn't exist). """ pep_list = pyopenms.PeptideIdentificationList() # Create two peptide IDs with different metavalues pep1 = pyopenms.PeptideIdentification() pep1.setRT(100.0) pep1.setMZ(500.0) hit1 = pyopenms.PeptideHit() hit1.setScore(10.0) hit1.setCharge(2) hit1.setSequence(pyopenms.AASequence.fromString('PEPTIDE')) hit1.setMetaValue('custom_score', 0.95) # Only pep1 has this metavalue pep1.setHits([hit1]) pep_list.append(pep1) pep2 = pyopenms.PeptideIdentification() pep2.setRT(200.0) pep2.setMZ(600.0) hit2 = pyopenms.PeptideHit() hit2.setScore(20.0) hit2.setCharge(3) hit2.setSequence(pyopenms.AASequence.fromString('ANOTHER')) # hit2 does NOT have 'custom_score' metavalue pep2.setHits([hit2]) pep_list.append(pep2) # This should not raise UnboundLocalError df = pep_list.get_df() assert len(df) == 2 def test_massql_df_empty_spectrum_no_division_by_zero(self): """Test that get_massql_df() handles empty/zero-intensity spectra. Regression test for division by zero when normalizing intensities. """ exp = pyopenms.MSExperiment() # Add a normal spectrum spec1 = pyopenms.MSSpectrum() spec1.setMSLevel(1) mzs = np.array([100.0, 200.0], dtype=np.float64) ints = np.array([1000.0, 2000.0], dtype=np.float32) spec1.set_peaks([mzs, ints]) exp.addSpectrum(spec1) # Add an empty spectrum (edge case) spec2 = pyopenms.MSSpectrum() spec2.setMSLevel(1) spec2.set_peaks([np.array([], dtype=np.float64), np.array([], dtype=np.float32)]) exp.addSpectrum(spec2) # This should not raise division by zero warning/error ms1_df, ms2_df = exp.get_massql_df() # Verify normalized columns are finite (no inf or nan from division) if len(ms1_df) > 0: assert ms1_df['i_norm'].notna().all() or (ms1_df['i_norm'] == 0).all() assert ms1_df['i_tic_norm'].notna().all() or (ms1_df['i_tic_norm'] == 0).all() def test_massql_df_zero_intensity_spectrum(self): """Test get_massql_df() with spectrum where all intensities are zero.""" exp = pyopenms.MSExperiment() spec = pyopenms.MSSpectrum() spec.setMSLevel(1) mzs = np.array([100.0, 200.0, 300.0], dtype=np.float64) ints = np.array([0.0, 0.0, 0.0], dtype=np.float32) # All zeros spec.set_peaks([mzs, ints]) exp.addSpectrum(spec) # This should handle division by zero gracefully ms1_df, ms2_df = exp.get_massql_df() # Normalized values should be 0 (not inf or nan) assert len(ms1_df) == 3 assert (ms1_df['i_norm'] == 0).all() assert (ms1_df['i_tic_norm'] == 0).all() def test_featuremap_missing_spectrum_native_id(self): """Test FeatureMap.get_df() handles missing spectrum_native_id metavalue. Regression test for bug where getMetaValue('spectrum_native_id') was called without checking if the metavalue exists, causing KeyError or unexpected behavior. """ fmap = pyopenms.FeatureMap() # Add a feature WITH spectrum_native_id f1 = pyopenms.Feature() f1.setRT(100.0) f1.setMZ(500.0) f1.setIntensity(1000.0) f1.setCharge(2) f1.setMetaValue('spectrum_native_id', 'scan=100') # Add peptide identification to trigger the code path pep1 = pyopenms.PeptideIdentification() hit1 = pyopenms.PeptideHit() hit1.setSequence(pyopenms.AASequence.fromString('PEPTIDE')) hit1.setScore(10.0) pep1.setHits([hit1]) pep_list1 = pyopenms.PeptideIdentificationList() pep_list1.push_back(pep1) f1.setPeptideIdentifications(pep_list1) fmap.push_back(f1) # Add a feature WITHOUT spectrum_native_id (the bug case) f2 = pyopenms.Feature() f2.setRT(200.0) f2.setMZ(600.0) f2.setIntensity(2000.0) f2.setCharge(3) # NO setMetaValue('spectrum_native_id', ...) - this is the bug case pep2 = pyopenms.PeptideIdentification() hit2 = pyopenms.PeptideHit() hit2.setSequence(pyopenms.AASequence.fromString('ANOTHER')) hit2.setScore(20.0) pep2.setHits([hit2]) pep_list2 = pyopenms.PeptideIdentificationList() pep_list2.push_back(pep2) f2.setPeptideIdentifications(pep_list2) fmap.push_back(f2) # This should not raise an error df = fmap.get_df(export_peptide_identifications=True) assert len(df) == 2 # First feature should have the native_id assert df.iloc[0]['ID_native_id'] == 'scan=100' # Second feature should have 'None' string (numpy converts None to string due to U100 dtype) assert df.iloc[1]['ID_native_id'] == 'None'
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Mobilogram.py
.py
3,877
116
import unittest import pyopenms class TestMobilogram(unittest.TestCase): def testMobilogram(self): mobilogram = pyopenms.Mobilogram() p = pyopenms.MobilityPeak1D() p.setMobility(25.0) p.setIntensity(1e5) mobilogram.push_back(p) p_back, = list(mobilogram) assert isinstance(p_back, pyopenms.MobilityPeak1D) assert p_back.getMobility() == 25.0 assert p_back.getIntensity() == 1e5 mobilogram.updateRanges() assert isinstance(mobilogram.getMinMobility(), float) assert isinstance(mobilogram.getMaxMobility(), float) assert isinstance(mobilogram.getMinIntensity(), float) assert isinstance(mobilogram.getMaxIntensity(), float) assert mobilogram.getMinIntensity() == 1e5 assert mobilogram.getMaxIntensity() == 1e5 def testMobilogramRT(self): mobilogram = pyopenms.Mobilogram() mobilogram.setRT(123.45) assert mobilogram.getRT() == 123.45 def testMobilogramDriftTimeUnit(self): mobilogram = pyopenms.Mobilogram() mobilogram.setDriftTimeUnit(pyopenms.DriftTimeUnit.MILLISECOND) assert mobilogram.getDriftTimeUnit() == pyopenms.DriftTimeUnit.MILLISECOND assert isinstance(mobilogram.getDriftTimeUnitAsString(), str) def testMobilogramGetSetPeaks(self): mobilogram = pyopenms.Mobilogram() # Set peaks using numpy arrays import numpy as np mobilities = np.array([10.0, 20.0, 30.0], dtype=np.float64) intensities = np.array([100.0, 200.0, 150.0], dtype=np.float32) mobilogram.set_peaks((mobilities, intensities)) # Get peaks back mb_out, int_out = mobilogram.get_peaks() assert len(mb_out) == 3 assert len(int_out) == 3 assert mb_out[0] == 10.0 assert mb_out[1] == 20.0 assert mb_out[2] == 30.0 assert int_out[0] == 100.0 assert int_out[1] == 200.0 assert int_out[2] == 150.0 def testMobilogramSorting(self): mobilogram = pyopenms.Mobilogram() p1 = pyopenms.MobilityPeak1D() p1.setMobility(30.0) p1.setIntensity(100.0) mobilogram.push_back(p1) p2 = pyopenms.MobilityPeak1D() p2.setMobility(10.0) p2.setIntensity(200.0) mobilogram.push_back(p2) p3 = pyopenms.MobilityPeak1D() p3.setMobility(20.0) p3.setIntensity(150.0) mobilogram.push_back(p3) # Sort by position mobilogram.sortByPosition() assert mobilogram[0].getMobility() == 10.0 assert mobilogram[1].getMobility() == 20.0 assert mobilogram[2].getMobility() == 30.0 assert mobilogram.isSorted() # Sort by intensity mobilogram.sortByIntensity(False) assert mobilogram[0].getIntensity() == 100.0 assert mobilogram[1].getIntensity() == 150.0 assert mobilogram[2].getIntensity() == 200.0 def testMobilogramDataArrays(self): mobilogram = pyopenms.Mobilogram() fda = pyopenms.FloatDataArray() fda.setName("Signal to Noise Array") fda.push_back(15.0) mobilogram.setFloatDataArrays([fda]) fdas = mobilogram.getFloatDataArrays() assert len(fdas) == 1 assert fdas[0].getName() == "Signal to Noise Array" def testMobilogramCalculateTIC(self): mobilogram = pyopenms.Mobilogram() p1 = pyopenms.MobilityPeak1D() p1.setMobility(10.0) p1.setIntensity(100.0) mobilogram.push_back(p1) p2 = pyopenms.MobilityPeak1D() p2.setMobility(20.0) p2.setIntensity(200.0) mobilogram.push_back(p2) tic = mobilogram.calculateTIC() assert tic == 300.0 if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_StandardTypes.py
.py
154
5
def test_if_available(): import pyopenms assert pyopenms.PeakMap == pyopenms.MSExperiment assert pyopenms.PeakSpectrum == pyopenms.MSSpectrum
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_BilinearInterpolation.py
.py
10,744
289
import unittest import math import random import pyopenms class TestBilinearInterpolation(unittest.TestCase): def test_BilinearInterpolation(self): mat = pyopenms.MatrixDouble(2, 3, 0.0) mat.setValue(0, 0, 17) mat.setValue(0, 1, 18.9) mat.setValue(0, 2, 20.333) mat.setValue(1, 0, -0.1) mat.setValue(1, 1, -0.13) mat.setValue(1, 2, -0.001) bilip = pyopenms.BilinearInterpolation() bilip.setData(mat) bilip.setMapping_0(13.0, 230.0, 14.0, 250.0) bilip.setMapping_1(15.0, 2100.0, 17.0, 2900.0) bilip_2 = pyopenms.BilinearInterpolation() bilip_2 = bilip self.assertAlmostEqual(bilip_2.getScale_0(), 20) self.assertAlmostEqual(bilip_2.getScale_1(), 400) self.assertAlmostEqual(bilip_2.getOffset_0(), -30) self.assertAlmostEqual(bilip_2.getOffset_1(), -3900) self.assertAlmostEqual(bilip_2.getInsideReferencePoint_0(), 13) self.assertAlmostEqual(bilip_2.getOutsideReferencePoint_0(), 230) self.assertAlmostEqual(bilip_2.getInsideReferencePoint_1(), 15) self.assertAlmostEqual(bilip_2.getOutsideReferencePoint_1(), 2100) for i in range(mat.rows()): for j in range(mat.cols()): self.assertAlmostEqual(bilip.getData().getValue(i, j), mat.getValue(i, j)) # same test for getData and setData def test_getData_setData(self): bilip = pyopenms.BilinearInterpolation() tmp = pyopenms.MatrixDouble(2, 3, 0.0) tmp.setValue(1, 2, 10012) tmp.setValue(0, 0, 10000) tmp.setValue(1, 0, 10010) bilip.setData(tmp) bilip_2 = pyopenms.BilinearInterpolation(bilip) self.assertAlmostEqual(bilip_2.getData().getValue(1, 2), 10012) self.assertAlmostEqual(bilip_2.getData().getValue(0, 0), 10000) self.assertAlmostEqual(bilip_2.getData().getValue(1, 0), 10010) def test_setMapping_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_0(1.0, 2.0, 3.0, 8.0) self.assertAlmostEqual(bilip.getScale_0(), 3) self.assertAlmostEqual(bilip.getOffset_0(), -1) self.assertAlmostEqual(bilip.getScale_1(), 1) self.assertAlmostEqual(bilip.getOffset_1(), 0) bilip2 = pyopenms.BilinearInterpolation() bilip2.setMapping_0(3.0, 1.0, 2.0) self.assertAlmostEqual(bilip2.getScale_0(), 3) self.assertAlmostEqual(bilip2.getOffset_0(), -1) self.assertAlmostEqual(bilip2.getScale_1(), 1) self.assertAlmostEqual(bilip2.getOffset_1(), 0) def test_setOffset_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setOffset_0(987) self.assertAlmostEqual(bilip.getOffset_0(), 987) def test_setScale_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setScale_0(987) self.assertAlmostEqual(bilip.getScale_0(), 987) def test_getInsideReferencePoint_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_0(1.0, 4.0, 3.0, 8.0) self.assertAlmostEqual(bilip.getInsideReferencePoint_0(), 1) self.assertAlmostEqual(bilip.getOutsideReferencePoint_0(), 4) self.assertAlmostEqual(bilip.getInsideReferencePoint_1(), 0) self.assertAlmostEqual(bilip.getOutsideReferencePoint_1(), 0) def test_index2key_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_0(3.0, 1.0, 2.0) self.assertAlmostEqual(bilip.index2key_0(0), -1) self.assertAlmostEqual(bilip.index2key_1(0), 0) def test_key2index_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_0(3.0, 1.0, 2.0) self.assertAlmostEqual(bilip.key2index_0(-1), 0) self.assertAlmostEqual(bilip.key2index_1(0), 0) def test_supportMax_0(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_0(3.0, 1.0, 2.0) bilip.setMapping_1(5.0, 3.0, 4.0) tmp = pyopenms.MatrixDouble(2, 3, 0.0) bilip.setData(tmp) self.assertAlmostEqual(bilip.index2key_0(0), -1) self.assertAlmostEqual(bilip.index2key_0(1), 2) self.assertAlmostEqual(bilip.supportMin_0(), -4) self.assertAlmostEqual(bilip.supportMax_0(), 5) self.assertAlmostEqual(bilip.index2key_1(0), -11) self.assertAlmostEqual(bilip.index2key_1(2), -1) self.assertAlmostEqual(bilip.supportMin_1(), -16) self.assertAlmostEqual(bilip.supportMax_1(), 4) def test_setMapping_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_1(1.0, 2.0, 3.0, 8.0) self.assertAlmostEqual(bilip.getScale_1(), 3) self.assertAlmostEqual(bilip.getOffset_1(), -1) self.assertAlmostEqual(bilip.getScale_0(), 1) self.assertAlmostEqual(bilip.getOffset_0(), 0) bilip2 = pyopenms.BilinearInterpolation() bilip2.setMapping_1(3.0, 1.0, 2.0) self.assertAlmostEqual(bilip2.getScale_1(), 3) self.assertAlmostEqual(bilip2.getOffset_1(), -1) self.assertAlmostEqual(bilip2.getScale_0(), 1) self.assertAlmostEqual(bilip2.getOffset_0(), 0) def test_setOffset_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setOffset_1(987) self.assertAlmostEqual(bilip.getOffset_1(), 987) def test_setScale_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setScale_1(987) self.assertAlmostEqual(bilip.getScale_1(), 987) def test_getInsideReferencePoint_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_1(1.0, 4.0, 3.0, 8.0) self.assertAlmostEqual(bilip.getInsideReferencePoint_1(), 1) self.assertAlmostEqual(bilip.getOutsideReferencePoint_1(), 4) self.assertAlmostEqual(bilip.getInsideReferencePoint_0(), 0) self.assertAlmostEqual(bilip.getOutsideReferencePoint_0(), 0) def test_index2key_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_1(3.0, 1.0, 2.0) self.assertAlmostEqual(bilip.index2key_1(0), -1) self.assertAlmostEqual(bilip.index2key_0(0), 0) def test_key2index_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_1(3.0, 1.0, 2.0) self.assertAlmostEqual(bilip.key2index_1(-1), 0) self.assertAlmostEqual(bilip.key2index_0(0), 0) def test_supportMax_1(self): bilip = pyopenms.BilinearInterpolation() bilip.setMapping_1(3.0, 1.0, 2.0) bilip.setMapping_0(5.0, 3.0, 4.0) tmp = pyopenms.MatrixDouble(3, 2, 0.0) bilip.setData(tmp) self.assertAlmostEqual(bilip.index2key_1(0), -1) self.assertAlmostEqual(bilip.index2key_1(1), 2) self.assertAlmostEqual(bilip.supportMin_1(), -4) self.assertAlmostEqual(bilip.supportMax_1(), 5) self.assertAlmostEqual(bilip.index2key_0(0), -11) self.assertAlmostEqual(bilip.index2key_0(2), -1) self.assertAlmostEqual(bilip.supportMin_0(), -16) self.assertAlmostEqual(bilip.supportMax_0(), 4) def test_empty(self): bilip = pyopenms.BilinearInterpolation() self.assertTrue(bilip.empty()) tmp = pyopenms.MatrixDouble(1, 2, 0.0) bilip.setData(tmp) self.assertFalse(bilip.empty()) tmp = pyopenms.MatrixDouble(0, 0, 0.0) bilip.setData(tmp) self.assertTrue(bilip.empty()) tmp = pyopenms.MatrixDouble(1, 2, 0.0) bilip.setData(tmp) self.assertFalse(bilip.empty()) tmp = pyopenms.MatrixDouble(1, 0, 0.0) bilip.setData(tmp) self.assertTrue(bilip.empty()) tmp = pyopenms.MatrixDouble(1, 2, 0.0) bilip.setData(tmp) self.assertFalse(bilip.empty()) tmp = pyopenms.MatrixDouble(0, 0, 0.0) bilip.setData(tmp) self.assertTrue(bilip.empty()) tmp = pyopenms.MatrixDouble(2, 2, 0.0) bilip.setData(tmp) self.assertFalse(bilip.empty()) tmp = bilip.getData() tmp = pyopenms.MatrixDouble(0, 0, 0.0) bilip.setData(tmp) self.assertTrue(bilip.empty()) def test_addValue(self): for i in range(-50, 101): p = i / 10.0 for j in range(-50, 101): q = j / 10.0 bilip_small = pyopenms.BilinearInterpolation() tmp = pyopenms.MatrixDouble(5, 5, 0.0) bilip_small.setData(tmp) bilip_small.setMapping_0(0.0, 0.0, 5.0, 5.0) bilip_small.setMapping_1(0.0, 0.0, 5.0, 5.0) bilip_small.addValue(p, q, 100) bilip_big = pyopenms.BilinearInterpolation() tmp = pyopenms.MatrixDouble(15, 15, 0.0) bilip_big.setData(tmp) bilip_big.setMapping_0(5.0, 0.0, 10.0, 5.0) bilip_big.setMapping_1(5.0, 0.0, 10.0, 5.0) bilip_big.addValue(p, q, 100) big_submatrix = pyopenms.MatrixDouble(5, 5, 0.0) for m in range(5): for n in range(5): big_submatrix.setValue(m, n, bilip_big.getData().getValue(m+5, n+5)) for m in range(bilip_small.getData().rows()): for n in range(bilip_small.getData().cols()): self.assertAlmostEqual(bilip_small.getData().getValue(m, n), big_submatrix.getValue(m, n)) def test_value(self): bilip_small = pyopenms.BilinearInterpolation() bilip_big = pyopenms.BilinearInterpolation() tmp_small = pyopenms.MatrixDouble(5, 5, 0.0) tmp_big = pyopenms.MatrixDouble(15, 15, 0.0) for i in range(5): for j in range(5): num = int(math.floor(random.random() * 100)) tmp_small.setValue(i, j, num) tmp_big.setValue(i + 5, j + 5, num) bilip_small.setData(tmp_small) bilip_big.setData(tmp_big) bilip_small.setMapping_0(0.0, 0.0, 5.0, 5.0) bilip_small.setMapping_1(0.0, 0.0, 5.0, 5.0) bilip_big.setMapping_0(5.0, 0.0, 10.0, 5.0) bilip_big.setMapping_1(5.0, 0.0, 10.0, 5.0) for i in range(-50, 101): p = i / 10.0 for j in range(-50, 101): q = j / 10.0 self.assertAlmostEqual(bilip_small.value(p, q), bilip_big.value(p, q)) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/collections_.py
.py
6,408
197
from __future__ import print_function from operator import itemgetter from heapq import nlargest from itertools import repeat try: from itertools import ifilter except ImportError: # Python 3 ifilter = filter class Counter(dict): '''Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> Counter('zyzygy') Counter({'y': 3, 'z': 2, 'g': 1}) ''' def __init__(self, iterable=None, **kwds): '''Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args ''' self.update(iterable, **kwds) def __missing__(self, key): return 0 def most_common(self, n=None): '''List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abbracadabbra').most_common(3) [('a', 5), ('b', 4), ('r', 2)] ''' if n is None: return sorted(self.items(), key=itemgetter(1), reverse=True) return nlargest(n, self.items(), key=itemgetter(1)) def elements(self): '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] If an element's count has been set to zero or is a negative number, elements() will ignore it. ''' for elem, count in self.items(): for _ in repeat(None, count): yield elem # Override dict methods where the meaning changes for Counter objects. @classmethod def fromkeys(cls, iterable, v=None): raise NotImplementedError( 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') def update(self, iterable=None, **kwds): '''Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 ''' if iterable is not None: if hasattr(iterable, 'items'): if self: self_get = self.get for elem, count in iterable.items(): self[elem] = self_get(elem, 0) + count else: dict.update(self, iterable) # fast path when counter is empty else: self_get = self.get for elem in iterable: self[elem] = self_get(elem, 0) + 1 if kwds: self.update(kwds) def copy(self): 'Like dict.copy() but returns a Counter instance instead of a dict.' return Counter(self) def __delitem__(self, elem): 'Like dict.__delitem__() but does not raise KeyError for missing values.' if elem in self: dict.__delitem__(self, elem) def __repr__(self): if not self: return '%s()' % self.__class__.__name__ items = ', '.join(map('%r: %r'.__mod__, self.most_common())) return '%s({%s})' % (self.__class__.__name__, items) # Multiset-style mathematical operations discussed in: # Knuth TAOCP Volume II section 4.6.3 exercise 19 # and at http://en.wikipedia.org/wiki/Multiset # # Outputs guaranteed to only include positive counts. # # To strip negative and zero counts, add-in an empty counter: # c += Counter() def __add__(self, other): '''Add counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem in set(self) | set(other): newcount = self[elem] + other[elem] if newcount > 0: result[elem] = newcount return result def __sub__(self, other): ''' Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem in set(self) | set(other): newcount = self[elem] - other[elem] if newcount > 0: result[elem] = newcount return result def __or__(self, other): '''Union is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc') Counter({'b': 3, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented _max = max result = Counter() for elem in set(self) | set(other): newcount = _max(self[elem], other[elem]) if newcount > 0: result[elem] = newcount return result def __and__(self, other): ''' Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) ''' if not isinstance(other, Counter): return NotImplemented _min = min result = Counter() if len(self) < len(other): self, other = other, self for elem in ifilter(self.__contains__, other): newcount = _min(self[elem], other[elem]) if newcount > 0: result[elem] = newcount return result if __name__ == '__main__': import doctest print(doctest.testmod())
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_MSSpectrum.py
.py
7,542
208
import unittest import numpy as np import pyopenms class TestMSSpectrum(unittest.TestCase): def testMSSpectrum(self): spec = pyopenms.MSSpectrum() p = pyopenms.Peak1D() p.setMZ(500.0) p.setIntensity(1e5) spec.push_back(p) p_back, = list(spec) assert isinstance(p_back, pyopenms.Peak1D) assert p_back.getMZ() == 500.0 assert p_back.getIntensity() == 1e5 spec.updateRanges() assert isinstance(spec.getMinMZ(), float) assert isinstance(spec.getMaxMZ(), float) assert isinstance(spec.getMinIntensity(), float) assert isinstance(spec.getMaxIntensity(), float) assert spec.getMinIntensity() == 1e5 assert spec.getMaxIntensity() == 1e5 def testMSSpectrumGetPeaks(self): """Test optimized get_peaks method""" spec = pyopenms.MSSpectrum() mz_exp = [100.0, 200.0, 300.0] int_exp = [1000.0, 2000.0, 500.0] spec.set_peaks((mz_exp, int_exp)) mz, intensities = spec.get_peaks() self.assertEqual(len(mz), 3) self.assertEqual(len(intensities), 3) self.assertEqual(mz.dtype, np.float64) self.assertEqual(intensities.dtype, np.float32) for m, e in zip(mz, mz_exp): self.assertAlmostEqual(m, e) for i, e in zip(intensities, int_exp): self.assertAlmostEqual(i, e, places=1) def testMSSpectrumGetPeaksEmpty(self): """Test get_peaks on empty spectrum""" spec = pyopenms.MSSpectrum() mz, intensities = spec.get_peaks() self.assertEqual(len(mz), 0) self.assertEqual(len(intensities), 0) self.assertEqual(mz.dtype, np.float64) self.assertEqual(intensities.dtype, np.float32) def testMSSpectrumGetMzArray(self): """Test get_mz_array method""" spec = pyopenms.MSSpectrum() mz_exp = [100.0, 200.0, 300.0] int_exp = [1000.0, 2000.0, 500.0] spec.set_peaks((mz_exp, int_exp)) mz = spec.get_mz_array() self.assertEqual(len(mz), 3) self.assertEqual(mz.dtype, np.float64) for m, e in zip(mz, mz_exp): self.assertAlmostEqual(m, e) def testMSSpectrumGetIntensityArray(self): """Test get_intensity_array method""" spec = pyopenms.MSSpectrum() mz_exp = [100.0, 200.0, 300.0] int_exp = [1000.0, 2000.0, 500.0] spec.set_peaks((mz_exp, int_exp)) intensities = spec.get_intensity_array() self.assertEqual(len(intensities), 3) self.assertEqual(intensities.dtype, np.float32) for i, e in zip(intensities, int_exp): self.assertAlmostEqual(i, e, places=1) def testMSSpectrumDriftTimeNoIM(self): """Test drift time methods when no IM data present""" spec = pyopenms.MSSpectrum() spec.set_peaks(([100.0, 200.0], [1000.0, 2000.0])) # Should return None when no IM data self.assertFalse(spec.containsIMData()) self.assertIsNone(spec.get_drift_time_array()) self.assertIsNone(spec.get_drift_time_array_mv()) self.assertIsNone(spec.get_drift_time_unit()) def testMSSpectrumDriftTimeWithIM(self): """Test drift time methods with ion mobility data""" spec = pyopenms.MSSpectrum() spec.set_peaks(([100.0, 200.0, 300.0], [1000.0, 2000.0, 500.0])) # Add ion mobility data via FloatDataArray fda = pyopenms.FloatDataArray() fda.setName("Ion Mobility") fda.push_back(1.5) fda.push_back(2.5) fda.push_back(3.5) spec.setFloatDataArrays([fda]) # Should now have IM data self.assertTrue(spec.containsIMData()) # Test get_drift_time_array (copy) drift = spec.get_drift_time_array() self.assertIsNotNone(drift) self.assertEqual(len(drift), 3) self.assertEqual(drift.dtype, np.float32) self.assertAlmostEqual(drift[0], 1.5, places=1) self.assertAlmostEqual(drift[1], 2.5, places=1) self.assertAlmostEqual(drift[2], 3.5, places=1) # Test get_drift_time_unit unit = spec.get_drift_time_unit() self.assertIsNotNone(unit) def testFloatDataArrayGetData(self): """Test FloatDataArray get_data method (returns copy - safe)""" fda = pyopenms.FloatDataArray() fda.push_back(1.0) fda.push_back(2.0) fda.push_back(3.0) # Get a copy (safe default) data_copy = fda.get_data() self.assertEqual(len(data_copy), 3) self.assertEqual(data_copy.dtype, np.float32) self.assertAlmostEqual(data_copy[0], 1.0, places=1) self.assertAlmostEqual(data_copy[1], 2.0, places=1) self.assertAlmostEqual(data_copy[2], 3.0, places=1) # Modify copy - original should be unchanged data_copy[0] = 100.0 self.assertAlmostEqual(fda[0], 1.0, places=1) def testFloatDataArrayGetDataMv(self): """Test FloatDataArray get_data_mv method (memory view - fast, unsafe)""" fda = pyopenms.FloatDataArray() fda.push_back(1.0) fda.push_back(2.0) fda.push_back(3.0) # Get a view (fast but unsafe) data_view = fda.get_data_mv() self.assertEqual(len(data_view), 3) self.assertAlmostEqual(data_view[0], 1.0, places=1) self.assertAlmostEqual(data_view[1], 2.0, places=1) self.assertAlmostEqual(data_view[2], 3.0, places=1) # Modify view - original SHOULD change (it's a view) data_view[0] = 100.0 self.assertAlmostEqual(fda[0], 100.0, places=1) def testFloatDataArrayEmpty(self): """Test FloatDataArray methods on empty array""" fda = pyopenms.FloatDataArray() # get_data returns empty array data_copy = fda.get_data() self.assertEqual(len(data_copy), 0) # get_data_mv returns None for empty data_view = fda.get_data_mv() self.assertIsNone(data_view) def testGetTypeWithQueryData(self): """Test getType(bool) method with query_data parameter""" spec = pyopenms.MSSpectrum() # Empty spectrum - should return UNKNOWN spec_type = spec.getType(False) self.assertIn(spec_type, [ pyopenms.SpectrumSettings.SpectrumType.UNKNOWN, pyopenms.SpectrumSettings.SpectrumType.CENTROID, pyopenms.SpectrumSettings.SpectrumType.PROFILE ]) # Set type explicitly spec.setType(pyopenms.SpectrumSettings.SpectrumType.CENTROID) spec_type = spec.getType(False) self.assertEqual(spec_type, pyopenms.SpectrumSettings.SpectrumType.CENTROID) # Test with query_data=True on spectrum with peaks spec2 = pyopenms.MSSpectrum() spec2.set_peaks(([100.0, 200.0, 300.0], [1000.0, 2000.0, 500.0])) # Without setting type, getType(False) should return UNKNOWN spec_type_no_query = spec2.getType(False) self.assertEqual(spec_type_no_query, pyopenms.SpectrumSettings.SpectrumType.UNKNOWN) # With query_data=True, it may estimate the type based on peak data spec_type_with_query = spec2.getType(True) self.assertIn(spec_type_with_query, [ pyopenms.SpectrumSettings.SpectrumType.UNKNOWN, pyopenms.SpectrumSettings.SpectrumType.CENTROID, pyopenms.SpectrumSettings.SpectrumType.PROFILE ]) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_ChromatogramExtractorAlgorithm.py
.py
2,442
70
import unittest import os import pyopenms class TestChromatogramExtractorAlgorithm(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() def test_readfile_content(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, exp) exp_size = exp.size() saccess = pyopenms.SpectrumAccessOpenMS(exp) ### double mz # mz around which should be extracted ### double rt_start # rt start of extraction (in seconds) ### double rt_end # rt end of extraction (in seconds) ### libcpp_string id # identifier targeted = [] coord = pyopenms.ExtractionCoordinates() coord.mz = 618.31 coord.rt_start = 4000 coord.rt_end = 5000 coord.id = b"tr3" targeted.append(coord) coord = pyopenms.ExtractionCoordinates() coord.mz = 628.45 coord.rt_start = 4000 coord.rt_end = 5000 coord.id = b"tr1" targeted.append(coord) coord = pyopenms.ExtractionCoordinates() coord.mz = 654.38 coord.rt_start = 4000 coord.rt_end = 5000 coord.id = b"tr2" targeted.append(coord) trafo = pyopenms.TransformationDescription() # Start with length zero tmp_out = [ pyopenms.OSChromatogram() for i in range(len(targeted))] self.assertEqual(len(tmp_out[0].get_intensity_array()), 0) extractor = pyopenms.ChromatogramExtractorAlgorithm() mz_extraction_window = 10.0 ppm = False extractor.extractChromatograms(saccess, tmp_out, targeted, mz_extraction_window, ppm, -1.0, b"tophat") # Basically test that the output is non-zero (e.g. the data is # correctly relayed to python) # The functionality is not tested here! self.assertEqual(len(tmp_out), len(targeted)) self.assertNotEqual(len(tmp_out), 0) # End with different length self.assertEqual(len(tmp_out[0].get_intensity_array()), exp_size) self.assertNotEqual(len(tmp_out[0].get_intensity_array()), 0) self.assertNotEqual(len(tmp_out[0].get_time_array()), 0) self.assertNotEqual(tmp_out[0].get_intensity_array()[0], 0) self.assertNotEqual(tmp_out[0].get_time_array()[0], 0) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Isobaric_Quantitation.py
.py
3,103
89
import unittest import os import pyopenms def general_setup(self): self.eightplex = pyopenms.ItraqEightPlexQuantitationMethod() self.fourplex = pyopenms.ItraqFourPlexQuantitationMethod() self.tmt = pyopenms.TMTSixPlexQuantitationMethod() class TestIsobaricQuantitationMethod(unittest.TestCase): def setUp(self): pass def test_init_fxn(self): eightplex = pyopenms.ItraqEightPlexQuantitationMethod() fourplex = pyopenms.ItraqFourPlexQuantitationMethod() tmt = pyopenms.TMTSixPlexQuantitationMethod() for inst in [eightplex, fourplex, tmt]: assert inst.getName() is not None assert inst.getChannelInformation() is not None assert inst.getNumberOfChannels() is not None assert inst.getIsotopeCorrectionMatrix() is not None assert inst.getReferenceChannel() is not None self.assertEqual(tmt.getIsotopeCorrectionMatrix().rows(), 6) self.assertEqual(tmt.getIsotopeCorrectionMatrix().cols(), 6) self.assertEqual(fourplex.getIsotopeCorrectionMatrix().rows(), 4) self.assertEqual(fourplex.getIsotopeCorrectionMatrix().cols(), 4) self.assertEqual(eightplex.getIsotopeCorrectionMatrix().rows(), 8) self.assertEqual(eightplex.getIsotopeCorrectionMatrix().cols(), 8) class TestIsobaricChannelExtractor(unittest.TestCase): def setUp(self): general_setup(self) def testInit(self): assert pyopenms.IsobaricChannelExtractor(self.eightplex) is not None assert pyopenms.IsobaricChannelExtractor(self.fourplex) is not None assert pyopenms.IsobaricChannelExtractor(self.tmt) is not None def testFunction(self): for method in [self.eightplex, self.fourplex, self.tmt]: inst = pyopenms.IsobaricChannelExtractor(method) map1 = pyopenms.ConsensusMap() exp = pyopenms.MSExperiment() assert inst.extractChannels is not None # Will not work with empty map # inst.extractChannels(exp, map1) class TestIsobaricNormalizer(unittest.TestCase): def setUp(self): general_setup(self) def testInit(self): assert pyopenms.IsobaricNormalizer(self.eightplex) is not None assert pyopenms.IsobaricNormalizer(self.fourplex) is not None assert pyopenms.IsobaricNormalizer(self.tmt) is not None def testFunction(self): for method in [self.eightplex, self.fourplex, self.tmt]: inst = pyopenms.IsobaricNormalizer(method) map1 = pyopenms.ConsensusMap() assert inst.normalize is not None inst.normalize(map1) #class TestIsobaricIsotopeCorrector(unittest.TestCase): # def setUp(self): # general_setup(self) #method not testable since it contains inherited class member in its signature (is there a way to test it?) #def testFunction(self): #for method in [self.eightplex, self.fourplex, self.tmt]: # assert correctIsotopicImpurities(map1, map2, method) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Convexhull.py
.py
813
34
import pyopenms def test_convex_hull_0(): ch = pyopenms.ConvexHull2D() def test_convex_hull_1(): ch = pyopenms.ConvexHull2D() points = [ [1.0, 1.0], [2.0, 1.0], [1.0, 2.0], [2.0, 2.0]] for p in points: ch.addPoint(p) assert ch.encloses([1.5, 1.5]) assert not ch.encloses([.5, 1.5]) hp = ch.getHullPoints() # order may change, so we use sort here: assert sorted(hp.tolist()) == sorted(points) ch.setHullPoints(hp) hp = ch.getHullPoints() # order may change, so we use sorted here: assert sorted(hp.tolist()) == sorted(points) ch.addPoints(hp+1.0) ch.addPoints(hp) hp = ch.getHullPoints() assert hp.shape == (6, 2) bb = ch.getBoundingBox() assert bb.minPosition() == [1.0, 1.0] assert bb.maxPosition() == [3.0, 3.0]
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_tutorial.py
.py
15,212
498
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import copy import os from pyopenms import String as s from pyopenms import * try: long except NameError: long = int from functools import wraps def report(f): @wraps(f) def wrapper(*a, **kw): print("run b", f.__name__) f(*a, **kw) return wrapper @report def testElementTutorial(): edb = ElementDB() assert edb.hasElement("O") assert edb.hasElement("S") oxygen = edb.getElement("O") assert oxygen.getName() == "Oxygen" assert oxygen.getSymbol() == "O" oxygen.getMonoWeight() isotopes = oxygen.getIsotopeDistribution() sulfur = edb.getElement("S") sulfur.getName() sulfur.getSymbol() sulfur.getMonoWeight() isotopes = sulfur.getIsotopeDistribution() for iso in isotopes.getContainer(): print (iso.getMZ(), ":", iso.getIntensity()) @report def testEmpiricalFormulaTutorial(): print("testEmpiricalFormulaTutorial") methanol = EmpiricalFormula("CH3OH") water = EmpiricalFormula("H2O") ethanol = EmpiricalFormula("CH2" + methanol.toString()) wm = water + methanol print(wm) print(wm.getElementalComposition()) # TODO: dicts are still using bytes! wm = water + methanol # only in pyOpenMS 2.4 m = wm.getElementalComposition() assert m[b"C"] == 1 assert m[b"H"] == 6 assert m[b"O"] == 2 wm = EmpiricalFormula("CH3OH") + EmpiricalFormula("H2O") isotopes = wm.getIsotopeDistribution( CoarseIsotopePatternGenerator(3) ) for iso in isotopes.getContainer(): print (iso.getMZ(), ":", iso.getIntensity()) isotopes = wm.getIsotopeDistribution( CoarseIsotopePatternGenerator(3, True) ) for iso in isotopes.getContainer(): print (iso.getMZ(), ":", iso.getIntensity()) @report def testResidueTutorial(): lys = ResidueDB().getResidue("Lysine") assert lys.getName() == "Lysine" lys.getThreeLetterCode() == "LYS" lys.getOneLetterCode() == "K" lys.getAverageWeight(Residue.ResidueType.Full) assert abs(lys.getMonoWeight(Residue.ResidueType.Full) - 146.1055284466) < 1e-5 lys.getPka() @report def testAASequenceLen(): """Test the __len__() method implementation for AASequence""" # Test basic len() functionality seq = AASequence.fromString("PEPTIDE") assert len(seq) == 7 assert len(seq) == seq.size() # Test with different sequences short_seq = AASequence.fromString("PEP") assert len(short_seq) == 3 long_seq = AASequence.fromString("PEPTIDESEQUENCE") assert len(long_seq) == 15 # Test with modified sequences modified_seq = AASequence.fromString("PEPTIDEM(Oxidation)") assert len(modified_seq) == 8 # Modification doesn't change sequence length # Test with empty sequence (if possible) empty_seq = AASequence.fromString("") assert len(empty_seq) == 0 print("All len() tests passed!") @report def testMSExperimentLen(): """Test the __len__() method implementation for MSExperiment""" # Test with empty experiment exp = MSExperiment() assert len(exp) == 0 assert len(exp) == exp.size() # Test with spectra added spectrum1 = MSSpectrum() spectrum1.setRT(1.0) exp.addSpectrum(spectrum1) assert len(exp) == 1 assert len(exp) == exp.size() spectrum2 = MSSpectrum() spectrum2.setRT(2.0) exp.addSpectrum(spectrum2) assert len(exp) == 2 assert len(exp) == exp.size() # Test with multiple spectra exp2 = MSExperiment() for i in range(5): spectrum = MSSpectrum() spectrum.setRT(float(i)) exp2.addSpectrum(spectrum) assert len(exp2) == 5 assert len(exp2) == exp2.size() assert len(exp2) == exp2.getNrSpectra() print("All MSExperiment len() tests passed!") @report def testAASequenceTutorial(): seq = AASequence.fromString("DFPIANGER") # Test the new len() functionality assert len(seq) == 9 # "DFPIANGER" has 9 amino acids assert len(seq) == seq.size() # len() should return same as size() prefix = seq.getPrefix(4) suffix = seq.getSuffix(5) concat = seq + seq # Test len() with different sequences assert len(prefix) == 4 assert len(suffix) == 5 assert len(concat) == 18 # concatenated sequence should be 2 * 9 print(seq) print(concat) print(suffix) print("len(seq) =", len(seq), ", seq.size() =", seq.size()) seq.getMonoWeight() # weight of M seq.getMonoWeight(Residue.ResidueType.Full, 2) # weight of M+2H mz = seq.getMonoWeight(Residue.ResidueType.Full, 2) / 2.0 # m/z of M+2H concat.getMonoWeight() print("Monoisotopic m/z of (M+2H)2+ is", mz) seq_formula = seq.getFormula() print("Peptide", seq, "has molecular formula", seq_formula) print("="*35) isotopes = seq_formula.getIsotopeDistribution( CoarseIsotopePatternGenerator(6) ) for iso in isotopes.getContainer(): print ("Isotope", iso.getMZ(), ":", iso.getIntensity()) suffix = seq.getSuffix(3) # y3 ion "GER" print("="*35) print("y3 ion :", suffix) y3_formula = suffix.getFormula(Residue.ResidueType.YIon, 2) # y3++ ion suffix.getMonoWeight(Residue.ResidueType.YIon, 2) / 2.0 # CORRECT suffix.getMonoWeight(Residue.ResidueType.XIon, 2) / 2.0 # CORRECT suffix.getMonoWeight(Residue.ResidueType.BIon, 2) / 2.0 # INCORRECT assert str(y3_formula) == "C13H24N6O6", str(y3_formula) assert str(seq_formula) == "C44H67N13O15" print("y3 mz :", suffix.getMonoWeight(Residue.ResidueType.YIon, 2) / 2.0 ) print(y3_formula) print(seq_formula) seq = AASequence.fromString("PEPTIDESEKUEM(Oxidation)CER") print(seq) print(seq.toString()) print(seq.toUnmodifiedString()) print(seq.toUniModString()) print(seq.toBracketString()) print(seq.toBracketString(False)) print(AASequence.fromString("DFPIAM(UniMod:35)GER")) print(AASequence.fromString("DFPIAM[+16]GER")) print(AASequence.fromString("DFPIAM[+15.99]GER")) print(AASequence.fromString("DFPIAM[147]GER")) print(AASequence.fromString("DFPIAM[147.035405]GER")) s = AASequence.fromString(".(Dimethyl)DFPIAMGER.") print(s, s.hasNTerminalModification()) s = AASequence.fromString(".DFPIAMGER.(Label:18O(2))") print(s, s.hasCTerminalModification()) s = AASequence.fromString(".DFPIAMGER(Phospho).") print(s, s.hasCTerminalModification()) bsa = FASTAEntry() bsa.sequence = "MKWVTFISLLLLFSSAYSRGVFRRDTHKSEIAHRFKDLGE" bsa.description = "BSA Bovine Albumin (partial sequence)" bsa.identifier = "BSA" alb = FASTAEntry() alb.sequence = "MKWVTFISLLFLFSSAYSRGVFRRDAHKSEVAHRFKDLGE" alb.description = "ALB Human Albumin (partial sequence)" alb.identifier = "ALB" entries = [bsa, alb] f = FASTAFile() f.store("example.fasta", entries) entries = [] f = FASTAFile() f.load("example.fasta", entries) print( len(entries) ) for e in entries: print (e.identifier, e.sequence) @report def testTheoreticalSpectrumGenTutorial(): tsg = TheoreticalSpectrumGenerator() spec1 = MSSpectrum() spec2 = MSSpectrum() peptide = AASequence.fromString("DFPIANGER") # standard behavior is adding b- and y-ions of charge 1 p = Param() p.setValue("add_b_ions", "false", "Add peaks of b-ions to the spectrum") tsg.setParameters(p) tsg.getSpectrum(spec1, peptide, 1, 1) p.setValue("add_b_ions", "true", "Add peaks of a-ions to the spectrum") p.setValue("add_metainfo", "true", "") tsg.setParameters(p) tsg.getSpectrum(spec2, peptide, 1, 2) print("Spectrum 1 has", spec1.size(), "peaks.") print("Spectrum 2 has", spec2.size(), "peaks.") # Iterate over annotated ions and their masses for ion, peak in zip(spec2.getStringDataArrays()[0], spec2): print(ion, peak.getMZ()) @report def testDigestionTutorial(): print("testDigestionTutorial") dig = ProteaseDigestion() dig.getEnzymeName() # Trypsin bsa = b'DEHVKLVNELTEFAKTCVADESHAGCEKSLHTLFGDELCKVASLRETYGDMADCCEKQEPERNECFLSHKDDSPDLPKLKPDPNTLCDEFKADEKKFWGKYLYEIARRHPYFYAPELLYYANKYNGVFQECCQAEDKGACLLPKIETMREKVLASSARQRLRCASIQKFGERALKAWSVARLSQKFPKAEFVEVTKLVTDLTKVHKECCHGDLLECADDRADLAKYICDNQDTISSKLKECCDKPLLEKSHCIAEVEKDAIPENLPPLTADFAEDKDVCKNYQEAKDAFLGSFLYEYSRRHPEYAVSVLLRLAKEYEATLEECCAKDDPHACYSTVFDKLKHLVDEPQNLIKQNCDQFEKLGEYGFQNALIVRYTRKVPQVSTPTLVEVSRSLGKVGTRCCTKPESERMPCTEDYLSLILNRLCVLHEKTPVSEKVTKCCTESLVNRRPCFSALTPDETYVPKAFDEKLFTFHADICTLPDTEKQIKKQTALVELLKHKPKATEEQLKTVMENFVAFVDKCCAADDKEACFAVEGPKLVVSTQTALA' bsa = AASequence.fromString(bsa) result = [] dig.digest(bsa, result) print(result[4]) len(result) # 74 peptides assert len(result) == 74 names = [] ProteaseDB().getAllNames(names) len(names) # 25 by default e = ProteaseDB().getEnzyme('Lys-C') e.getRegExDescription() e.getRegEx() dig = ProteaseDigestion() dig.setEnzyme('Lys-C') result = [] dig.digest(bsa, result) print(result[4]) len(result) # 53 peptides assert len(result) == 53 def gaussian(x, mu, sig): import numpy as np return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) @report def testDatastructuresTutorial(): ################################### # Spectrum # ******** ################################### spectrum = MSSpectrum() mz = range(1500, 500, -100) i = [0 for mass in mz] spectrum.set_peaks([mz, i]) # Sort the peaks according to ascending mass-to-charge ratio spectrum.sortByPosition() # Iterate over spectrum of those peaks for p in spectrum: print(p.getMZ(), p.getIntensity()) # More efficient peak access for mz, i in zip(*spectrum.get_peaks()): print(mz, i) # Access a peak by index print(spectrum[1].getMZ(), spectrum[1].getIntensity()) ################################### ################################### spectrum = MSSpectrum() spectrum.setDriftTime(25) # 25 ms spectrum.setRT(205.2) # 205.2 s spectrum.setMSLevel(3) # MS3 p = Precursor() p.setIsolationWindowLowerOffset(1.5) p.setIsolationWindowUpperOffset(1.5) p.setMZ(600) # isolation at 600 +/- 1.5 Th p.setActivationEnergy(40) # 40 eV p.setCharge(4) # 4+ ion spectrum.setPrecursors( [p] ) fda = FloatDataArray() fda.setName("Signal to Noise Array") fda.push_back(15) sda = StringDataArray() sda.setName("Peak annotation") sda.push_back("y15++") spectrum.setFloatDataArrays( [fda] ) spectrum.setStringDataArrays( [sda] ) spectrum.set_peaks( ([401.5], [900]) ) # Store as mzML exp = MSExperiment() exp.addSpectrum(spectrum) spectrum = MSSpectrum() spectrum.set_peaks( ([1, 2], [1, 2]) ) exp.addSpectrum(spectrum) MzMLFile().store("testfile.mzML", exp) ################################### # Peak Map # ********* ################################### # The following examples creates a MSExperiment containing four MSSpectrum instances. exp = MSExperiment() for i in range(6): spectrum = MSSpectrum() spectrum.setRT(i) spectrum.setMSLevel(1) for mz in range(500, 900, 100): peak = Peak1D() peak.setMZ(mz + i) peak.setIntensity(100 - 25*abs(i-2.5) ) spectrum.push_back(peak) exp.addSpectrum(spectrum) # Iterate over spectra for s in exp: for p in s: print (s.getRT(), p.getMZ(), p.getIntensity()) # Sum intensity of all spectra between RT 2.0 and 3.0 print(sum([p.getIntensity() for s in exp if s.getRT() >= 2.0 and s.getRT() <= 3.0 for p in s])) # Store as mzML MzMLFile().store("testfile2.mzML", exp) ################################### # Chromatogram # ************ ################################### chromatogram = MSChromatogram() rt = range(1500, 500, -100) i = [gaussian(rtime, 1000, 150) for rtime in rt] chromatogram.set_peaks([rt, i]) # Sort the peaks according to ascending retention time chromatogram.sortByPosition() # Iterate over chromatogram of those peaks for p in chromatogram: print(p.getRT(), p.getIntensity()) # Access a peak by index print(chromatogram[1].getRT(), chromatogram[1].getIntensity()) chromatogram.setNativeID("Trace XIC@405.2") p = Precursor() p.setIsolationWindowLowerOffset(1.5) p.setIsolationWindowUpperOffset(1.5) p.setMZ(405.2) # isolation at 405.2 +/- 1.5 Th p.setActivationEnergy(40) # 40 eV p.setCharge(2) # 2+ ion p.setMetaValue("description", "test_description") p.setMetaValue("description", chromatogram.getNativeID()) p.setMetaValue("peptide_sequence", chromatogram.getNativeID()) chromatogram.setPrecursor(p) p = Product() p.setMZ(603.4) # transition from 405.2 -> 603.4 chromatogram.setProduct(p) # Store as mzML exp = MSExperiment() exp.addChromatogram(chromatogram) MzMLFile().store("testfile3.mzML", exp) @report def testMSSpectrumLen(): """Test the __len__() method implementation for MSSpectrum""" # Test with empty spectrum spectrum = MSSpectrum() assert len(spectrum) == 0 assert len(spectrum) == spectrum.size() # Test with peaks added p1 = Peak1D() p1.setMZ(500.0) p1.setIntensity(1e5) spectrum.push_back(p1) assert len(spectrum) == 1 assert len(spectrum) == spectrum.size() p2 = Peak1D() p2.setMZ(600.0) p2.setIntensity(2e5) spectrum.push_back(p2) assert len(spectrum) == 2 assert len(spectrum) == spectrum.size() # Test with multiple peaks using set_peaks spectrum2 = MSSpectrum() mz_values = [100.0, 200.0, 300.0, 400.0, 500.0] intensity_values = [1.0, 2.0, 3.0, 4.0, 5.0] spectrum2.set_peaks([mz_values, intensity_values]) assert len(spectrum2) == 5 assert len(spectrum2) == spectrum2.size() print("All MSSpectrum len() tests passed!") @report def testMSChromatogramLen(): """Test the __len__() method implementation for MSChromatogram""" # Test with empty chromatogram chromatogram = MSChromatogram() assert len(chromatogram) == 0 assert len(chromatogram) == chromatogram.size() # Test with peaks added p1 = ChromatogramPeak() p1.setRT(1.0) p1.setIntensity(100.0) chromatogram.push_back(p1) assert len(chromatogram) == 1 assert len(chromatogram) == chromatogram.size() p2 = ChromatogramPeak() p2.setRT(2.0) p2.setIntensity(200.0) chromatogram.push_back(p2) assert len(chromatogram) == 2 assert len(chromatogram) == chromatogram.size() # Test with multiple peaks using set_peaks chromatogram2 = MSChromatogram() rt_values = [1.0, 2.0, 3.0, 4.0, 5.0] intensity_values = [10.0, 20.0, 30.0, 40.0, 50.0] chromatogram2.set_peaks([rt_values, intensity_values]) assert len(chromatogram2) == 5 assert len(chromatogram2) == chromatogram2.size() print("All MSChromatogram len() tests passed!")
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_TargetedQuantitation.py
.py
15,523
457
""" Test suite and examples for Targeted Quantitation algorithms. This module demonstrates the usage of the SmartPeaks-derived algorithms for MRM/SRM and SWATH/DIA quantitation workflows. Classes covered: - MRMFeatureSelectorScore, MRMFeatureSelectorQMIP - SelectorParameters - MRMBatchFeatureSelector - MRMFeatureFilter, MRMFeatureQC - AbsoluteQuantitation, AbsoluteQuantitationMethod - PeakIntegrator - EmgGradientDescent - TargetedSpectraExtractor """ import math import unittest import pyopenms as oms class TestMRMFeatureQC(unittest.TestCase): """Test MRMFeatureQC data structure.""" def test_component_qcs(self): """Test ComponentQCs creation and attributes.""" qc = oms.MRMFeatureQC() # Create component QC comp_qc = oms.MRMFQC_ComponentQCs() comp_qc.component_name = "glucose_quantifier" comp_qc.retention_time_l = 5.0 comp_qc.retention_time_u = 7.0 comp_qc.intensity_l = 1000.0 comp_qc.intensity_u = 1e9 comp_qc.overall_quality_l = 0.5 comp_qc.overall_quality_u = 1.0 # Note: For pyOpenMS vectors, you need to assign the whole list qc.component_qcs = [comp_qc] self.assertEqual(len(qc.component_qcs), 1) self.assertEqual(qc.component_qcs[0].component_name, "glucose_quantifier") self.assertAlmostEqual(qc.component_qcs[0].retention_time_l, 5.0) def test_component_group_qcs(self): """Test ComponentGroupQCs creation with ion ratio.""" qc = oms.MRMFeatureQC() group_qc = oms.MRMFQC_ComponentGroupQCs() group_qc.component_group_name = "glucose" group_qc.n_heavy_l = 1 group_qc.n_light_l = 1 group_qc.ion_ratio_pair_name_1 = "glucose_qualifier" group_qc.ion_ratio_pair_name_2 = "glucose_quantifier" group_qc.ion_ratio_l = 0.3 group_qc.ion_ratio_u = 0.5 # Note: For pyOpenMS vectors, you need to assign the whole list qc.component_group_qcs = [group_qc] self.assertEqual(len(qc.component_group_qcs), 1) self.assertEqual(qc.component_group_qcs[0].component_group_name, "glucose") def test_component_group_pair_qcs(self): """Test ComponentGroupPairQCs for isotopic pairs.""" qc = oms.MRMFeatureQC() pair_qc = oms.MRMFQC_ComponentGroupPairQCs() pair_qc.component_group_name = "glucose" pair_qc.resolution_pair_name = "glucose_13C6" pair_qc.resolution_l = 1.5 pair_qc.resolution_u = 10.0 pair_qc.rt_diff_l = 0.0 pair_qc.rt_diff_u = 0.5 # Note: For pyOpenMS vectors, you need to assign the whole list qc.component_group_pair_qcs = [pair_qc] self.assertEqual(len(qc.component_group_pair_qcs), 1) class TestMRMFeatureFilter(unittest.TestCase): """Test MRMFeatureFilter QC filtering.""" def test_filter_creation(self): """Test MRMFeatureFilter instantiation.""" filter_obj = oms.MRMFeatureFilter() params = filter_obj.getParameters() # Check that flag_or_filter parameter exists self.assertTrue(params.exists("flag_or_filter")) def test_calculate_ion_ratio(self): """Test ion ratio calculation between features.""" filter_obj = oms.MRMFeatureFilter() # Create two features with peak intensities f1 = oms.Feature() f1.setMetaValue("peak_apex_int", 1000.0) f2 = oms.Feature() f2.setMetaValue("peak_apex_int", 500.0) ratio = filter_obj.calculateIonRatio(f1, f2, "peak_apex_int") self.assertAlmostEqual(ratio, 2.0, places=5) def test_calculate_rt_difference(self): """Test RT difference calculation between features.""" filter_obj = oms.MRMFeatureFilter() # Create two features at different RTs f1 = oms.Feature() f1.setRT(100.0) f2 = oms.Feature() f2.setRT(105.5) rt_diff = filter_obj.calculateRTDifference(f1, f2) self.assertAlmostEqual(rt_diff, 5.5, places=5) def test_calculate_resolution(self): """Test chromatographic resolution calculation.""" filter_obj = oms.MRMFeatureFilter() # Create two features with RT and width info f1 = oms.Feature() f1.setRT(100.0) f1.setMetaValue("width_at_50", 2.0) # FWHM f2 = oms.Feature() f2.setRT(106.0) f2.setMetaValue("width_at_50", 2.0) # FWHM # Resolution = 2 * |RT2 - RT1| / (W1 + W2) # where W = FWHM * 1.7 (width at base) # Resolution = 2 * 6 / (3.4 + 3.4) = 12 / 6.8 ≈ 1.76 resolution = filter_obj.calculateResolution(f1, f2) self.assertGreater(resolution, 1.5) self.assertLess(resolution, 2.0) class TestAbsoluteQuantitationMethod(unittest.TestCase): """Test AbsoluteQuantitationMethod configuration.""" def test_method_configuration(self): """Test setting up a quantitation method.""" method = oms.AbsoluteQuantitationMethod() method.setComponentName("glucose") method.setFeatureName("peak_apex_int") method.setISName("glucose_13C6") method.setConcentrationUnits("uM") method.setTransformationModel("linear") method.setLLOD(0.1) method.setULOD(1000.0) method.setLLOQ(1.0) method.setULOQ(500.0) self.assertEqual(method.getComponentName(), "glucose") self.assertEqual(method.getISName(), "glucose_13C6") self.assertAlmostEqual(method.getLLOQ(), 1.0) self.assertAlmostEqual(method.getULOQ(), 500.0) class TestAbsoluteQuantitation(unittest.TestCase): """Test AbsoluteQuantitation workflow.""" def test_quantitation_setup(self): """Test setting up quantitation methods.""" aq = oms.AbsoluteQuantitation() # Create a method method = oms.AbsoluteQuantitationMethod() method.setComponentName("test_compound") method.setFeatureName("peak_apex_int") method.setTransformationModel("linear") # Set methods aq.setQuantMethods([method]) # Retrieve methods methods = aq.getQuantMethods() self.assertEqual(len(methods), 1) self.assertEqual(methods[0].getComponentName(), "test_compound") def test_calculate_ratio(self): """Test ratio calculation between analyte and IS.""" aq = oms.AbsoluteQuantitation() # Create analyte feature analyte = oms.Feature() analyte.setMetaValue("peak_apex_int", 2000.0) # Create IS feature internal_std = oms.Feature() internal_std.setMetaValue("peak_apex_int", 1000.0) ratio = aq.calculateRatio(analyte, internal_std, "peak_apex_int") self.assertAlmostEqual(ratio, 2.0, places=5) def test_calculate_bias(self): """Test bias calculation.""" aq = oms.AbsoluteQuantitation() # Bias = (calculated - actual) / actual * 100 bias = aq.calculateBias(100.0, 110.0) self.assertAlmostEqual(bias, 10.0, places=5) class TestPeakIntegrator(unittest.TestCase): """Test PeakIntegrator for peak area calculation.""" def test_integrator_creation(self): """Test PeakIntegrator instantiation and parameters.""" pi = oms.PeakIntegrator() params = pi.getParameters() # Check default parameters self.assertTrue(params.exists("integration_type")) self.assertTrue(params.exists("baseline_type")) def test_integrate_chromatogram(self): """Test peak integration on a chromatogram.""" pi = oms.PeakIntegrator() # Create a simple Gaussian-like chromatogram chrom = oms.MSChromatogram() # Generate Gaussian peak centered at RT=10 for i in range(20): rt = 5.0 + i * 0.5 intensity = 1000.0 * math.exp(-0.5 * ((rt - 10.0) / 1.0) ** 2) peak = oms.ChromatogramPeak() peak.setRT(rt) peak.setIntensity(intensity) chrom.push_back(peak) # Integrate peak result = pi.integratePeak(chrom, 7.0, 13.0) # Check results self.assertGreater(result.area, 0) self.assertGreater(result.height, 0) self.assertGreater(result.apex_pos, 0) def test_peak_shape_metrics(self): """Test peak shape metrics calculation.""" pi = oms.PeakIntegrator() # Create a chromatogram chrom = oms.MSChromatogram() for i in range(40): rt = 5.0 + i * 0.25 intensity = 1000.0 * math.exp(-0.5 * ((rt - 10.0) / 1.0) ** 2) peak = oms.ChromatogramPeak() peak.setRT(rt) peak.setIntensity(intensity) chrom.push_back(peak) # Get peak area first area_result = pi.integratePeak(chrom, 7.0, 13.0) # Calculate shape metrics metrics = pi.calculatePeakShapeMetrics( chrom, 7.0, 13.0, area_result.height, area_result.apex_pos ) # Check metrics self.assertGreater(metrics.width_at_50, 0) self.assertGreater(metrics.total_width, 0) class TestEmgGradientDescent(unittest.TestCase): """Test EmgGradientDescent for EMG peak fitting.""" def test_emg_creation(self): """Test EmgGradientDescent instantiation.""" emg = oms.EmgGradientDescent() params = oms.Param() emg.getDefaultParameters(params) # Check that parameters exist self.assertTrue(params.exists("max_gd_iter")) class TestSelectorParameters(unittest.TestCase): """Test SelectorParameters configuration.""" def test_default_parameters(self): """Test SelectorParameters default values.""" params = oms.SelectorParameters() # Check default values self.assertEqual(params.nn_threshold, 4) self.assertEqual(params.segment_window_length, 8) self.assertEqual(params.segment_step_length, 4) self.assertAlmostEqual(params.optimal_threshold, 0.5) def test_modify_parameters(self): """Test modifying SelectorParameters.""" params = oms.SelectorParameters() # Modify parameters params.nn_threshold = 6 params.optimal_threshold = 0.7 params.select_transition_group = False self.assertEqual(params.nn_threshold, 6) self.assertAlmostEqual(params.optimal_threshold, 0.7) self.assertFalse(params.select_transition_group) class TestMRMFeatureSelector(unittest.TestCase): """Test MRMFeatureSelector LP-based selection.""" def test_score_selector(self): """Test MRMFeatureSelectorScore instantiation.""" selector = oms.MRMFeatureSelectorScore() self.assertIsNotNone(selector) def test_qmip_selector(self): """Test MRMFeatureSelectorQMIP instantiation.""" selector = oms.MRMFeatureSelectorQMIP() self.assertIsNotNone(selector) class TestTargetedSpectraExtractor(unittest.TestCase): """Test TargetedSpectraExtractor for DDA processing.""" def test_extractor_creation(self): """Test TargetedSpectraExtractor instantiation.""" extractor = oms.TargetedSpectraExtractor() params = oms.Param() extractor.getDefaultParameters(params) # Check key parameters self.assertTrue(params.exists("rt_window")) self.assertTrue(params.exists("mz_tolerance")) def test_pick_spectrum(self): """Test spectrum peak picking.""" extractor = oms.TargetedSpectraExtractor() # Create a simple spectrum spectrum = oms.MSSpectrum() for i in range(100): mz = 100.0 + i * 1.0 # Add some peaks if i in [20, 50, 80]: intensity = 1000.0 else: intensity = 10.0 + 5.0 * math.sin(i * 0.1) peak = oms.Peak1D() peak.setMZ(mz) peak.setIntensity(intensity) spectrum.push_back(peak) picked = oms.MSSpectrum() extractor.pickSpectrum(spectrum, picked) # Should have picked some peaks self.assertGreater(len(picked), 0) # Example usage demonstration def example_targeted_quantitation_workflow(): """ Complete example of targeted quantitation workflow. This demonstrates the typical workflow for MRM/SRM quantitation: 1. Load chromatograms and transitions 2. Pick peaks with MRMTransitionGroupPicker 3. Integrate peaks with PeakIntegrator 4. Apply QC filtering with MRMFeatureFilter 5. Select optimal features with MRMFeatureSelector 6. Quantify with AbsoluteQuantitation """ print("=== Targeted Quantitation Workflow Example ===\n") # Step 1: Set up QC criteria print("Step 1: Setting up QC criteria...") qc = oms.MRMFeatureQC() # Component-level QC comp_qc = oms.MRMFQC_ComponentQCs() comp_qc.component_name = "glucose_quantifier" comp_qc.retention_time_l = 5.0 comp_qc.retention_time_u = 7.0 comp_qc.intensity_l = 1000.0 comp_qc.intensity_u = 1e9 qc.component_qcs = [comp_qc] # Assign list directly print(f" Added QC for: {comp_qc.component_name}") # Step 2: Configure quantitation method print("\nStep 2: Configuring quantitation method...") method = oms.AbsoluteQuantitationMethod() method.setComponentName("glucose") method.setFeatureName("peak_apex_int") method.setISName("glucose_13C6") method.setConcentrationUnits("uM") method.setTransformationModel("linear") method.setLLOQ(1.0) method.setULOQ(500.0) print(f" Component: {method.getComponentName()}") print(f" Internal Standard: {method.getISName()}") print(f" LLOQ-ULOQ: {method.getLLOQ()}-{method.getULOQ()} {method.getConcentrationUnits()}") # Step 3: Set up AbsoluteQuantitation print("\nStep 3: Setting up AbsoluteQuantitation...") aq = oms.AbsoluteQuantitation() aq.setQuantMethods([method]) print(f" Configured {len(aq.getQuantMethods())} quantitation method(s)") # Step 4: Configure feature selector print("\nStep 4: Configuring feature selector...") params = oms.SelectorParameters() params.nn_threshold = 4 params.segment_window_length = 8 params.optimal_threshold = 0.5 print(f" Nearest neighbors: {params.nn_threshold}") print(f" Window length: {params.segment_window_length}") print(f" Optimal threshold: {params.optimal_threshold}") # Step 5: Demonstrate PeakIntegrator print("\nStep 5: Demonstrating PeakIntegrator...") pi = oms.PeakIntegrator() pi_params = pi.getParameters() pi_params.setValue("integration_type", "trapezoid") pi_params.setValue("baseline_type", "base_to_base") pi.setParameters(pi_params) print(f" Integration type: {pi_params.getValue('integration_type')}") print(f" Baseline type: {pi_params.getValue('baseline_type')}") print("\n=== Workflow setup complete! ===") print("\nIn a real workflow, you would now:") print(" 1. Load your mzML/featureXML data") print(" 2. Run MRMTransitionGroupPicker for peak picking") print(" 3. Apply MRMFeatureFilter with your QC criteria") print(" 4. Use MRMFeatureSelectorScore or MRMFeatureSelectorQMIP") print(" 5. Call aq.quantifyComponents() on your unknowns") if __name__ == "__main__": # Run the example example_targeted_quantitation_workflow() # Run unit tests print("\n\n=== Running Unit Tests ===\n") unittest.main(verbosity=2)
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_SpectrumAccessOpenMS.py
.py
829
27
import unittest import os import pyopenms class TestSpectrumAccessOpenMS(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() def test_readfile_content(self): exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, exp) saccess = pyopenms.SpectrumAccessOpenMS(exp) spectrum = saccess.getSpectrumById(0) mz = spectrum.get_mz_array() intensity = spectrum.get_intensity_array() self.assertAlmostEqual(mz[0], 350.0000305) self.assertAlmostEqual(intensity[0], 0.0) self.assertAlmostEqual(mz[10], 358.075134277) self.assertAlmostEqual(intensity[10], 9210.931640625) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_MRMFeatureFinderScoring.py
.py
1,850
49
import unittest import os import pytest import pyopenms eps = 2 class TestMRMFeatureFinderScoring(unittest.TestCase): @pytest.fixture(autouse=True) def setup_test_data(self, openms_test_data_dir): """Setup test with test data directory from pytest fixture.""" self.dirname = os.path.dirname(os.path.abspath(__file__)) self.testdirname = openms_test_data_dir # set up files self.chromatograms = os.path.join(self.testdirname, "OpenSwathAnalyzer_1_input_chrom.mzML").encode() self.tramlfile = os.path.join(self.testdirname, "OpenSwathAnalyzer_1_input.TraML").encode() def test_run_mrmfeaturefinder(self): # load chromatograms chromatograms = pyopenms.MSExperiment() fh = pyopenms.FileHandler() fh.loadExperiment(self.chromatograms, chromatograms) # load TraML file targeted = pyopenms.TargetedExperiment(); tramlfile = pyopenms.TraMLFile(); tramlfile.load(self.tramlfile, targeted); # Create empty files as input and finally as output empty_swath = pyopenms.MSExperiment() trafo = pyopenms.TransformationDescription() output = pyopenms.FeatureMap(); # set up featurefinder and run featurefinder = pyopenms.MRMFeatureFinderScoring() featurefinder.pickExperiment(chromatograms, output, targeted, trafo, empty_swath) self.assertAlmostEqual(output.size(), 3) self.assertAlmostEqual(output[0].getRT(), 3119.092041015, eps) self.assertAlmostEqual(output[0].getIntensity(), 3614.99755859375, eps) self.assertAlmostEqual(output[0].getMetaValue(b"var_xcorr_shape_weighted"), 0.997577965259552, eps) self.assertAlmostEqual(output[0].getMetaValue(b"sn_ratio"), 86.00413513183594, eps) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/testLightTargetedExperiment.py
.py
2,743
105
import pyopenms import unittest class TestLightTargetedExperiment(unittest.TestCase): def setUp(self): lt = pyopenms.LightTransition() lt.fragment_charge = 2 lt.transition_name = b"X" lt.peptide_ref = b"Y" lt.library_intensity = 12.0 lt.product_mz = 22.0 self.lt = lt lm = pyopenms.LightModification() lm.location = 13 lm.unimod_id = 4 self.lm = lm lpep = pyopenms.LightCompound() lpep.rt = 12.0 lpep.charge = 2 lpep.sequence = b"SEQ" lpep.protein_refs = [b"REF"] lpep.modifications = [lm] self.lpep = lpep lprot = pyopenms.LightProtein() lprot.id = b"1234" lprot.sequence = b"ABC" self.lprot = lprot lte = pyopenms.LightTargetedExperiment() lte.compounds = [self.lpep] lte.proteins = [self.lprot] lte.transitions = [self.lt] self.lte = lte @staticmethod def _test_light_transition(lt): assert lt.fragment_charge == 2 assert lt.getProductChargeState() == lt.fragment_charge assert lt.transition_name == b"X" assert lt.peptide_ref == b"Y" assert lt.library_intensity == 12.0 assert lt.product_mz == 22.0 @staticmethod def _test_light_modification(lm): assert lm.location == 13 assert lm.unimod_id == 4 @staticmethod def _test_light_peptide(lpep): assert lpep.rt == 12.0 assert lpep.charge == 2 assert lpep.sequence == b"SEQ" assert lpep.protein_refs == [b"REF"] mod, = lpep.modifications TestLightTargetedExperiment._test_light_modification(mod) @staticmethod def _test_light_protein(lprot): assert lprot.id == b"1234" assert lprot.sequence == b"ABC" def test_light_transition(self): TestLightTargetedExperiment._test_light_transition(self.lt) def test_light_modification(self): TestLightTargetedExperiment._test_light_modification(self.lm) def test_light_peptide(self): TestLightTargetedExperiment._test_light_peptide(self.lpep) def test_light_protein(self): TestLightTargetedExperiment._test_light_protein(self.lprot) def test_light_targeted_experiment(self): lprot, = self.lte.proteins lpep, = self.lte.compounds ltrans, = self.lte.transitions TestLightTargetedExperiment._test_light_protein(lprot) TestLightTargetedExperiment._test_light_peptide(lpep) TestLightTargetedExperiment._test_light_transition(ltrans) ltrans, = self.lte.getTransitions() TestLightTargetedExperiment._test_light_transition(ltrans)
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_Hash.py
.py
13,349
494
""" Test hash functions for various OpenMS data types. Tests that: 1. Equal objects have equal hashes 2. Objects can be used as dictionary keys 3. Objects can be used in sets """ import unittest from pyopenms import ( Peak1D, Peak2D, ChromatogramPeak, MobilityPeak1D, AASequence, EmpiricalFormula, PeptideHit, PeptideEvidence, FeatureHandle, DateTime, Adduct, DataValue, MetaInfoInterface, CVTerm, Software, Precursor, ProteinHit, PeptideIdentification, Product, SpectrumSettings, ChromatogramSettings ) class TestPeak1DHash(unittest.TestCase): """Test hash function for Peak1D""" def test_equal_peaks_have_equal_hash(self): p1 = Peak1D() p1.setMZ(100.5) p1.setIntensity(1000.0) p2 = Peak1D() p2.setMZ(100.5) p2.setIntensity(1000.0) self.assertEqual(hash(p1), hash(p2)) def test_different_peaks_have_different_hash(self): p1 = Peak1D() p1.setMZ(100.5) p1.setIntensity(1000.0) p2 = Peak1D() p2.setMZ(200.5) p2.setIntensity(1000.0) self.assertNotEqual(hash(p1), hash(p2)) def test_can_use_in_dict(self): p1 = Peak1D() p1.setMZ(100.5) p1.setIntensity(1000.0) d = {p1: "value1"} self.assertEqual(d[p1], "value1") # Test that equal peak retrieves same value p2 = Peak1D() p2.setMZ(100.5) p2.setIntensity(1000.0) self.assertEqual(d[p2], "value1") def test_can_use_in_set(self): p1 = Peak1D() p1.setMZ(100.5) p1.setIntensity(1000.0) p2 = Peak1D() p2.setMZ(100.5) p2.setIntensity(1000.0) p3 = Peak1D() p3.setMZ(200.5) p3.setIntensity(1000.0) s = {p1, p2, p3} self.assertEqual(len(s), 2) # p1 and p2 are equal class TestPeak2DHash(unittest.TestCase): """Test hash function for Peak2D""" def test_equal_peaks_have_equal_hash(self): p1 = Peak2D() p1.setRT(10.5) p1.setMZ(100.5) p1.setIntensity(1000.0) p2 = Peak2D() p2.setRT(10.5) p2.setMZ(100.5) p2.setIntensity(1000.0) self.assertEqual(hash(p1), hash(p2)) def test_can_use_in_dict(self): p1 = Peak2D() p1.setRT(10.5) p1.setMZ(100.5) p1.setIntensity(1000.0) d = {p1: 42} self.assertEqual(d[p1], 42) class TestChromatogramPeakHash(unittest.TestCase): """Test hash function for ChromatogramPeak""" def test_equal_peaks_have_equal_hash(self): p1 = ChromatogramPeak() p1.setRT(10.5) p1.setIntensity(1000.0) p2 = ChromatogramPeak() p2.setRT(10.5) p2.setIntensity(1000.0) self.assertEqual(hash(p1), hash(p2)) def test_can_use_in_dict(self): p1 = ChromatogramPeak() p1.setRT(10.5) p1.setIntensity(1000.0) d = {p1: "test"} self.assertEqual(d[p1], "test") class TestMobilityPeak1DHash(unittest.TestCase): """Test hash function for MobilityPeak1D""" def test_equal_peaks_have_equal_hash(self): p1 = MobilityPeak1D() p1.setMobility(1.5) p1.setIntensity(1000.0) p2 = MobilityPeak1D() p2.setMobility(1.5) p2.setIntensity(1000.0) self.assertEqual(hash(p1), hash(p2)) def test_can_use_in_dict(self): p1 = MobilityPeak1D() p1.setMobility(1.5) p1.setIntensity(1000.0) d = {p1: 99} self.assertEqual(d[p1], 99) class TestAASequenceHash(unittest.TestCase): """Test hash function for AASequence""" def test_equal_sequences_have_equal_hash(self): seq1 = AASequence.fromString("PEPTIDE") seq2 = AASequence.fromString("PEPTIDE") self.assertEqual(hash(seq1), hash(seq2)) def test_different_sequences_have_different_hash(self): seq1 = AASequence.fromString("PEPTIDE") seq2 = AASequence.fromString("PROTEIN") self.assertNotEqual(hash(seq1), hash(seq2)) def test_can_use_in_dict(self): seq = AASequence.fromString("PEPTIDE") d = {seq: "peptide_value"} seq2 = AASequence.fromString("PEPTIDE") self.assertEqual(d[seq2], "peptide_value") def test_can_use_in_set(self): seqs = { AASequence.fromString("PEPTIDE"), AASequence.fromString("PEPTIDE"), # duplicate AASequence.fromString("PROTEIN") } self.assertEqual(len(seqs), 2) class TestEmpiricalFormulaHash(unittest.TestCase): """Test hash function for EmpiricalFormula""" def test_equal_formulas_have_equal_hash(self): f1 = EmpiricalFormula("H2O") f2 = EmpiricalFormula("H2O") self.assertEqual(hash(f1), hash(f2)) def test_different_formulas_have_different_hash(self): f1 = EmpiricalFormula("H2O") f2 = EmpiricalFormula("CO2") self.assertNotEqual(hash(f1), hash(f2)) def test_can_use_in_dict(self): f = EmpiricalFormula("H2O") d = {f: "water"} f2 = EmpiricalFormula("H2O") self.assertEqual(d[f2], "water") def test_isotope_formulas_have_different_hash(self): """Test that C and (13)C have different hashes""" f1 = EmpiricalFormula("C") f2 = EmpiricalFormula("(13)C") self.assertNotEqual(hash(f1), hash(f2)) class TestPeptideEvidenceHash(unittest.TestCase): """Test hash function for PeptideEvidence""" def test_equal_evidences_have_equal_hash(self): pe1 = PeptideEvidence() pe1.setProteinAccession("sp|P12345|TEST") pe1.setStart(10) pe1.setEnd(20) pe2 = PeptideEvidence() pe2.setProteinAccession("sp|P12345|TEST") pe2.setStart(10) pe2.setEnd(20) self.assertEqual(hash(pe1), hash(pe2)) def test_can_use_in_dict(self): pe = PeptideEvidence() pe.setProteinAccession("sp|P12345|TEST") pe.setStart(10) pe.setEnd(20) d = {pe: "evidence"} self.assertEqual(d[pe], "evidence") class TestDateTimeHash(unittest.TestCase): """Test hash function for DateTime""" def test_equal_datetimes_have_equal_hash(self): dt1 = DateTime() dt1.set("2024-12-25 10:30:00") dt2 = DateTime() dt2.set("2024-12-25 10:30:00") self.assertEqual(hash(dt1), hash(dt2)) def test_can_use_in_dict(self): dt = DateTime() dt.set("2024-12-25 10:30:00") d = {dt: "christmas"} self.assertEqual(d[dt], "christmas") class TestAdductHash(unittest.TestCase): """Test hash function for Adduct""" def test_equal_adducts_have_equal_hash(self): a1 = Adduct(1, 1, 22.989769, "Na", -5.0, 0.0, "") a2 = Adduct(1, 1, 22.989769, "Na", -5.0, 0.0, "") self.assertEqual(hash(a1), hash(a2)) def test_can_use_in_dict(self): a = Adduct(1, 1, 22.989769, "Na", -5.0, 0.0, "") d = {a: "sodium"} self.assertEqual(d[a], "sodium") class TestDataValueHash(unittest.TestCase): """Test hash function for DataValue - critical epsilon test""" def test_equal_int_values_have_equal_hash(self): dv1 = DataValue(42) dv2 = DataValue(42) self.assertEqual(hash(dv1), hash(dv2)) def test_equal_string_values_have_equal_hash(self): dv1 = DataValue("test") dv2 = DataValue("test") self.assertEqual(hash(dv1), hash(dv2)) def test_double_epsilon_compatibility(self): """Critical test: doubles within epsilon (1e-6) must have equal hashes""" dv1 = DataValue(1.0000001) dv2 = DataValue(1.0000002) # Within epsilon # These are equal per operator== so must have equal hash self.assertEqual(hash(dv1), hash(dv2)) def test_different_doubles_have_different_hash(self): dv1 = DataValue(1.0) dv2 = DataValue(2.0) self.assertNotEqual(hash(dv1), hash(dv2)) def test_can_use_in_dict(self): dv = DataValue(42) d = {dv: "answer"} self.assertEqual(d[dv], "answer") class TestMetaInfoInterfaceHash(unittest.TestCase): """Test hash function for MetaInfoInterface - critical order-independence test""" def test_equal_meta_have_equal_hash(self): m1 = MetaInfoInterface() m1.setMetaValue("key1", "value1") m2 = MetaInfoInterface() m2.setMetaValue("key1", "value1") self.assertEqual(hash(m1), hash(m2)) def test_order_independent_hash(self): """Critical test: insertion order should not affect hash""" m1 = MetaInfoInterface() m1.setMetaValue("name", "test") m1.setMetaValue("score", 1.5) m2 = MetaInfoInterface() m2.setMetaValue("score", 1.5) # Different order m2.setMetaValue("name", "test") self.assertEqual(hash(m1), hash(m2)) def test_can_use_in_dict(self): m = MetaInfoInterface() m.setMetaValue("key", "value") d = {m: "meta"} self.assertEqual(d[m], "meta") class TestPeptideHitHash(unittest.TestCase): """Test hash function for PeptideHit""" def test_equal_hits_have_equal_hash(self): ph1 = PeptideHit() ph1.setSequence(AASequence.fromString("PEPTIDE")) ph1.setScore(10.5) ph1.setCharge(2) ph2 = PeptideHit() ph2.setSequence(AASequence.fromString("PEPTIDE")) ph2.setScore(10.5) ph2.setCharge(2) self.assertEqual(hash(ph1), hash(ph2)) def test_different_hits_have_different_hash(self): ph1 = PeptideHit() ph1.setSequence(AASequence.fromString("PEPTIDE")) ph2 = PeptideHit() ph2.setSequence(AASequence.fromString("PROTEIN")) self.assertNotEqual(hash(ph1), hash(ph2)) def test_can_use_in_set(self): hits = set() for seq in ["PEPTIDE", "PROTEIN", "PEPTIDE"]: # PEPTIDE twice ph = PeptideHit() ph.setSequence(AASequence.fromString(seq)) hits.add(ph) self.assertEqual(len(hits), 2) class TestCVTermHash(unittest.TestCase): """Test hash function for CVTerm""" def test_equal_terms_have_equal_hash(self): cv1 = CVTerm() cv1.setAccession("MS:1000001") cv1.setName("sample number") cv2 = CVTerm() cv2.setAccession("MS:1000001") cv2.setName("sample number") self.assertEqual(hash(cv1), hash(cv2)) def test_can_use_in_dict(self): cv = CVTerm() cv.setAccession("MS:1000001") d = {cv: "term"} self.assertEqual(d[cv], "term") class TestSoftwareHash(unittest.TestCase): """Test hash function for Software""" def test_equal_software_have_equal_hash(self): sw1 = Software() sw1.setName("OpenMS") sw1.setVersion("3.0") sw2 = Software() sw2.setName("OpenMS") sw2.setVersion("3.0") self.assertEqual(hash(sw1), hash(sw2)) def test_can_use_in_dict(self): sw = Software() sw.setName("OpenMS") d = {sw: "software"} self.assertEqual(d[sw], "software") class TestPrecursorHash(unittest.TestCase): """Test hash function for Precursor""" def test_equal_precursors_have_equal_hash(self): p1 = Precursor() p1.setMZ(500.0) p1.setCharge(2) p2 = Precursor() p2.setMZ(500.0) p2.setCharge(2) self.assertEqual(hash(p1), hash(p2)) def test_can_use_in_dict(self): p = Precursor() p.setMZ(500.0) d = {p: "precursor"} self.assertEqual(d[p], "precursor") class TestProteinHitHash(unittest.TestCase): """Test hash function for ProteinHit""" def test_equal_hits_have_equal_hash(self): ph1 = ProteinHit() ph1.setAccession("sp|P12345|TEST") ph1.setScore(100.0) ph2 = ProteinHit() ph2.setAccession("sp|P12345|TEST") ph2.setScore(100.0) self.assertEqual(hash(ph1), hash(ph2)) def test_can_use_in_set(self): hits = set() for acc in ["P12345", "P67890", "P12345"]: ph = ProteinHit() ph.setAccession(acc) hits.add(ph) self.assertEqual(len(hits), 2) class TestPeptideIdentificationHash(unittest.TestCase): """Test hash function for PeptideIdentification""" def test_equal_ids_have_equal_hash(self): pi1 = PeptideIdentification() pi1.setIdentifier("test_run") pi1.setScoreType("XCorr") pi2 = PeptideIdentification() pi2.setIdentifier("test_run") pi2.setScoreType("XCorr") self.assertEqual(hash(pi1), hash(pi2)) def test_can_use_in_dict(self): pi = PeptideIdentification() pi.setIdentifier("test") d = {pi: "identification"} self.assertEqual(d[pi], "identification") class TestProductHash(unittest.TestCase): """Test hash function for Product""" def test_equal_products_have_equal_hash(self): p1 = Product() p1.setMZ(500.0) p2 = Product() p2.setMZ(500.0) self.assertEqual(hash(p1), hash(p2)) def test_can_use_in_dict(self): p = Product() p.setMZ(500.0) d = {p: "product"} self.assertEqual(d[p], "product") if __name__ == "__main__": unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_DataProcessing.py
.py
3,256
88
import unittest import pyopenms class TestDataProcessing(unittest.TestCase): def test_processingActionToString(self): """Test converting ProcessingAction enum to string.""" # Test known processing actions self.assertEqual( pyopenms.DataProcessing.processingActionToString( pyopenms.DataProcessing.ProcessingAction.PEAK_PICKING), "Peak picking" ) self.assertEqual( pyopenms.DataProcessing.processingActionToString( pyopenms.DataProcessing.ProcessingAction.SMOOTHING), "Smoothing" ) self.assertEqual( pyopenms.DataProcessing.processingActionToString( pyopenms.DataProcessing.ProcessingAction.CALIBRATION), "Calibration of m/z positions" ) self.assertEqual( pyopenms.DataProcessing.processingActionToString( pyopenms.DataProcessing.ProcessingAction.DEISOTOPING), "Deisotoping" ) def test_toProcessingAction(self): """Test converting string to ProcessingAction enum.""" # Test known processing action strings self.assertEqual( pyopenms.DataProcessing.toProcessingAction("Peak picking"), pyopenms.DataProcessing.ProcessingAction.PEAK_PICKING ) self.assertEqual( pyopenms.DataProcessing.toProcessingAction("Smoothing"), pyopenms.DataProcessing.ProcessingAction.SMOOTHING ) self.assertEqual( pyopenms.DataProcessing.toProcessingAction("Calibration of m/z positions"), pyopenms.DataProcessing.ProcessingAction.CALIBRATION ) self.assertEqual( pyopenms.DataProcessing.toProcessingAction("Deisotoping"), pyopenms.DataProcessing.ProcessingAction.DEISOTOPING ) def test_roundtrip_processingAction(self): """Test that enum -> string -> enum roundtrip works.""" PA = pyopenms.DataProcessing.ProcessingAction actions = [ PA.DATA_PROCESSING, PA.CHARGE_DECONVOLUTION, PA.DEISOTOPING, PA.SMOOTHING, PA.PEAK_PICKING, PA.ALIGNMENT, PA.CALIBRATION, PA.NORMALIZATION, PA.FILTERING, ] for action in actions: action_str = pyopenms.DataProcessing.processingActionToString(action) result = pyopenms.DataProcessing.toProcessingAction(action_str) self.assertEqual(result, action) def test_getAllNamesOfProcessingAction(self): """Test getting all processing action names.""" names = pyopenms.DataProcessing.getAllNamesOfProcessingAction() self.assertGreater(len(names), 0) # getAllNames returns bytes self.assertIn(b"Peak picking", names) self.assertIn(b"Smoothing", names) self.assertIn(b"Calibration of m/z positions", names) def test_toProcessingAction_invalid(self): """Test that invalid string raises exception.""" with self.assertRaises(Exception): pyopenms.DataProcessing.toProcessingAction("InvalidProcessingAction") if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_backward_compatibility.py
.py
14,063
332
import unittest import os import tempfile import warnings import pyopenms class TestBackwardCompatibilityIdXMLFile(unittest.TestCase): """Test backward compatibility for IdXMLFile with Python lists""" def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.idXML").encode() def test_load_with_python_list(self): """Test that IdXMLFile.load() works with Python lists (deprecated API)""" idxml_file = pyopenms.IdXMLFile() protein_ids = [] peptide_ids = [] # Deprecated: Python list # This should work but emit a DeprecationWarning with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") idxml_file.load(self.filename, protein_ids, peptide_ids) # Verify deprecation warning was emitted self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) self.assertIn("deprecated", str(w[0].message).lower()) # Verify the results self.assertEqual(len(protein_ids), 1) self.assertEqual(len(peptide_ids), 3) self.assertIsInstance(peptide_ids, list) self.assertIsInstance(peptide_ids[0], pyopenms.PeptideIdentification) def test_load_with_peptide_identification_list(self): """Test that IdXMLFile.load() works with PeptideIdentificationList (new API)""" idxml_file = pyopenms.IdXMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() # New API # This should work without any warnings with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") idxml_file.load(self.filename, protein_ids, peptide_ids) # Verify no deprecation warning was emitted deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] self.assertEqual(len(deprecation_warnings), 0) # Verify the results self.assertEqual(len(protein_ids), 1) self.assertEqual(peptide_ids.size(), 3) self.assertIsInstance(peptide_ids, pyopenms.PeptideIdentificationList) def test_store_with_python_list(self): """Test that IdXMLFile.store() works with Python lists (deprecated API)""" # First load data using new API idxml_file = pyopenms.IdXMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() idxml_file.load(self.filename, protein_ids, peptide_ids) # Convert to list for deprecated API test peptide_ids_list = list(peptide_ids) # Now store using deprecated Python list with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.idXML') as tmpfile: temp_filename = tmpfile.name try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") idxml_file.store(temp_filename.encode(), protein_ids, peptide_ids_list) # Verify deprecation warning was emitted self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) # Verify we can read it back protein_ids_2 = [] peptide_ids_2 = pyopenms.PeptideIdentificationList() idxml_file.load(temp_filename.encode(), protein_ids_2, peptide_ids_2) self.assertEqual(len(protein_ids_2), 1) self.assertEqual(peptide_ids_2.size(), 3) finally: if os.path.exists(temp_filename): os.unlink(temp_filename) def test_store_with_peptide_identification_list(self): """Test that IdXMLFile.store() works with PeptideIdentificationList (new API)""" # First load data idxml_file = pyopenms.IdXMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() idxml_file.load(self.filename, protein_ids, peptide_ids) # Now store using new-style PeptideIdentificationList with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.idXML') as tmpfile: temp_filename = tmpfile.name try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") idxml_file.store(temp_filename.encode(), protein_ids, peptide_ids) # Verify no deprecation warning was emitted deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] self.assertEqual(len(deprecation_warnings), 0) # Verify we can read it back protein_ids_2 = [] peptide_ids_2 = pyopenms.PeptideIdentificationList() idxml_file.load(temp_filename.encode(), protein_ids_2, peptide_ids_2) self.assertEqual(len(protein_ids_2), 1) self.assertEqual(peptide_ids_2.size(), 3) finally: if os.path.exists(temp_filename): os.unlink(temp_filename) class TestBackwardCompatibilityPepXMLFile(unittest.TestCase): """Test backward compatibility for PepXMLFile with Python lists""" def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.pep.xml").encode() def test_load_with_python_list(self): """Test that PepXMLFile.load() works with Python lists (deprecated API)""" pepxml_file = pyopenms.PepXMLFile() protein_ids = [] peptide_ids = [] # Deprecated: Python list # This should work but emit a DeprecationWarning with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") pepxml_file.load(self.filename, protein_ids, peptide_ids) # Verify deprecation warning was emitted self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) # Verify the results self.assertEqual(len(protein_ids), 3) self.assertEqual(len(peptide_ids), 19) self.assertIsInstance(peptide_ids, list) self.assertIsInstance(peptide_ids[0], pyopenms.PeptideIdentification) def test_load_with_peptide_identification_list(self): """Test that PepXMLFile.load() works with PeptideIdentificationList (new API)""" pepxml_file = pyopenms.PepXMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() # New API # This should work without any warnings with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") pepxml_file.load(self.filename, protein_ids, peptide_ids) # Verify no deprecation warning was emitted deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] self.assertEqual(len(deprecation_warnings), 0) # Verify the results self.assertEqual(len(protein_ids), 3) self.assertEqual(peptide_ids.size(), 19) self.assertIsInstance(peptide_ids, pyopenms.PeptideIdentificationList) def test_store_with_python_list(self): """Test that PepXMLFile.store() works with Python lists (deprecated API)""" # First load data using new API pepxml_file = pyopenms.PepXMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() pepxml_file.load(self.filename, protein_ids, peptide_ids) # Convert to list for deprecated API test peptide_ids_list = list(peptide_ids) # Now store using deprecated Python list with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.pep.xml') as tmpfile: temp_filename = tmpfile.name try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") pepxml_file.store(temp_filename.encode(), protein_ids, peptide_ids_list) # Verify deprecation warning was emitted self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) # Verify we can read it back protein_ids_2 = [] peptide_ids_2 = pyopenms.PeptideIdentificationList() pepxml_file.load(temp_filename.encode(), protein_ids_2, peptide_ids_2) # Note: PepXML format has limitations and may not preserve all protein IDs # during roundtrip, but peptide IDs should be preserved self.assertGreaterEqual(len(protein_ids_2), 1) self.assertEqual(peptide_ids_2.size(), 19) finally: if os.path.exists(temp_filename): os.unlink(temp_filename) class TestBackwardCompatibilityMzIdentMLFile(unittest.TestCase): """Test backward compatibility for MzIdentMLFile with Python lists""" def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.mzid").encode() def test_load_with_python_list(self): """Test that MzIdentMLFile.load() works with Python lists (deprecated API)""" mzid_file = pyopenms.MzIdentMLFile() protein_ids = [] peptide_ids = [] # Deprecated: Python list # This should work but emit a DeprecationWarning with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") mzid_file.load(self.filename, protein_ids, peptide_ids) # Verify deprecation warning was emitted self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) # Verify the results self.assertGreater(len(protein_ids), 0) self.assertGreater(len(peptide_ids), 0) self.assertIsInstance(peptide_ids, list) self.assertIsInstance(peptide_ids[0], pyopenms.PeptideIdentification) def test_load_with_peptide_identification_list(self): """Test that MzIdentMLFile.load() works with PeptideIdentificationList (new API)""" mzid_file = pyopenms.MzIdentMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() # New API # This should work without any warnings with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") mzid_file.load(self.filename, protein_ids, peptide_ids) # Verify no deprecation warning was emitted deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] self.assertEqual(len(deprecation_warnings), 0) # Verify the results self.assertGreater(len(protein_ids), 0) self.assertGreater(peptide_ids.size(), 0) self.assertIsInstance(peptide_ids, pyopenms.PeptideIdentificationList) def test_store_with_python_list(self): """Test that MzIdentMLFile.store() works with Python lists (deprecated API)""" # First load data using new API mzid_file = pyopenms.MzIdentMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() mzid_file.load(self.filename, protein_ids, peptide_ids) original_peptide_count = peptide_ids.size() # Convert to list for deprecated API test peptide_ids_list = list(peptide_ids) # Now store using deprecated Python list with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.mzid') as tmpfile: temp_filename = tmpfile.name try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") mzid_file.store(temp_filename.encode(), protein_ids, peptide_ids_list) # Verify deprecation warning was emitted self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) # Verify we can read it back protein_ids_2 = [] peptide_ids_2 = pyopenms.PeptideIdentificationList() mzid_file.load(temp_filename.encode(), protein_ids_2, peptide_ids_2) self.assertGreater(len(protein_ids_2), 0) self.assertEqual(peptide_ids_2.size(), original_peptide_count) finally: if os.path.exists(temp_filename): os.unlink(temp_filename) def test_store_with_peptide_identification_list(self): """Test that MzIdentMLFile.store() works with PeptideIdentificationList (new API)""" # First load data mzid_file = pyopenms.MzIdentMLFile() protein_ids = [] peptide_ids = pyopenms.PeptideIdentificationList() mzid_file.load(self.filename, protein_ids, peptide_ids) original_peptide_count = peptide_ids.size() # Now store using new-style PeptideIdentificationList with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.mzid') as tmpfile: temp_filename = tmpfile.name try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") mzid_file.store(temp_filename.encode(), protein_ids, peptide_ids) # Verify no deprecation warning was emitted deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] self.assertEqual(len(deprecation_warnings), 0) # Verify we can read it back protein_ids_2 = [] peptide_ids_2 = pyopenms.PeptideIdentificationList() mzid_file.load(temp_filename.encode(), protein_ids_2, peptide_ids_2) self.assertGreater(len(protein_ids_2), 0) self.assertEqual(peptide_ids_2.size(), original_peptide_count) finally: if os.path.exists(temp_filename): os.unlink(temp_filename) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_InstrumentSettings.py
.py
2,694
84
import unittest import pyopenms class TestInstrumentSettings(unittest.TestCase): def test_scanModeToString(self): """Test converting ScanMode enum to string.""" SM = pyopenms.InstrumentSettings.ScanMode # Test known scan modes self.assertEqual( pyopenms.InstrumentSettings.scanModeToString(SM.MS1SPECTRUM), "MS1Spectrum" ) self.assertEqual( pyopenms.InstrumentSettings.scanModeToString(SM.MSNSPECTRUM), "MSnSpectrum" ) self.assertEqual( pyopenms.InstrumentSettings.scanModeToString(SM.SIM), "SelectedIonMonitoring" ) self.assertEqual( pyopenms.InstrumentSettings.scanModeToString(SM.SRM), "SelectedReactionMonitoring" ) def test_toScanMode(self): """Test converting string to ScanMode enum.""" SM = pyopenms.InstrumentSettings.ScanMode # Test known scan mode strings self.assertEqual( pyopenms.InstrumentSettings.toScanMode("MS1Spectrum"), SM.MS1SPECTRUM ) self.assertEqual( pyopenms.InstrumentSettings.toScanMode("MSnSpectrum"), SM.MSNSPECTRUM ) self.assertEqual( pyopenms.InstrumentSettings.toScanMode("SelectedIonMonitoring"), SM.SIM ) self.assertEqual( pyopenms.InstrumentSettings.toScanMode("SelectedReactionMonitoring"), SM.SRM ) def test_roundtrip_scanMode(self): """Test that enum -> string -> enum roundtrip works.""" SM = pyopenms.InstrumentSettings.ScanMode modes = [ SM.UNKNOWN, SM.MASSSPECTRUM, SM.MS1SPECTRUM, SM.MSNSPECTRUM, SM.SIM, SM.SRM, SM.CRM, SM.PRECURSOR, ] for mode in modes: mode_str = pyopenms.InstrumentSettings.scanModeToString(mode) result = pyopenms.InstrumentSettings.toScanMode(mode_str) self.assertEqual(result, mode) def test_getAllNamesOfScanMode(self): """Test getting all scan mode names.""" names = pyopenms.InstrumentSettings.getAllNamesOfScanMode() self.assertGreater(len(names), 0) # getAllNames returns bytes self.assertIn(b"MS1Spectrum", names) self.assertIn(b"MSnSpectrum", names) def test_toScanMode_invalid(self): """Test that invalid string raises exception.""" with self.assertRaises(Exception): pyopenms.InstrumentSettings.toScanMode("InvalidScanMode") if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_TraML.py
.py
2,018
52
import unittest import os import pyopenms class TestTraMLFile(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test.TraML").encode() def test_readfile(self): targeted = pyopenms.TargetedExperiment(); tramlfile = pyopenms.TraMLFile(); tramlfile.load(self.filename, targeted); def test_readfile_content(self): targeted = pyopenms.TargetedExperiment(); tramlfile = pyopenms.TraMLFile(); tramlfile.load(self.filename, targeted); self.assertEqual(len( targeted.getTransitions() ), 3 ) self.assertAlmostEqual(targeted.getTransitions()[0].getPrecursorMZ(), 500.0) self.assertAlmostEqual(targeted.getTransitions()[0].getProductMZ(), 628.45, places=4) self.assertEqual(targeted.getTransitions()[0].getName(), "tr1" ) self.assertEqual(targeted.getTransitions()[0].getNativeID(), "tr1" ) self.assertEqual(targeted.getTransitions()[0].getPeptideRef(), "tr_gr1") def test_TargetedExperiment(self): targeted = pyopenms.TargetedExperiment(); tramlfile = pyopenms.TraMLFile(); tramlfile.load(self.filename, targeted); self.assertEqual(len( targeted.getTransitions() ), 3 ) targeted.setCVs(targeted.getCVs()) targeted.setTargetCVTerms(targeted.getTargetCVTerms()) targeted.setPeptides(targeted.getPeptides()) targeted.setProteins(targeted.getProteins()) targeted.setTransitions(targeted.getTransitions()) first_transition = targeted.getTransitions()[0] first_peptide = targeted.getPeptides()[0] targeted.addTransition(first_transition) targeted.addPeptide(first_peptide) self.assertTrue( targeted.getPeptideByRef(first_transition.getPeptideRef()) is not None) self.assertTrue( targeted.getProteinByRef(first_peptide.protein_refs[0]) is not None) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/pyOpenMS/tests/unittests/test_BaselineFiltering.py
.py
1,182
35
import unittest import os import pyopenms class TestMorphologicalFilter(unittest.TestCase): def setUp(self): dirname = os.path.dirname(os.path.abspath(__file__)) self.filename = os.path.join(dirname, "test2.mzML").encode() self.exp = pyopenms.MSExperiment() pyopenms.MzMLFile().load(self.filename, self.exp) def test_init(self): thisfilter = pyopenms.MorphologicalFilter(); def test_run(self): thisfilter = pyopenms.MorphologicalFilter(); old_firstspec = self.exp[0] # needs different parameters to have any effect ... params = pyopenms.MorphologicalFilter().getDefaults(); params.setValue(b"struc_elem_length", 0.05, b'') thisfilter.setParameters(params); thisfilter.filterExperiment(self.exp) self.assertNotEqual(self.exp.size(), 0) self.assertNotEqual(old_firstspec, self.exp[0]) # MZ should not change, Intensity should self.assertEqual(old_firstspec[10].getMZ(), self.exp[0][10].getMZ()) self.assertNotEqual(old_firstspec[10].getIntensity(), self.exp[0][10].getIntensity()) if __name__ == '__main__': unittest.main()
Python
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/Macros.h
.h
952
25
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <cassert> // Simple implementation of PRE and POST conditions using assert (should be on // during debug mode and off during release mode) with a informative message // which is printed alongside the dump. // see http://stackoverflow.com/questions/3692954/add-custom-messages-in-assert // "Since a pointer "is true" if it's non-null, you can use the &&-operator to // chain and display the message". #define OPENSWATH_PRECONDITION(condition, message)\ assert( (condition) && (message)); #define OPENSWATH_POSTCONDITION(condition, message)\ assert( (condition) && (message));
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h
.h
1,954
62
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <vector> #include <string> #include <memory> #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> namespace OpenSwath { // Datastructures for Scoring class OPENSWATHALGO_DLLAPI IFeature { public: virtual ~IFeature(){} virtual void getRT(std::vector<double>& rt) const = 0; virtual void getIntensity(std::vector<double>& intens) const = 0; virtual float getIntensity() const = 0; virtual double getRT() const = 0; }; class OPENSWATHALGO_DLLAPI IMRMFeature { public: virtual ~IMRMFeature(){} virtual std::shared_ptr<OpenSwath::IFeature> getFeature(std::string nativeID) = 0; virtual std::shared_ptr<OpenSwath::IFeature> getPrecursorFeature(std::string nativeID) = 0; virtual std::vector<std::string> getNativeIDs() const = 0; virtual std::vector<std::string> getPrecursorIDs() const = 0; virtual float getIntensity() const = 0; virtual double getRT() const = 0; virtual double getMetaValue(std::string name) const = 0; virtual size_t size() const = 0; }; struct OPENSWATHALGO_DLLAPI ITransitionGroup { virtual ~ITransitionGroup() {} virtual std::size_t size() const = 0; virtual std::vector<std::string> getNativeIDs() const = 0; virtual void getLibraryIntensities(std::vector<double>& intensities) const = 0; }; struct OPENSWATHALGO_DLLAPI ISignalToNoise { virtual ~ISignalToNoise() {} virtual double getValueAtRT(double RT) = 0; // cannot be const due to OpenMS implementation }; typedef std::shared_ptr<ISignalToNoise> ISignalToNoisePtr; } //end Namespace OpenSwath
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/MockObjects.h
.h
2,815
123
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h> #include <memory> #include <map> #include <vector> #include <string> namespace OpenSwath { /** @brief Mock object implementing IFeature */ class OPENSWATHALGO_DLLAPI MockFeature : public OpenSwath::IFeature { public: MockFeature(); ~MockFeature() override; void getRT(std::vector<double>& rt) const override; void getIntensity(std::vector<double>& intens) const override; float getIntensity() const override; double getRT() const override; std::vector<double> m_rt_vec; std::vector<double> m_intensity_vec; float m_intensity; double m_rt; }; /** @brief Mock object implementing IMRMFeature */ class OPENSWATHALGO_DLLAPI MockMRMFeature : public OpenSwath::IMRMFeature { public: MockMRMFeature(); ~MockMRMFeature() override; std::shared_ptr<OpenSwath::IFeature> getFeature(std::string nativeID) override; std::shared_ptr<OpenSwath::IFeature> getPrecursorFeature(std::string nativeID) override; std::vector<std::string> getNativeIDs() const override; std::vector<std::string> getPrecursorIDs() const override; float getIntensity() const override; double getRT() const override; double getMetaValue(std::string name) const override; size_t size() const override; std::map<std::string, std::shared_ptr<MockFeature> > m_features; std::map<std::string, std::shared_ptr<MockFeature> > m_precursor_features; float m_intensity; double m_rt; double m_metavalue; }; /** @brief Mock object implementing ITransitionGroup */ class OPENSWATHALGO_DLLAPI MockTransitionGroup : public OpenSwath::ITransitionGroup { public: MockTransitionGroup(); ~MockTransitionGroup() override; std::size_t size() const override; std::vector<std::string> getNativeIDs() const override; void getLibraryIntensities(std::vector<double>& intensities) const override; std::size_t m_size; std::vector<std::string> m_native_ids; std::vector<double> m_library_intensities; }; /** @brief Mock object implementing ISignalToNoise */ class OPENSWATHALGO_DLLAPI MockSignalToNoise : public OpenSwath::ISignalToNoise { public: MockSignalToNoise(); double getValueAtRT(double /* RT */) override; double m_sn_value; }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/TransitionHelper.h
.h
1,062
40
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> #include <map> #include <vector> #include <string> namespace OpenSwath { struct LightCompound; struct LightTargetedExperiment; struct LightTransition; struct OPENSWATHALGO_DLLAPI TransitionHelper { static void convert(LightTargetedExperiment& lte, std::map<std::string, std::vector<LightTransition> >& transmap); // TODO : remove and explain German comments // spiegel static bool findPeptide(const LightTargetedExperiment& lte, const std::string& peptideRef, LightCompound& pep); }; } //end namespace
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h
.h
8,158
293
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Darren Kessner, Hannes Roest, Witold Wolski$ // -------------------------------------------------------------------------- #pragma once #include <string> #include <vector> #include <memory> #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> namespace OpenSwath { /** @brief The datastructures used by the OpenSwath interfaces Many of them are closely related to Proteowizard data structures, originally written by Darren Kessner and released under the Apache 2.0 licence. Original author: Darren Kessner <darren@proteowizard.org> Copyright 2007 Spielberg Family Center for Applied Proteomics Cedars-Sinai Medical Center, Los Angeles, California 90048 The following datastructures are used : - BinaryDataArray : a struct that holds a std::vector<double> with the data - ChromatogramMeta : meta information of a chromatogram (index) - Chromatogram : chromatogram data. Contains a vector of pointers to BinaryDataArray, the first one is time array (RT), the second one is intensity - SpectrumMeta : meta information of a spectrum (index, identifier, RT, ms_level) - Spectrum : spectrum data. Contains a vector of pointers to BinaryDataArray, the first one is mz array, the second one is intensity */ /// The structure into which encoded binary data goes. struct OPENSWATHALGO_DLLAPI OSBinaryDataArray { /// this optional attribute may reference the 'id' attribute of the appropriate dataProcessing. //DataProcessingPtr dataProcessingPtr; /// the binary data. std::vector<double> data; /// (optional) data description for non-standard arrays. std::string description; }; typedef OSBinaryDataArray BinaryDataArray; typedef std::shared_ptr<BinaryDataArray> BinaryDataArrayPtr; /// Identifying information for a chromatogram struct OPENSWATHALGO_DLLAPI OSChromatogramMeta { /// the zero-based, consecutive index of the chromatogram in the ChromatogramList. std::size_t index; /// a unique identifier for this chromatogram. std::string id; OSChromatogramMeta() : index() { } }; typedef OSChromatogramMeta ChromatogramMeta; typedef std::shared_ptr<ChromatogramMeta> ChromatogramMetaPtr; /// A single chromatogram. struct OPENSWATHALGO_DLLAPI OSChromatogram { private: /// default length of binary data arrays contained in this element. std::size_t defaultArrayLength; /// this attribute can optionally reference the 'id' of the appropriate dataProcessing. //DataProcessingPtr dataProcessingPtr; /// description of precursor ion information (i.e. Q1 settings) //Precursor precursor; /// description of product ion information (i.e. Q3 settings) //Product product; /// list of binary data arrays. std::vector<BinaryDataArrayPtr> binaryDataArrayPtrs; public: OSChromatogram() : defaultArrayLength(2), binaryDataArrayPtrs(defaultArrayLength) { initvec(); } private: void initvec() { for (std::size_t i = 0; i < defaultArrayLength; ++i) { BinaryDataArrayPtr empty(new BinaryDataArray); binaryDataArrayPtrs[i] = empty; } } public: /// get time array (may be null) BinaryDataArrayPtr getTimeArray() { return binaryDataArrayPtrs[0]; } /// set time array void setTimeArray(BinaryDataArrayPtr data) { binaryDataArrayPtrs[0] = data; } /// get intensity array (may be null) BinaryDataArrayPtr getIntensityArray() { return binaryDataArrayPtrs[1]; } /// set intensity array void setIntensityArray(BinaryDataArrayPtr data) { binaryDataArrayPtrs[1] = data; } /// non-mutable access to the underlying data arrays const std::vector<BinaryDataArrayPtr> & getDataArrays() const { return binaryDataArrayPtrs; } /// mutable access to the underlying data arrays std::vector<BinaryDataArrayPtr> & getDataArrays() { return binaryDataArrayPtrs; } /// set all binary data arrays /// @param[in] val Vector of binary data arrays to be set void setDataArrays(std::vector<BinaryDataArrayPtr>& val) { binaryDataArrayPtrs = val; } }; typedef OSChromatogram Chromatogram; typedef std::shared_ptr<Chromatogram> ChromatogramPtr; /// Identifying information for a spectrum struct OPENSWATHALGO_DLLAPI OSSpectrumMeta { /// the zero-based, consecutive index of the spectrum in the SpectrumList. size_t index; /// a unique identifier for this spectrum. std::string id; double RT; int ms_level; OSSpectrumMeta() : index(0) { } ///Comparator for the retention time. struct RTLess { inline bool operator()(const OSSpectrumMeta& a, const OSSpectrumMeta& b) const { return a.RT < b.RT; } }; }; typedef OSSpectrumMeta SpectrumMeta; typedef std::shared_ptr<SpectrumMeta> SpectrumMetaPtr; /// The structure that captures the generation of a peak list (including the underlying acquisitions) struct OPENSWATHALGO_DLLAPI OSSpectrum { private: /// default length of binary data arrays contained in this element. std::size_t defaultArrayLength; /// list of binary data arrays. std::vector<BinaryDataArrayPtr> binaryDataArrayPtrs; public: OSSpectrum() : defaultArrayLength(2), binaryDataArrayPtrs(defaultArrayLength) { initvec(); } private: void initvec() { for (std::size_t i = 0; i < defaultArrayLength; ++i) { BinaryDataArrayPtr empty(new BinaryDataArray); binaryDataArrayPtrs[i] = empty; } } public: /// get m/z array (may be null) BinaryDataArrayPtr getMZArray() const { return binaryDataArrayPtrs[0]; } /// set m/z array void setMZArray(BinaryDataArrayPtr data) { binaryDataArrayPtrs[0] = data; } /// get intensity array (may be null) BinaryDataArrayPtr getIntensityArray() const { return binaryDataArrayPtrs[1]; } /// set intensity array void setIntensityArray(BinaryDataArrayPtr data) { binaryDataArrayPtrs[1] = data; } void setDriftTimeArray(BinaryDataArrayPtr data) { data->description = "Ion Mobility"; binaryDataArrayPtrs.push_back(data); } /// get drift time array (may be null) BinaryDataArrayPtr getDriftTimeArray() const { // The array name starts with "Ion Mobility", but may carry additional // information such as the actual unit in which it was measured (seconds, // milliseconds, volt-second per square centimeter). We currently ignore // the unit but return the correct array. // For diaPASEF data converted with proteowizard ion mobility arrays are stored in "inverse reduced ion mobility" for (auto & bda : binaryDataArrayPtrs) { if (bda->description.find("Ion Mobility") == 0) { return bda; } else if (bda->description.find("mean inverse reduced ion mobility array") == 0) { return bda; } } return BinaryDataArrayPtr(); // return null } /// non-mutable access to the underlying data arrays const std::vector<BinaryDataArrayPtr> & getDataArrays() const { return binaryDataArrayPtrs; } /// mutable access to the underlying data arrays std::vector<BinaryDataArrayPtr> & getDataArrays() { return binaryDataArrayPtrs; } /// set all binary data arrays /// @param[in] val Vector of binary data arrays to be set void setDataArrays(std::vector<BinaryDataArrayPtr>& val) { binaryDataArrayPtrs = val; } }; typedef OSSpectrum Spectrum; typedef std::shared_ptr<Spectrum> SpectrumPtr; } //end Namespace OpenSwath
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h
.h
13,311
499
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <string> #include <vector> #include <map> #include <cstdint> #include <functional> #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> namespace OpenSwath { /// @brief Compact enum for fragment ion types (replaces string storage) /// Reduces memory from ~32 bytes (std::string) to 1 byte enum class FragmentIonType : uint8_t { Unknown = 0, AIon, ///< a-ion BIon, ///< b-ion CIon, ///< c-ion XIon, ///< x-ion YIon, ///< y-ion ZIon, ///< z-ion ZPrimeIon, ///< z'-ion (z prime) ZDotIon, ///< z.-ion (z dot) Precursor, ///< Precursor ion BMinusH2O, ///< b-ion with water loss YMinusH2O, ///< y-ion with water loss BMinusNH3, ///< b-ion with ammonia loss YMinusNH3, ///< y-ion with ammonia loss Empty = 255 ///< No fragment type set }; /// @brief Convert fragment ion type string to enum /// @param s Fragment type string (e.g. "y", "b", "prec") /// @return Corresponding FragmentIonType enum value inline FragmentIonType stringToFragmentIonType(const std::string& s) { if (s.empty()) return FragmentIonType::Empty; if (s == "a") return FragmentIonType::AIon; if (s == "b") return FragmentIonType::BIon; if (s == "c") return FragmentIonType::CIon; if (s == "x") return FragmentIonType::XIon; if (s == "y") return FragmentIonType::YIon; if (s == "z") return FragmentIonType::ZIon; if (s == "z'") return FragmentIonType::ZPrimeIon; if (s == "z.") return FragmentIonType::ZDotIon; if (s == "prec" || s == "precursor") return FragmentIonType::Precursor; if (s == "b-H2O" || s == "b-H20") return FragmentIonType::BMinusH2O; if (s == "y-H2O" || s == "y-H20") return FragmentIonType::YMinusH2O; if (s == "b-NH3") return FragmentIonType::BMinusNH3; if (s == "y-NH3") return FragmentIonType::YMinusNH3; return FragmentIonType::Unknown; } /// @brief Convert fragment ion type enum to string /// @param t FragmentIonType enum value /// @return Fragment type string (e.g. "y", "b", "prec") inline std::string fragmentIonTypeToString(FragmentIonType t) { switch (t) { case FragmentIonType::Empty: return ""; case FragmentIonType::AIon: return "a"; case FragmentIonType::BIon: return "b"; case FragmentIonType::CIon: return "c"; case FragmentIonType::XIon: return "x"; case FragmentIonType::YIon: return "y"; case FragmentIonType::ZIon: return "z"; case FragmentIonType::ZPrimeIon: return "z'"; case FragmentIonType::ZDotIon: return "z."; case FragmentIonType::Precursor: return "prec"; case FragmentIonType::BMinusH2O: return "b-H2O"; case FragmentIonType::YMinusH2O: return "y-H2O"; case FragmentIonType::BMinusNH3: return "b-NH3"; case FragmentIonType::YMinusNH3: return "y-NH3"; case FragmentIonType::Unknown: default: return "unknown"; } } /// @brief Packed boolean flags for transitions /// Reduces memory from 4 bytes (4 separate bools) to 1 byte struct TransitionFlags { uint8_t decoy : 1; uint8_t detecting : 1; uint8_t quantifying : 1; uint8_t identifying : 1; uint8_t reserved : 4; TransitionFlags() : decoy(0), detecting(1), quantifying(1), identifying(0), reserved(0) {} }; struct LightTransition { std::string transition_name; std::string peptide_ref; double library_intensity{}; double product_mz{}; double precursor_mz{}; double precursor_im{-1}; int8_t fragment_charge{}; ///< Fragment charge (compact: range typically 1-8) TransitionFlags flags{}; ///< Packed boolean flags // Additional fields for roundtrip TSV/PQP I/O int16_t fragment_nr{-1}; ///< Fragment ion ordinal (e.g. 7 for y7) FragmentIonType fragment_type{FragmentIonType::Empty}; ///< Fragment ion type enum std::vector<std::string> peptidoforms; ///< Peptidoforms for IPF // Legacy bool accessors for API compatibility bool getDecoy() const { return flags.decoy; } void setDecoy(bool d) { flags.decoy = d; } // Fragment type string accessors for backward compatibility std::string getFragmentType() const { return fragmentIonTypeToString(fragment_type); } void setFragmentType(const std::string& s) { fragment_type = stringToFragmentIonType(s); } /// Reconstruct annotation from fragment_type, fragment_nr, and fragment_charge /// Returns string like "b8", "y6^2", "prec", or empty if no fragment info set std::string getAnnotation() const { if (fragment_type == FragmentIonType::Empty) { return ""; } if (fragment_type == FragmentIonType::Precursor) { return "prec"; } std::string result = fragmentIonTypeToString(fragment_type); if (fragment_nr >= 0) { result += std::to_string(fragment_nr); } if (fragment_charge > 0) { result += "^" + std::to_string(static_cast<int>(fragment_charge)); } return result; } int getProductChargeState() const { return fragment_charge; } bool isProductChargeStateSet() const { return !(fragment_charge == 0); } bool isPrecursorImSet() const { return !(precursor_im == -1); } std::string getNativeID() const { return transition_name; } std::string getPeptideRef() const { return peptide_ref; } std::string getCompoundRef() const { return peptide_ref; } double getLibraryIntensity() const { return library_intensity; } void setLibraryIntensity(double l) { library_intensity = l; } double getProductMZ() const { return product_mz; } double getPrecursorMZ() const { return precursor_mz; } double getPrecursorIM() const { return precursor_im; } void setDetectingTransition (bool d) { flags.detecting = d; } bool isDetectingTransition() const { return flags.detecting; } void setQuantifyingTransition (bool q) { flags.quantifying = q; } bool isQuantifyingTransition() const { return flags.quantifying; } void setIdentifyingTransition (bool i) { flags.identifying = i; } bool isIdentifyingTransition() const { return flags.identifying; } /// Equality operator - compares transition_name (consistent with hash) bool operator==(const LightTransition& rhs) const { return transition_name == rhs.transition_name; } bool operator!=(const LightTransition& rhs) const { return !(*this == rhs); } }; struct LightModification { int location; int unimod_id; /// Equality operator - compares location and unimod_id (consistent with hash) bool operator==(const LightModification& rhs) const { return location == rhs.location && unimod_id == rhs.unimod_id; } bool operator!=(const LightModification& rhs) const { return !(*this == rhs); } }; // A compound is either a peptide or a metabolite struct LightCompound { LightCompound() : drift_time(-1), charge(0) { } double drift_time; double rt; int charge; std::string sequence; std::vector<std::string> protein_refs; // Peptide group label (corresponds to MS:1000893, all peptides that are isotopic forms of the same peptide should be assigned the same peptide group label) std::string peptide_group_label; std::string gene_name; std::string id; // for metabolites std::string sum_formula; std::string compound_name; // Additional fields for roundtrip TSV/PQP I/O std::string label_type; ///< Label type (e.g. "heavy" or "light") std::string smiles; ///< SMILES representation (metabolomics) std::string adducts; ///< Adducts (metabolomics) // By convention, if there is no (metabolic) compound name, it is a peptide bool isPeptide() const { return compound_name.empty(); } void setChargeState(int ch) { charge = ch; } int getChargeState() const { return charge; } void setDriftTime(double d) { drift_time = d; } double getDriftTime() const { return drift_time; } std::vector<LightModification> modifications; /// Equality operator - compares id (consistent with hash) bool operator==(const LightCompound& rhs) const { return id == rhs.id; } bool operator!=(const LightCompound& rhs) const { return !(*this == rhs); } }; struct LightProtein { std::string id; std::string sequence; // Additional fields for roundtrip TSV/PQP I/O std::string uniprot_id; ///< UniProt identifier /// Equality operator - compares id (consistent with hash) bool operator==(const LightProtein& rhs) const { return id == rhs.id; } bool operator!=(const LightProtein& rhs) const { return !(*this == rhs); } }; struct LightTargetedExperiment { LightTargetedExperiment() : compound_reference_map_dirty_(true) {} typedef LightTransition Transition; typedef LightCompound Peptide; typedef LightCompound Compound; typedef LightProtein Protein; std::vector<LightTransition> transitions; std::vector<LightCompound> compounds; std::vector<LightProtein> proteins; std::vector<LightTransition> & getTransitions() { return transitions; } const std::vector<LightTransition> & getTransitions() const { return transitions; } std::vector<LightCompound> & getCompounds() { return compounds; } const std::vector<LightCompound> & getCompounds() const { return compounds; } std::vector<LightProtein> & getProteins() { return proteins; } const std::vector<LightProtein> & getProteins() const { return proteins; } // legacy const LightCompound& getPeptideByRef(const std::string& ref) { return getCompoundByRef(ref); } const LightCompound& getCompoundByRef(const std::string& ref) { if (compound_reference_map_dirty_) { createPeptideReferenceMap_(); } return *(compound_reference_map_[ref]); } private: void createPeptideReferenceMap_() { for (size_t i = 0; i < getCompounds().size(); i++) { compound_reference_map_[getCompounds()[i].id] = &getCompounds()[i]; } compound_reference_map_dirty_ = false; } // Map of compounds (peptides or metabolites) bool compound_reference_map_dirty_; std::map<std::string, LightCompound*> compound_reference_map_; }; } //end Namespace OpenSwath // Hash function specializations for OpenSwath types namespace std { /** * @brief Hash function for LightTransition. * * Hashes based on the transition_name which serves as the unique identifier. * This enables use in std::unordered_map and std::unordered_set. */ template<> struct hash<OpenSwath::LightTransition> { std::size_t operator()(const OpenSwath::LightTransition& t) const noexcept { return std::hash<std::string>{}(t.transition_name); } }; /** * @brief Hash function for LightCompound. * * Hashes based on the id which serves as the unique identifier. * This enables use in std::unordered_map and std::unordered_set. */ template<> struct hash<OpenSwath::LightCompound> { std::size_t operator()(const OpenSwath::LightCompound& c) const noexcept { return std::hash<std::string>{}(c.id); } }; /** * @brief Hash function for LightProtein. * * Hashes based on the id which serves as the unique identifier. * This enables use in std::unordered_map and std::unordered_set. */ template<> struct hash<OpenSwath::LightProtein> { std::size_t operator()(const OpenSwath::LightProtein& p) const noexcept { return std::hash<std::string>{}(p.id); } }; /** * @brief Hash function for LightModification. * * Hashes based on location and unimod_id using a proper combining function * to reduce collision probability. * This enables use in std::unordered_map and std::unordered_set. */ template<> struct hash<OpenSwath::LightModification> { std::size_t operator()(const OpenSwath::LightModification& m) const noexcept { std::size_t seed = std::hash<int>{}(m.location); // Use standard hash combine formula (from boost) for better distribution seed ^= std::hash<int>{}(m.unimod_id) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h
.h
5,387
134
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest, Witold Wolski $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h> #include <memory> #include <string> #include <vector> namespace OpenMS { using SpectrumSequence = std::vector<OpenSwath::SpectrumPtr>; ///< a vector of spectrum pointers that DIA scores can operate on, allows for clever integration of only the target regions } namespace OpenSwath { using SpectrumSequence = OpenMS::SpectrumSequence; /** @brief The interface of a mass spectrometry experiment. */ class OPENSWATHALGO_DLLAPI ISpectrumAccess { public: /// Destructor virtual ~ISpectrumAccess(); /** @brief Light clone operator to produce a copy for concurrent read access. This function guarantees to produce a copy of the underlying object that provides thread-safe concurrent read access to the underlying data. It should be implemented with minimal copy-overhead to make this operation as fast as possible. To use this function, each thread should call this function to produce an individual copy on which it can operate. */ virtual std::shared_ptr<ISpectrumAccess> lightClone() const = 0; /// Return a pointer to a spectrum at the given id virtual SpectrumPtr getSpectrumById(int id) = 0; /// Return pointer to a spectrum at the given id, the spectrum will be filtered by drift time SpectrumPtr getSpectrumById(int id, double drift_start, double drift_end ); /// Return a vector of ids of spectra that are within RT +/- deltaRT virtual std::vector<std::size_t> getSpectraByRT(double RT, double deltaRT) const = 0; /// Returns the number of spectra available virtual size_t getNrSpectra() const = 0; /// Returns the meta information for a spectrum virtual SpectrumMeta getSpectrumMetaById(int id) const = 0; /// Return a pointer to a chromatogram at the given id virtual ChromatogramPtr getChromatogramById(int id) = 0; /// Returns the number of chromatograms available virtual std::size_t getNrChromatograms() const = 0; /// Returns the native id of the chromatogram at the given id virtual std::string getChromatogramNativeID(int id) const = 0; /* @brief Fetches a spectrumSequence (multiple spectra pointers) closest to the given RT * @p RT = target RT * @p nr_spectra_to_fetch = # spectra around target RT to fetch (length of the spectrum sequence) */ SpectrumSequence getMultipleSpectra(double RT, int nr_spectra_to_fetch); /* @brief Fetches a spectrumSequence (multiple spectra pointers) closest to the given RT. Filters all spectra by specified @p drift_start and @p drift_end * @p RT = target RT * @p nr_spectra_to_fetch = # spectra around target RT to fetch (length of the spectrum sequence) */ SpectrumSequence getMultipleSpectra(double RT, int nr_spectra_to_fetch, double drift_start, double drift_end); /// filters a spectrum by drift time, spectrum pointer returned is a copy static SpectrumPtr filterByDrift(const SpectrumPtr& input, double drift_start, double drift_end) { // NOTE: this function is very inefficient because filtering unsorted array //OPENMS_PRECONDITION(drift_start <= 0, "Cannot filter by drift time if drift_start is not set"); //OPENMS_PRECONDITION(drift_end - drift_start < 0, "Cannot filter by drift time if range is empty"); //OPENMS_PRECONDITION(input->getDriftTimeArray() != nullptr, "Cannot filter by drift time if no drift time is available."); //if (input->getDriftTimeArray() == nullptr) //{ //throw Exception::NullPointer(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); //} OpenSwath::SpectrumPtr output(new OpenSwath::Spectrum); OpenSwath::BinaryDataArrayPtr mz_arr = input->getMZArray(); OpenSwath::BinaryDataArrayPtr int_arr = input->getIntensityArray(); OpenSwath::BinaryDataArrayPtr im_arr = input->getDriftTimeArray(); auto mz_it = mz_arr->data.cbegin(); auto int_it = int_arr->data.cbegin(); auto im_it = im_arr->data.cbegin(); auto mz_end = mz_arr->data.cend(); OpenSwath::BinaryDataArrayPtr mz_arr_out(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr intens_arr_out(new OpenSwath::BinaryDataArray); OpenSwath::BinaryDataArrayPtr im_arr_out(new OpenSwath::BinaryDataArray); im_arr_out->description = im_arr->description; while (mz_it != mz_end) { if ( (drift_start <= *im_it) && (drift_end >= *im_it) ) { mz_arr_out->data.push_back( *mz_it ); intens_arr_out->data.push_back( *int_it ); im_arr_out->data.push_back( *im_it ); } ++mz_it; ++int_it; ++im_it; } output->setMZArray(mz_arr_out); output->setIntensityArray(intens_arr_out); output->getDataArrays().push_back(im_arr_out); return output; } }; typedef std::shared_ptr<ISpectrumAccess> SpectrumAccessPtr; }
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/DataFrameWriter.h
.h
1,607
66
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #pragma once #include <fstream> #include <string> #include <vector> #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> namespace OpenSwath { struct OPENSWATHALGO_DLLAPI IDataFrameWriter { virtual ~IDataFrameWriter(); virtual void colnames(const std::vector<std::string>& colnames) = 0; virtual void store(const std::string& rowname, const std::vector<double>& values) = 0; }; struct OPENSWATHALGO_DLLAPI DataMatrix : IDataFrameWriter { private: std::vector<std::string> colnames_; std::vector<std::string> rownames_; std::vector<std::vector<double> > store_; public: DataMatrix(); void store(const std::string& rowname, const std::vector<double>& values) override; void colnames(const std::vector<std::string>& colnames) override; }; struct OPENSWATHALGO_DLLAPI CSVWriter : IDataFrameWriter { private: std::ofstream file_stream_; std::string sep_; std::string eol_; public: explicit CSVWriter(std::string filename); void store(const std::string& rowname, const std::vector<double>& values) override; ~CSVWriter() override; void colnames(const std::vector<std::string>& colnames) override; }; }
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/SpectrumHelpers.h
.h
519
21
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest, Witold Wolski $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h> #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> namespace OpenSwath { }
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/Transitions.h
.h
1,053
48
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> #include <string> #include <vector> #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h> namespace OpenSwath { struct OPENSWATHALGO_DLLAPI Peptide { double rt; int charge; std::string sequence; std::string id; int getChargeState() const { return charge; } std::vector<LightModification> modifications; std::vector<LightTransition> transitions; }; struct OPENSWATHALGO_DLLAPI Protein { std::string id; std::string sequence; std::vector<Peptide> peptides; }; struct OPENSWATHALGO_DLLAPI TargetedExperiment { std::vector<Protein> proteins; }; }
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h
.h
1,876
73
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h> #include <cmath> namespace OpenSwath { /** * @brief Data structure to hold one SWATH map with information about upper / * lower isolation window and whether the map is MS1 or MS2. */ struct SwathMap { OpenSwath::SpectrumAccessPtr sptr; double lower; double upper; double center; double imLower; double imUpper; bool ms1; SwathMap() : lower(0.0), upper(0.0), center(0.0), imLower(-1), imUpper(-1), ms1(false) {} SwathMap(double mz_start, double mz_end, double mz_center, bool is_ms1) : lower(mz_start), upper(mz_end), center(mz_center), imLower(-1), imUpper(-1), ms1(is_ms1) {} SwathMap(double mz_start, double mz_end, double mz_center, double imLower, double imUpper, bool is_ms1) : lower(mz_start), upper(mz_end), center(mz_center), imLower(imLower), imUpper(imUpper), ms1(is_ms1) {} bool isEqual(const SwathMap& other, double tolerance = 1e-6) const { return (std::fabs(lower - other.lower) < tolerance) && (std::fabs(upper - other.upper) < tolerance) && (std::fabs(center - other.center) < tolerance) && (std::fabs(imLower - other.imLower) < tolerance) && (std::fabs(imUpper - other.imUpper) < tolerance) && (ms1 == other.ms1); } }; } //end Namespace OpenSwath
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/Scoring.h
.h
5,448
137
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest$ // $Authors: Hannes Roest$ // -------------------------------------------------------------------------- #pragma once #include <numeric> #include <map> #include <vector> #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> namespace OpenSwath { /** @brief Scoring functions used by MRMScoring Many helper functions to calculate cross-correlations between data */ namespace Scoring { /** @name Type defs and helper structures*/ //@{ typedef std::pair<unsigned int, unsigned int> pos2D; /// Simple hash function for Scoring::pos2D struct pair_hash { template <class T1, class T2> std::size_t operator () (const std::pair<T1,T2> &p) const { auto h1 = std::hash<T1>{}(p.first); auto h2 = std::hash<T2>{}(p.second); return h1 ^ h2; } }; /// Cross Correlation array contains (lag,correlation) pairs typedef std::pair<int, double> XCorrEntry; struct XCorrArrayType { public: std::vector<XCorrEntry> data; // Access functions typedef std::vector<XCorrEntry>::iterator iterator; typedef std::vector<XCorrEntry>::const_iterator const_iterator; iterator begin() {return data.begin();} const_iterator begin() const {return data.begin();} iterator end() {return data.end();} const_iterator end() const {return data.end();} }; //@} /** @name Helper functions */ //@{ /** @brief Calculate the normalized Manhattan distance between two arrays * * Equivalent to the function "delta_ratio_sum" from mQuest to calculate * similarity between library intensity and experimental ones. * * The delta_ratio_sum is calculated as follows: @f[ d = \sqrt{\frac{1}{N} \sum_{i=0}^N |\frac{x_i}{\mu_x} - \frac{y_i}{\mu_y}|) } @f] */ OPENSWATHALGO_DLLAPI double NormalizedManhattanDist(double x[], double y[], int n); /** @brief Calculate the RMSD (root means square deviation) * * The RMSD is calculated as follows: @f[ RMSD = \sqrt{\frac{1}{N} \sum_{i=0}^N (x_i - y_i)^2 } @f] */ OPENSWATHALGO_DLLAPI double RootMeanSquareDeviation(double x[], double y[], int n); /** @brief Calculate the Spectral angle (acosine of the normalized dotproduct) * * The spectral angle is calculated as follows: @f[ \theta = acos \left( \frac{\sum_{i=0}^N (x_i * y_i))}{\sqrt{\sum_{i=0}^N (x_i * x_i) \sum_{i=0}^N (y_i * y_i)} } \right) @f] */ OPENSWATHALGO_DLLAPI double SpectralAngle(double x[], double y[], int n); /// Calculate crosscorrelation on std::vector data - Deprecated! /// Legacy code, this is a 1:1 port of the function from mQuest OPENSWATHALGO_DLLAPI XCorrArrayType calcxcorr_legacy_mquest_(std::vector<double>& data1, std::vector<double>& data2, bool normalize); /// Calculate crosscorrelation on std::vector data (which is first normalized) /// NOTE: this replaces calcxcorr OPENSWATHALGO_DLLAPI XCorrArrayType normalizedCrossCorrelation(std::vector<double>& data1, std::vector<double>& data2, const int maxdelay, const int lag); /// Calculate crosscorrelation on std::vector data that is already normalized OPENSWATHALGO_DLLAPI XCorrArrayType normalizedCrossCorrelationPost(std::vector<double>& normalized_data1, std::vector<double>& normalized_data2, const int maxdelay, const int lag); /// Calculate crosscorrelation on std::vector data without normalization OPENSWATHALGO_DLLAPI XCorrArrayType calculateCrossCorrelation(const std::vector<double>& data1, const std::vector<double>& data2, const int maxdelay, const int lag); /// Find best peak in an cross-correlation (highest apex) OPENSWATHALGO_DLLAPI XCorrArrayType::const_iterator xcorrArrayGetMaxPeak(const XCorrArrayType & array); /// Standardize a vector (subtract mean, divide by standard deviation) OPENSWATHALGO_DLLAPI void standardize_data(std::vector<double>& data); /// Divide each element of x by the sum of the vector OPENSWATHALGO_DLLAPI void normalize_sum(double x[], unsigned int n); // Compute rank of vector elements, append it to @p ranks and return the highest rank OPENSWATHALGO_DLLAPI unsigned int computeAndAppendRank(const std::vector<double>& v, std::vector<unsigned int>& ranks); // Compute rank of vector elements and its highest rank for each row in a 2D array OPENSWATHALGO_DLLAPI std::vector<unsigned int> computeRankVector(const std::vector<std::vector<double>>& intensity, std::vector<std::vector<unsigned int>>& ranks); // Estimate mutual information between two vectors of ranks OPENSWATHALGO_DLLAPI double rankedMutualInformation(std::vector<unsigned int>& ranked_data1, std::vector<unsigned int>& ranked_data2, const unsigned int max_rank1, const unsigned int max_rank2); //@} } }
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/include/OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h
.h
4,938
206
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h> #include <algorithm> #include <cmath> #include <complex> #include <numeric> #include <vector> #include <cstddef> namespace OpenSwath { /** @brief Normalize intensities in vector by normalization_factor */ OPENSWATHALGO_DLLAPI void normalize(const std::vector<double>& intensities, double normalization_factor, std::vector<double>& normalized_intensities); /** @brief compute the Euclidean norm of the vector */ template <typename T> double norm(T beg, T end) { double res = 0.0; for (; beg != end; ++beg) { double tmp = *beg; res += tmp * tmp; } return sqrt(res); } /** @brief compute dotprod of vectors */ template <typename Texp, typename Ttheo> double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo); /// @cond // Explicit template instantiation declarations (tell the compiler these exist) extern template double dotProd<std::vector<double>::const_iterator, std::vector<double>::const_iterator>( std::vector<double>::const_iterator, std::vector<double>::const_iterator, std::vector<double>::const_iterator); extern template double dotProd<std::vector<float>::const_iterator, std::vector<float>::const_iterator>( std::vector<float>::const_iterator, std::vector<float>::const_iterator, std::vector<float>::const_iterator); extern template double dotProd<std::vector<int>::const_iterator, std::vector<int>::const_iterator>( std::vector<int>::const_iterator, std::vector<int>::const_iterator, std::vector<int>::const_iterator); /// @endcond /** @brief the dot product scoring sqrt data, normalize by vector norm compute dotprod */ OPENSWATHALGO_DLLAPI double dotprodScoring(std::vector<double> intExp, std::vector<double> theorint); /** @brief compute manhattan distance between Exp and Theo */ template <typename Texp, typename Ttheo> double manhattanDist(Texp itExpBeg, Texp itExpEnd, Ttheo itTheo) { double sum = 0.0; for (; itExpBeg < itExpEnd; ++itExpBeg, ++itTheo) { sum += fabs(*itExpBeg - *itTheo); } return sum; } /** @brief manhattan scoring sqrt intensities normalize vector by TIC compute manhattan score */ OPENSWATHALGO_DLLAPI double manhattanScoring(std::vector<double> intExp, std::vector<double> theorint); /** @brief compute pearson correlation of vector x and y */ template <typename TInputIterator, typename TInputIteratorY> typename std::iterator_traits<TInputIterator>::value_type cor_pearson( TInputIterator xBeg, TInputIterator xEnd, TInputIteratorY yBeg ) { typedef typename std::iterator_traits<TInputIterator>::value_type value_type; value_type m1, m2; value_type s1, s2; value_type corr; m1 = m2 = s1 = s2 = 0.0; corr = 0.0; ptrdiff_t n = std::distance(xBeg, xEnd); value_type nd = static_cast<value_type>(n); for (; xBeg != xEnd; ++xBeg, ++yBeg) { corr += *xBeg * *yBeg; m1 += *xBeg; m2 += *yBeg; s1 += *xBeg * *xBeg; s2 += *yBeg * *yBeg; } m1 /= nd; m2 /= nd; s1 -= m1 * m1 * nd; s2 -= m2 * m2 * nd; if (s1 < 1.0e-12 || s2 < 1.0e-12) return 0.0; else { corr -= m1 * m2 * (double)n; corr /= sqrt(s1 * s2); return corr; } } /** @brief functor to compute the mean and stddev of sequence using the std::foreach algorithm */ class OPENSWATHALGO_DLLAPI mean_and_stddev { double m_, q_; unsigned long c_; public: typedef double argument_type, result_type; mean_and_stddev() : m_(0.0), q_(0.0), c_(0u) { } void operator()(double sample) { double const delta = sample - m_; m_ += delta / ++c_; q_ += delta * (sample - m_); } double sample_variance() const { return (c_ > 1u) ? (q_ / (c_ - 1)) : 0; } double standard_variance() const { return (c_ > 1u) ? (q_ / c_) : 0; } double sample_stddev() const { return std::sqrt(sample_variance()); } double standard_stddev() const { return std::sqrt(standard_variance()); } double mean() const { return m_; } unsigned long count() const { return c_; } double variance() const { return sample_variance(); } double stddev() const { return sample_stddev(); } double operator()() const { return stddev(); } }; } //end namespace OpenSwath
Unknown
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/SwathMap.cpp
.cpp
444
15
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> namespace OpenMS { } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.cpp
.cpp
3,032
103
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest, Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h> #include <boost/numeric/conversion/cast.hpp> #include <cmath> #include <string> #include <vector> namespace OpenSwath { ISpectrumAccess::~ISpectrumAccess() { } SpectrumSequence ISpectrumAccess::getMultipleSpectra(double RT, int nr_spectra_to_fetch) { std::vector<std::size_t> indices = getSpectraByRT(RT, 0.0); SpectrumSequence all_spectra; if (indices.empty() ) { return all_spectra; } int closest_idx = boost::numeric_cast<int>(indices[0]); if (indices[0] != 0 && std::fabs(getSpectrumMetaById(boost::numeric_cast<int>(indices[0]) - 1).RT - RT) < std::fabs(getSpectrumMetaById(boost::numeric_cast<int>(indices[0])).RT - RT)) { closest_idx--; } all_spectra.push_back(getSpectrumById(closest_idx)); int nrSpectra = (int) getNrSpectra(); for (int i = 1; i <= nr_spectra_to_fetch / 2; i++) // cast to int is intended! { if (closest_idx - i >= 0) { all_spectra.push_back(getSpectrumById(closest_idx - i)); } if (closest_idx + i < nrSpectra) { all_spectra.push_back(getSpectrumById(closest_idx + i)); } } return all_spectra; } SpectrumSequence ISpectrumAccess::getMultipleSpectra(double RT, int nr_spectra_to_fetch, double drift_start, double drift_end) { std::vector<std::size_t> indices = getSpectraByRT(RT, 0.0); SpectrumSequence all_spectra; if (indices.empty() ) { return all_spectra; } int closest_idx = boost::numeric_cast<int>(indices[0]); if (indices[0] != 0 && std::fabs(getSpectrumMetaById(boost::numeric_cast<int>(indices[0]) - 1).RT - RT) < std::fabs(getSpectrumMetaById(boost::numeric_cast<int>(indices[0])).RT - RT)) { closest_idx--; } all_spectra.push_back(getSpectrumById(closest_idx, drift_start, drift_end)); int nrSpectra = (int) getNrSpectra(); for (int i = 1; i <= nr_spectra_to_fetch / 2; i++) // cast to int is intended! { if (closest_idx - i >= 0) { all_spectra.push_back(getSpectrumById(closest_idx - i, drift_start, drift_end)); } if (closest_idx + i < nrSpectra) { all_spectra.push_back(getSpectrumById(closest_idx + i, drift_start, drift_end)); } } return all_spectra; } SpectrumPtr ISpectrumAccess::getSpectrumById(int id, double drift_start, double drift_end) { // first fetch the spectrum OpenSwath::SpectrumPtr spectrum = getSpectrumById(id); // then filter by drift return ISpectrumAccess::filterByDrift(spectrum, drift_start, drift_end); } }
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/Transitions.cpp
.cpp
430
15
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/Transitions.h> namespace OpenSwath { }
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/TransitionHelper.cpp
.cpp
2,126
64
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionHelper.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h> namespace OpenSwath { void TransitionHelper::convert(LightTargetedExperiment& lte, std::map<std::string, std::vector<OpenSwath::LightTransition> >& transmap) { typedef std::pair<std::string, std::vector<OpenSwath::LightTransition> > Mpair; typedef std::map<std::string, std::vector<OpenSwath::LightTransition> > Mmap; std::vector<LightTransition> ltrans = lte.getTransitions(); /*iterate over transitions*/ std::vector<LightTransition>::iterator ltrit = ltrans.begin(); std::vector<LightTransition>::iterator ltrend = ltrans.end(); for (; ltrit != ltrend; ++ltrit) { std::string pepref = ltrit->getPeptideRef(); Mmap::iterator it = transmap.find(pepref); if (it == transmap.end()) { std::vector<LightTransition> ltv; ltv.push_back(*ltrit); transmap.insert(Mpair(pepref, ltv)); } else { it->second.push_back(*ltrit); } } } //end convert bool TransitionHelper::findPeptide(const LightTargetedExperiment& lte, const std::string& peptideRef, LightCompound& pep) { std::vector<LightCompound>::const_iterator beg = lte.compounds.begin(); std::vector<LightCompound>::const_iterator end = lte.compounds.end(); for (; beg != end; ++beg) { //std::cout << beg->id << " " << peptideRef << std::endl; if (beg->id.compare(peptideRef) == 0) { pep = *beg; return true; } } return false; } } // namespace OpenSwath
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/DataFrameWriter.cpp
.cpp
1,958
83
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/DataFrameWriter.h> #include <iostream> #include <iomanip> namespace OpenSwath { IDataFrameWriter::~IDataFrameWriter() { } DataMatrix::DataMatrix() : colnames_(), rownames_(), store_() { } void DataMatrix::store(const std::string& rowname, const std::vector<double>& values) { rownames_.push_back(rowname); store_.push_back(values); } void DataMatrix::colnames(const std::vector<std::string>& colnames) { colnames_ = colnames; } CSVWriter::CSVWriter(std::string filename) : sep_("\t"), eol_("\n") { file_stream_.open(filename.c_str()); } void CSVWriter::store(const std::string& rowname, const std::vector<double>& values) { file_stream_ << rowname; file_stream_ << sep_; std::size_t ncol = values.size(); for (size_t i = 0; i < ncol; ++i) { file_stream_ << std::setprecision(5) << values[i]; if (i < (ncol - 1)) { file_stream_ << sep_; } } file_stream_ << eol_; //append line-end } CSVWriter::~CSVWriter() { file_stream_.flush(); file_stream_.close(); std::cout << "have flushed and closed the file stream" << std::endl; } void CSVWriter::colnames(const std::vector<std::string>& colnames) { std::size_t ncol = colnames.size(); for (size_t i = 0; i < ncol; ++i) { file_stream_ << colnames[i]; if (i < (ncol - 1)) { file_stream_ << sep_; } } file_stream_ << eol_; //append line-end } } // namespace OpenSwath
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/SpectrumHelpers.cpp
.cpp
567
20
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest, Witold Wolski $ // $Authors: Hannes Roest, Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/SpectrumHelpers.h> #include <OpenMS/OPENSWATHALGO/Macros.h> #include <algorithm> #include <numeric> #include <stdexcept> namespace OpenSwath { }
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/DATAACCESS/MockObjects.cpp
.cpp
2,819
136
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/MockObjects.h> namespace OpenSwath { MockFeature::MockFeature() { } MockFeature::~MockFeature() { } void MockFeature::getRT(std::vector<double>& rt) const { rt = m_rt_vec; } void MockFeature::getIntensity(std::vector<double>& intens) const { intens = m_intensity_vec; } float MockFeature::getIntensity() const { return m_intensity; } double MockFeature::getRT() const { return m_rt; } MockMRMFeature::MockMRMFeature() { } MockMRMFeature::~MockMRMFeature() { } std::shared_ptr<OpenSwath::IFeature> MockMRMFeature::getFeature(std::string nativeID) { return std::static_pointer_cast<OpenSwath::IFeature>(m_features[nativeID]); } std::shared_ptr<OpenSwath::IFeature> MockMRMFeature::getPrecursorFeature(std::string nativeID) { return std::static_pointer_cast<OpenSwath::IFeature>(m_precursor_features[nativeID]); } std::vector<std::string> MockMRMFeature::getNativeIDs() const { std::vector<std::string> v; for (std::map<std::string, std::shared_ptr<MockFeature> >::const_iterator it = m_features.begin(); it != m_features.end(); ++it) { v.push_back(it->first); } return v; } std::vector<std::string> MockMRMFeature::getPrecursorIDs() const { std::vector<std::string> v; for (std::map<std::string, std::shared_ptr<MockFeature> >::const_iterator it = m_precursor_features.begin(); it != m_precursor_features.end(); ++it) { v.push_back(it->first); } return v; } float MockMRMFeature::getIntensity() const { return m_intensity; } double MockMRMFeature::getRT() const { return m_rt; } double MockMRMFeature::getMetaValue(std::string /* name */) const { return m_metavalue; } size_t MockMRMFeature::size() const { return m_features.size(); } MockTransitionGroup::MockTransitionGroup() { } MockTransitionGroup::~MockTransitionGroup() { } std::size_t MockTransitionGroup::size() const { return m_size; } std::vector<std::string> MockTransitionGroup::getNativeIDs() const { return m_native_ids; } void MockTransitionGroup::getLibraryIntensities(std::vector<double>& intensities) const { intensities = m_library_intensities; } MockSignalToNoise::MockSignalToNoise() { } double MockSignalToNoise::getValueAtRT(double /* RT */) { return m_sn_value; } }
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/ALGO/Scoring.cpp
.cpp
10,443
313
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/ALGO/Scoring.h> #include <OpenMS/OPENSWATHALGO/Macros.h> #include <cmath> #include <algorithm> #include <unordered_map> namespace OpenSwath::Scoring { void normalize_sum(double x[], unsigned int n) { double sumx = std::accumulate(&x[0], &x[0] + n, 0.0); if (sumx == 0.0) { // avoid divide by zero below return; } auto inverse_sum = 1 / sumx; // precompute inverse since division is expensive! for (unsigned int i = 0; i < n; ++i) { x[i] *= inverse_sum; } } double NormalizedManhattanDist(double x[], double y[], int n) { OPENSWATH_PRECONDITION(n > 0, "Need at least one element"); double delta_ratio_sum = 0; normalize_sum(x, n); normalize_sum(y, n); for (int i = 0; i < n; i++) { delta_ratio_sum += std::fabs(x[i] - y[i]); } return delta_ratio_sum / n; } double RootMeanSquareDeviation(double x[], double y[], int n) { OPENSWATH_PRECONDITION(n > 0, "Need at least one element"); double result = 0; for (int i = 0; i < n; i++) { result += (x[i] - y[i]) * (x[i] - y[i]); } return std::sqrt(result / n); } double SpectralAngle(double x[], double y[], int n) { OPENSWATH_PRECONDITION(n > 0, "Need at least one element"); double dotprod = 0; double x_len = 0; double y_len = 0; for (int i = 0; i < n; i++) { dotprod += x[i] * y[i]; x_len += x[i] * x[i]; y_len += y[i] * y[i]; } x_len = std::sqrt(x_len); y_len = std::sqrt(y_len); // normalise, avoiding a divide by zero. See unit tests for what happens // when one of the vectors has a length of zero. double denominator = x_len * y_len; double theta = (denominator == 0) ? 0.0 : dotprod / denominator; // clip to range [-1, 1] to save acos blowing up theta = std::max(-1.0, std::min(1.0, theta)); return std::acos(theta); } XCorrArrayType::const_iterator xcorrArrayGetMaxPeak(const XCorrArrayType& array) { OPENSWATH_PRECONDITION(array.data.size() > 0, "Cannot get highest apex from empty array."); XCorrArrayType::const_iterator max_it = array.begin(); double max = array.begin()->second; for (XCorrArrayType::const_iterator it = array.begin(); it != array.end(); ++it) { if (it->second > max) { max = it->second; max_it = it; } } return max_it; } void standardize_data(std::vector<double>& data) { if (data.empty()) { return; } // subtract the mean and divide by the standard deviation double mean = std::accumulate(data.begin(), data.end(), 0.0) / (double) data.size(); double sqsum = 0; for (std::vector<double>::iterator it = data.begin(); it != data.end(); ++it) { sqsum += (*it - mean) * (*it - mean); } double stdev = sqrt(sqsum / data.size()); // standard deviation if (mean == 0 && stdev == 0) { return; // all data is zero } if (stdev == 0) { stdev = 1; // all data is equal } for (std::size_t i = 0; i < data.size(); i++) { data[i] = (data[i] - mean) / stdev; } } XCorrArrayType normalizedCrossCorrelation(std::vector<double>& data1, std::vector<double>& data2, const int maxdelay, const int lag = 1) { OPENSWATH_PRECONDITION(data1.size() != 0 && data1.size() == data2.size(), "Both data vectors need to have the same length"); // normalize the data standardize_data(data1); standardize_data(data2); return normalizedCrossCorrelationPost(data1, data2, maxdelay, lag); } XCorrArrayType normalizedCrossCorrelationPost(std::vector<double>& normalized_data1, std::vector<double>& normalized_data2, const int maxdelay, const int lag = 1) { XCorrArrayType result = calculateCrossCorrelation(normalized_data1, normalized_data2, maxdelay, lag); for (XCorrArrayType::iterator it = result.begin(); it != result.end(); ++it) { it->second /= normalized_data1.size(); } return result; } XCorrArrayType calculateCrossCorrelation(const std::vector<double>& data1, const std::vector<double>& data2, const int maxdelay, const int lag) { OPENSWATH_PRECONDITION(data1.size() == data2.size(), "Both data vectors need to have the same length"); XCorrArrayType result; result.data.reserve( (size_t)std::ceil((2*maxdelay + 1) / lag)); int datasize = static_cast<int>(data1.size()); int i, j, delay; for (delay = -maxdelay; delay <= maxdelay; delay = delay + lag) { double sxy = 0; for (i = 0; i < datasize; ++i) { j = i + delay; if (j < 0 || j >= datasize) { continue; } sxy += (data1[i]) * (data2[j]); } result.data.push_back(std::make_pair(delay, sxy)); } return result; } XCorrArrayType calcxcorr_legacy_mquest_(std::vector<double>& data1, std::vector<double>& data2, bool normalize) { OPENSWATH_PRECONDITION(!data1.empty() && data1.size() == data2.size(), "Both data vectors need to have the same length"); int maxdelay = static_cast<int>(data1.size()); int lag = 1; double mean1 = std::accumulate(data1.begin(), data1.end(), 0.) / (double)data1.size(); double mean2 = std::accumulate(data2.begin(), data2.end(), 0.) / (double)data2.size(); double denominator = 1.0; int datasize = static_cast<int>(data1.size()); int i, j, delay; // Normalized cross-correlation = subtract the mean and divide by the standard deviation if (normalize) { double sqsum1 = 0; double sqsum2 = 0; for (std::vector<double>::iterator it = data1.begin(); it != data1.end(); ++it) { sqsum1 += (*it - mean1) * (*it - mean1); } for (std::vector<double>::iterator it = data2.begin(); it != data2.end(); ++it) { sqsum2 += (*it - mean2) * (*it - mean2); } // sigma_1 * sigma_2 * n denominator = sqrt(sqsum1 * sqsum2); } //avoids division in the for loop denominator = 1/denominator; XCorrArrayType result; result.data.reserve( (size_t)std::ceil((2*maxdelay + 1) / lag)); int cnt = 0; for (delay = -maxdelay; delay <= maxdelay; delay = delay + lag, cnt++) { double sxy = 0; for (i = 0; i < datasize; i++) { j = i + delay; if (j < 0 || j >= datasize) { continue; } if (normalize) { sxy += (data1[i] - mean1) * (data2[j] - mean2); } else { sxy += (data1[i]) * (data2[j]); } } if (denominator > 0) { result.data.emplace_back(delay, sxy*denominator); } else { // e.g. if all datapoints are zero result.data.emplace_back(delay, 0); } } return result; } unsigned int computeAndAppendRank(const std::vector<double>& v_temp, std::vector<unsigned int>& ranks_out) { std::vector<unsigned int> ranks{}; ranks.resize(v_temp.size()); std::iota(ranks.begin(), ranks.end(), 0); std::sort(ranks.begin(), ranks.end(), [&v_temp](unsigned int i, unsigned int j) { return v_temp[i] < v_temp[j]; }); ranks_out.resize(v_temp.size()); double x = 0; unsigned int y = 0; for(unsigned int i = 0; i < ranks.size();++i) { if(v_temp[ranks[i]] != x) { x = v_temp[ranks[i]]; y = i; } ranks_out[ranks[i]] = y; } return y; } std::vector<unsigned int> computeRankVector(const std::vector<std::vector<double>>& intensity, std::vector<std::vector<unsigned int>>& ranks) { unsigned int pre_rank_size = ranks.size(); ranks.resize(pre_rank_size + intensity.size()); std::vector<unsigned int> max_rank_vec(intensity.size()); for (std::size_t i = 0; i < intensity.size(); i++) { max_rank_vec[i] = computeAndAppendRank(intensity[i], ranks[pre_rank_size + i]); } return max_rank_vec; } double rankedMutualInformation(std::vector<unsigned int>& ranked_data1, std::vector<unsigned int>& ranked_data2, const unsigned int max_rank1, const unsigned int max_rank2) { OPENSWATH_PRECONDITION(ranked_data1.size() != 0 && ranked_data1.size() == ranked_data2.size(), "Both data vectors need to have the same length"); unsigned int inputVectorlength = ranked_data1.size(); unsigned int firstNumStates = max_rank1 + 1; unsigned int secondNumStates = max_rank2 + 1; std::vector<double> firstStateCounts(firstNumStates,0); std::vector<double> secondStateCounts(secondNumStates,0); std::unordered_map<pos2D, double, pair_hash> jointStateCounts{}; for (unsigned int i = 0; i < inputVectorlength; i++) { firstStateCounts[ranked_data1[i]] += 1; secondStateCounts[ranked_data2[i]] += 1; jointStateCounts[std::make_pair(ranked_data1[i], ranked_data2[i])] += 1; } double mutualInformation = 0.0; for (const auto &[pos, jointStateCount_val]: jointStateCounts) { mutualInformation += jointStateCount_val * log(jointStateCount_val / firstStateCounts[pos.first] / secondStateCounts[pos.second]); } mutualInformation /= inputVectorlength; mutualInformation += log(inputVectorlength); mutualInformation /= log(2.0); return mutualInformation; } } //namespace OpenMS // namespace Scoring
C++
3D
OpenMS/OpenMS
src/openswathalgo/source/OPENSWATHALGO/ALGO/StatsHelpers.cpp
.cpp
3,983
102
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h> #include <algorithm> #include <numeric> #include <functional> #include <stdexcept> #include <Eigen/Core> namespace OpenSwath { void normalize( const std::vector<double> & intensities, double normalizer, std::vector<double> & normalized_intensities) { //compute total intensities //normalize intensities normalized_intensities.resize(intensities.size()); if (normalizer > 0) { std::transform(intensities.cbegin(), intensities.cend(), normalized_intensities.begin(), [&normalizer](double val) { return val / normalizer; }); } } double dotprodScoring(std::vector<double> intExp, std::vector<double> theorint) { for (unsigned int i = 0; i < intExp.size(); ++i) { intExp[i] = sqrt(intExp[i]); theorint[i] = sqrt(theorint[i]); } double intExptotal = norm(intExp.begin(), intExp.end()); double intTheorTotal = norm(theorint.begin(), theorint.end()); OpenSwath::normalize(intExp, intExptotal, intExp); OpenSwath::normalize(theorint, intTheorTotal, theorint); double score2 = OpenSwath::dotProd(intExp.begin(), intExp.end(), theorint.begin()); return score2; } double manhattanScoring(std::vector<double> intExp, std::vector<double> theorint) { for (unsigned int i = 0; i < intExp.size(); ++i) { intExp[i] = sqrt(intExp[i]); theorint[i] = sqrt(theorint[i]); //std::transform(intExp.begin(), intExp.end(), intExp.begin(), sqrt); //std::transform(theorint.begin(), theorint.end(), theorint.begin(), sqrt); } double intExptotal = std::accumulate(intExp.begin(), intExp.end(), 0.0); double intTheorTotal = std::accumulate(theorint.begin(), theorint.end(), 0.0); OpenSwath::normalize(intExp, intExptotal, intExp); OpenSwath::normalize(theorint, intTheorTotal, theorint); double score2 = OpenSwath::manhattanDist(intExp.begin(), intExp.end(), theorint.begin()); return score2; } // Template implementation (only compiled in this .cpp file) template <typename Texp, typename Ttheo> double dotProd(Texp intExpBeg, Texp intExpEnd, Ttheo intTheo) { size_t size = std::distance(intExpBeg, intExpEnd); // Get the value types using ExpType = typename std::iterator_traits<Texp>::value_type; using TheoType = typename std::iterator_traits<Ttheo>::value_type; // Create appropriate Eigen maps based on the actual data types Eigen::Map<const Eigen::Matrix<ExpType, Eigen::Dynamic, 1>> vec1(&(*intExpBeg), size); Eigen::Map<const Eigen::Matrix<TheoType, Eigen::Dynamic, 1>> vec2(&(*intTheo), size); // Compute dot product and cast result to double return static_cast<double>(vec1.dot(vec2)); } // Explicit template instantiation definitions (compile these specific versions) template OPENSWATHALGO_DLLAPI double dotProd<std::vector<double>::const_iterator, std::vector<double>::const_iterator>( std::vector<double>::const_iterator, std::vector<double>::const_iterator, std::vector<double>::const_iterator); template OPENSWATHALGO_DLLAPI double dotProd<std::vector<float>::const_iterator, std::vector<float>::const_iterator>( std::vector<float>::const_iterator, std::vector<float>::const_iterator, std::vector<float>::const_iterator); template OPENSWATHALGO_DLLAPI double dotProd<std::vector<int>::const_iterator, std::vector<int>::const_iterator>( std::vector<int>::const_iterator, std::vector<int>::const_iterator, std::vector<int>::const_iterator); }
C++
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/SpectrumRangeManager.h
.h
5,245
156
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Administrator $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/RangeManager.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <map> #include <set> namespace OpenMS { class MSSpectrum; // Forward declaration for MSSpectrum /** @brief Advanced range manager for MS spectra with separate ranges for each MS level This class extends the basic RangeManager to provide separate range tracking for different MS levels (MS1, MS2, etc.). It manages four types of ranges: - m/z (mass-to-charge ratio) - intensity - retention time (RT) - ion mobility A global range is tracked for all MS levels, and additional ranges are maintained for each specific MS level. This allows for efficient querying of ranges for specific MS levels, which is useful for visualization, filtering, and processing operations that need to work with specific MS levels. The class inherits from RangeManager and adds MS level-specific functionality. The base RangeManager functionality is used for the global ranges, while a map of MS levels to RangeManagers is used for the MS level-specific ranges. @see RangeManager @see MSSpectrum @see ChromatogramRangeManager @see MSExperiment @ingroup Kernel */ class OPENMS_DLLAPI SpectrumRangeManager : public RangeManager<RangeMZ, RangeIntensity, RangeMobility, RangeRT> { public: /// Base type using BaseType = RangeManager<RangeMZ, RangeIntensity, RangeMobility, RangeRT>; /// Default constructor SpectrumRangeManager() = default; /// Copy constructor SpectrumRangeManager(const SpectrumRangeManager& source) = default; /// Move constructor SpectrumRangeManager(SpectrumRangeManager&& source) = default; /// Assignment operator SpectrumRangeManager& operator=(const SpectrumRangeManager& source) = default; /// Move assignment operator SpectrumRangeManager& operator=(SpectrumRangeManager&& source) = default; /// Destructor ~SpectrumRangeManager() = default; /** @brief Clears all ranges (global and MS level-specific) */ void clearRanges() { BaseType::clearRanges(); ms_level_ranges_.clear(); } /** @brief Extends the ranges with the ranges of another range manager @param[in] other The other range manager to extend from @param[in] ms_level The MS level for which to extend the ranges (0 for global ranges) */ void extend(const BaseType& other, UInt ms_level = 0) { ms_level == 0 ? BaseType::extend(other) : ms_level_ranges_[ms_level].extend(other); } /** @brief Gets the ranges for a specific MS level @param[in] ms_level The MS level for which to retrieve the ranges @return The ranges for the specified MS level @throw Exception::InvalidValue if no ranges exist for the specified MS level */ const BaseType& byMSLevel(UInt ms_level = 0) const { if (auto it = ms_level_ranges_.find(ms_level); it != ms_level_ranges_.end()) { return it->second; } throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No ranges for this MS level", String(ms_level)); } /** @brief Gets all MS levels for which specific ranges exist @return The set of MS levels */ std::set<UInt> getMSLevels() const { std::set<UInt> ms_levels; for (const auto& [level, _] : ms_level_ranges_) { ms_levels.insert(level); } return ms_levels; } /** @brief Extends the RT range with an MS level parameter @param[in] rt The RT value to extend with @param[in] ms_level The MS level for which to extend the RT range (0 for global range) */ void extendRT(double rt, UInt ms_level = 0) { ms_level == 0 ? BaseType::extendRT(rt) : ms_level_ranges_[ms_level].extendRT(rt); } /** @brief Extends the m/z range with an MS level parameter @param[in] mz The m/z value to extend with @param[in] ms_level The MS level for which to extend the m/z range (0 for global range) */ void extendMZ(double mz, UInt ms_level = 0) { ms_level == 0 ? BaseType::extendMZ(mz) : ms_level_ranges_[ms_level].extendMZ(mz); } /** @brief Extends the ranges with the ranges of a spectrum using an MS level parameter @param[in] spectrum The spectrum whose ranges to extend from @param[in] ms_level The MS level for which to extend the ranges (0 for global ranges) */ void extendUnsafe(const MSSpectrum& spectrum, UInt ms_level = 0) { ms_level == 0 ? BaseType::extendUnsafe(spectrum.getRange()) : ms_level_ranges_[ms_level].extendUnsafe(spectrum.getRange()); } protected: /// MS level-specific ranges std::map<UInt, BaseType> ms_level_ranges_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/Peak2D.h
.h
9,040
345
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <iosfwd> #include <functional> namespace OpenMS { /** @brief A 2-dimensional raw data point or peak. This data structure is intended for continuous data or peak data. If you want to annotated single peaks with meta data, use RichPeak2D instead. @ingroup Kernel */ class OPENMS_DLLAPI Peak2D { public: ///@name Type definitions ///@{ /// Intensity type typedef float IntensityType; /// Coordinate type (of the position) typedef double CoordinateType; /// Position type typedef DPosition<2> PositionType; ///@} /// @name Dimension descriptions ///@{ /// This enum maps the symbolic names of the dimensions to numbers enum DimensionDescription { RT = 0, ///< Retention time dimension id (0 if used as a const int) MZ = 1, ///< Mass-to-charge dimension id (1 if used as a const int) DIMENSION = 2 ///< Number of dimensions }; /// Short name of the dimension (abbreviated form) static char const * shortDimensionName(UInt const dim); /// Short name of the dimension (abbreviated form) static char const * shortDimensionNameRT(); /// Short name of the dimension (abbreviated form) static char const * shortDimensionNameMZ(); /// Full name of the dimension (self-explanatory form) static char const * fullDimensionName(UInt const dim); /// Full name of the dimension (self-explanatory form) static char const * fullDimensionNameRT(); /// Full name of the dimension (self-explanatory form) static char const * fullDimensionNameMZ(); /// Unit of measurement (abbreviated form) static char const * shortDimensionUnit(UInt const dim); /// Unit of measurement (abbreviated form) static char const * shortDimensionUnitRT(); /// Unit of measurement (abbreviated form) static char const * shortDimensionUnitMZ(); /// Unit of measurement (self-explanatory form) static char const * fullDimensionUnit(UInt const dim); /// Unit of measurement (self-explanatory form) static char const * fullDimensionUnitRT(); /// Unit of measurement (self-explanatory form) static char const * fullDimensionUnitMZ(); ///@} protected: /// @name Dimension descriptions ///@{ /// Short name of the dimension (abbreviated form) static char const * const dimension_name_short_[DIMENSION]; /// Full name of the dimension (self-explanatory form) static char const * const dimension_name_full_[DIMENSION]; /// Unit of measurement (abbreviated form) static char const * const dimension_unit_short_[DIMENSION]; /// Unit of measurement (self-explanatory form) static char const * const dimension_unit_full_[DIMENSION]; ///@} public: ///@name Constructors and Destructor ///@{ /// Default constructor Peak2D() = default; /// Member constructor explicit Peak2D(const PositionType& pos, const IntensityType in) : position_(pos), intensity_(in) {} /// Copy constructor Peak2D(const Peak2D & p) = default; /// Move constructor Peak2D(Peak2D&&) noexcept = default; /// Assignment operator Peak2D& operator=(const Peak2D& rhs) = default; /// Move assignment operator Peak2D& operator=(Peak2D&&) noexcept = default; /** @brief Destructor @note The destructor is non-virtual although many classes are derived from Peak2D. This is intentional, since otherwise we would "waste" space for a vtable pointer in each instance. Normally you should not derive other classes from Peak2D (unless you know what you are doing, of course). */ ~Peak2D() noexcept = default; ///@} ///@name Accessors ///@{ /// Non-mutable access to the data point intensity (height) IntensityType getIntensity() const { return intensity_; } /// Sets data point intensity (height) void setIntensity(IntensityType intensity) { intensity_ = intensity; } /// Non-mutable access to the position PositionType const & getPosition() const { return position_; } /// Mutable access to the position PositionType & getPosition() { return position_; } /// Mutable access to the position void setPosition(const PositionType & position) { position_ = position; } /// Returns the m/z coordinate (index 1) CoordinateType getMZ() const { return position_[MZ]; } /// Mutable access to the m/z coordinate (index 1) void setMZ(CoordinateType coordinate) { position_[MZ] = coordinate; } /// Returns the RT coordinate (index 0) CoordinateType getRT() const { return position_[RT]; } /// Mutable access to the RT coordinate (index 0) void setRT(CoordinateType coordinate) { position_[RT] = coordinate; } ///@} /// Equality operator bool operator==(const Peak2D& rhs) const = default; /// Equality operator bool operator!=(const Peak2D & rhs) const { return !(operator==(rhs)); } /** @name Comparator classes. These classes implement binary predicates that can be used to compare two peaks with respect to their intensities, positions, etc. */ ///@{ /// Comparator by intensity struct IntensityLess { bool operator()(const Peak2D & left, const Peak2D & right) const { return left.getIntensity() < right.getIntensity(); } bool operator()(const Peak2D & left, IntensityType right) const { return left.getIntensity() < right; } bool operator()(IntensityType left, const Peak2D & right) const { return left < right.getIntensity(); } bool operator()(IntensityType left, IntensityType right) const { return left < right; } }; /// Comparator by RT position struct RTLess { bool operator()(const Peak2D & left, const Peak2D & right) const { return left.getRT() < right.getRT(); } bool operator()(const Peak2D & left, CoordinateType right) const { return left.getRT() < right; } bool operator()(CoordinateType left, const Peak2D & right) const { return left < right.getRT(); } bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by m/z position struct MZLess { bool operator()(const Peak2D & left, const Peak2D & right) const { return left.getMZ() < right.getMZ(); } bool operator()(const Peak2D & left, CoordinateType right) const { return left.getMZ() < right; } bool operator()(CoordinateType left, const Peak2D & right) const { return left < right.getMZ(); } bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by position. Lexicographical comparison (first RT then m/z) is done. struct PositionLess { bool operator()(const Peak2D & left, const Peak2D & right) const { return left.getPosition() < right.getPosition(); } bool operator()(const Peak2D & left, const PositionType & right) const { return left.getPosition() < right; } bool operator()(const PositionType & left, const Peak2D & right) const { return left < right.getPosition(); } bool operator()(const PositionType & left, const PositionType & right) const { return left < right; } }; ///@} friend OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const Peak2D & point); protected: /// The data point position PositionType position_{}; /// The data point intensity IntensityType intensity_{}; }; /// Print the contents to a stream. OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const Peak2D & point); } // namespace OpenMS // Hash function specialization for Peak2D namespace std { template<> struct hash<OpenMS::Peak2D> { std::size_t operator()(const OpenMS::Peak2D& p) const noexcept { std::size_t seed = OpenMS::hash_float(p.getRT()); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getMZ())); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIntensity())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/RangeUtils.h
.h
19,010
670
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <functional> #include <algorithm> #include <vector> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/METADATA/Precursor.h> #include <OpenMS/METADATA/IonSource.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/CONCEPT/LogStream.h> namespace OpenMS { /** @defgroup RangeUtils RangeUtils @brief Predicates for range operations @ingroup Kernel A group of predicates that can be used to perform range operations on MS data. They operate on classes that have the save interface as Spectrum or Peak1D or Peak2D, respectively. <BR> <BR> The code for the removal of spectra in a certain retention time range from a vector of spectra might look like this: @code //data std::vector< MSSpectrum> spectra; //... spectra are added to the vector ... //range from 0.0 to 36.0 s InRTRange< MSSpectrum> range(0.0, 36.0); //remove the range std::erase_if(spectra, range); @endcode The code for the removal of peaks within certain intensity range from a spectrum might look like this: @code //data MSSpectrum spectrum; //... peaks are added to the spectrum ... //range from 0.0 to 5000.0 intensity InIntensityRange range< Peak1D >(0.0, 5000.0); //remove the range std::erase_if(spectrum, range); @endcode */ /** @brief Predicate that determines if a class has a certain metavalue MetaContainer must be a MetaInfoInterface or have the same interface @ingroup RangeUtils */ template <class MetaContainer> class HasMetaValue { public: /** @brief Constructor @param[in] metavalue MetaValue that needs to be present. @param[in] reverse if @p reverse is true, operator() returns true if the metavalue does not exist. */ HasMetaValue(String metavalue, bool reverse = false) : metavalue_key_(metavalue), reverse_(reverse) {} inline bool operator()(const MetaContainer& s) const { bool has_meta_value = s.metaValueExists(metavalue_key_); // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ has_meta_value; } protected: String metavalue_key_; bool reverse_; }; /** @brief Predicate that determines if a spectrum lies inside/outside a specific retention time range SpectrumType must be a Spectrum or have the same interface @ingroup RangeUtils */ template <class SpectrumType> class InRTRange { public: /** @brief Constructor @param[in] min lower boundary @param[in] max upper boundary @param[in] reverse if @p reverse is true, operator() returns true if the spectrum lies outside the range */ InRTRange(double min, double max, bool reverse = false) : min_(min), max_(max), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { double tmp = s.getRT(); // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ (min_ <= tmp && tmp <= max_); } protected: double min_, max_; bool reverse_; }; /** @brief Predicate that determines if a spectrum lies inside/outside a specific MS level set SpectrumType must be a Spectrum or have the same interface @ingroup RangeUtils */ template <class SpectrumType> class InMSLevelRange { public: /** @brief Constructor @param[in] levels an array of MS levels @param[in] reverse if @p reverse is true, operator() returns true if the spectrum lies outside the set */ InMSLevelRange(const IntList& levels, bool reverse = false) : levels_(levels), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { Int tmp = s.getMSLevel(); // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ (std::find(levels_.begin(), levels_.end(), tmp) != levels_.end()); } protected: IntList levels_; bool reverse_; }; /** @brief Predicate that determines if a spectrum has a certain scan mode SpectrumType must be a Spectrum or have the same interface (SpectrumSettings) @ingroup RangeUtils */ template <class SpectrumType> class HasScanMode { public: /** @brief Constructor @param[in] mode scan mode @param[in] reverse if @p reverse is true, operator() returns true if the spectrum has a different scan mode */ HasScanMode(Int mode, bool reverse = false) : mode_(mode), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ (static_cast<Int>(s.getInstrumentSettings().getScanMode()) == mode_); } protected: Int mode_; bool reverse_; }; /** @brief Predicate that determines if a spectrum has a certain scan polarity SpectrumType must be a Spectrum or have the same interface (SpectrumSettings) @ingroup RangeUtils */ template <class SpectrumType> class HasScanPolarity { public: /** @brief Constructor @param[in] polarity scan polarity @param[in] reverse if @p reverse is true, operator() returns true if the spectrum has a different scan polarity */ HasScanPolarity(IonSource::Polarity polarity, bool reverse = false) : polarity_(polarity), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ (s.getInstrumentSettings().getPolarity() == polarity_); } protected: IonSource::Polarity polarity_; bool reverse_; }; /** @brief Predicate that determines if a spectrum is empty. SpectrumType must have a empty() method @ingroup RangeUtils */ template <class SpectrumType> class IsEmptySpectrum { public: /** @brief Constructor @param[in] reverse if @p reverse is true, operator() returns true if the spectrum is not empty */ explicit IsEmptySpectrum(bool reverse = false) : reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ s.empty(); } protected: bool reverse_; }; /** @brief Predicate that determines if a spectrum is a zoom (enhanced resolution) spectrum. SpectrumType must have a getInstrumentSettings() method @ingroup RangeUtils */ template <class SpectrumType> class IsZoomSpectrum { public: /** @brief Constructor @param[in] reverse if @p reverse is true, operator() returns true if the spectrum is not a zoom spectrum */ explicit IsZoomSpectrum(bool reverse = false) : reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ s.getInstrumentSettings().getZoomScan(); } protected: bool reverse_; }; /** @brief Predicate that determines if a spectrum was generated using any activation method given in the constructor list. SpectrumType must have a getPrecursors() method @ingroup RangeUtils */ template <class SpectrumType> class HasActivationMethod { public: /** @brief Constructor @param[in] methods List of methods that is compared against precursor activation methods. @param[in] reverse if @p reverse is true, operator() returns true if the spectrum is not using one of the specified activation methods. */ HasActivationMethod(const StringList& methods, bool reverse = false) : methods_(methods), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { for (const Precursor& p : s.getPrecursors()) { for (const Precursor::ActivationMethod am : p.getActivationMethods()) { if (ListUtils::contains(methods_, Precursor::NamesOfActivationMethod[static_cast<size_t>(am)])) { // found matching activation method if (reverse_) return false; else return true; } } } return reverse_; } protected: StringList methods_; bool reverse_; }; /** @brief Predicate that determines if a spectrum's precursor is within a certain m/z range. SpectrumType must have a getPrecursors() method If multiple precursors are present, all must fulfill the range criterion. @ingroup RangeUtils */ template <class SpectrumType> class InPrecursorMZRange { public: /** @brief Constructor @param[in] mz_left left m/z boundary (closed interval) @param[in] mz_right right m/z boundary (closed interval) @param[in] reverse if @p reverse is true, operator() returns true if the precursor's m/z is outside of the given interval. */ InPrecursorMZRange(const double& mz_left, const double& mz_right, bool reverse = false) : mz_left_(mz_left), mz_right_(mz_right), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { for (std::vector<Precursor>::const_iterator it = s.getPrecursors().begin(); it != s.getPrecursors().end(); ++it) { //std::cerr << mz_left_ << " " << mz_right_ << " " << it->getMZ() << "\n"; if (!(mz_left_ <= it->getMZ() && it->getMZ() <= mz_right_)) { // found PC outside of allowed window if (reverse_) return true; else return false; } } if (reverse_) return false; else return true; } protected: double mz_left_; double mz_right_; bool reverse_; }; /** @brief Predicate that determines if a spectrum has a certain precursor charge as given in the constructor list. SpectrumType must have a getPrecursors() method @ingroup RangeUtils */ template <class SpectrumType> class HasPrecursorCharge { public: /** @brief Constructor @param[in] charges List of charges that is compared against precursor charge. @param[in] reverse if @p reverse is true, operator() returns true if the spectrum has not one of the specified precursor charges. */ HasPrecursorCharge(const IntList& charges, bool reverse = false) : charges_(charges), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { bool match = false; for (std::vector<Precursor>::const_iterator it = s.getPrecursors().begin(); it != s.getPrecursors().end(); ++it) { Int tmp = it->getCharge(); match = match || (std::find(charges_.begin(), charges_.end(), tmp) != charges_.end()); } if (reverse_) return !match; else return match; } protected: IntList charges_; bool reverse_; }; /** @brief Predicate that determines if a peak lies inside/outside a specific m/z range PeakType must have a getPosition() method. @note It is assumed that the m/z dimension is dimension 0! @ingroup RangeUtils */ template <class PeakType> class InMzRange { public: /** @brief Constructor @param[in] min lower boundary @param[in] max upper boundary @param[in] reverse if @p reverse is true, operator() returns true if the peak lies outside the range */ InMzRange(double min, double max, bool reverse = false) : min_(min), max_(max), reverse_(reverse) {} inline bool operator()(const PeakType& p) const { double tmp = p.getPosition()[0]; // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ (min_ <= tmp && tmp <= max_); } protected: double min_, max_; bool reverse_; }; /** @brief Predicate that determines if a peak lies inside/outside a specific intensity range PeakType must have a getIntensity() method. @ingroup RangeUtils */ template <class PeakType> class InIntensityRange { public: /** @brief Constructor @param[in] min lower boundary @param[in] max upper boundary @param[in] reverse if @p reverse is true, operator() returns true if the peak lies outside the set */ InIntensityRange(double min, double max, bool reverse = false) : min_(min), max_(max), reverse_(reverse) {} inline bool operator()(const PeakType& p) const { double tmp = p.getIntensity(); // XOR(^): same as 'if (rev_) return !(test) else return test;' where (test) is the condition; Speed: XOR is about 25% faster in VS10 return reverse_ ^ (min_ <= tmp && tmp <= max_); } protected: double min_, max_; bool reverse_; }; /** @brief Predicate that determines if an MSn spectrum was generated with a collision energy in the given range. @note This applies only to CID and HCD spectra. For spectra that do not have a collision energy, the predicate will return true. @note This predicate will return always true for spectra with getMSLevel() = 1. @ingroup RangeUtils */ template <class SpectrumType> class IsInCollisionEnergyRange { public: /** @brief Constructor @param[in] min minimum collision energy to be included in the range. @param[in] max maximum collision energy to be included in the range. @param[in] reverse if @p reverse is true, operator() returns true if the collision energy lies outside the range. */ IsInCollisionEnergyRange(double min, double max, bool reverse = false) : min_energy_(min), max_energy_(max), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { // leave non-fragmentation spectra untouched if (s.getMSLevel() == 1) return false; bool isIn = false; bool hasCollisionEnergy = false; for (std::vector<Precursor>::const_iterator it = s.getPrecursors().begin(); it != s.getPrecursors().end(); ++it) { if (it->metaValueExists("collision energy")) { hasCollisionEnergy = true; double cE = it->getMetaValue("collision energy"); isIn |= !(cE > max_energy_ || cE < min_energy_); } } // we accept all spectra that have no collision energy value if (!hasCollisionEnergy) return false; if (reverse_) return !isIn; else return isIn; } private: double min_energy_, max_energy_; bool reverse_; }; /** @brief Predicate that determines if the width of the isolation window of an MSn spectrum is in the given range. @note This predicate will return always true for spectra with getMSLevel() = 1. @ingroup RangeUtils */ template <class SpectrumType> class IsInIsolationWindowSizeRange { public: /** @brief Constructor @param[in] min_size minimum width of the isolation window. @param[in] max_size maximum width of the isolation window. @param[in] reverse if @p reverse is true, operator() returns true if the width of the isolation window lies outside the range. */ IsInIsolationWindowSizeRange(double min_size, double max_size, bool reverse = false) : min_size_(min_size), max_size_(max_size), reverse_(reverse) {} inline bool operator()(const SpectrumType& s) const { // leave non-fragmentation spectra untouched if (s.getMSLevel() == 1) return false; bool isIn = false; for (std::vector<Precursor>::const_iterator it = s.getPrecursors().begin(); it != s.getPrecursors().end(); ++it) { const double isolationWindowSize = it->getIsolationWindowUpperOffset() + it->getIsolationWindowLowerOffset(); isIn |= !(isolationWindowSize > max_size_ || isolationWindowSize < min_size_); } if (reverse_) return !isIn; else return isIn; } private: double min_size_, max_size_; bool reverse_; }; /** @brief Predicate that determines if the isolation window covers ANY of the given m/z values. @note This predicate will return always true for spectra with getMSLevel() = 1. @ingroup RangeUtils */ template <class SpectrumType> class IsInIsolationWindow { public: /** @brief Constructor @param[in] vec_mz Vector of m/z values, of which at least one needs to be covered @param[in] reverse if @p reverse is true, operator() returns true if the isolation window is outside for ALL m/z values. */ IsInIsolationWindow(std::vector<double> vec_mz, bool reverse = false) : vec_mz_(vec_mz), reverse_(reverse) { std::sort(vec_mz_.begin(), vec_mz_.end()); } inline bool operator()(const SpectrumType& s) const { // leave non-fragmentation spectra untouched if (s.getMSLevel() == 1) return false; bool isIn = false; for (std::vector<Precursor>::const_iterator it = s.getPrecursors().begin(); it != s.getPrecursors().end(); ++it) { if (it->getIsolationWindowLowerOffset() == 0 || it->getIsolationWindowUpperOffset() == 0) { OPENMS_LOG_WARN << "IsInIsolationWindow(): Lower/Upper Offset for Precursor Isolation Window is Zero! " << "Filtering will probably be too strict (unless you hit the exact precursor m/z)!" << std::endl; } const double lower_mz = it->getMZ() - it->getIsolationWindowLowerOffset(); std::vector<double>::const_iterator it_mz = std::lower_bound(vec_mz_.begin(), vec_mz_.end(), lower_mz); if (it_mz != vec_mz_.end()) // left side ok { // right side? const double upper_mz = it->getMZ() + it->getIsolationWindowUpperOffset(); isIn |= (*it_mz <= upper_mz); } } if (reverse_) return !isIn; else return isIn; } private: std::vector<double> vec_mz_; bool reverse_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/MobilityPeak1D.h
.h
6,041
216
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <iosfwd> #include <functional> namespace OpenMS { /** @brief A 1-dimensional raw data mobility point or peak. The unit (ms, 1/K_0, etc) is implicit. This data structure is intended for continuous mobility data or centroided mobility data. @ingroup Kernel */ class OPENMS_DLLAPI MobilityPeak1D { public: ///@name Type definitions ///@{ /// Dimension enum{ DIMENSION = 1 }; /// Intensity type using IntensityType = float; /// Position type using PositionType = DPosition<1>; /// Coordinate type using CoordinateType = double; ///@} ///@name Constructors and Destructor ///@{ /// Default constructor MobilityPeak1D() = default; /// construct with position and intensity MobilityPeak1D(PositionType a, IntensityType b) : position_(a), intensity_(b) { } /// Copy constructor MobilityPeak1D(const MobilityPeak1D& p) = default; // Move constructor MobilityPeak1D(MobilityPeak1D&&) noexcept = default; /// Assignment operator MobilityPeak1D& operator=(const MobilityPeak1D& rhs) = default; /// Move assignment operator MobilityPeak1D& operator=(MobilityPeak1D&&) noexcept = default; /** @brief Destructor @note The destructor is non-virtual although many classes are derived from MobilityPeak1D. This is intentional, since otherwise we would "waste" space for a vtable pointer in each instance. Normally you should not derive other classes from MobilityPeak1D (unless you know what you are doing, of course). */ ~MobilityPeak1D() noexcept = default; ///@} /** @name Accessors */ ///@{ /// Non-mutable access to the data point intensity (height) IntensityType getIntensity() const; /// Mutable access to the data point intensity (height) void setIntensity(IntensityType intensity); /// Non-mutable access to m/z CoordinateType getMobility() const; /// Mutable access to mobility void setMobility(CoordinateType mobility); /// Alias for getMobility() CoordinateType getPos() const; /// Alias for setMobility() void setPos(CoordinateType pos); /// Non-mutable access to the position PositionType const& getPosition() const; /// Mutable access to the position PositionType& getPosition(); /// Mutable access to the position void setPosition(PositionType const& position); ///@} /// Equality operator bool operator==(const MobilityPeak1D& rhs) const; /// Equality operator bool operator!=(const MobilityPeak1D& rhs) const; /** @name Comparator classes. These classes implement binary predicates that can be used to compare two peaks with respect to their intensities, positions. */ ///@{ /// Comparator by intensity struct IntensityLess { inline bool operator()(MobilityPeak1D const& left, MobilityPeak1D const& right) const { return left.getIntensity() < right.getIntensity(); } inline bool operator()(MobilityPeak1D const& left, IntensityType right) const { return left.getIntensity() < right; } inline bool operator()(IntensityType left, MobilityPeak1D const& right) const { return left < right.getIntensity(); } inline bool operator()(IntensityType left, IntensityType right) const { return left < right; } }; /// Comparator by mobility position. struct MobilityLess { inline bool operator()(const MobilityPeak1D& left, const MobilityPeak1D& right) const { return left.getMobility() < right.getMobility(); } inline bool operator()(MobilityPeak1D const& left, CoordinateType right) const { return left.getMobility() < right; } inline bool operator()(CoordinateType left, MobilityPeak1D const& right) const { return left < right.getMobility(); } inline bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by position. As this class has dimension 1, this is basically an alias for MobilityLess. struct PositionLess { inline bool operator()(const MobilityPeak1D& left, const MobilityPeak1D& right) const { return left.getPosition() < right.getPosition(); } inline bool operator()(const MobilityPeak1D& left, const PositionType& right) const { return left.getPosition() < right; } inline bool operator()(const PositionType& left, const MobilityPeak1D& right) const { return left < right.getPosition(); } inline bool operator()(const PositionType& left, const PositionType& right) const { return left < right; } }; ///@} protected: /// The data point position PositionType position_{}; /// The data point intensity IntensityType intensity_ = 0.0; }; /// Print the contents to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const MobilityPeak1D& point); } // namespace OpenMS // Hash function specialization for MobilityPeak1D namespace std { template<> struct hash<OpenMS::MobilityPeak1D> { std::size_t operator()(const OpenMS::MobilityPeak1D& p) const noexcept { std::size_t seed = OpenMS::hash_float(p.getMobility()); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIntensity())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/ChromatogramTools.h
.h
9,194
221
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/RangeUtils.h> #include <OpenMS/CONCEPT/LogStream.h> #include <map> namespace OpenMS { /** @brief Conversion class to convert chromatograms There are basically two methods implemented, conversion of chromatograms into spectra representation and vice versa. @ingroup Kernel */ class ChromatogramTools { public: /// @name Constructors and destructors //@{ /// default constructor ChromatogramTools() {} /// copy constructor ChromatogramTools(const ChromatogramTools & /*rhs*/) {} /// destructor virtual ~ChromatogramTools() {} //@} /// @name Accessors //@{ /** @brief converts the chromatogram to a list of spectra with instrument settings This conversion may be necessary as most of the spectra formats do not support chromatograms, except of mzML. However, most formats support e.g. SRM chromatogram as a list of spectra with instrument settings SRM and a separate spectrum for each data point. The disadvantage of storing chromatograms in spectra is its exhaustive memory consumption. */ template <typename ExperimentType> void convertChromatogramsToSpectra(ExperimentType & exp) { for (std::vector<MSChromatogram >::const_iterator it = exp.getChromatograms().begin(); it != exp.getChromatograms().end(); ++it) { // for each peak add a new spectrum for (typename ExperimentType::ChromatogramType::const_iterator pit = it->begin(); pit != it->end(); ++pit) { typename ExperimentType::SpectrumType spec; // add precursor and product peaks to spectrum settings spec.getPrecursors().push_back(it->getPrecursor()); spec.getProducts().push_back(it->getProduct()); spec.setRT(pit->getRT()); spec.setMSLevel(2); spec.setInstrumentSettings(it->getInstrumentSettings()); spec.setAcquisitionInfo(it->getAcquisitionInfo()); spec.setSourceFile(it->getSourceFile()); // TODO implement others if (it->getChromatogramType() == ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM) { spec.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SRM); } if (it->getChromatogramType() == ChromatogramSettings::ChromatogramType::SELECTED_ION_MONITORING_CHROMATOGRAM) { spec.getInstrumentSettings().setScanMode(InstrumentSettings::ScanMode::SIM); } // new spec contains one peak, with product m/z and intensity spec.emplace_back(it->getMZ(), pit->getIntensity()); exp.addSpectrum(spec); } } exp.setChromatograms(std::vector<MSChromatogram >()); } /** @brief converts e.g. SRM spectra to chromatograms This conversion is necessary to convert chromatograms, e.g. from SRM or MRM experiments to real chromatograms. mzML 1.1.0 has support for chromatograms which can be stored much more efficiently than spectra based chromatograms. However, most other file formats do not support chromatograms. @param[in,out] exp the experiment to be converted. @param[in] remove_spectra if set to true, the chromatogram spectra are removed from the experiment. @param[in] force_conversion Convert even if ScanMode is not SRM or if there are no precursors (e.g. GC-MS data) */ template <typename ExperimentType> void convertSpectraToChromatograms(ExperimentType & exp, bool remove_spectra = false, bool force_conversion = false) { typedef typename ExperimentType::SpectrumType SpectrumType; std::map<double, std::map<double, std::vector<SpectrumType> > > chroms; std::map<double, MSChromatogram > chroms_xic; for (typename ExperimentType::ConstIterator it = exp.begin(); it != exp.end(); ++it) { // TODO other types if (it->getInstrumentSettings().getScanMode() == InstrumentSettings::ScanMode::SRM || force_conversion) { // exactly one precursor and one product ion if (it->getPrecursors().size() == 1 && it->size() == 1) { chroms[it->getPrecursors().begin()->getMZ()][it->begin()->getMZ()].push_back(*it); } // Exactly one precursor and more than one product ion. // This is how some converters (e.g. ReAdW 4.0.2) store SRM data, // collecting all information from one precursor in a single // pseudo-spectrum else if (it->getPrecursors().size() == 1 && it->size() > 0) { for (Size peak_idx = 0; peak_idx < it->size(); peak_idx++) { // copy spectrum and delete all data, but keep metadata, then add single peak SpectrumType dummy = *it; dummy.clear(false); dummy.push_back((*it)[peak_idx]); chroms[it->getPrecursors().begin()->getMZ()][(*it)[peak_idx].getMZ()].push_back(dummy); } } // We have no precursor, so this may be a MS1 chromatogram scan (as encountered in GC-MS) else if (force_conversion) { for (auto& p : *it) { double mz = p.getMZ(); ChromatogramPeak chr_p; chr_p.setRT(it->getRT()); chr_p.setIntensity(p.getIntensity()); if (chroms_xic.find(mz) == chroms_xic.end()) { // new chromatogram chroms_xic[mz].getPrecursor().setMZ(mz); // chroms_xic[mz].setProduct(prod); // probably no product chroms_xic[mz].setInstrumentSettings(it->getInstrumentSettings()); chroms_xic[mz].getPrecursor().setMetaValue("description", String("XIC @ " + String(mz))); chroms_xic[mz].setAcquisitionInfo(it->getAcquisitionInfo()); chroms_xic[mz].setSourceFile(it->getSourceFile()); } chroms_xic[mz].push_back(chr_p); } } else { OPENMS_LOG_WARN << "ChromatogramTools: need exactly one precursor (given " << it->getPrecursors().size() << ") and one or more product ions (" << it->size() << "), skipping conversion of this spectrum to chromatogram. If this is a MS1 chromatogram, please force conversion (e.g. with -convert_to_chromatograms)." << std::endl; } } else { // This does not makes sense to warn here, because it would also warn on simple mass spectra... // TODO think what to to here //OPENMS_LOG_WARN << "ChromatogramTools: cannot convert other chromatogram spectra types than 'Selected Reaction Monitoring', skipping conversion." << std::endl; // } } // Add the XIC chromatograms for (auto & chrom: chroms_xic) exp.addChromatogram(chrom.second); // Add the SRM chromatograms typename std::map<double, std::map<double, std::vector<SpectrumType> > >::const_iterator it1 = chroms.begin(); for (; it1 != chroms.end(); ++it1) { typename std::map<double, std::vector<SpectrumType> >::const_iterator it2 = it1->second.begin(); for (; it2 != it1->second.end(); ++it2) { typename ExperimentType::ChromatogramType chrom; chrom.setPrecursor(*it2->second.begin()->getPrecursors().begin()); Product prod; prod.setMZ(it2->first); chrom.setProduct(prod); chrom.setInstrumentSettings(it2->second.begin()->getInstrumentSettings()); chrom.setAcquisitionInfo(it2->second.begin()->getAcquisitionInfo()); chrom.setSourceFile(it2->second.begin()->getSourceFile()); typename std::vector<SpectrumType>::const_iterator it3 = it2->second.begin(); for (; it3 != it2->second.end(); ++it3) { typename ExperimentType::ChromatogramType::PeakType p; p.setRT(it3->getRT()); p.setIntensity(it3->begin()->getIntensity()); chrom.push_back(p); } chrom.setNativeID("chromatogram=" + it2->second.begin()->getNativeID()); // TODO native id? chrom.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM); exp.addChromatogram(chrom); } } if (remove_spectra) { exp.getSpectra().erase(remove_if(exp.begin(), exp.end(), HasScanMode<SpectrumType>(static_cast<Int>(InstrumentSettings::ScanMode::SRM))), exp.end()); } } //@} }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/MobilityPeak2D.h
.h
9,465
337
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <iosfwd> #include <functional> namespace OpenMS { /** @brief A 2-dimensional raw data point or peak. This data structure is intended for continuous data or peak data. If you want to annotated single peaks with meta data, use RichMobilityPeak2D instead. @ingroup Kernel */ class OPENMS_DLLAPI MobilityPeak2D { public: ///@name Type definitions ///@{ /// Intensity type typedef float IntensityType; /// Coordinate type (of the position) typedef double CoordinateType; /// Position type typedef DPosition<2> PositionType; ///@} /// @name Dimension descriptions ///@{ /// This enum maps the symbolic names of the dimensions to numbers enum DimensionDescription { IM = 0, ///< Ion Mobility dimension id (0 if used as a const int) MZ = 1, ///< Mass-to-charge dimension id (1 if used as a const int) DIMENSION = 2 ///< Number of dimensions }; /// Short name of the dimension (abbreviated form) static char const * shortDimensionName(UInt const dim); /// Short name of the dimension (abbreviated form) static char const * shortDimensionNameIM(); /// Short name of the dimension (abbreviated form) static char const * shortDimensionNameMZ(); /// Full name of the dimension (self-explanatory form) static char const * fullDimensionName(UInt const dim); /// Full name of the dimension (self-explanatory form) static char const * fullDimensionNameIM(); /// Full name of the dimension (self-explanatory form) static char const * fullDimensionNameMZ(); /// Unit of measurement (abbreviated form) static char const * shortDimensionUnit(UInt const dim); /// Unit of measurement (abbreviated form) static char const * shortDimensionUnitIM(); /// Unit of measurement (abbreviated form) static char const * shortDimensionUnitMZ(); /// Unit of measurement (self-explanatory form) static char const * fullDimensionUnit(UInt const dim); /// Unit of measurement (self-explanatory form) static char const * fullDimensionUnitIM(); /// Unit of measurement (self-explanatory form) static char const * fullDimensionUnitMZ(); ///@} protected: /// @name Dimension descriptions ///@{ /// Short name of the dimension (abbreviated form) static char const * const dimension_name_short_[DIMENSION]; /// Full name of the dimension (self-explanatory form) static char const * const dimension_name_full_[DIMENSION]; /// Unit of measurement (abbreviated form) static char const * const dimension_unit_short_[DIMENSION]; /// Unit of measurement (self-explanatory form) static char const * const dimension_unit_full_[DIMENSION]; ///@} public: ///@name Constructors and Destructor ///@{ /// Default constructor MobilityPeak2D() = default; /// Member constructor explicit MobilityPeak2D(const PositionType& pos, const IntensityType in) : position_(pos), intensity_(in) {} /// Copy constructor MobilityPeak2D(const MobilityPeak2D & p) = default; /// Move constructor MobilityPeak2D(MobilityPeak2D&&) noexcept = default; /// Assignment operator MobilityPeak2D& operator=(const MobilityPeak2D& rhs) = default; /// Move assignment operator MobilityPeak2D& operator=(MobilityPeak2D&&) noexcept = default; /** @brief Destructor @note The destructor is non-virtual although many classes are derived from MobilityPeak2D. This is intentional, since otherwise we would "waste" space for a vtable pointer in each instance. Normally you should not derive other classes from MobilityPeak2D (unless you know what you are doing, of course). */ ~MobilityPeak2D() noexcept = default; ///@} ///@name Accessors ///@{ /// Non-mutable access to the data point intensity (height) IntensityType getIntensity() const { return intensity_; } /// Sets data point intensity (height) void setIntensity(IntensityType intensity) { intensity_ = intensity; } /// Non-mutable access to the position PositionType const & getPosition() const { return position_; } /// Mutable access to the position PositionType & getPosition() { return position_; } /// Mutable access to the position void setPosition(const PositionType & position) { position_ = position; } /// Returns the m/z coordinate (index 1) CoordinateType getMZ() const { return position_[MZ]; } /// Mutable access to the m/z coordinate (index 1) void setMZ(CoordinateType coordinate) { position_[MZ] = coordinate; } /// Returns the IM coordinate (index 0) CoordinateType getMobility() const { return position_[IM]; } /// Mutable access to the IM coordinate (index 0) void setMobility(CoordinateType coordinate) { position_[IM] = coordinate; } ///@} /// Equality operator bool operator==(const MobilityPeak2D & rhs) const { return std::tie(intensity_, position_) == std::tie(rhs.intensity_, rhs.position_); } /// Equality operator bool operator!=(const MobilityPeak2D& rhs) const { return !(operator==(rhs)); } /** @name Comparator classes. These classes implement binary predicates that can be used to compare two peaks with respect to their intensities, positions, etc. */ ///@{ /// Comparator by intensity struct IntensityLess { bool operator()(const MobilityPeak2D & left, const MobilityPeak2D & right) const { return left.getIntensity() < right.getIntensity(); } bool operator()(const MobilityPeak2D & left, IntensityType right) const { return left.getIntensity() < right; } bool operator()(IntensityType left, const MobilityPeak2D & right) const { return left < right.getIntensity(); } bool operator()(IntensityType left, IntensityType right) const { return left < right; } }; /// Comparator by IM position struct IMLess { bool operator()(const MobilityPeak2D & left, const MobilityPeak2D & right) const { return left.getMobility() < right.getMobility(); } bool operator()(const MobilityPeak2D & left, CoordinateType right) const { return left.getMobility() < right; } bool operator()(CoordinateType left, const MobilityPeak2D & right) const { return left < right.getMobility(); } bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by m/z position struct MZLess { bool operator()(const MobilityPeak2D & left, const MobilityPeak2D & right) const { return left.getMZ() < right.getMZ(); } bool operator()(const MobilityPeak2D & left, CoordinateType right) const { return left.getMZ() < right; } bool operator()(CoordinateType left, const MobilityPeak2D & right) const { return left < right.getMZ(); } bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by position. Lexicographical comparison (first IM then m/z) is done. struct PositionLess { bool operator()(const MobilityPeak2D & left, const MobilityPeak2D & right) const { return left.getPosition() < right.getPosition(); } bool operator()(const MobilityPeak2D & left, const PositionType & right) const { return left.getPosition() < right; } bool operator()(const PositionType & left, const MobilityPeak2D & right) const { return left < right.getPosition(); } bool operator()(const PositionType & left, const PositionType & right) const { return left < right; } }; ///@} friend OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const MobilityPeak2D & point); protected: /// The data point position PositionType position_{}; /// The data point intensity IntensityType intensity_ {}; }; /// Print the contents to a stream. OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const MobilityPeak2D & point); } // namespace OpenMS // Hash function specialization for MobilityPeak2D namespace std { template<> struct hash<OpenMS::MobilityPeak2D> { std::size_t operator()(const OpenMS::MobilityPeak2D& p) const noexcept { std::size_t seed = OpenMS::hash_float(p.getMobility()); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getMZ())); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIntensity())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/Peak1D.h
.h
6,157
249
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <iosfwd> #include <functional> namespace OpenMS { /** @brief A 1-dimensional raw data point or peak. This data structure is intended for continuous data or peak data. If you want to annotated single peaks with meta data, use RichPeak1D instead. @ingroup Kernel */ class OPENMS_DLLAPI Peak1D { public: ///@name Type definitions ///@{ /// Dimension enum {DIMENSION = 1}; /// Intensity type using IntensityType = float; /// Position type using PositionType = DPosition<1>; /// Coordinate type using CoordinateType = double; ///@} ///@name Constructors and Destructor ///@{ /// Default constructor inline Peak1D() = default; /// construct with position and intensity inline Peak1D(PositionType a, IntensityType b) : position_(a), intensity_(b) {} /// Copy constructor Peak1D(const Peak1D & p) = default; Peak1D(Peak1D&&) noexcept = default; /// Assignment operator Peak1D& operator=(const Peak1D& rhs) = default; /// Move assignment operator Peak1D& operator=(Peak1D&&) noexcept = default; /** @brief Destructor @note The destructor is non-virtual although many classes are derived from Peak1D. This is intentional, since otherwise we would "waste" space for a vtable pointer in each instance. Normally you should not derive other classes from Peak1D (unless you know what you are doing, of course). */ ~Peak1D() = default; ///@} /** @name Accessors */ ///@{ /// Non-mutable access to the data point intensity (height) inline IntensityType getIntensity() const { return intensity_; } /// Mutable access to the data point intensity (height) inline void setIntensity(IntensityType intensity) { intensity_ = intensity; } /// Non-mutable access to m/z inline CoordinateType getMZ() const { return position_[0]; } /// Mutable access to m/z inline void setMZ(CoordinateType mz) { position_[0] = mz; } /// Alias for getMZ() inline CoordinateType getPos() const { return position_[0]; } /// Alias for setMZ() inline void setPos(CoordinateType pos) { position_[0] = pos; } /// Non-mutable access to the position inline PositionType const & getPosition() const { return position_; } /// Mutable access to the position inline PositionType & getPosition() { return position_; } /// Mutable access to the position inline void setPosition(PositionType const & position) { position_ = position; } ///@} /// Equality operator bool operator==(const Peak1D& rhs) const = default; /// Equality operator bool operator!=(const Peak1D & rhs) const { return !(operator==(rhs)); } /** @name Comparator classes. These classes implement binary predicates that can be used to compare two peaks with respect to their intensities, positions. */ ///@{ /// Comparator by intensity struct IntensityLess { inline bool operator()(Peak1D const & left, Peak1D const & right) const { return left.getIntensity() < right.getIntensity(); } inline bool operator()(Peak1D const & left, IntensityType right) const { return left.getIntensity() < right; } inline bool operator()(IntensityType left, Peak1D const & right) const { return left < right.getIntensity(); } inline bool operator()(IntensityType left, IntensityType right) const { return left < right; } }; /// Comparator by m/z position. struct MZLess { inline bool operator()(const Peak1D & left, const Peak1D & right) const { return left.getMZ() < right.getMZ(); } inline bool operator()(Peak1D const & left, CoordinateType right) const { return left.getMZ() < right; } inline bool operator()(CoordinateType left, Peak1D const & right) const { return left < right.getMZ(); } inline bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by position. As this class has dimension 1, this is basically an alias for MZLess. struct PositionLess { inline bool operator()(const Peak1D & left, const Peak1D & right) const { return left.getPosition() < right.getPosition(); } inline bool operator()(const Peak1D & left, const PositionType & right) const { return left.getPosition() < right; } inline bool operator()(const PositionType & left, const Peak1D & right) const { return left < right.getPosition(); } inline bool operator()(const PositionType & left, const PositionType & right) const { return left < right; } }; ///@} protected: /// The data point position PositionType position_; /// The data point intensity IntensityType intensity_ = 0.0; }; /// Print the contents to a stream. OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const Peak1D & point); } // namespace OpenMS // Hash function specialization for Peak1D namespace std { template<> struct hash<OpenMS::Peak1D> { std::size_t operator()(const OpenMS::Peak1D& p) const noexcept { std::size_t seed = OpenMS::hash_float(p.getMZ()); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIntensity())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/MSChromatogram.h
.h
13,035
423
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/METADATA/ChromatogramSettings.h> #include <OpenMS/METADATA/MetaInfoDescription.h> #include <OpenMS/KERNEL/RangeManager.h> #include <OpenMS/KERNEL/ChromatogramPeak.h> #include <OpenMS/METADATA/DataArrays.h> namespace OpenMS { class ChromatogramPeak; /** @brief The representation of a chromatogram. @ingroup Kernel */ class OPENMS_DLLAPI MSChromatogram : private std::vector<ChromatogramPeak>, public RangeManagerContainer<RangeRT, RangeIntensity>, public ChromatogramSettings { public: /// Comparator for the precursor m/z time. struct OPENMS_DLLAPI MZLess { bool operator()(const MSChromatogram& a, const MSChromatogram& b) const; }; ///@name Base type definitions ///@{ /// Peak type typedef ChromatogramPeak PeakType; /// Coordinate (RT) type typedef typename PeakType::CoordinateType CoordinateType; /// Chromatogram base type typedef std::vector<PeakType> ContainerType; /// RangeManager typedef RangeManager<RangeRT, RangeIntensity> RangeManagerType; /// Float data array vector type typedef OpenMS::DataArrays::FloatDataArray FloatDataArray ; typedef std::vector<FloatDataArray> FloatDataArrays; /// String data array vector type typedef OpenMS::DataArrays::StringDataArray StringDataArray ; typedef std::vector<StringDataArray> StringDataArrays; /// Integer data array vector type typedef OpenMS::DataArrays::IntegerDataArray IntegerDataArray ; typedef std::vector<IntegerDataArray> IntegerDataArrays; //@} ///@name Peak container iterator type definitions //@{ /// Mutable iterator typedef typename ContainerType::iterator Iterator; /// Non-mutable iterator typedef typename ContainerType::const_iterator ConstIterator; /// Mutable reverse iterator typedef typename ContainerType::reverse_iterator ReverseIterator; /// Non-mutable reverse iterator typedef typename ContainerType::const_reverse_iterator ConstReverseIterator; //@} ///@name Export methods from std::vector //@{ using ContainerType::operator[]; using ContainerType::begin; using ContainerType::cbegin; using ContainerType::rbegin; using ContainerType::end; using ContainerType::cend; using ContainerType::rend; using ContainerType::resize; using ContainerType::size; using ContainerType::push_back; using ContainerType::emplace_back; using ContainerType::pop_back; using ContainerType::empty; using ContainerType::front; using ContainerType::back; using ContainerType::reserve; using ContainerType::insert; using ContainerType::erase; using ContainerType::swap; using typename ContainerType::iterator; using typename ContainerType::const_iterator; using typename ContainerType::size_type; using typename ContainerType::value_type; using typename ContainerType::reference; using typename ContainerType::const_reference; using typename ContainerType::pointer; using typename ContainerType::difference_type; //@} /// Constructor MSChromatogram() = default; /// Copy constructor MSChromatogram(const MSChromatogram&) = default; /// Move constructor MSChromatogram(MSChromatogram&&) = default; /// Destructor ~MSChromatogram() = default; /// Assignment operator MSChromatogram& operator=(const MSChromatogram& source); /// Move assignment operator MSChromatogram& operator=(MSChromatogram&&) & = default; /// Equality operator bool operator==(const MSChromatogram& rhs) const; /// Equality operator bool operator!=(const MSChromatogram& rhs) const { return !(operator==(rhs)); } // Docu in base class (RangeManager) void updateRanges() override; ///@name Accessors for meta information ///@{ /// Returns the name const String& getName() const; /// Sets the name void setName(const String& name); ///@} /// returns the mz of the product entry, makes sense especially for MRM scans double getMZ() const; /** @name Peak data array methods These methods are used to annotate each peak in a chromatogram with meta information. It is an intermediate way between storing the information in the peak's MetaInfoInterface and deriving a new peak type with members for this information. These statements should help you chose which approach to use - Access to meta info arrays is slower than to a member variable - Access to meta info arrays is faster than to a %MetaInfoInterface - Meta info arrays are stored when using mzML format for storing */ ///@{ /// Returns a const reference to the float meta data arrays const FloatDataArrays& getFloatDataArrays() const; /// Returns a mutable reference to the float meta data arrays FloatDataArrays& getFloatDataArrays(); /// Sets the float meta data arrays void setFloatDataArrays(const FloatDataArrays& fda) { float_data_arrays_ = fda; } /// Returns a const reference to the string meta data arrays const StringDataArrays& getStringDataArrays() const; /// Returns a mutable reference to the string meta data arrays StringDataArrays& getStringDataArrays(); /// Sets the string meta data arrays void setStringDataArrays(const StringDataArrays& sda) { string_data_arrays_ = sda; } /// Returns a const reference to the integer meta data arrays const IntegerDataArrays& getIntegerDataArrays() const; /// Returns a mutable reference to the integer meta data arrays IntegerDataArrays& getIntegerDataArrays(); /// Sets the integer meta data arrays void setIntegerDataArrays(const IntegerDataArrays& ida) { integer_data_arrays_ = ida; } ///@} ///@name Sorting peaks ///@{ /** @brief Lexicographically sorts the peaks by their intensity. Sorts the peaks according to ascending intensity. Meta data arrays will be sorted accordingly. */ void sortByIntensity(bool reverse = false); /** @brief Lexicographically sorts the peaks by their position. The chromatogram is sorted with respect to position. Meta data arrays will be sorted accordingly. */ void sortByPosition(); ///Checks if all peaks are sorted with respect to ascending RT bool isSorted() const; ///@} ///@name Searching a peak or peak range ///@{ /** @brief Binary search for the peak nearest to a specific RT @param[in] rt The searched for mass-to-charge ratio searched @return Returns the index of the peak. @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. @exception Exception::Precondition is thrown if the chromatogram is empty (not only in debug mode) */ Size findNearest(CoordinateType rt) const; /** @brief Binary search for peak range begin @note Make sure the chromatogram is sorted with respect to retention time! Otherwise the result is undefined. */ Iterator RTBegin(CoordinateType rt); /** @brief Binary search for peak range begin @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. */ Iterator RTBegin(Iterator begin, CoordinateType rt, Iterator end); /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ Iterator RTEnd(CoordinateType rt); /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ Iterator RTEnd(Iterator begin, CoordinateType rt, Iterator end); /** @brief Binary search for peak range begin @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. */ ConstIterator RTBegin(CoordinateType rt) const; /** @brief Binary search for peak range begin @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. */ ConstIterator RTBegin(ConstIterator begin, CoordinateType rt, ConstIterator end) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ ConstIterator RTEnd(CoordinateType rt) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ ConstIterator RTEnd(ConstIterator begin, CoordinateType rt, ConstIterator end) const; /** @brief Binary search for peak range begin Alias for RTBegin() @note Make sure the chromatogram is sorted with respect to retention time! Otherwise the result is undefined. */ Iterator PosBegin(CoordinateType rt); /** @brief Binary search for peak range begin Alias for RTBegin() @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. */ Iterator PosBegin(Iterator begin, CoordinateType rt, Iterator end); /** @brief Binary search for peak range begin Alias for RTBegin() @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. */ ConstIterator PosBegin(CoordinateType rt) const; /** @brief Binary search for peak range begin Alias for RTBegin() @note Make sure the chromatogram is sorted with respect to RT! Otherwise the result is undefined. */ ConstIterator PosBegin(ConstIterator begin, CoordinateType rt, ConstIterator end) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for RTEnd() @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ Iterator PosEnd(CoordinateType rt); /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for RTEnd() @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ Iterator PosEnd(Iterator begin, CoordinateType rt, Iterator end); /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for RTEnd() @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ ConstIterator PosEnd(CoordinateType rt) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for RTEnd() @note Make sure the chromatogram is sorted with respect to RT. Otherwise the result is undefined. */ ConstIterator PosEnd(ConstIterator begin, CoordinateType rt, ConstIterator end) const; /** @brief Clears all data and meta data @param[in] clear_meta_data If @em true, all meta data is cleared in addition to the data. */ void clear(bool clear_meta_data); ///@} /** @brief Adds all the chromatogram peaks from another MSChromatogram and updates the metadata to indicate a merge @note Make sure BOTH chromatograms are sorted with respect to RT. Otherwise the result is undefined. @note Peak level metadata stored in float_array string_array and int_array of the destination MSChromatogram is not guaranteed to be correct after merging MZ of the destination MSChromatogram remains unchanged. @param[in,out] other A reference to the MSChromatogram to take ChromatogramPeaks from @param[in] add_meta If true, a metavalue "merged_chromatogram_mzs" is added with the m/z of @p other */ void mergePeaks(MSChromatogram& other, bool add_meta=false); protected: /// Name String name_; /// Float data arrays FloatDataArrays float_data_arrays_; /// String data arrays StringDataArrays string_data_arrays_; /// Integer data arrays IntegerDataArrays integer_data_arrays_; }; /// Print the contents to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const MSChromatogram& chrom); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/ConsensusFeature.h
.h
9,196
314
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DRange.h> #include <OpenMS/KERNEL/BaseFeature.h> #include <OpenMS/KERNEL/FeatureHandle.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OpenMSConfig.h> #include <set> namespace OpenMS { class FeatureMap; class Peak2D; /** @brief A consensus feature spanning multiple LC-MS/MS experiments. A ConsensusFeature represents analytes that have been quantified across multiple LC-MS/MS experiments. Each analyte in a ConsensusFeature is linked to its original LC-MS/MS run through a unique identifier. A consensus feature represents corresponding features in multiple feature maps. The corresponding features are represented a set of @ref FeatureHandle instances. Each ConsensusFeature "contains" zero or more FeatureHandles. @see ConsensusMap @ingroup Kernel */ class OPENMS_DLLAPI ConsensusFeature : public BaseFeature { public: ///Type definitions //@{ typedef std::set<FeatureHandle, FeatureHandle::IndexLess> HandleSetType; typedef HandleSetType::const_iterator const_iterator; typedef HandleSetType::iterator iterator; typedef HandleSetType::const_reverse_iterator const_reverse_iterator; typedef HandleSetType::reverse_iterator reverse_iterator; //@} /// Compare by size(), the number of consensus elements struct SizeLess { inline bool operator()(ConsensusFeature const& left, ConsensusFeature const& right) const { return left.size() < right.size(); } inline bool operator()(ConsensusFeature const& left, UInt64 const& right) const { return left.size() < right; } inline bool operator()(UInt64 const& left, ConsensusFeature const& right) const { return left < right.size(); } inline bool operator()(const UInt64& left, const UInt64& right) const { return left < right; } }; /// Compare by the sets of consensus elements (lexicographically) struct MapsLess { inline bool operator()(ConsensusFeature const& left, ConsensusFeature const& right) const { return std::lexicographical_compare(left.begin(), left.end(), right.begin(), right.end(), FeatureHandle::IndexLess()); } }; /// slim struct to feed the need for systematically storing of ratios. struct Ratio { Ratio() { } Ratio(const Ratio& rhs) = default; virtual ~Ratio() { } Ratio& operator=(const Ratio& rhs) = default; // @TODO: members are public, names shouldn't end in underscores double ratio_value_; String denominator_ref_; String numerator_ref_; std::vector<String> description_; //TODO ratio cv info }; ///@name Constructors and Destructor //@{ /// Default constructor ConsensusFeature(); /// Copy constructor ConsensusFeature(const ConsensusFeature& rhs) = default; /// Move constructor ConsensusFeature(ConsensusFeature&& rhs) = default; /// Constructor from basic feature explicit ConsensusFeature(const BaseFeature& feature); /** @brief Constructor with map and element index for a singleton consensus feature. Sets the consensus feature position and intensity to the values of @p element as well. */ ConsensusFeature(UInt64 map_index, const Peak2D& element, UInt64 element_index); /** @brief Constructor with map index for a singleton consensus feature. Sets the consensus feature position, intensity, charge, quality, and peptide identifications to the values of @p element as well. */ ConsensusFeature(UInt64 map_index, const BaseFeature& element); /// Assignment operator ConsensusFeature& operator=(const ConsensusFeature& rhs) = default; /// Move Assignment operator ConsensusFeature& operator=(ConsensusFeature&& rhs) = default; /// Destructor ~ConsensusFeature() override; //@} ///@name Management of feature handles //@{ /** @brief Adds all feature handles (of the CF) into the consensus feature */ void insert(const ConsensusFeature& cf); void insert(ConsensusFeature&& cf); /** @brief Adds an feature handle into the consensus feature @exception Exception::InvalidValue is thrown if a handle with the same map index and unique id already exists. */ void insert(const FeatureHandle& handle); void insert(FeatureHandle&& handle); /// Adds all feature handles in @p handle_set to this consensus feature. void insert(const HandleSetType& handle_set); void insert(HandleSetType&& handle_set); /** @brief Creates a FeatureHandle and adds it @exception Exception::InvalidValue is thrown if a handle with the same map index and unique id already exists. */ void insert(UInt64 map_index, const Peak2D& element, UInt64 element_index); /** @brief Creates a FeatureHandle and adds it @exception Exception::InvalidValue is thrown if a handle with the same map index and unique id already exists. */ void insert(UInt64 map_index, const BaseFeature& element); /// Non-mutable access to the contained feature handles const HandleSetType& getFeatures() const; /// Mutable access to a copy of the contained feature handles std::vector<FeatureHandle> getFeatureList() const; /// Set the feature set to a new one void setFeatures(HandleSetType h); //@} ///@name Accessors //@{ /// Returns the position range of the contained elements DRange<2> getPositionRange() const; /// Returns the intensity range of the contained elements DRange<1> getIntensityRange() const; //@} /** @brief Computes and updates the consensus position, intensity, and charge. The position and intensity of the contained feature handles is averaged. The most frequent charge state wins, while the tie breaking prefers smaller (absolute) charges. @note This method has to be called explicitly, <i>after</i> adding the feature handles. */ void computeConsensus(); /** @brief Computes and updates the consensus position, intensity, and charge. The m/z position is the lowest m/z value of the feature handles. The RT position and intensity of the contained feature handles is averaged. The most frequent charge state wins, while the tie breaking prefers smaller (absolute) charges. @note This method has to be called explicitly, <i>after</i> adding the feature handles. */ void computeMonoisotopicConsensus(); /** @brief Computes the uncharged parent RT & mass, assuming the handles are charge variants. The position of the feature handles (decharged) is averaged (using intensity as weights if @p intensity_weighted_averaging is true). Intensities are summed up. Charge is set to 0. Mass calculation: If the given features contain a metavalue "dc_charge_adduct_mass" then this will be used as adduct mass instead of weight(H+) * charge. @note This method has to be called explicitly, <i>after</i> adding the feature handles. @param[in] fm Input feature map, which provides additional information on the features @param[in] intensity_weighted_averaging Use unweighted averaging (default) or weighted by intensity */ void computeDechargeConsensus(const FeatureMap& fm, bool intensity_weighted_averaging = false); /** @brief Add a ratio. Connects a ratio to the ConsensusFeature. @note still experimental. consensusfeaturehandler will ignore it. */ void addRatio(const Ratio& r); /** @brief Add a ratio vector. Connects the ratios to the ConsensusFeature. @note still experimental. consensusfeaturehandler will ignore it. */ void setRatios(std::vector<Ratio>& rs); /** @brief Get the ratio vector. */ const std::vector<Ratio>& getRatios() const; /** @brief Get the ratio vector. */ std::vector<Ratio>& getRatios(); ///@name Accessors for set of FeatureHandles //@{ Size size() const; const_iterator begin() const; iterator begin(); const_iterator end() const; iterator end(); const_reverse_iterator rbegin() const; reverse_iterator rbegin(); const_reverse_iterator rend() const; reverse_iterator rend(); void clear(); bool empty() const; //@} private: HandleSetType handles_; std::vector<Ratio> ratios_; }; ///Print the contents of a ConsensusFeature to a stream OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const ConsensusFeature& cons); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/BaseFeature.h
.h
7,664
228
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Hendrik Weisser, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/RichPeak2D.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <OpenMS/METADATA/ID/IdentificationData.h> #include <optional> namespace OpenMS { class FeatureHandle; /** @brief A basic LC-MS feature. This class represents a "minimal" feature, defined by a position in RT and m/z, intensity, charge, quality, and annotated peptides. Most classes dealing with features will use the subclasses Feature or ConsensusFeature directly. However, algorithms that rely on very general characteristics of features can use this class to provide a unified solution for both "normal" features and consensus features. @ingroup Kernel */ class OPENMS_DLLAPI BaseFeature : public RichPeak2D { public: /// @name Type definitions ///@{ /// Type of quality values typedef float QualityType; /// Type of charge values typedef Int ChargeType; /// Type of feature width/FWHM (RT) typedef float WidthType; /// state of identification, use getAnnotationState() to query it enum class AnnotationState { FEATURE_ID_NONE, FEATURE_ID_SINGLE, FEATURE_ID_MULTIPLE_SAME, FEATURE_ID_MULTIPLE_DIVERGENT, SIZE_OF_ANNOTATIONSTATE }; static const std::string NamesOfAnnotationState[static_cast<size_t>(AnnotationState::SIZE_OF_ANNOTATIONSTATE)]; ///@} /// @name Constructors and Destructor ///@{ /// Default constructor BaseFeature(); /// Copy constructor BaseFeature(const BaseFeature& feature) = default; /// Move constructor /// Note: can't be "noexcept = default" because of missing noexcept on some standard containers /// so we need to explicitly define it noexcept and provide an implementation. BaseFeature(BaseFeature&& feature) noexcept : RichPeak2D(std::move(feature)) { quality_ = feature.quality_; charge_ = feature.charge_; width_ = feature.width_; // Note: will terminate program if move assignment throws because of noexcept // but we can't recover in that case anyways and we need to mark it noexcept for the move. peptides_ = std::move(feature.peptides_); primary_id_ = std::move(feature.primary_id_); id_matches_ = std::move(feature.id_matches_); } /// Copy constructor with a new map_index BaseFeature(const BaseFeature& rhs, UInt64 map_index); /// Constructor from raw data point explicit BaseFeature(const Peak2D& point); /// Constructor from raw data point with meta information explicit BaseFeature(const RichPeak2D& point); /// Constructor from a featurehandle explicit BaseFeature(const FeatureHandle& fh); /// Destructor ~BaseFeature() override; ///@} /// @name Quality methods ///@{ /// Non-mutable access to the overall quality QualityType getQuality() const; /// Set the overall quality void setQuality(QualityType q); /// Compare by quality struct QualityLess { bool operator()(const BaseFeature& left, const BaseFeature& right) const { return left.getQuality() < right.getQuality(); } bool operator()(const BaseFeature& left, const QualityType& right) const { return left.getQuality() < right; } bool operator()(const QualityType& left, const BaseFeature& right) const { return left < right.getQuality(); } bool operator()(const QualityType& left, const QualityType& right) const { return left < right; } }; ///@} /// Non-mutable access to the features width (full width at half max, FWHM) WidthType getWidth() const; /// Set the width of the feature (FWHM) void setWidth(WidthType fwhm); /// Non-mutable access to charge state const ChargeType& getCharge() const; /// Set charge state void setCharge(const ChargeType& ch); /// Assignment operator BaseFeature& operator=(const BaseFeature& rhs) = default; /// Move Assignment operator BaseFeature& operator=(BaseFeature&& rhs) & = default; /// Equality operator bool operator==(const BaseFeature& rhs) const; /// Inequality operator bool operator!=(const BaseFeature& rhs) const; /// @name Functions for dealing with identifications in legacy format ///@{ /// returns a const reference to the PeptideIdentification vector const PeptideIdentificationList& getPeptideIdentifications() const; /// returns a mutable reference to the PeptideIdentification vector PeptideIdentificationList& getPeptideIdentifications(); /// sets the PeptideIdentification vector void setPeptideIdentifications(const PeptideIdentificationList& peptides); /// sorts PeptideIdentifications, assuming they have the same scoreType. void sortPeptideIdentifications(); ///@} /// state of peptide identifications attached to this feature. If one ID has multiple hits, the output depends on the top-hit only AnnotationState getAnnotationState() const; /// @name Functions for dealing with identifications in new format ///@{ /// has a primary ID (peptide, RNA, compound) been assigned? bool hasPrimaryID() const; /** @brief Return the primary ID (peptide, RNA, compound) assigned to this feature. @throw Exception::MissingInformation if no ID was assigned */ const IdentificationData::IdentifiedMolecule& getPrimaryID() const; /// clear any primary ID that was assigned void clearPrimaryID(); /// set the primary ID (peptide, RNA, compound) for this feature void setPrimaryID(const IdentificationData::IdentifiedMolecule& id); /// immutable access to the set of matches (e.g. PSMs) with IDs for this feature const std::set<IdentificationData::ObservationMatchRef>& getIDMatches() const; /// mutable access to the set of matches (e.g. PSMs) with IDs for this feature std::set<IdentificationData::ObservationMatchRef>& getIDMatches(); /// add an ID match (e.g. PSM) for this feature void addIDMatch(IdentificationData::ObservationMatchRef ref); /*! @brief Update ID references (primary ID, matches) for this feature This is needed e.g. after the IdentificationData instance containing the referenced data has been copied. */ void updateIDReferences(const IdentificationData::RefTranslator& trans); ///@} protected: /// Overall quality measure of the feature QualityType quality_; /// Charge of the peptide represented by this feature. The default value is 0, which represents an unknown charge state. ChargeType charge_; /// Width (FWHM) for the feature. The default value is 0.0, a feature finding algorithm can compute this form the model. WidthType width_; /// PeptideIdentifications belonging to the feature PeptideIdentificationList peptides_; /// primary ID (peptide, RNA, compound) assigned to this feature std::optional<IdentificationData::IdentifiedMolecule> primary_id_; /// set of observation matches (e.g. PSMs) with IDs for this feature std::set<IdentificationData::ObservationMatchRef> id_matches_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/PeakIndex.h
.h
4,030
132
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <limits> namespace OpenMS { /** @brief Index of a peak or feature This struct can be used to store both peak or feature indices. */ struct PeakIndex { /// Default constructor. Creates an invalid peak reference inline PeakIndex() : peak((std::numeric_limits<Size>::max)()), spectrum((std::numeric_limits<Size>::max)()) {} /// Constructor that sets the peak index (for feature maps) explicit inline PeakIndex(Size lpeak) : peak(lpeak), spectrum((std::numeric_limits<Size>::max)()) {} /// Constructor that sets the peak and spectrum index (for peak maps) inline PeakIndex(Size lspectrum, Size lpeak) : peak(lpeak), spectrum(lspectrum) {} /// returns if the current peak ref is valid inline bool isValid() const { return peak != (std::numeric_limits<Size>::max)(); } /// Invalidates the current index inline void clear() { peak = (std::numeric_limits<Size>::max)(); spectrum = (std::numeric_limits<Size>::max)(); } /** @brief Access to the feature (or consensus feature) corresponding to this index This method is intended for arrays of features e.g. FeatureMap The main advantage of using this method instead accessing the data directly is that range check performed in debug mode. @exception Exception::Precondition is thrown if this index is invalid for the @p map (only in debug mode) */ template <typename FeatureMapType> const typename FeatureMapType::value_type & getFeature(const FeatureMapType & map) const { OPENMS_PRECONDITION(peak < map.size(), "Feature index exceeds map size"); return map[peak]; } /** @brief Access to a peak corresponding to this index. This method is intended for arrays of DSpectra e.g. MSExperiment The main advantage of using this method instead accessing the data directly is that range check performed in debug mode. @exception Exception::Precondition is thrown if this index is invalid for the @p map (only in debug mode) */ template <typename PeakMapType> const typename PeakMapType::PeakType & getPeak(const PeakMapType & map) const { OPENMS_PRECONDITION(spectrum < map.size(), "Spectrum index exceeds map size"); OPENMS_PRECONDITION(peak < map[spectrum].size(), "Peak index exceeds spectrum size"); return map[spectrum][peak]; } /** @brief Access to a spectrum corresponding to this index This method is intended for arrays of DSpectra e.g. MSExperiment. The main advantage of using this method instead accessing the data directly is that range check performed in debug mode. @exception Exception::Precondition is thrown if this index is invalid for the @p map (only in debug mode) */ template <typename PeakMapType> const typename PeakMapType::SpectrumType & getSpectrum(const PeakMapType & map) const { OPENMS_PRECONDITION(spectrum < map.size(), "Spectrum index exceeds map size"); return map[spectrum]; } /// Equality operator inline bool operator==(const PeakIndex & rhs) const { return peak == rhs.peak && spectrum == rhs.spectrum; } /// Inequality operator inline bool operator!=(const PeakIndex & rhs) const { return peak != rhs.peak || spectrum != rhs.spectrum; } /// Peak or feature index Size peak; /// Spectrum index Size spectrum; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/FeatureHandle.h
.h
5,893
193
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/CONCEPT/UniqueIdInterface.h> #include <OpenMS/KERNEL/Peak2D.h> #include <OpenMS/OpenMSConfig.h> #include <functional> #include <iosfwd> #include <vector> namespace OpenMS { class BaseFeature; /** @brief Representation of a Peak2D, RichPeak2D or Feature . The position and the intensity of the referenced feature are stored in the base class Peak2D. The original datapoint is referenced by the map and unique id. @ingroup Kernel */ class OPENMS_DLLAPI FeatureHandle : public Peak2D, public UniqueIdInterface { public: class FeatureHandleMutable_; ///@name Type definitions //@{ /// Charge type typedef Int ChargeType; /// Feature width type typedef float WidthType; //@} ///@name Constructors and destructor //@{ /// Default constructor FeatureHandle(); /// Constructor with map index, element index and position FeatureHandle(UInt64 map_index, const Peak2D& point, UInt64 element_index); /// Constructor from map index and basic feature FeatureHandle(UInt64 map_index, const BaseFeature& feature); /// Copy constructor FeatureHandle(const FeatureHandle& rhs); /// Assignment operator FeatureHandle& operator=(const FeatureHandle& rhs); /// Destructor ~FeatureHandle() override; /** @brief Override (most of all) constness. We provide this such that you can modify instances FeatureHandle which are stored within a ConsensusFeature. Note that std::set does not provide non-const iterators, because these could be used to change the relative ordering of the elements, and iterators are (by design/concept) unaware of their containers. Since ConsensusFeature uses the ordering by IndexLess (which see), you <i>must not</i> modify the map index of element index if there is more than one FeatureHandle stored in a ConsensusFeature. Consequently, we "disable" setMapIndex() or setElementIndex() even within FeatureHandleMutable_. On the other hand, it is perfectly safe to apply FeatureHandle::setRT(), FeatureHandle::setMZ(), FeatureHandle::setIntensity(), FeatureHandle::setCharge(), etc.. */ FeatureHandleMutable_& asMutable() const; //@} ///@name Accessors //@{ /// Returns the map index UInt64 getMapIndex() const; /// Set the map index void setMapIndex(UInt64 i); /// Sets the charge void setCharge(ChargeType charge); /// Returns the charge ChargeType getCharge() const; /// Sets the width (FWHM) void setWidth(WidthType width); /// Returns the width (FWHM) WidthType getWidth() const; //@} /// Equality operator bool operator==(const FeatureHandle& i) const; /// Equality operator bool operator!=(const FeatureHandle& i) const; /// Comparator by map and unique id struct IndexLess { bool operator()(FeatureHandle const& left, FeatureHandle const& right) const; }; protected: /// Index of the element's container UInt64 map_index_; /// Charge of the feature Int charge_; /// Width of the feature (FWHM) float width_; }; /** @brief Helper class returned by FeatureHandle::asMutable(), which see. Note that the mutators for unique id and map index are declared private. This is done because these are used by IndexLess comparator. This way it is a bit harder to use FeatureHandle::asMutable() for illegal purposes ;-) */ class OPENMS_DLLAPI FeatureHandle::FeatureHandleMutable_ : public FeatureHandle { private: using FeatureHandle::setUniqueId; using FeatureHandle::setMapIndex; FeatureHandleMutable_(); FeatureHandleMutable_(const FeatureHandleMutable_&); }; inline FeatureHandle::FeatureHandleMutable_& FeatureHandle::asMutable() const { // the const cast is to remove constness, but note that FeatureHandleMutable_ lacks some mutators // TODO use const_cast return static_cast<FeatureHandleMutable_&>(const_cast<FeatureHandle&>(*this)); } inline bool FeatureHandle::IndexLess::operator()(FeatureHandle const& left, FeatureHandle const& right) const { // if map indices are equal, use unique ids if (left.map_index_ == right.map_index_) { return left.getUniqueId() < right.getUniqueId(); } //else use map indices return left.map_index_ < right.map_index_; } ///Print the contents of a FeatureHandle to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const FeatureHandle& cons); } // namespace OpenMS // Hash function specialization for FeatureHandle namespace std { template<> struct hash<OpenMS::FeatureHandle> { std::size_t operator()(const OpenMS::FeatureHandle& fh) const noexcept { // Hash Peak2D base class components std::size_t seed = OpenMS::hash_float(fh.getRT()); OpenMS::hash_combine(seed, OpenMS::hash_float(fh.getMZ())); OpenMS::hash_combine(seed, OpenMS::hash_float(fh.getIntensity())); // Hash UniqueIdInterface component OpenMS::hash_combine(seed, OpenMS::hash_int(fh.getUniqueId())); // Hash FeatureHandle-specific members OpenMS::hash_combine(seed, OpenMS::hash_int(fh.getMapIndex())); OpenMS::hash_combine(seed, OpenMS::hash_int(fh.getCharge())); OpenMS::hash_combine(seed, OpenMS::hash_float(fh.getWidth())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/Mobilogram.h
.h
18,448
593
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/MobilityPeak1D.h> #include <OpenMS/METADATA/MetaInfoDescription.h> #include <OpenMS/KERNEL/RangeManager.h> #include <OpenMS/METADATA/DataArrays.h> #include <OpenMS/IONMOBILITY/IMTypes.h> #include <OpenMS/KERNEL/RangeManager.h> namespace OpenMS { enum class DriftTimeUnit; /** @brief The representation of a 1D ion mobilogram. It contains peak data of type MobilityPeak1D. @note For range operations, see \ref RangeUtils "RangeUtils module"! @ingroup Kernel */ class OPENMS_DLLAPI Mobilogram final : public RangeManagerContainer<RangeMobility, RangeIntensity> { public: /// Comparator for the RT of the mobilogram. struct OPENMS_DLLAPI RTLess { bool operator()(const Mobilogram& a, const Mobilogram& b) const; }; ///@name Base type definitions //@{ /// Peak type using PeakType = MobilityPeak1D; /// Coordinate (mobility) type using CoordinateType = PeakType::CoordinateType; /// Mobilogram base type using ContainerType = std::vector<PeakType>; /// RangeManager using RangeManagerContainerType = RangeManagerContainer<RangeMobility, RangeIntensity>; using RangeManagerType = RangeManager<RangeMobility, RangeIntensity>; /// Float data array vector type typedef OpenMS::DataArrays::FloatDataArray FloatDataArray ; typedef std::vector<FloatDataArray> FloatDataArrays; /// String data array vector type typedef OpenMS::DataArrays::StringDataArray StringDataArray ; typedef std::vector<StringDataArray> StringDataArrays; /// Integer data array vector type typedef OpenMS::DataArrays::IntegerDataArray IntegerDataArray ; typedef std::vector<IntegerDataArray> IntegerDataArrays; //@} ///@name Peak container iterator type definitions //@{ /// Mutable iterator using Iterator = ContainerType::iterator; using iterator = Iterator; /// Non-mutable iterator using ConstIterator = ContainerType::const_iterator; using const_iterator = ConstIterator; /// Mutable reverse iterator using ReverseIterator = ContainerType::reverse_iterator; using reverse_iterator = ReverseIterator; /// Non-mutable reverse iterator using ConstReverseIterator = ContainerType::const_reverse_iterator; using const_reverse_iterator = ConstReverseIterator; //@} /*using typename ContainerType::const_reference; using typename ContainerType::difference_type; using typename ContainerType::pointer; using typename ContainerType::reference; using typename ContainerType::size_type; using typename ContainerType::value_type;*/ // rule of 6 /// Constructor Mobilogram() = default; /// Copy constructor Mobilogram(const Mobilogram& source) = default; /// Move constructor Mobilogram(Mobilogram&&) noexcept = default; /// Assignment operator Mobilogram& operator=(const Mobilogram& source) = default; /// Move assignment operator Mobilogram& operator=(Mobilogram&&) noexcept = default; /// Destructor ~Mobilogram() = default; /// Equality operator bool operator==(const Mobilogram& rhs) const; /// Equality operator bool operator!=(const Mobilogram& rhs) const { return !(operator==(rhs)); } ///@name Export methods for std::vector<MobilityPeak1D> //@{ MobilityPeak1D& operator[](Size i) noexcept { return data_[i]; } const MobilityPeak1D& operator[](Size i) const noexcept { return data_[i]; } MobilityPeak1D& front() noexcept { return data_.front(); } const MobilityPeak1D& front() const noexcept { return data_.front(); } MobilityPeak1D& back() noexcept { return data_.back(); } const MobilityPeak1D& back() const noexcept { return data_.back(); } Iterator begin() noexcept { return data_.begin(); } ConstIterator begin() const noexcept { return data_.begin(); } ConstIterator cbegin() const noexcept { return data_.cbegin(); } Iterator end() noexcept { return data_.end(); } ConstIterator end() const noexcept { return data_.end(); } ConstIterator cend() const noexcept { return data_.cend(); } ReverseIterator rbegin() noexcept { return data_.rbegin(); } ConstReverseIterator crbegin() const { return data_.crbegin(); } ReverseIterator rend() noexcept { return data_.rend(); } ConstReverseIterator crend() const { return data_.crend(); } bool empty() const noexcept { return data_.empty(); } ConstIterator erase(ConstIterator where) noexcept { return data_.erase(where); } void push_back(MobilityPeak1D mb) { data_.push_back(mb); } MobilityPeak1D& emplace_back(MobilityPeak1D mb) { return data_.emplace_back(mb); } template<class... Args> void emplace_back(Args&&... args) { data_.emplace_back(args...); } void pop_back() { data_.pop_back(); } Iterator insert(ConstIterator where, ConstIterator first, ConstIterator last) { return data_.insert(where, first, last); } void resize(size_t new_size) { return data_.resize(new_size); } void reserve(size_t new_size) { return data_.reserve(new_size); } size_t size() const noexcept { return data_.size(); } void swap(Mobilogram& mb) noexcept { data_.swap(mb.data_); std::swap(retention_time_, mb.retention_time_); std::swap(drift_time_unit_, mb.drift_time_unit_); } //@} // Docu in base class (RangeManager) void updateRanges() override; /// Returns the retention time (in seconds) double getRT() const noexcept { return retention_time_; } /// Sets the retention time (in seconds) void setRT(double rt) noexcept { retention_time_ = rt; } /** @brief Returns the ion mobility drift time unit */ DriftTimeUnit getDriftTimeUnit() const noexcept { return drift_time_unit_; } /// returns the ion mobility drift time unit as string String getDriftTimeUnitAsString() const; /** @brief Sets the ion mobility drift time unit */ void setDriftTimeUnit(DriftTimeUnit dt) noexcept; //@} /** @name Peak data array methods These methods are used to annotate each peak in a chromatogram with meta information. It is an intermediate way between storing the information in the peak's MetaInfoInterface and deriving a new peak type with members for this information. These statements should help you chose which approach to use - Access to meta info arrays is slower than to a member variable - Access to meta info arrays is faster than to a %MetaInfoInterface - Meta info arrays are stored when using mzML format for storing */ ///@{ /// Returns a const reference to the float meta data arrays const FloatDataArrays& getFloatDataArrays() const; /// Returns a mutable reference to the float meta data arrays FloatDataArrays& getFloatDataArrays(); /// Sets the float meta data arrays void setFloatDataArrays(const FloatDataArrays& fda) { float_data_arrays_ = fda; } /// Returns a const reference to the string meta data arrays const StringDataArrays& getStringDataArrays() const; /// Returns a mutable reference to the string meta data arrays StringDataArrays& getStringDataArrays(); /// Sets the string meta data arrays void setStringDataArrays(const StringDataArrays& sda) { string_data_arrays_ = sda; } /// Returns a const reference to the integer meta data arrays const IntegerDataArrays& getIntegerDataArrays() const; /// Returns a mutable reference to the integer meta data arrays IntegerDataArrays& getIntegerDataArrays(); /// Sets the integer meta data arrays void setIntegerDataArrays(const IntegerDataArrays& ida) { integer_data_arrays_ = ida; } ///@} ///@name Sorting peaks //@{ /** @brief Lexicographically sorts the peaks by their intensity. Sorts the peaks according to ascending intensity. */ void sortByIntensity(bool reverse = false); /** @brief Lexicographically sorts the peaks by their position (mobility). The mobilogram is sorted with respect to position (mobility). */ void sortByPosition(); /// Checks if all peaks are sorted with respect to ascending mobility bool isSorted() const; /// Checks if container is sorted by a certain user-defined property. /// You can pass any lambda function with <tt>[](Size index_1, Size index_2) --> bool</tt> /// which given two indices into Mobilogram (either for peaks or data arrays) returns a weak-ordering. /// (you need to capture the Mobilogram in the lambda and operate on it, based on the indices) template<class Predicate> bool isSorted(const Predicate& lambda) const { auto value_2_index_wrapper = [this, &lambda](const PeakType& value1, const PeakType& value2) { // translate values into indices (this relies on no copies being made!) const Size index1 = (&value1) - (&this->front()); const Size index2 = (&value2) - (&this->front()); // just make sure the pointers above are actually pointing to a Peak inside our container assert(index1 < this->size()); assert(index2 < this->size()); return lambda(index1, index2); }; return std::is_sorted(this->begin(), this->end(), value_2_index_wrapper); } //@} ///@name Searching a peak or peak range ///@{ /** @brief Binary search for the peak nearest to a specific mobility @param[in] mb The target mobility value @return Returns the index of the peak. @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. @exception Exception::Precondition is thrown if the mobilogram is empty (not only in debug mode) */ Size findNearest(CoordinateType mb) const; /** @brief Binary search for the peak nearest to a specific mobility given a +/- tolerance windows @param[in] mb The target mobility value @param[in] tolerance The non-negative tolerance applied to both sides of @p mb @return Returns the index of the peak or -1 if no peak present in tolerance window or if mobilogram is empty @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. @note Peaks exactly on borders are considered in tolerance window. */ Int findNearest(CoordinateType mb, CoordinateType tolerance) const; /** @brief Search for the peak nearest to a specific mobility given two +/- tolerance windows @param[in] mb The target mobility value @param[in] tolerance_left The non-negative tolerance applied left of @p mb @param[in] tolerance_right The non-negative tolerance applied right of @p mb @return Returns the index of the peak or -1 if no peak present in tolerance window or if mobilogram is empty @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. @note Peaks exactly on borders are considered in tolerance window. @note Search for the left border is done using a binary search followed by a linear scan */ Int findNearest(CoordinateType mb, CoordinateType tolerance_left, CoordinateType tolerance_right) const; /** @brief Search for the peak with highest intensity among the peaks near to a specific mobility given two +/- tolerance windows in Th @param[in] mb The target mobility value @param[in] tolerance_left The non-negative tolerance applied left of @p mb @param[in] tolerance_right The non-negative tolerance applied right of @p mb @return Returns the index of the peak or -1 if no peak present in tolerance window or if mobilogram is empty @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. @note Peaks exactly on borders are considered in tolerance window. */ Int findHighestInWindow(CoordinateType mb, CoordinateType tolerance_left, CoordinateType tolerance_right) const; /** @brief Binary search for peak range begin @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ Iterator MBBegin(CoordinateType mb); /** @brief Binary search for peak range begin @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ Iterator MBBegin(Iterator begin, CoordinateType mb, Iterator end); /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ Iterator MBEnd(CoordinateType mb); /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ Iterator MBEnd(Iterator begin, CoordinateType mb, Iterator end); /** @brief Binary search for peak range begin @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ ConstIterator MBBegin(CoordinateType mb) const; /** @brief Binary search for peak range begin @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ ConstIterator MBBegin(ConstIterator begin, CoordinateType mb, ConstIterator end) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ ConstIterator MBEnd(CoordinateType mb) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ ConstIterator MBEnd(ConstIterator begin, CoordinateType mb, ConstIterator end) const; /** @brief Binary search for peak range begin Alias for MBBegin() @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ Iterator PosBegin(CoordinateType mb); /** @brief Binary search for peak range begin Alias for MBBegin() @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ Iterator PosBegin(Iterator begin, CoordinateType mb, Iterator end); /** @brief Binary search for peak range begin Alias for MBBegin() @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ ConstIterator PosBegin(CoordinateType mb) const; /** @brief Binary search for peak range begin Alias for MBBegin() @note Make sure the mobilogram is sorted with respect to mobility! Otherwise the result is undefined. */ ConstIterator PosBegin(ConstIterator begin, CoordinateType mb, ConstIterator end) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for MBEnd() @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ Iterator PosEnd(CoordinateType mb); /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for MBEnd() @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ Iterator PosEnd(Iterator begin, CoordinateType mb, Iterator end); /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for MBEnd() @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ ConstIterator PosEnd(CoordinateType mb) const; /** @brief Binary search for peak range end (returns the past-the-end iterator) Alias for MBEnd() @note Make sure the mobilogram is sorted with respect to mobility. Otherwise the result is undefined. */ ConstIterator PosEnd(ConstIterator begin, CoordinateType mb, ConstIterator end) const; //@} /** @brief Clears all data and ranges Will delete (clear) all peaks contained in the mobilogram */ void clear() noexcept; /// return the peak with the highest intensity. If the peak is not unique, the first peak in the container is returned. /// The function works correctly, even if the mobilogram is unsorted. ConstIterator getBasePeak() const; /// return the peak with the highest intensity. If the peak is not unique, the first peak in the container is returned. /// The function works correctly, even if the mobilogram is unsorted. Iterator getBasePeak(); /// compute the total ion count (sum of all peak intensities) PeakType::IntensityType calculateTIC() const; protected: /// the actual peaks std::vector<MobilityPeak1D> data_; /// Retention time double retention_time_ = -1; /// Drift time unit DriftTimeUnit drift_time_unit_ = DriftTimeUnit::NONE; /// Float data arrays FloatDataArrays float_data_arrays_; /// String data arrays StringDataArrays string_data_arrays_; /// Integer data arrays IntegerDataArrays integer_data_arrays_; }; OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Mobilogram& mb); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/SpectrumHelper.h
.h
8,116
213
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/MATH/StatisticFunctions.h> #include <OpenMS/METADATA/DataArrays.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/CONCEPT/LogStream.h> namespace OpenMS { class String; /** @brief Helper functions for MSSpectrum and MSChromatogram. @ingroup Kernel */ /// Returns an iterator to the first data array with the given name. /// The end iterator is returned in case no data array with given name exists. template <class DataArrayT> typename DataArrayT::iterator getDataArrayByName(DataArrayT& a, const String& name) { typename DataArrayT::iterator it = a.begin(); for (; it != a.end(); ++it) { if (it->getName() == name) return it; } return it; } template <class DataArrayT> typename DataArrayT::const_iterator getDataArrayByName(const DataArrayT& a, const String& name) { typename DataArrayT::const_iterator it = a.begin(); for (; it != a.end(); ++it) { if (it->getName() == name) return it; } return it; } /// remove all peaks EXCEPT in the given range template <typename PeakContainerT> void removePeaks( PeakContainerT& p, const double pos_start, const double pos_end, const bool ignore_data_arrays = false ) { typename PeakContainerT::iterator it_start = p.PosBegin(pos_start); typename PeakContainerT::iterator it_end = p.PosEnd(pos_end); if (!ignore_data_arrays) { Size hops_left = std::distance(p.begin(), it_start); Size n_elems = std::distance(it_start, it_end); typename PeakContainerT::StringDataArrays& SDAs = p.getStringDataArrays(); for (DataArrays::StringDataArray& sda : SDAs) { if (sda.size() == p.size()) { sda.erase(sda.begin() + hops_left + n_elems, sda.end()); sda.erase(sda.begin(), sda.begin() + hops_left); } } typename PeakContainerT::FloatDataArrays& FDAs = p.getFloatDataArrays(); for (DataArrays::FloatDataArray& fda : FDAs) { if (fda.size() == p.size()) { fda.erase(fda.begin() + hops_left + n_elems, fda.end()); fda.erase(fda.begin(), fda.begin() + hops_left); } } typename PeakContainerT::IntegerDataArrays& IDAs = p.getIntegerDataArrays(); for (DataArrays::IntegerDataArray& ida : IDAs) { if (ida.size() == p.size()) { ida.erase(ida.begin() + hops_left + n_elems, ida.end()); ida.erase(ida.begin(), ida.begin() + hops_left); } } } if (it_start == it_end) { // no elements left p.resize(0); } else { // if it_end != it_start, the second erase operation is safe p.erase(it_end, p.end()); p.erase(p.begin(), it_start); } } template <typename PeakContainerT> void subtractMinimumIntensity(PeakContainerT& p) { if (p.empty()) return; typename PeakContainerT::iterator it = std::min_element(p.begin(), p.end(), [](typename PeakContainerT::PeakType& a, typename PeakContainerT::PeakType& b) { return a.getIntensity() < b.getIntensity(); }); const double rebase = - it->getIntensity(); for (typename PeakContainerT::PeakType& peak : p) { peak.setIntensity(peak.getIntensity() + rebase); } // Note: data arrays are not updated } /** * @brief Possible methods for merging peak intensities. * * @see makePeakPositionUnique() **/ enum class IntensityAveragingMethod : int { MEDIAN, MEAN, SUM, MIN, MAX }; /** * @brief Make peak positions unique. * * A peak container may contain multiple peaks with the same position, i.e. either * an MSSpectrum containing peaks with the same m/z position, or an MSChromatogram * containing peaks with identical RT position. One scenario where this might happen * is when multiple spectra are merged to a single one. * * The method combines peaks with the same position to a single one with the * intensity determined by method m. * * @param[in] p The peak container to be manipulated. * @param[in] m The method for determining peak intensity from peaks with same position (median, mean, sum, min, max). **/ template <typename PeakContainerT> void makePeakPositionUnique(PeakContainerT& p, const IntensityAveragingMethod m = IntensityAveragingMethod::MEDIAN) { if (!p.getFloatDataArrays().empty() || !p.getStringDataArrays().empty() || !p.getIntegerDataArrays().empty()) { OPENMS_LOG_WARN << "Warning: data arrays are being ignored in the method SpectrumHelper::makePeakPositionUnique().\n"; } if (p.empty()) return; p.sortByPosition(); double current_position = p.begin()->getPos(); PeakContainerT p_new; double intensity_new(0); std::vector<double> intensities_at_same_position; for (typename PeakContainerT::PeakType& peak : p) { if (peak.getPos() > current_position) { // add a peak to the new peak container switch(m) { case IntensityAveragingMethod::MEDIAN: intensity_new = Math::median(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::MEAN: intensity_new = Math::mean(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::SUM: intensity_new = Math::sum(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::MIN: intensity_new = *std::min_element(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::MAX: intensity_new = *std::max_element(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; } typename PeakContainerT::PeakType peak_new(current_position, intensity_new); p_new.push_back(peak_new); current_position = peak.getPos(); intensities_at_same_position.clear(); } intensities_at_same_position.push_back(peak.getIntensity()); } // add the very last peak to the new peak container switch(m) { case IntensityAveragingMethod::MEDIAN : intensity_new = Math::median(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::MEAN : intensity_new = Math::mean(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::SUM : intensity_new = Math::sum(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::MIN : intensity_new = *std::min_element(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; case IntensityAveragingMethod::MAX : intensity_new = *std::max_element(intensities_at_same_position.begin(), intensities_at_same_position.end()); break; } typename PeakContainerT::PeakType peak_new(current_position, intensity_new); p_new.push_back(peak_new); std::swap(p_new, p); } /** * @brief Copies only the meta data contained in the input spectrum to the output spectrum. * * @note Actual data is not copied. * * @param[in] input The input spectrum. * @param[out] output The output spectrum (will be cleared and will contain all metadata of the input spectrum). * @param[in] clear_spectrum Whether the output spectrum should be cleared first (all raw data and data arrays will be deleted) **/ OPENMS_DLLAPI void copySpectrumMeta(const MSSpectrum & input, MSSpectrum & output, bool clear_spectrum = true); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/ConversionHelper.h
.h
2,975
81
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/FeatureMap.h> namespace OpenMS { class OPENMS_DLLAPI MapConversion { public: /** @brief Similar to @p convert for FeatureMaps. Only the @p n most intense elements are copied. Currently PeakMap does not have a unique id but ConsensusMap has one, so we assign a new one here. @param[in] input_map_index The index of the input map. @param[in,out] input_map The input map to be converted. @param[out] output_map The resulting ConsensusMap. @param[in] n The maximum number of elements to be copied. */ static void convert(UInt64 const input_map_index, PeakMap& input_map, ConsensusMap& output_map, Size n = -1); /** @brief Convert a ConsensusMap to a FeatureMap (of any feature type). The previous content of output_map is cleared. UID's of the elements and the container is copied if the @p keep_uids flag is set. @param[in] input_map The container to be converted. @param[in] keep_uids Shall the UID's of the elements and the container be kept or created anew @param[out] output_map The resulting ConsensusMap. */ static void convert(ConsensusMap const& input_map, const bool keep_uids, FeatureMap& output_map); /** @brief Convert a FeatureMap (of any feature type) to a ConsensusMap. Each ConsensusFeature contains a map index, so this has to be given as well. The previous content of @p output_map is cleared. An arguable design decision is that the unique id of the FeatureMap is copied (!) to the ConsensusMap, because that is the way it is meant to be used in the algorithms. Only the first (!) @p n elements are copied. (This parameter exists mainly for compatibility with @p convert for MSExperiments. To use it in a meaningful way, apply one of the sorting methods to @p input_map beforehand.) @param[in] input_map_index The index of the input map. @param[in] input_map The container to be converted. @param[out] output_map The resulting ConsensusMap. @param[in] n The maximum number of elements to be copied. */ static void convert(UInt64 const input_map_index, FeatureMap const& input_map, ConsensusMap& output_map, Size n = -1); }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/Feature.h
.h
6,162
187
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/ConvexHull2D.h> #include <OpenMS/KERNEL/BaseFeature.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <vector> namespace OpenMS { /** @brief An LC-MS feature. The Feature class is used to describe the two-dimensional signal caused by an analyte. It can store a charge state and a list of peptide identifications (for peptides). The area occupied by the Feature in the LC-MS data set is represented by a list of convex hulls (one for each isotopic peak). There is also a convex hull for the entire Feature. The model description can store the parameters of a two-dimensional theoretical model of the underlying signal in LC-MS. Currently, non-peptide compounds are also represented as features. By convention in %OpenMS, the position of a feature is defined as maximum position of the model for the retention time dimension and the mass of the monoisotopic peak for the m/z dimension. The intensity of a feature is (proportional to) its total ion count. Feature is derived from RichPeak2D. Also inherited is a MetaInfoInterface. Features as usually are contained in a FeatureMap. See also FeatureHandle and ConsensusFeature. @ingroup Kernel */ class OPENMS_DLLAPI Feature : public BaseFeature { public: /** @name Constructors and Destructor */ //@{ /// Default constructor Feature(); /// explicit C'tor from BaseFeature explicit Feature(const BaseFeature& base); /// Copy constructor Feature(const Feature& feature); /// Move constructor Feature(Feature&&) noexcept; /// Destructor ~Feature() override; //@} /// @name Model and quality methods //@{ /// Non-mutable access to the overall quality QualityType getOverallQuality() const; /// Set the overall quality void setOverallQuality(QualityType q); /// Non-mutable access to the quality in dimension c QualityType getQuality(Size index) const; /// Set the quality in dimension c void setQuality(Size index, QualityType q); /// Compare by quality typedef QualityLess OverallQualityLess; //@} ///@name Convex hulls and bounding box //@{ /// Non-mutable access to the convex hulls const std::vector<ConvexHull2D>& getConvexHulls() const; /// Mutable access to the convex hulls of single mass traces std::vector<ConvexHull2D>& getConvexHulls(); /// Set the convex hulls of single mass traces void setConvexHulls(const std::vector<ConvexHull2D>& hulls); /** @brief Returns the overall convex hull of the feature (calculated from the convex hulls of the mass traces) @note the bounding box of the feature can be accessed through the returned convex hull */ ConvexHull2D& getConvexHull() const; /// Returns if the mass trace convex hulls of the feature enclose the position specified by @p rt and @p mz bool encloses(double rt, double mz) const; //@} /// Assignment operator Feature& operator=(const Feature& rhs); /// Move assignment operator Feature& operator=(Feature&&) & noexcept; /// Equality operator bool operator==(const Feature& rhs) const; /// immutable access to subordinate features const std::vector<Feature>& getSubordinates() const; /// mutable access to subordinate features std::vector<Feature>& getSubordinates(); /// mutable access to subordinate features void setSubordinates(const std::vector<Feature>& rhs); /** @brief Applies a member function of Type to the feature (including subordinates). The returned values are accumulated. <b>Example:</b> The following will print the number of features (parent feature and subordinates) with invalid unique ids: @code Feature f; (...) std::cout << f.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId) << std::endl; @endcode See e.g. UniqueIdInterface for what else can be done this way. */ template <typename Type> Size applyMemberFunction(Size (Type::* member_function)()) { Size assignments = 0; assignments += ((*this).*member_function)(); for (std::vector<Feature>::iterator iter = subordinates_.begin(); iter != subordinates_.end(); ++iter) { assignments += iter->applyMemberFunction(member_function); } return assignments; } /// The "const" variant. template <typename Type> Size applyMemberFunction(Size (Type::* member_function)() const) const { Size assignments = 0; assignments += ((*this).*member_function)(); for (std::vector<Feature>::const_iterator iter = subordinates_.begin(); iter != subordinates_.end(); ++iter) { assignments += iter->applyMemberFunction(member_function); } return assignments; } /*! @brief Update ID references (primary ID, input matches) for this feature and any subfeatures This is needed e.g. after the IdentificationData instance containing the referenced data has been copied. */ void updateAllIDReferences(const IdentificationData::RefTranslator& trans); protected: /// Quality measures for each dimension QualityType qualities_[2]; /// Array of convex hulls (one for each mass trace) std::vector<ConvexHull2D> convex_hulls_; /// Flag that indicates if the overall convex hull needs to be recomputed (i.e. mass trace convex hulls were modified) mutable bool convex_hulls_modified_{}; /// Overall convex hull of the feature mutable ConvexHull2D convex_hull_; /// subordinate features (e.g. features that represent alternative explanations, usually with lower quality) std::vector<Feature> subordinates_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/StandardTypes.h
.h
967
49
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> namespace OpenMS { class MSSpectrum; class MSChromatogram; class Mobilogram; class MSExperiment; //@{ /** @brief Spectrum consisting of raw data points or peaks. Meta information includes retention time and MS-level. @ingroup Kernel */ typedef MSSpectrum PeakSpectrum; /** @brief Two-dimensional map of raw data points or peaks. @ingroup Kernel */ typedef MSExperiment PeakMap; /** @brief Chromatogram consisting of raw data points or peaks @ingroup Kernel */ typedef MSChromatogram Chromatogram; //@} }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/MSExperiment.h
.h
55,060
1,349
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Tom Waschischeck $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/KERNEL/AreaIterator.h> #include <OpenMS/KERNEL/ChromatogramRangeManager.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/SpectrumRangeManager.h> #include <OpenMS/METADATA/ExperimentalSettings.h> #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <vector> namespace OpenMS { class Peak1D; class ChromatogramPeak; using MSRun = MSExperiment; /** @brief In-Memory representation of a mass spectrometry run. This representation of an MS run is organized as list of spectra and chromatograms and provides an in-memory representation of popular mass-spectrometric file formats such as mzXML or mzML. The meta-data associated with an experiment is contained in ExperimentalSettings (by inheritance) while the raw data (as well as spectra and chromatogram level meta data) is stored in objects of type MSSpectrum and MSChromatogram, which are accessible through the getSpectrum and getChromatogram functions. @note For range operations, see \ref RangeUtils "RangeUtils module"! @note Some of the meta data is associated with the spectra directly (e.g. DataProcessing) and therefore the spectra need to be present to retain this information. @note For an on-disc representation of an MS experiment, see OnDiskExperiment. @ingroup Kernel */ class OPENMS_DLLAPI MSExperiment final : public ExperimentalSettings { public: typedef Peak1D PeakT; typedef ChromatogramPeak ChromatogramPeakT; /// @name Base type definitions //@{ /// Peak type typedef PeakT PeakType; /// Chromatogram peak type typedef ChromatogramPeakT ChromatogramPeakType; /// Coordinate type of peak positions typedef PeakType::CoordinateType CoordinateType; /// Intensity type of peaks typedef PeakType::IntensityType IntensityType; /// Combined RangeManager type to store the overall range of all spectra and chromatograms (for backward compatibility) typedef RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility> RangeManagerType; /// Spectrum range manager type for tracking ranges with MS level separation typedef SpectrumRangeManager SpectrumRangeManagerType; /// Chromatogram range manager type for tracking chromatogram-specific ranges typedef ChromatogramRangeManager ChromatogramRangeManagerType; /// Spectrum Type typedef MSSpectrum SpectrumType; /// Chromatogram type typedef MSChromatogram ChromatogramType; /// STL base class type typedef std::vector<SpectrumType> Base; //@} /// @name Iterator type definitions //@{ /// Mutable iterator typedef std::vector<SpectrumType>::iterator Iterator; /// Non-mutable iterator typedef std::vector<SpectrumType>::const_iterator ConstIterator; /// Mutable area iterator type (for traversal of a rectangular subset of the peaks) typedef Internal::AreaIterator<PeakT, PeakT&, PeakT*, Iterator, SpectrumType::Iterator> AreaIterator; /// Immutable area iterator type (for traversal of a rectangular subset of the peaks) typedef Internal::AreaIterator<const PeakT, const PeakT&, const PeakT*, ConstIterator, SpectrumType::ConstIterator> ConstAreaIterator; //@} /// @name Delegations of calls to the vector of MSSpectra // Attention: these refer to the spectra vector only! //@{ typedef Base::value_type value_type; typedef Base::iterator iterator; typedef Base::const_iterator const_iterator; /// Constructor MSExperiment(); /// Copy constructor MSExperiment(const MSExperiment & source); /// Move constructor MSExperiment(MSExperiment&&) = default; /// Assignment operator MSExperiment & operator=(const MSExperiment & source); /// Move assignment operator MSExperiment& operator=(MSExperiment&&) & = default; /// Assignment operator MSExperiment & operator=(const ExperimentalSettings & source); /// D'tor ~MSExperiment() override; /// Equality operator bool operator==(const MSExperiment & rhs) const; /// Equality operator bool operator!=(const MSExperiment & rhs) const; /// The number of spectra Size size() const noexcept; /// Resize to @p n spectra void resize(Size n); /// Are there any spectra (does not consider chromatograms) bool empty() const noexcept; /// Reserve space for @p n spectra void reserve(Size n); /// Random access to @p n'th spectrum SpectrumType& operator[](Size n); /// Random access to @p n'th spectrum const SpectrumType& operator[](Size n) const; Iterator begin() noexcept; ConstIterator begin() const noexcept; ConstIterator cbegin() const noexcept; Iterator end(); ConstIterator end() const noexcept; ConstIterator cend() const noexcept; //@} // Aliases / chromatograms void reserveSpaceSpectra(Size s); void reserveSpaceChromatograms(Size s); ///@name Conversion to/from 2D data //@{ /** @brief Reads out a 2D Spectrum Container can be a PeakArray or an STL container of peaks which supports push_back(), end() and back() */ template <class Container> void get2DData(Container& cont) const { for (typename Base::const_iterator spec = spectra_.begin(); spec != spectra_.end(); ++spec) { if (spec->getMSLevel() != 1) { continue; } typename Container::value_type s; // explicit object here, since instantiation within push_back() fails on VS<12 for (typename SpectrumType::const_iterator it = spec->begin(); it != spec->end(); ++it) { cont.push_back(s); cont.back().setRT(spec->getRT()); cont.back().setMZ(it->getMZ()); cont.back().setIntensity(it->getIntensity()); } } } /** @brief Assignment of a data container with RT and MZ to an MSExperiment Fill MSExperiment with data. Note that all data present (including meta-data) will be deleted prior to adding new data! @param[in] container An iterable type whose elements support getRT(), getMZ() and getIntensity() @exception Exception::Precondition is thrown if the container is not sorted according to retention time (in debug AND release mode) */ template <class Container> void set2DData(const Container& container) { set2DData<false, Container>(container); } /** @brief Assignment of a data container with RT and MZ to an MSExperiment Fill MSExperiment with data. Note that all data present (including meta-data) will be deleted prior to adding new data! @param[in] container An iterable type whose elements support getRT(), getMZ() and getIntensity() @param[in] store_metadata_names [MetaInfoInterface input only] Names of metadata arrays which should be created; data is filled from the metainfointerface of each element of the input container. Currently, only float data is supported! @exception Exception::Precondition is thrown if the container is not sorted according to retention time (in debug AND release mode) */ template <class Container> void set2DData(const Container& container, const StringList& store_metadata_names) { // clean up the container first clear(true); SpectrumType* spectrum = nullptr; typename PeakType::CoordinateType current_rt = -std::numeric_limits<typename PeakType::CoordinateType>::max(); for (typename Container::const_iterator iter = container.begin(); iter != container.end(); ++iter) { // check if the retention time has changed if (current_rt != iter->getRT() || spectrum == nullptr) { // append new spectrum if (current_rt > iter->getRT()) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Input container is not sorted!"); } current_rt = iter->getRT(); spectrum = createSpec_(current_rt, store_metadata_names); } // add either data point or mass traces (depending on template argument value) ContainerAdd_<typename Container::value_type, false>::addData_(spectrum, &(*iter), store_metadata_names); } } /** @brief Assignment of a data container with RT and MZ to an MSExperiment Fill MSExperiment with data. Note that all data present (including meta-data) will be deleted prior to adding new data! @tparam Container An iterable type whose elements support getRT(), getMZ() and getIntensity() @tparam add_mass_traces If true, each container element is searched for the metavalue "num_of_masstraces". If found, "masstrace_intensity" (X>=0) meta values are added as data points (with 13C spacing). This is useful for, e.g., FF-Metabo output. Note that the actual feature will NOT be added if mass traces are found (since MT0 is usually identical) @param[in] container The input data with RT,m/z and intensity @exception Exception::Precondition is thrown if the container is not sorted according to retention time (in debug AND release mode) OR a "masstrace_intensity" value is expected but not found */ template <bool add_mass_traces, class Container> void set2DData(const Container& container) { // clean up the container first clear(true); SpectrumType* spectrum = nullptr; typename PeakType::CoordinateType current_rt = -std::numeric_limits<typename PeakType::CoordinateType>::max(); for (typename Container::const_iterator iter = container.begin(); iter != container.end(); ++iter) { // check if the retention time has changed if (current_rt != iter->getRT() || spectrum == nullptr) { // append new spectrum if (current_rt > iter->getRT()) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Input container is not sorted!"); } current_rt = iter->getRT(); spectrum = createSpec_(current_rt); } // add either data point or mass traces (depending on template argument value) ContainerAdd_<typename Container::value_type, add_mass_traces>::addData_(spectrum, &(*iter)); } } //@} ///@name Iterating ranges and areas //@{ /// Returns an area iterator for @p area AreaIterator areaBegin(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, UInt ms_level = 1); /// Returns an area iterator for all peaks in @p range. If a dimension is empty(), it is ignored (i.e. does not restrict the area) AreaIterator areaBegin(const RangeManagerType& range, UInt ms_level = 1); /// Returns an invalid area iterator marking the end of an area AreaIterator areaEnd(); /// Returns a non-mutable area iterator for @p area ConstAreaIterator areaBeginConst(CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, UInt ms_level = 1) const; /// Returns a non-mutable area iterator for all peaks in @p range. If a dimension is empty(), it is ignored (i.e. does not restrict the area) ConstAreaIterator areaBeginConst(const RangeManagerType& range, UInt ms_level = 1) const; /// Returns a non-mutable invalid area iterator marking the end of an area ConstAreaIterator areaEndConst() const; /* @brief Retrieves the peak data in the given mz-rt range and store data spectrum-wise in separate arrays. * * For fast pyOpenMS access to peak data in format: [rt, [mz, intensity]] * * @param[in] min_rt The minimum retention time. * @param[in] max_rt The maximum retention time. * @param[in] min_mz The minimum m/z value. * @param[in] max_mz The maximum m/z value. * @param[in] ms_level The MS level of the spectra to consider. * @param[out] rt The vector to store the retention times in. * @param[out] mz The vector to store the m/z values in. * @param[out] intensity The vector to store the intensities in. */ void get2DPeakDataPerSpectrum( CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<std::vector<float>>& mz, std::vector<std::vector<float>>& intensity) const; /* @brief Retrieves the peak data in the given mz-rt range and store data spectrum-wise in separate arrays. * * For fast pyOpenMS access to MS1 peak data in format: [rt, [mz, intensity, ion mobility]] * * @param[in] min_rt The minimum retention time. * @param[in] max_rt The maximum retention time. * @param[in] min_mz The minimum m/z value. * @param[in] max_mz The maximum m/z value. * @param[in] ms_level The MS level of the spectra to consider. * @param[out] rt The vector to store the retention times in. * @param[out] mz The vector to store the m/z values in. * @param[out] intensity The vector to store the intensities in. * @param[out] ion_mobility The vector to store the ion mobility values in. */ void get2DPeakDataIMPerSpectrum( CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<std::vector<float>>& mz, std::vector<std::vector<float>>& intensity, std::vector<std::vector<float>>& ion_mobility) const; /* @brief Retrieves the peak data in the given mz-rt range and store in separate arrays. * * For fast pyOpenMS access to MS1 peak data in format: [rt, mz, intensity] * * @param[in] min_rt The minimum retention time. * @param[in] max_rt The maximum retention time. * @param[in] min_mz The minimum m/z value. * @param[in] max_mz The maximum m/z value. * @param[in] ms_level The MS level of the spectra to consider. * @param[out] rt The vector to store the retention times in. * @param[out] mz The vector to store the m/z values in. * @param[out] intensity The vector to store the intensities in. */ void get2DPeakData( CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<float>& mz, std::vector<float>& intensity) const; /* @brief Retrieves the peak data in the given mz-rt range and store in separate arrays. * * For fast pyOpenMS access to MS1 peak data in format: [rt, mz, intensity, ion mobility] * * @param[in] min_rt The minimum retention time. * @param[in] max_rt The maximum retention time. * @param[in] min_mz The minimum m/z value. * @param[in] max_mz The maximum m/z value. * @param[in] ms_level The MS level of the spectra to consider. * @param[out] rt The vector to store the retention times in. * @param[out] mz The vector to store the m/z values in. * @param[out] intensity The vector to store the intensities in. */ void get2DPeakDataIM( CoordinateType min_rt, CoordinateType max_rt, CoordinateType min_mz, CoordinateType max_mz, Size ms_level, std::vector<float>& rt, std::vector<float>& mz, std::vector<float>& intensity, std::vector<float>& ion_mobility) const; /** * @brief Calculates the sum of intensities for a range of elements. * * @tparam Iterator The iterator type. * @param[in] begin The iterator pointing to the beginning of the range. * @param[in] end The iterator pointing to the end of the range. * @return The sum of intensities. * * @throws static assert fails if the iterator value type does not have a `getIntensity()` member function. */ struct SumIntensityReduction { template <typename Iterator> auto operator()(Iterator begin, Iterator end) const { // Static assert to verify iterator type has intensity accessor using ValueType = typename std::iterator_traits<Iterator>::value_type; using IntensityType = decltype(std::declval<ValueType>().getIntensity()); static_assert(std::is_member_function_pointer_v<decltype(&ValueType::getIntensity)>, "Iterator value type must have getIntensity() member function"); IntensityType sum{}; for (auto it = begin; it != end; ++it) { sum += it->getIntensity(); } return sum; } }; /** * @brief Aggregates data over specified m/z and RT ranges at a given MS level using a custom reduction function. * * This function processes spectra at a specified MS level and aggregates data within specified m/z (mass-to-charge) * and RT (retention time) ranges. For each m/z and RT range, it computes a result using the provided m/z reduction * function over the peaks that fall within the range. * * The results are organized in a two-dimensional vector, where each sub-vector corresponds to a particular m/z and RT * range, and contains the aggregated results for each spectrum that falls within that RT range. * * This function allows for flexible aggregation of data within specified m/z and RT ranges, and is useful for XIC extraction. * * @tparam MzReductionFunctionType * A callable type (function, lambda, or functor) that takes two iterators (`begin_it` and `end_it`) over peaks * (`MSSpectrum::ConstIterator`) and returns a `CoordinateType`. The function defines how to reduce or aggregate * the peaks within the specified m/z range (e.g., summing intensities, computing the mean m/z, etc.). * * @param[in] mz_rt_ranges * A vector of pairs of `RangeMZ` and `RangeRT` specifying the m/z and RT ranges over which to aggregate data. * Each pair defines a rectangular region in the m/z-RT plane. The ranges are processed in the order supplied and * are not modified by this function. * * @param[in] ms_level * The MS level of the spectra to be processed. Only spectra matching this MS level will be considered in the aggregation. * * @param[in] func_mz_reduction * A function or functor that performs the m/z reduction. It should have the signature: * `CoordinateType func_mz_reduction(MSSpectrum::ConstIterator begin_it, MSSpectrum::ConstIterator end_it);` * The function receives iterators to the beginning and end of the peaks within the m/z range for a specific spectrum. * It should process these peaks and return a single `CoordinateType` value representing the aggregated result. * * @return * A vector of vectors of `MSExperiment::CoordinateType`. Each sub-vector corresponds to an m/z and RT range in * `mz_rt_ranges`, and contains the aggregated results for each spectrum that falls within that RT range. * The size of each sub-vector equals the number of spectra that overlap with the RT range. * * @note * - If `mz_rt_ranges` is empty or there are no spectra at the specified MS level, the function returns an empty vector. * - The function uses OpenMP for parallelization over spectra. Ensure that your reduction function is thread-safe. * - The aggregation is performed only on the peaks that fall within both the specified m/z and RT ranges. * - This methods works best with larger number of m/z and RT ranges and a large number of spectra. * * @warning * - The provided `func_mz_reduction` must be able to handle empty ranges (i.e., when `begin_it == end_it`). * - The function does not reorder or otherwise mutate `mz_rt_ranges`; pass a pre-sorted range if a particular order is required. * * @exception None */ template<class MzReductionFunctionType> std::vector<std::vector<MSExperiment::CoordinateType>> aggregate( const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges, unsigned int ms_level, MzReductionFunctionType func_mz_reduction) const { // Early exit if there are no ranges if (mz_rt_ranges.empty()) { // likely an error, but we return an empty vector instead of throwing an exception for now return {}; } // Create a view of the spectra with given MS level std::vector<std::reference_wrapper<const MSSpectrum>> spectra_view; spectra_view.reserve(spectra_.size()); std::copy_if(spectra_.begin(), spectra_.end(), std::back_inserter(spectra_view), [ms_level](const auto& spec) { return spec.getMSLevel() == ms_level; }); // Early exit if there are no spectra with the given MS level if (spectra_view.empty()) { // could be valid use or an error -> we return an empty vector return {}; } // Get the indices of the spectra covered by the RT ranges by considering the MS level // If start and stop are the same, the range is empty auto getCoveredSpectra = []( const std::vector<std::reference_wrapper<const MSSpectrum>>& spectra_view, const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges) -> std::vector<std::pair<size_t, size_t>> { std::vector<std::pair<size_t, size_t>> res; res.reserve(mz_rt_ranges.size()); for (const auto & mz_rt : mz_rt_ranges) { // std::cout << "rt range: " << mz_rt.second.getMin() << " - " << mz_rt.second.getMax() << std::endl; // std::cout << "specs start:" << spectra_view[0].get().getRT() << " specs end:" << spectra_view[spectra_view.size() - 1].get().getRT() << std::endl; auto start_it = std::lower_bound(spectra_view.begin(), spectra_view.end(), mz_rt.second.getMin(), [](const auto& spec, double rt) { return spec.get().getRT() < rt; }); auto stop_it = std::upper_bound(spectra_view.begin(), spectra_view.end(), mz_rt.second.getMax(), [](double rt, const auto& spec) { return rt < spec.get().getRT(); }); res.emplace_back( std::distance(spectra_view.begin(), start_it), std::distance(spectra_view.begin(), stop_it) ); // std::cout << "start: " << std::distance(spectra_view.begin(), start_it) << " stop: " << std::distance(spectra_view.begin(), stop_it) << std::endl; } return res; }; // For each range, gets (spectrum start index, spectrum stop index). The spectra covered by each RT range. const std::vector<std::pair<size_t, size_t>> rt_ranges_idcs = getCoveredSpectra(spectra_view, mz_rt_ranges); // Initialize result vector std::vector<std::vector<MSExperiment::CoordinateType>> result(mz_rt_ranges.size()); // Initialize counts per spectrum index and total mappings std::vector<std::vector<size_t>> spec_idx_to_range_idx(spectra_view.size()); // Build spectrum to range index mapping for (size_t i = 0; i < rt_ranges_idcs.size(); ++i) { const auto& [start, stop] = rt_ranges_idcs[i]; result[i].resize(stop - start); // std::cout << "start: " << start << " stop: " << stop << std::endl; for (size_t j = start; j < stop; ++j) { spec_idx_to_range_idx[j].push_back(i); } } #pragma omp parallel for schedule(dynamic) for (Int64 i = 0; i < (Int64)spec_idx_to_range_idx.size(); ++i) // OpenMP on windows still requires signed loop variable { if (spec_idx_to_range_idx[i].empty()) continue; // no ranges for this spectrum? skip it const auto& spec = spectra_view[i].get(); auto spec_begin = spec.cbegin(); auto spec_end = spec.cend(); for (size_t range_idx : spec_idx_to_range_idx[i]) { const auto& mz_range = mz_rt_ranges[range_idx].first; // Find data points within MZ range auto start_it = spec.PosBegin(spec_begin, mz_range.getMinMZ(), spec_end); auto end_it = start_it; while (end_it != spec_end && end_it->getPosition() <= mz_range.getMaxMZ()) { ++end_it; } // std::cout << "calculating reduction on range: " << range_idx << " for spectrum: " << i << " and peaks " << std::distance(spec.begin(), start_it) << " - " << std::distance(spec.begin(), end_it) << std::endl; // Calculate result using provided reduction function result[range_idx][i - rt_ranges_idcs[range_idx].first] = func_mz_reduction(start_it, end_it); } } return result; } // Overload without func_mz_reduction parameter (default to SumIntensityReduction). Needed because of template deduction issues std::vector<std::vector<MSExperiment::CoordinateType>> aggregate( const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges, unsigned int ms_level) const { return aggregate(mz_rt_ranges, ms_level, SumIntensityReduction()); } /** * @brief Extracts extracted ion chromatograms (XICs) from the MSExperiment. * * This function takes a vector of mz_rt_ranges, an ms_level, and a MzReductionFunctionType * and extracts the XICs from the MSExperiment based on the given parameters. * * @param[in] mz_rt_ranges A vector of pairs of RangeMZ and RangeRT representing the m/z and retention time ranges. * @param[in] ms_level The MS level of the spectra to consider. * @param[in] func_mz_reduction The MzReductionFunctionType used to reduce the m/z values. * * @return A vector of MSChromatogram objects representing the extracted XICs. */ template<class MzReductionFunctionType> std::vector<MSChromatogram> extractXICs( const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges, unsigned int ms_level, MzReductionFunctionType func_mz_reduction) const { // Early exit if there are no ranges if (mz_rt_ranges.empty()) { // likely an error, but we return an empty vector instead of throwing an exception for now return {}; } // Create a view of the spectra with given MS level std::vector<std::reference_wrapper<const MSSpectrum>> spectra_view; spectra_view.reserve(spectra_.size()); std::copy_if(spectra_.begin(), spectra_.end(), std::back_inserter(spectra_view), [ms_level](const auto& spec) { return spec.getMSLevel() == ms_level; }); // Early exit if there are no spectra with the given MS level if (spectra_view.empty()) { // could be valid use or an error -> we return an empty vector return {}; } // Get the indices of the spectra covered by the RT ranges by considering the MS level // If start and stop are the same, the range is empty auto getCoveredSpectra = []( const std::vector<std::reference_wrapper<const MSSpectrum>>& spectra_view, const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges) -> std::vector<std::pair<size_t, size_t>> { std::vector<std::pair<size_t, size_t>> res; res.reserve(mz_rt_ranges.size()); for (const auto & mz_rt : mz_rt_ranges) { auto start_it = std::lower_bound(spectra_view.begin(), spectra_view.end(), mz_rt.second.getMin(), [](const auto& spec, double rt) { return spec.get().getRT() < rt; }); auto stop_it = std::upper_bound(spectra_view.begin(), spectra_view.end(), mz_rt.second.getMax(), [](double rt, const auto& spec) { return rt < spec.get().getRT(); }); res.emplace_back( std::distance(spectra_view.begin(), start_it), std::distance(spectra_view.begin(), stop_it) ); } return res; }; // For each range, gets (spectrum start index, spectrum stop index). The spectra covered by each RT range. const std::vector<std::pair<size_t, size_t>> rt_ranges_idcs = getCoveredSpectra(spectra_view, mz_rt_ranges); // Initialize result vector std::vector<MSChromatogram> result(mz_rt_ranges.size()); // Initialize counts per spectrum index and total mappings std::vector<std::vector<size_t>> spec_idx_to_range_idx(spectra_view.size()); // Build spectrum to range index mapping for (size_t i = 0; i < rt_ranges_idcs.size(); ++i) { const auto& [start, stop] = rt_ranges_idcs[i]; result[i].resize(stop - start); result[i].getProduct().setMZ( (mz_rt_ranges[i].first.getMinMZ() + mz_rt_ranges[i].first.getMaxMZ()) / 2.0); for (size_t j = start; j < stop; ++j) { spec_idx_to_range_idx[j].push_back(i); } } #pragma omp parallel for schedule(dynamic) for (Int64 i = 0; i < (Int64)spec_idx_to_range_idx.size(); ++i) // OpenMP on windows still requires signed loop variable { if (spec_idx_to_range_idx[i].empty()) continue; // no ranges for this spectrum? skip const auto& spec = spectra_view[i].get(); const double rt = spec.getRT(); auto spec_begin = spec.cbegin(); auto spec_end = spec.cend(); for (size_t range_idx : spec_idx_to_range_idx[i]) { const auto& mz_range = mz_rt_ranges[range_idx].first; // Find data points within MZ range auto start_it = spec.PosBegin(spec_begin, mz_range.getMinMZ(), spec_end); auto end_it = start_it; while (end_it != spec_end && end_it->getPosition() <= mz_range.getMaxMZ()) { ++end_it; } // Calculate result using provided reduction function result[range_idx][i - rt_ranges_idcs[range_idx].first] = ChromatogramPeak(rt, func_mz_reduction(start_it, end_it)); } } for (auto& r : result) r.updateRanges(); // TODO: prob.. faster to look at first and last peaks as range is sorted return result; } // Overload without func_mz_reduction parameter (needed because of template deduction issue) std::vector<MSChromatogram> extractXICs( const std::vector<std::pair<RangeMZ, RangeRT>>& mz_rt_ranges, unsigned int ms_level) const { return extractXICs(mz_rt_ranges, ms_level, SumIntensityReduction()); } /** * @brief Wrapper for aggregate function that takes a matrix of m/z and RT ranges * * @param[in] ranges Matrix where each row contains [mz_min, mz_max, rt_min, rt_max] * @param[in] ms_level MS level to process * @param[in] mz_agg Aggregation function for m/z values ("sum", "max", "min", "mean") * @return Vector of vectors containing aggregated intensity values for each range */ std::vector<std::vector<MSExperiment::CoordinateType>> aggregateFromMatrix( const Matrix<double>& ranges, unsigned int ms_level, const std::string& mz_agg) const { // Check matrix dimensions if (ranges.cols() != 4) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Range matrix must have 4 columns [mz_min, mz_max, rt_min, rt_max]"); } // Convert matrix rows to vector of pairs std::vector<std::pair<RangeMZ, RangeRT>> mz_rt_ranges; mz_rt_ranges.reserve((Size)ranges.rows()); for (Size i = 0; i < (Size)ranges.rows(); ++i) { mz_rt_ranges.emplace_back( RangeMZ(ranges(i, 0), ranges(i, 1)), // min max mz RangeRT(ranges(i, 2), ranges(i, 3)) // min max rt ); // std::cout << "mz: " << ranges(i, 0) << " - " << ranges(i, 1) << " rt: " << ranges(i, 2) << " - " << ranges(i, 3) << std::endl; } // Call appropriate aggregation function based on mz_agg parameter if (mz_agg == "sum") { return aggregate(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it) { return std::accumulate(begin_it, end_it, 0.0, [](double a, const Peak1D& b) { return a + b.getIntensity(); }); }); } else if (mz_agg == "max") { return aggregate(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it)->double { if (begin_it == end_it) return 0.0; return std::max_element(begin_it, end_it, [](const Peak1D& a, const Peak1D& b) { return a.getIntensity() < b.getIntensity(); } )->getIntensity(); }); } else if (mz_agg == "min") { return aggregate(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it)->double { if (begin_it == end_it) return 0.0; return std::min_element(begin_it, end_it, [](const Peak1D& a, const Peak1D& b) { return a.getIntensity() < b.getIntensity(); } )->getIntensity(); }); } else if (mz_agg == "mean") { return aggregate(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it) { if (begin_it == end_it) return 0.0; double sum = std::accumulate(begin_it, end_it, 0.0, [](double a, const Peak1D& b) { return a + b.getIntensity(); }); return sum / static_cast<double>(std::distance(begin_it, end_it)); }); } else { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid aggregation function", mz_agg); } } /** * @brief Wrapper for extractXICs function that takes a matrix of m/z and RT ranges * * @param[in] ranges Matrix where each row contains [mz_min, mz_max, rt_min, rt_max] * @param[in] ms_level MS level to process * @param[in] mz_agg Aggregation function for m/z values ("sum", "max", "min", "mean") * @return Vector of MSChromatogram objects, one for each range */ std::vector<MSChromatogram> extractXICsFromMatrix( const Matrix<double>& ranges, unsigned int ms_level, const std::string& mz_agg) const { // Check matrix dimensions if (ranges.cols() != 4) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Range matrix must have 4 columns [mz_min, mz_max, rt_min, rt_max]"); } // Convert matrix rows to vector of pairs std::vector<std::pair<RangeMZ, RangeRT>> mz_rt_ranges; mz_rt_ranges.reserve((Size)ranges.rows()); for (Size i = 0; i < (Size)ranges.rows(); ++i) { mz_rt_ranges.emplace_back( RangeMZ(ranges(i, 0), ranges(i, 1)), RangeRT(ranges(i, 2), ranges(i, 3)) ); } // Call appropriate extractXICs function based on mz_agg parameter if (mz_agg == "sum") { return extractXICs(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it) { return std::accumulate(begin_it, end_it, 0.0, [](double a, const Peak1D& b) { return a + b.getIntensity(); }); }); } else if (mz_agg == "max") { return extractXICs(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it)->double { if (begin_it == end_it) return 0.0; return std::max_element(begin_it, end_it, [](const Peak1D& a, const Peak1D& b) { return a.getIntensity() < b.getIntensity(); } )->getIntensity(); }); } else if (mz_agg == "min") { return extractXICs(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it)->double { if (begin_it == end_it) return 0.0; return std::min_element(begin_it, end_it, [](const Peak1D& a, const Peak1D& b) { return a.getIntensity() < b.getIntensity(); } )->getIntensity(); }); } else if (mz_agg == "mean") { return extractXICs(mz_rt_ranges, ms_level, [](auto begin_it, auto end_it) { if (begin_it == end_it) return 0.0; double sum = std::accumulate(begin_it, end_it, 0.0, [](double a, const Peak1D& b) { return a + b.getIntensity(); }); return sum / static_cast<double>(std::distance(begin_it, end_it)); }); } else { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid aggregation function", mz_agg); } } /** @brief Fast search for spectrum range begin Returns the first scan which has equal or higher (>=) RT than @p rt. @note Make sure the spectra are sorted with respect to retention time! Otherwise the result is undefined. */ ConstIterator RTBegin(CoordinateType rt) const; /** @brief Fast search for spectrum range end (returns the past-the-end iterator) Returns the first scan which has higher (>) RT than @p rt. @note Make sure the spectra are sorted with respect to retention time! Otherwise the result is undefined. */ ConstIterator RTEnd(CoordinateType rt) const; /** @brief Fast search for spectrum range begin @note Make sure the spectra are sorted with respect to retention time! Otherwise the result is undefined. */ Iterator RTBegin(CoordinateType rt); /** @brief Fast search for spectrum range end (returns the past-the-end iterator) @note Make sure the spectra are sorted with respect to retention time! Otherwise the result is undefined. */ Iterator RTEnd(CoordinateType rt); /** @brief Fast search for spectrum range begin Returns the first scan which has equal or higher (>=) ion mobility than @p rt. @note Make sure the spectra are sorted with respect to ion mobility! Otherwise the result is undefined. */ ConstIterator IMBegin(CoordinateType im) const; /** @brief Fast search for spectrum range end (returns the past-the-end iterator) Returns the first scan which has higher (>) ion mobility than @p im. @note Make sure the spectra are sorted with respect to ion mobility! Otherwise the result is undefined. */ ConstIterator IMEnd(CoordinateType im) const; //@} /** @name Range methods @note The range values (min, max, etc.) are not updated automatically. Call updateRanges() to update the values! */ ///@{ /// Delegate methods for backward compatibility /** * @brief Clear all ranges in all range managers * * This clears the ranges in the combined range manager, the spectrum range manager, * and the chromatogram range manager. */ void clearRanges() { combined_ranges_.clearRanges(); spectrum_ranges_.clearRanges(); chromatogram_ranges_.clearRanges(); } /// Get the minimum RT value from the combined ranges (includes both chromatogram and spectra ranges) double getMinRT() const { return combined_ranges_.getMinRT(); } /// Get the maximum RT value from the combined ranges (includes both chromatogram and spectra ranges) double getMaxRT() const { return combined_ranges_.getMaxRT(); } /// Get the minimum m/z value from the combined ranges (includes both chromatogram and spectra ranges) double getMinMZ() const { return combined_ranges_.getMinMZ(); } /// Get the maximum m/z value from the combined ranges (includes both chromatogram and spectra ranges) double getMaxMZ() const { return combined_ranges_.getMaxMZ(); } /// Get the minimum intensity value from the combined ranges (includes both chromatogram and spectra ranges) double getMinIntensity() const { return combined_ranges_.getMinIntensity(); } /// Get the maximum intensity value from the combined ranges (includes both chromatogram and spectra ranges) double getMaxIntensity() const { return combined_ranges_.getMaxIntensity(); } /// Get the minimum mobility value from the combined ranges (includes both chromatogram and spectra ranges) double getMinMobility() const { return combined_ranges_.getMinMobility(); } /// Get the maximum mobility value from the combined ranges (includes both chromatogram and spectra ranges) double getMaxMobility() const { return combined_ranges_.getMaxMobility(); } /** @brief Updates the m/z, intensity, mobility, and retention time ranges of all spectra and chromatograms This method updates all three range managers: - The spectrum range manager (for spectra ranges with MS level separation) - The chromatogram range manager (for chromatogram ranges) - The combined range manager (for overall ranges across both spectra and chromatograms) Call this method after modifying spectra or chromatograms to ensure that all range information is up-to-date. */ void updateRanges(); /// returns the total number of peaks (spectra and chromatograms included) UInt64 getSize() const; /// returns a sorted array of MS levels (calculated on demand) std::vector<UInt> getMSLevels() const; ///@} /// If the file is loaded from an sqMass file, this run-ID allows to connect to the corresponding OSW identification file /// If the run-ID was not stored (older version) or this MSExperiment was not loaded from sqMass, then 0 is returned. UInt64 getSqlRunID() const; /// sets the run-ID which is used when storing an sqMass file void setSqlRunID(UInt64 id); ///@name Sorting spectra and peaks ///@{ /** @brief Sorts the data points by retention time @param[in] sort_mz if @em true, spectra are sorted by m/z position as well */ void sortSpectra(bool sort_mz = true); /** @brief Sorts the data points of the chromatograms by m/z @param[in] sort_rt if @em true, chromatograms are sorted by rt position as well */ void sortChromatograms(bool sort_rt = true); /** @brief Checks if all spectra are sorted with respect to ascending RT @param[in] check_mz if @em true, checks if all peaks are sorted with respect to ascending m/z */ bool isSorted(bool check_mz = true) const; //@} /// Clear all internal data (spectra, ranges, metadata) void reset(); /** @brief Clears the meta data arrays of all contained spectra (float, integer and string arrays) @return @em true if meta data arrays were present and removed. @em false otherwise. */ bool clearMetaDataArrays(); /// returns the meta information of this experiment (const access) const ExperimentalSettings& getExperimentalSettings() const; /// returns the meta information of this experiment (mutable access) ExperimentalSettings& getExperimentalSettings(); /// get the file path to the first MS run void getPrimaryMSRunPath(StringList& toFill) const; /** @brief Returns the precursor spectrum of the scan pointed to by @p iterator If there is no (matching) precursor scan the past-the-end iterator is returned. This assumes that precursors occur somewhere before the current spectrum but not necessarily the first one from the last MS level (we double-check with the annotated precursorList. If precursor annotations are present, uses the native spectrum ID from the @em first precursor entry of the current scan for comparisons -> Works for multiple precursor ranges from the same precursor scan but not for multiple precursor ranges from different precursor scans. If none are present, picks the first scan of a lower level. */ ConstIterator getPrecursorSpectrum(ConstIterator iterator) const; /** @brief Returns the index of the precursor spectrum for spectrum at index @p zero_based_index If there is no precursor scan -1 is returned. */ int getPrecursorSpectrum(int zero_based_index) const; /** @brief Returns the first product spectrum of the scan pointed to by @p iterator A product spectrum is a spectrum of the next higher MS level that has the current spectrum as precursor. If there is no product scan, the past-the-end iterator is returned. This assumes that product occurs somewhere after the current spectrum and comes before the next scan that is of a level that is lower than the current one. \verbatim Example: MS1 - ix: 0 MS2 - ix: 1, prec: 0 MS2 - ix: 2, prec: 0 <-- current scan MS3 - ix: 3, prec: 1 MS3 - ix: 4, prec: 2 <-- product scan MS2 - ix: 5, prec: 0 MS3 - ix: 6, prec: 5 MS1 - ix: 7 ... <-- Not searched anymore. Returns end of experiment iterator if not found until here. \endverbatim Uses the native spectrum ID from the @em first precursor entry of the potential product scans for comparisons -> Works for multiple precursor ranges from the same precursor scan but not for multiple precursor ranges from different precursor scans. */ ConstIterator getFirstProductSpectrum(ConstIterator iterator) const; /** @brief Returns the index of the first product spectrum given an index. @param[in] zero_based_index The index of the current spectrum. @return Index of the first product spectrum or -1 if not found. */ int getFirstProductSpectrum(int zero_based_index) const; /// Swaps the content of this map with the content of @p from void swap(MSExperiment& from); /// sets the spectrum list void setSpectra(const std::vector<MSSpectrum>& spectra); void setSpectra(std::vector<MSSpectrum>&& spectra); /// adds a spectrum to the list void addSpectrum(const MSSpectrum& spectrum); void addSpectrum(MSSpectrum&& spectrum); /// returns the spectrum list const std::vector<MSSpectrum>& getSpectra() const; /// returns the spectrum list (mutable) std::vector<MSSpectrum>& getSpectra(); /// Returns the closest(=nearest) spectrum in retention time to the given RT ConstIterator getClosestSpectrumInRT(const double RT) const; Iterator getClosestSpectrumInRT(const double RT); /// Returns the closest(=nearest) spectrum in retention time to the given RT of a certain MS level ConstIterator getClosestSpectrumInRT(const double RT, UInt ms_level) const; Iterator getClosestSpectrumInRT(const double RT, UInt ms_level); /// sets the chromatogram list void setChromatograms(const std::vector<MSChromatogram>& chromatograms); void setChromatograms(std::vector<MSChromatogram>&& chromatograms); /// adds a chromatogram to the list void addChromatogram(const MSChromatogram& chromatogram); void addChromatogram(MSChromatogram&& chrom); /// returns the chromatogram list const std::vector<MSChromatogram>& getChromatograms() const; /// returns the chromatogram list (mutable) std::vector<MSChromatogram>& getChromatograms(); /// @name Easy Access interface //@{ /// returns a single chromatogram MSChromatogram& getChromatogram(Size id); /// returns a single spectrum MSSpectrum& getSpectrum(Size id); /// get the total number of spectra available Size getNrSpectra() const; /// get the total number of chromatograms available Size getNrChromatograms() const; //@} /** @brief Computes the total ion chromatogram (TIC) for a given MS level (use ms_level = 0 for all levels). By default, each MS spectrum's intensity just gets summed up. Regular RT bins can be obtained by specifying @p rt_bin_size. If a bin size in RT seconds greater than 0 is given resampling is used. @param[in] rt_bin_size RT bin size in seconds (0 = no resampling) @param[in] ms_level MS level of spectra for calculation (0 = all levels) @return TIC Chromatogram **/ const MSChromatogram calculateTIC(float rt_bin_size = 0, UInt ms_level = 1) const; /** @brief Clears all data and meta data @param[in] clear_meta_data If @em true, all meta data is cleared in addition to the data. */ void clear(bool clear_meta_data); /// returns true if at least one of the spectra has the specified level bool containsScanOfLevel(size_t ms_level) const; /// returns true if any MS spectra of trthe specified level contain at least one peak with intensity of 0.0 bool hasZeroIntensities(size_t ms_level) const; /// Are all MSSpectra in this experiment part of an IM Frame? I.e. they all have the same RT, but different drift times bool isIMFrame() const; protected: /// chromatograms std::vector<MSChromatogram > chromatograms_; /// spectra std::vector<SpectrumType> spectra_; /// Spectrum range manager for tracking m/z, intensity, RT, and ion mobility ranges of spectra with MS level separation SpectrumRangeManagerType spectrum_ranges_; /// Chromatogram range manager for tracking RT, intensity, and m/z ranges of chromatograms ChromatogramRangeManagerType chromatogram_ranges_; /// Combined range manager that provides overall ranges across both spectra and chromatograms (maintained for backward compatibility) RangeManagerType combined_ranges_; public: /** * @brief Returns a const reference to the spectrum range manager * * The spectrum range manager provides access to m/z, intensity, retention time, and ion mobility * ranges for spectra, with separate tracking for different MS levels. * * @return Const reference to the spectrum range manager * @see SpectrumRangeManager */ const SpectrumRangeManagerType& spectrumRanges() const { return spectrum_ranges_; } /** * @brief Returns a const reference to the chromatogram range manager * * The chromatogram range manager provides access to retention time, m/z, and intensity * ranges for chromatograms. * * @return Const reference to the chromatogram range manager * @see ChromatogramRangeManager */ const ChromatogramRangeManagerType& chromatogramRanges() const { return chromatogram_ranges_; } /** * @brief Returns a const reference to the combined range manager * * The combined range manager provides access to the overall ranges across both spectra and chromatograms. * This is maintained for backward compatibility with code that expects a single range manager. * * @return Const reference to the combined range manager */ const RangeManagerType& combinedRanges() const { return combined_ranges_; } private: /// Helper class to add either general data points in set2DData or use mass traces from meta values template<typename ContainerValueType, bool addMassTraces> struct ContainerAdd_ { static void addData_(SpectrumType* spectrum, const ContainerValueType* item); static void addData_(SpectrumType* spectrum, const ContainerValueType* item, const StringList& store_metadata_names); }; template<typename ContainerValueType> struct ContainerAdd_<ContainerValueType, false> { /// general method for adding data points static void addData_(SpectrumType* spectrum, const ContainerValueType* item) { // create temporary peak and insert it into spectrum spectrum->insert(spectrum->end(), PeakType()); spectrum->back().setIntensity(item->getIntensity()); spectrum->back().setPosition(item->getMZ()); } /// general method for adding data points, including metadata arrays (populated from metainfointerface) static void addData_(SpectrumType* spectrum, const ContainerValueType* item, const StringList& store_metadata_names) { addData_(spectrum, item); for (StringList::const_iterator itm = store_metadata_names.begin(); itm != store_metadata_names.end(); ++itm) { float val = std::numeric_limits<float>::quiet_NaN(); if (item->metaValueExists(*itm)) val = item->getMetaValue(*itm); spectrum->getFloatDataArrays()[itm - store_metadata_names.begin()].push_back(val); } } }; template<typename ContainerValueType> struct ContainerAdd_<ContainerValueType, true> { /// specialization for adding feature mass traces (does not support metadata_names currently) static void addData_(SpectrumType* spectrum, const ContainerValueType* item) { if (item->metaValueExists("num_of_masstraces")) { Size mts = item->getMetaValue("num_of_masstraces"); int charge = (item->getCharge()==0 ? 1 : item->getCharge()); // set to 1 if charge is 0, otherwise div/0 below for (Size i = 0; i < mts; ++i) { String meta_name = String("masstrace_intensity_") + i; if (!item->metaValueExists(meta_name)) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Meta value '") + meta_name + "' expected but not found in container."); } ContainerValueType p; p.setIntensity(item->getMetaValue(meta_name)); p.setPosition(item->getMZ() + Constants::C13C12_MASSDIFF_U / charge * i); ContainerAdd_<ContainerValueType, false>::addData_(spectrum, &p); } } else ContainerAdd_<ContainerValueType, false>::addData_(spectrum, item); } }; /* @brief Append a spectrum to current MSExperiment @param[in] rt RT of new spectrum @return Pointer to newly created spectrum */ SpectrumType* createSpec_(PeakType::CoordinateType rt); /* @brief Append a spectrum including floatdata arrays to current MSExperiment @param[in] rt RT of new spectrum @param[in] metadata_names Names of floatdata arrays attached to this spectrum @return Pointer to newly created spectrum */ SpectrumType* createSpec_(PeakType::CoordinateType rt, const StringList& metadata_names); }; /// Print the contents to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const MSExperiment& exp); } // namespace OpenMS #include <OpenMS/KERNEL/StandardTypes.h>
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/DPeak.h
.h
980
47
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/Peak1D.h> #include <OpenMS/KERNEL/Peak2D.h> namespace OpenMS { /** @brief Metafunction to choose among Peak1D respectively Peak2D through a template argument. The result is accessible via typedef Type: - @c DPeak<1>::Type is @c Peak1D - @c DPeak<2>::Type is @c Peak2D */ template <UInt dimensions> struct DPeak {}; // We do not want these classes to show up in the docu /// @cond HIDDENSTUFF template <> struct DPeak<1> { typedef Peak1D Type; }; template <> struct DPeak<2> { typedef Peak2D Type; }; /// @endcond } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/OnDiscMSExperiment.h
.h
8,235
275
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/DataStructures.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/METADATA/ExperimentalSettings.h> #include <OpenMS/FORMAT/HANDLERS/IndexedMzMLHandler.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <vector> #include <limits> #include <memory> namespace OpenMS { /** @brief Representation of a mass spectrometry experiment on disk. @ingroup Kernel This class allows random access to spectra and chromatograms in indexed mzML files without loading the entire file into memory. @section OnDiscMSExperiment_filtering Filtering with PeakFileOptions PeakFileOptions can be used to filter data when retrieving spectra/chromatograms: - RT range, MS level, and precursor m/z range filters: Checked BEFORE loading peak data (skips I/O) - m/z range and intensity filters: Applied AFTER loading peak data @note Unlike in-memory loading (FileHandler), where filtered spectra are completely removed from the container, OnDiscMSExperiment preserves all indices. When a spectrum doesn't pass RT range or MS level filters, getSpectrum() returns the spectrum with metadata but no peaks (I/O is skipped). This preserves the index mapping to the file. Example: @code OnDiscMSExperiment exp; exp.openFile("data.mzML"); exp.getOptions().setMSLevels({2}); // Only want MS2 exp.getOptions().setRTRange(DRange<1>(100, 200)); for (Size i = 0; i < exp.size(); ++i) { MSSpectrum s = exp.getSpectrum(i); if (s.empty()) continue; // Filtered out, no I/O was performed // Process MS2 spectrum in RT range... } @endcode @note This implementation is @a not thread-safe since it keeps internally a single file access pointer which it moves when accessing a specific data item. Please provide a separate copy to each thread, e.g. @code #pragma omp parallel for firstprivate(ondisc_map) @endcode */ class OPENMS_DLLAPI OnDiscMSExperiment { typedef ChromatogramPeak ChromatogramPeakT; typedef Peak1D PeakT; public: /** @brief Constructor This initializes the object, use openFile to open a file. */ OnDiscMSExperiment() = default; /** @brief Open a specific file on disk. This tries to read the indexed mzML by parsing the index and then reading the meta information into memory. @return Whether the parsing of the file was successful (if false, the file most likely was not an indexed mzML file) */ bool openFile(const String& filename, bool skipMetaData = false); /// Copy constructor OnDiscMSExperiment(const OnDiscMSExperiment& source) : filename_(source.filename_), indexed_mzml_file_(source.indexed_mzml_file_), meta_ms_experiment_(source.meta_ms_experiment_), options_(source.options_) { } /** @brief Equality operator This only checks whether the underlying file is the same and the parsed meta-information is the same. Note that the file reader (e.g. the std::ifstream of the file) might be in a different state. */ bool operator==(const OnDiscMSExperiment& rhs) const { if (meta_ms_experiment_ == nullptr || rhs.meta_ms_experiment_ == nullptr) { return filename_ == rhs.filename_ && meta_ms_experiment_ == rhs.meta_ms_experiment_; } // check if file and meta information is the same return filename_ == rhs.filename_ && (*meta_ms_experiment_) == (*rhs.meta_ms_experiment_); // do not check if indexed_mzml_file_ is equal -> they have the same filename... } /// Inequality operator bool operator!=(const OnDiscMSExperiment& rhs) const { return !(operator==(rhs)); } /** @brief Checks if all spectra are sorted with respect to ascending RT Note that we cannot check whether all spectra are sorted (except if we were to load them all and check). */ bool isSortedByRT() const { if (!meta_ms_experiment_) return false; return meta_ms_experiment_->isSorted(false); } /// alias for getNrSpectra inline Size size() const { return getNrSpectra(); } /// returns whether spectra are empty inline bool empty() const { return getNrSpectra() == 0; } /// get the total number of spectra available inline Size getNrSpectra() const { return indexed_mzml_file_.getNrSpectra(); } /// get the total number of chromatograms available inline Size getNrChromatograms() const { return indexed_mzml_file_.getNrChromatograms(); } /// returns the meta information of this experiment (const access) std::shared_ptr<const ExperimentalSettings> getExperimentalSettings() const { return std::static_pointer_cast<const ExperimentalSettings>(meta_ms_experiment_); } std::shared_ptr<PeakMap> getMetaData() const { return meta_ms_experiment_; } /// alias for getSpectrum inline MSSpectrum operator[](Size n) { return getSpectrum(n); } /** @brief returns a single spectrum If PeakFileOptions has m/z or intensity range set, the spectrum will be filtered accordingly. @param[in] id The index of the spectrum */ MSSpectrum getSpectrum(Size id); /** @brief returns a single spectrum (without applying PeakFileOptions filters) */ OpenMS::Interfaces::SpectrumPtr getSpectrumById(Size id) { return indexed_mzml_file_.getSpectrumById((int)id); } /** @brief returns a single chromatogram If PeakFileOptions has RT or intensity range set, the chromatogram will be filtered accordingly. @param[in] id The index of the chromatogram */ MSChromatogram getChromatogram(Size id); /** @brief returns a single chromatogram @param[in] id The native identifier of the chromatogram */ MSChromatogram getChromatogramByNativeId(const std::string& id); /** @brief returns a single spectrum @param[in] id The native identifier of the spectrum */ MSSpectrum getSpectrumByNativeId(const std::string& id); /** @brief returns a single chromatogram */ OpenMS::Interfaces::ChromatogramPtr getChromatogramById(Size id); /// sets whether to skip some XML checks and be fast instead void setSkipXMLChecks(bool skip); /// @brief Mutable access to the options for loading/storing PeakFileOptions& getOptions(); /// @brief Non-mutable access to the options for loading/storing const PeakFileOptions& getOptions() const; /// @brief set options for loading/storing void setOptions(const PeakFileOptions& options); private: /// Private Assignment operator -> we cannot copy file streams in IndexedMzMLHandler OnDiscMSExperiment& operator=(const OnDiscMSExperiment& /* source */); void loadMetaData_(const String& filename); MSChromatogram getMetaChromatogramById_(const std::string& id); MSSpectrum getMetaSpectrumById_(const std::string& id); protected: /// The filename of the underlying data file String filename_; /// The index of the underlying data file Internal::IndexedMzMLHandler indexed_mzml_file_; /// The meta-data std::shared_ptr<PeakMap> meta_ms_experiment_; /// Mapping of chromatogram native ids to offsets std::unordered_map< std::string, Size > chromatograms_native_ids_; /// Mapping of spectra native ids to offsets std::unordered_map< std::string, Size > spectra_native_ids_; /// Options for loading / storing PeakFileOptions options_; }; typedef OpenMS::OnDiscMSExperiment OnDiscPeakMap; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/RangeManager.h
.h
28,849
917
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/CommonEnums.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/config.h> #include <algorithm> // for min/max #include <cassert> #include <cmath> // for nan() #include <iosfwd> // for std::ostream namespace OpenMS { /// Dimensions of data acquisition for MS data enum class MSDim { RT, MZ, INT, IM }; struct RangeRT; struct RangeMZ; struct RangeIntensity; struct RangeMobility; /// Base class for a simple range with minimum and maximum struct OPENMS_DLLAPI RangeBase { public: /// C'tor: initialize with empty range RangeBase() = default; /// Cutom C'tor which sets the range to a singular point RangeBase(const double single): min_(single), max_(single) { } /// Custom C'tor to set min and max /// @throws Exception::InvalidRange if min > max RangeBase(const double min, const double max): min_(min), max_(max) { if (min_ > max_) throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid initialization of range"); } /// Copy C'tor RangeBase(const RangeBase& rhs) = default; /// Move C'tor (seems useless, but is required for completeness in derived classes' move c'tor) RangeBase(RangeBase&& rhs) noexcept = default; /// Assignment operator RangeBase& operator=(const RangeBase& rhs) = default; /// Move assignment (seems useless, but is required for completeness in derived classes' move c'tor) RangeBase& operator=(RangeBase&& rhs) noexcept = default; /// D'tor ~RangeBase() noexcept = default; /// conversion operator to allow accepting a RangeBase (instead of RangeRT) for the implicitly defined special members, e.g. assignment operator /// (RangeRT& operator=(const RangeRT&)) operator RangeRT() const; /// conversion operator to allow accepting a RangeBase (instead of RangeMZ) for the implicitly defined special members, e.g. assignment operator /// (RangeMZ& operator=(const RangeMZ&)) operator RangeMZ() const; /// conversion operator to allow accepting a RangeBase (instead of RangeIntensity) for the implicitly defined special members, e.g. assignment /// operator (RangeIntensity& operator=(const RangeIntensity&)) operator RangeIntensity() const; /// conversion operator to allow accepting a RangeBase (instead of RangeMobility) for the implicitly defined special members, e.g. assignment /// operator (RangeMobility& operator=(const RangeMobility&)) operator RangeMobility() const; /// make the range empty, i.e. isEmpty() will be true void clear() { *this = RangeBase(); // overwrite with fresh instance } /// is the range empty (i.e. min > max)? bool isEmpty() const { return min_ > max_; } /// is @p value within [min, max]? bool contains(const double value) const { return uint8_t(min_ <= value) & uint8_t(value <= max_); // using && leads to branches on all compilers in Debug and in Release on MVSC } /// is the range @p inner_range within [min, max]? bool contains(const RangeBase& inner_range) const { return uint8_t(contains(inner_range.min_)) & uint8_t(contains(inner_range.max_)); // using && leads to branches on all compilers in Debug and in Release on MVSC } /** @name Accessors for min and max We use accessors, to keep range consistent (i.e. ensure that min <= max) */ ///@{ /// sets the minimum (and the maximum, if uninitialized) void setMin(const double min) { min_ = min; if (max_ < min) max_ = min; } /// sets the maximum (and the minimum, if uninitialized) void setMax(const double max) { max_ = max; if (min_ > max) min_ = max; } /// Get the minimum value of the range /// @throws Exception::InvalidRange if the range is empty double getMin() const { if (isEmpty()) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Empty or uninitalized range object. Did you forget to call updateRanges()?"); } return min_; } /// Get the maximum value of the range /// @throws Exception::InvalidRange if the range is empty double getMax() const { if (isEmpty()) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Empty or uninitialized range object. Did you forget to call updateRanges()?"); } return max_; } ///@} /// ensure the range includes the range of @p other void extend(const RangeBase& other) { min_ = std::min(min_, other.min_); max_ = std::max(max_, other.max_); } /// extend the range such that it includes the given @p value void extend(const double value) { min_ = std::min(min_, value); max_ = std::max(max_, value); } /// Extend the range by @p by units to left and right /// Using negative values will shrink the range. It may become empty. /// Calling this on an empty range will not have any effect. void extendLeftRight(const double by) { if (isEmpty()) return; min_ -= by; max_ += by; } /** * \brief If the current range is a single point, e.g. min==max, then extend the range by @p min_span / 2 on either side. * * Calling span() afterwards, returns @p min_span. */ void minSpanIfSingular(const double min_span) { if (min_ == max_) extendLeftRight(min_span / 2); } /// Ensure the range of this does not exceed the range of @p other. /// If @p other already contains() this range, nothing changes. /// If this range is entirely outside the range of @p other, /// the resulting range is empty. /// Empty ranges are not modified. /// @throw Exception::InvalidRange if @p other is empty void clampTo(const RangeBase& other) { if (isEmpty()) return; if (other.isEmpty()) throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); min_ = std::max(min_, other.min_); max_ = std::min(max_, other.max_); } /// Move range of *this to min/max of @p sandbox, without changing the span, if possible. /// This does tighten the range unless @p sandbox's ranges are smaller than *this. /// Empty ranges are not modified. /// @param[in] sandbox Range to translate/move the current range into /// @throw Exception::InvalidRange if @p sandbox is empty void pushInto(const RangeBase& sandbox) { if (isEmpty()) return; if (sandbox.isEmpty()) throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); if (! sandbox.contains(*this)) { if (getSpan() > sandbox.getSpan()) { // make interval fit into sandbox (= ensure full containment) max_ = min_ + sandbox.getSpan(); } if (min_ < sandbox.min_) { // need to shift right (positive shift) shift(sandbox.min_ - min_); } else if (max_ > sandbox.max_) { // need to shift left (negative shift) shift(sandbox.max_ - max_); } } } /** @brief Scale the range of the dimension by a @p factor. A factor > 1 increases the range; factor < 1 decreases it. Let d = max - min; then min = min - d*(factor-1)/2, i.e. scale(1.5) extends the range by 25% on each side. Scaling an empty range will not have any effect. @param[in] factor The multiplier to increase the range by */ void scaleBy(const double factor) { if (isEmpty()) return; const double dist = max_ - min_; const double extension = dist * (factor - 1) / 2; min_ -= extension; max_ += extension; } /// Move the range by @p distance (negative values shift left) /// Shifting an empty range will not have any effect. void shift(const double distance) { if (isEmpty()) return; min_ += distance; max_ += distance; } /// Compute the center point of the range /// If range is empty(), 'nan' will be returned double center() const { if (isEmpty()) return nan(""); return min_ + (max_ - min_) / 2.0; } /// Get the 'width' of the range /// If range is empty(), 'nan' will be returned double getSpan() const { if (isEmpty()) return nan(""); return max_ - min_; } bool operator==(const RangeBase& rhs) const { return min_ == rhs.min_ && max_ == rhs.max_; } /** * \brief Return the current range, or (if empty) a full range (-1e308, 1e308). * \return A range where always: min <= max */ std::pair<double, double> getNonEmptyRange() const { // pair with full range if (isEmpty()) return {std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()}; else return {min_, max_}; } protected: // make members non-accessible to maintain invariant: min <= max (unless uninitialized) double min_ = std::numeric_limits<double>::max(); double max_ = std::numeric_limits<double>::lowest(); }; OPENMS_DLLAPI std::ostream& operator<<(std::ostream& out, const RangeBase& b); struct OPENMS_DLLAPI RangeRT : public RangeBase { const static MSDim DIM = MSDim::RT; // Rule of 0! using RangeBase::RangeBase; // inherit C'tors from base using RangeBase::operator=; // inherit assignment operator from base /** @name Accessors for min and max We use accessors, to keep range consistent (i.e. ensure that min <= max) */ ///@{ /// sets the minimum (and the maximum, if uninitialized) void setMinRT(const double min) { setMin(min); } /// sets the maximum (and the minimum, if uninitialized) void setMaxRT(const double max) { setMax(max); } /// Get the minimum RT value of the range /// @throws Exception::InvalidRange if the range is empty double getMinRT() const { return getMin(); } /// Get the maximum RT value of the range /// @throws Exception::InvalidRange if the range is empty double getMaxRT() const { return getMax(); } ///@} /// extend the range such that it includes the given @p value void extendRT(const double value) { extend(value); } /// is @p value within [min, max]? bool containsRT(const double value) const { return RangeBase::contains(value); } /// is the range @p inner_range within [min, max] of this range? bool containsRT(const RangeBase& inner_range) const { return RangeBase::contains(inner_range); } }; OPENMS_DLLAPI std::ostream& operator<<(std::ostream& out, const RangeRT& range); struct OPENMS_DLLAPI RangeMZ : public RangeBase { const static MSDim DIM = MSDim::MZ; // Rule of 0! using RangeBase::RangeBase; // inherit C'tors from base using RangeBase::operator=; // inherit assignment operator /** @name Accessors for min and max We use accessors, to keep range consistent (i.e. ensure that min <= max) */ ///@{ /// sets the minimum (and the maximum, if uninitialized) void setMinMZ(const double min) { setMin(min); } /// sets the maximum (and the minimum, if uninitialized) void setMaxMZ(const double max) { setMax(max); } /// Get the minimum MZ value of the range /// @throws Exception::InvalidRange if the range is empty double getMinMZ() const { return getMin(); } /// Get the maximum MZ value of the range /// @throws Exception::InvalidRange if the range is empty double getMaxMZ() const { return getMax(); } ///@} /// extend the range such that it includes the given @p value void extendMZ(const double value) { extend(value); } /// is @p value within [min, max]? bool containsMZ(const double value) const { return RangeBase::contains(value); } /// is the range @p inner_range within [min, max] of this range? bool containsMZ(const RangeBase& inner_range) const { return RangeBase::contains(inner_range); } }; OPENMS_DLLAPI std::ostream& operator<<(std::ostream& out, const RangeMZ& range); struct OPENMS_DLLAPI RangeIntensity : public RangeBase { const static MSDim DIM = MSDim::INT; // Rule of 0! using RangeBase::RangeBase; // inherit C'tors from base using RangeBase::operator=; // inherit assignment operator /** @name Accessors for min and max We use accessors, to keep range consistent (i.e. ensure that min <= max) */ ///@{ /// sets the minimum (and the maximum, if uninitialized) void setMinIntensity(const double min) { setMin(min); } /// sets the maximum (and the minimum, if uninitialized) void setMaxIntensity(const double max) { setMax(max); } /// Get the minimum intensity value of the range /// @throws Exception::InvalidRange if the range is empty double getMinIntensity() const { return getMin(); } /// Get the maximum intensity value of the range /// @throws Exception::InvalidRange if the range is empty double getMaxIntensity() const { return getMax(); } ///@} /// extend the range such that it includes the given @p value void extendIntensity(const double value) { extend(value); } /// is @p value within [min, max]? bool containsIntensity(const double value) const { return RangeBase::contains(value); } /// is the range @p inner_range within [min, max] of this range? bool containsIntensity(const RangeBase& inner_range) const { return RangeBase::contains(inner_range); } }; OPENMS_DLLAPI std::ostream& operator<<(std::ostream& out, const RangeIntensity& range); struct OPENMS_DLLAPI RangeMobility : public RangeBase { const static MSDim DIM = MSDim::IM; // Rule of 0! using RangeBase::RangeBase; // inherit C'tors from base using RangeBase::operator=; // inherit assignment operator /** @name Accessors for min and max We use accessors, to keep range consistent (i.e. ensure that min <= max) */ ///@{ /// sets the minimum (and the maximum, if uninitialized) void setMinMobility(const double min) { setMin(min); } /// sets the maximum (and the minimum, if uninitialized) void setMaxMobility(const double max) { setMax(max); } /// Get the minimum mobility value of the range /// @throws Exception::InvalidRange if the range is empty double getMinMobility() const { return getMin(); } /// Get the maximum mobility value of the range /// @throws Exception::InvalidRange if the range is empty double getMaxMobility() const { return getMax(); } ///@} /// extend the range such that it includes the given @p value void extendMobility(const double value) { extend(value); } /// is @p value within [min, max]? bool containsMobility(const double value) const { return RangeBase::contains(value); } /// is the range @p inner_range within [min, max] of this range? bool containsMobility(const RangeBase& inner_range) const { return RangeBase::contains(inner_range); } }; OPENMS_DLLAPI std::ostream& operator<<(std::ostream& out, const RangeMobility& range); /// Enum listing state of dimensions (RangeBases) enum class HasRangeType { ALL, ///< all dimensions are filled SOME, ///< some dimensions are empty, some are filled NONE ///< all dimensions are empty (=cleared) }; /** @brief Handles the management of a multidimensional range, e.g. RangeMZ and RangeIntensity for spectra. Instantiate it with the dimensions which are supported/required, e.g. `RangeManager<RangeRT, RangeMZ> range_spec` for a spectrum and use the strongly typed features, such as `range_spec.getMaxRT()/setMaxRT(500.0)` or `range_spec.extend(RangeMZ{100, 1500})`. Use RangeManagerContainer as a base class for all peak and feature containers like MSSpectrum, MSExperiment and FeatureMap. The implementation uses non-virtual multiple inheritance using variadic templates. Each dimension, e.g. RangeRT, is inherited from, thus all members of the base class become accessible in the RangeManager, e.g. getMaxRT(). Operations (e.g. assignment, or extension of ranges) across RangeManagers with a different, yet overlapping set of base classes is enabled using fold expressions and constexpr evaluations, which are resolved at compile time (see for_each_base_ member function). */ template<typename... RangeBases> class RangeManager : public RangeBases... { public: using ThisRangeType = RangeManager<RangeBases...>; // rule of 0 -- no need for a virtual d'tor or anything fancy // ... bool operator==(const RangeManager& rhs) const { bool equal = true; for_each_base_([&](auto* base) { using T_BASE = std::decay_t<decltype(*base)>; // remove const/ref qualifiers equal &= ((T_BASE&)rhs == (T_BASE&)*this); }); return equal; } bool operator!=(const RangeManager& rhs) const { return ! operator==(rhs); } /// copy all overlapping dimensions from @p rhs to this instance. /// Dimensions which are not contained in @p rhs are left untouched. /// @param[in] rhs Range to copy from /// @return true if one or more dimensions overlapped template<typename... RangeBasesOther> bool assignUnsafe(const RangeManager<RangeBasesOther...>& rhs) { bool found = false; for_each_base_([&](auto* base) { using T_BASE = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if constexpr (std::is_base_of_v<T_BASE, RangeManager<RangeBasesOther...>>) { base->operator=((T_BASE&)rhs); found = true; } }); return found; } /// copy all overlapping dimensions from @p rhs to this instance. /// Dimensions which are not contained in @p rhs are left untouched. /// @param[in] rhs Range to copy from /// @throw Exception::InvalidRange if no dimensions overlapped template<typename... RangeBasesOther> auto& assign(const RangeManager<RangeBasesOther...>& rhs) { if (! assignUnsafe(rhs)) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No assignment took place (no dimensions in common!);"); } return *this; } /// extend all dimensions which overlap with @p rhs to contain the range of @p rhs /// Dimensions which are not contained in @p rhs are left untouched. /// @param[in] rhs Range to extend from /// @return false if no dimensions overlapped template<typename... RangeBasesOther> bool extendUnsafe(const RangeManager<RangeBasesOther...>& rhs) { bool found = false; for_each_base_([&](auto* base) { using T_BASE = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if constexpr (std::is_base_of_v<T_BASE, RangeManager<RangeBasesOther...>>) { base->extend((T_BASE&)rhs); found = true; } }); return found; } /// extend all dimensions which overlap with @p rhs to contain the range of @p rhs /// Dimensions which are not contained in @p rhs are left untouched. /// @param[in] rhs Range to extend from /// @throw Exception::InvalidRange if no dimensions overlapped template<typename... RangeBasesOther> void extend(const RangeManager<RangeBasesOther...>& rhs) { if (! extendUnsafe(rhs)) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No assignment took place (no dimensions in common!);"); } } /// calls RangeBase::scale() for each dimension void scaleBy(const double factor) { for_each_base_([&](auto* base) { base->scaleBy(factor); }); } /** * \brief If any dimension is a single point, e.g. min==max, then extend this dimension by @p min_span / 2 on either side. * * Empty dimensions remain unchanged. * * @see DimBase::minSpanIfSingular * */ void minSpanIfSingular(const double min_span) { for_each_base_([&](auto* base) { base->minSpanIfSingular(min_span); }); } /// Move range of *this to min/max of @p rhs, without changing the span, if possible. /// This does tighten the range unless @p rhs's ranges are smaller than *this. /// Dimensions which are not contained in @p rhs or are empty are left untouched. /// @param[in] rhs Range to translate/move the current range into /// @return true if dimensions overlapped, false otherwise template<typename... RangeBasesOther> bool pushIntoUnsafe(const RangeManager<RangeBasesOther...>& rhs) { bool found = false; for_each_base_([&](auto* base) { using T_BASE = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if constexpr (std::is_base_of_v<T_BASE, RangeManager<RangeBasesOther...>>) { const auto& rhs_base = (T_BASE&)rhs; if (! rhs_base.isEmpty()) base->pushInto(rhs_base); found = true; } }); return found; } /// Move range of *this to min/max of @p sandbox, without changing the span, if possible. /// This does tighten the range unless @p sandbox's ranges are smaller than *this. /// Dimensions which are not contained in @p sandbox or are empty are left untouched. /// @param[in] sandbox Range to translate/move the current range into /// @throw Exception::InvalidRange if no dimensions overlapped template<typename... RangeBasesOther> void pushInto(const RangeManager<RangeBasesOther...>& sandbox) { if (! pushIntoUnsafe(sandbox)) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No assignment took place (no dimensions in common!);"); } } /// Clamp min/max of all overlapping dimensions to min/max of @p rhs /// Dimensions which are not contained in @p rhs or where rhs is empty are left untouched. /// @param[in] rhs Range to clamp to /// @return true if dimensions overlapped, false otherwise template<typename... RangeBasesOther> bool clampToUnsafe(const RangeManager<RangeBasesOther...>& rhs) { bool found = false; for_each_base_([&](auto* base) { using T_BASE = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if constexpr (std::is_base_of_v<T_BASE, RangeManager<RangeBasesOther...>>) { const auto& rhs_base = (T_BASE&)rhs; if (! rhs_base.isEmpty()) base->clampTo(rhs_base); found = true; } }); return found; } /// Clamp min/max of all overlapping dimensions to min/max of @p rhs. /// This may tighten the range (even to a single point). /// Dimensions which are not contained in @p rhs or where rhs is empty are left untouched. /// @param[in] rhs Range to clamp to /// @throw Exception::InvalidRange if no dimensions overlapped template<typename... RangeBasesOther> void clampTo(const RangeManager<RangeBasesOther...>& rhs) { if (! clampToUnsafe(rhs)) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No assignment took place (no dimensions in common!);"); } } /// obtain a range dimension at runtime using @p dim const RangeBase& getRangeForDim(MSDim dim) const { RangeBase* r_base = nullptr; static_for_each_base_([&](auto* base) { using Base = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if (base->DIM == dim) r_base = (Base*)this; }); assert((r_base != nullptr) && "No base class has this MSDim!"); return *r_base; } /// obtain a range dimension at runtime using @p dim RangeBase& getRangeForDim(MSDim dim) { RangeBase* r_base = nullptr; static_for_each_base_([&](auto* base) { using Base = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if (base->DIM == dim) r_base = (Base*)this; }); assert((r_base != nullptr) && "No base class has this MSDim!"); return *r_base; } /// is any/some/all dimension in this range populated? HasRangeType hasRange() const { constexpr size_t total {sizeof...(RangeBases)}; // total number of bases size_t count {0}; for_each_base_([&](auto* base) { count += ! base->isEmpty(); }); switch (count) { case 0: return HasRangeType::NONE; case total: return HasRangeType::ALL; default: return HasRangeType::SOME; } } /// Are all dimensions of @p rhs (which overlap with this Range) contained in this range? /// An empty dimension is considered contained in the other dimension (even if that one is empty as well). /// If only all overlapping dimensions are empty, true is returned. /// @throws Exception::InvalidRange if no dimensions overlap template<typename... RangeBasesOther> bool containsAll(const RangeManager<RangeBasesOther...>& rhs) const { bool contained = true; // assume rhs is contained, until proven otherwise bool has_overlap = false; for_each_base_([&](auto* base) { using T_BASE = std::decay_t<decltype(*base)>; // remove const/ref qualifiers if constexpr (std::is_base_of_v<T_BASE, RangeManager<RangeBasesOther...>>) { has_overlap = true; // at least one dimension overlaps if (((T_BASE&)rhs).isEmpty()) return; if (base->contains((T_BASE&)rhs)) return; contained = false; } }); if (! has_overlap) throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); return contained; } /// Resets all ranges void clearRanges() { for_each_base_([&](auto* base) { base->clear(); }); } /// Resets the dimension of the given @p range. Any type of ion mobility in @p range will clear the Mobility dimension. /// If the @p range is not contained in this class, then nothing happens. ThisRangeType& clear(const DIM_UNIT range) { switch (range) { case DIM_UNIT::RT: if constexpr (std::is_base_of_v<RangeRT, ThisRangeType>) this->RangeRT::clear(); break; case DIM_UNIT::MZ: if constexpr (std::is_base_of_v<RangeMZ, ThisRangeType>) this->RangeMZ::clear(); break; case DIM_UNIT::INT: if constexpr (std::is_base_of_v<RangeIntensity, ThisRangeType>) this->RangeIntensity::clear(); break; // assume all ion mobility ranges are the same and never occur together. If this is violated at some point, then split RangeMobility into // subclasses... case DIM_UNIT::IM_MS: case DIM_UNIT::IM_VSSC: case DIM_UNIT::FAIMS_CV: if constexpr (std::is_base_of_v<RangeMobility, ThisRangeType>) this->RangeMobility::clear(); break; default: // all cases should be covered above assert(false && "This should never be reached. Did you forget to implement a new DIM_UNIT?"); } return *this; } /// print each dimension (base classes) to a stream void printRange(std::ostream& out) const { for_each_base_([&](auto* base) { out << *base; }); } protected: /// use fold expression to iterate over all RangeBases of RangeManager and apply a lambda (Visitor) for each one template<typename Visitor> void for_each_base_(Visitor&& visitor) { (void(visitor(static_cast<RangeBases*>(this))), ...); } /// .. and a const version template<typename Visitor> void for_each_base_(Visitor&& visitor) const { (void(visitor(static_cast<const RangeBases*>(this))), ...); } /// use fold expression to iterate over all RangeBases of RangeManager and apply a lambda (Visitor) for each one (for static members) template<typename Visitor> static void static_for_each_base_(Visitor&& visitor) { (void(visitor(static_cast<const RangeBases*>(nullptr))), ...); } }; template<typename... Range> std::ostream& operator<<(std::ostream& out, const RangeManager<Range...>& me) { me.printRange(out); return out; } /// use this class as a base class for containers, e.g. MSSpectrum. It forces them to implement 'updateRanges()' as a common interface /// and provides a 'getRange()' member which saves casting to a range type manually template<typename... RangeBases> class RangeManagerContainer : public RangeManager<RangeBases...> { public: using ThisRangeType = typename RangeManager<RangeBases...>::ThisRangeType; /// D'tor virtual ~RangeManagerContainer() = default; // required since we have virtual methods /// implement this function to reflect the underlying data of the derived class (e.g. an MSSpectrum) /// Usually, call clearRanges() internally and then populate the dimensions. virtual void updateRanges() = 0; /// get range of current data (call updateRanges() before to ensure the range is accurate) const ThisRangeType& getRange() const { return (ThisRangeType&)*this; } /// get mutable range, provided for efficiency reasons (avoid updateRanges(), if only minor changes were made) ThisRangeType& getRange() { return (ThisRangeType&)*this; } }; /// Range which contains all known dimensions using RangeAllType = RangeManager<RangeRT, RangeMZ, RangeIntensity, RangeMobility>; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/MRMTransitionGroup.h
.h
16,003
476
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/KERNEL/MRMFeature.h> #include <boost/numeric/conversion/cast.hpp> namespace OpenMS { /** @brief The representation of a group of transitions in a targeted proteomics experiment. The transition group carries information about the transitions (assays), the individual chromatograms as well as features found on these chromatograms. On the one hand, the MRMTransitionGroup provides a convenient way to store the mapping between the individual transitions (containing the meta-data) and the actual chromatographic data points (measured data) relating to it. In addition, the structure allows storage of features found (regions of the chromatograms) where a potential elution peak was detected (see MRMFeature). Note that these features are usually found on the full collection of chromatograms and therefore relate to the whole collection of chromatograms. Note that for the data structure to be consistent, it needs to have the same identifiers for the chromatograms as well as for the transitions. Since not all the functions in OpenMS will work with MSChromatogram data structures, this needs to accept also MSSpectrum as a type for raw data storage. */ template <typename ChromatogramType, typename TransitionType> class MRMTransitionGroup { public: ///Type definitions //@{ /// List of MRM Features type typedef std::vector<MRMFeature> MRMFeatureListType; /// List of Reaction Monitoring transitions (meta data) type typedef std::vector<TransitionType> TransitionsType; /// Peak type typedef typename ChromatogramType::PeakType PeakType; //@} /** @name Constructors and Destructor */ //@{ /// Default constructor MRMTransitionGroup() { } /// Copy Constructor MRMTransitionGroup(const MRMTransitionGroup & rhs) : tr_gr_id_(rhs.tr_gr_id_), transitions_(rhs.transitions_), chromatograms_(rhs.chromatograms_), precursor_chromatograms_(rhs.precursor_chromatograms_), mrm_features_(rhs.mrm_features_), chromatogram_map_(rhs.chromatogram_map_), precursor_chromatogram_map_(rhs.precursor_chromatogram_map_), transition_map_(rhs.transition_map_) { } /// Destructor virtual ~MRMTransitionGroup() { } //@} MRMTransitionGroup & operator=(const MRMTransitionGroup & rhs) { if (&rhs != this) { tr_gr_id_ = rhs.tr_gr_id_; transitions_ = rhs.transitions_; chromatograms_ = rhs.chromatograms_; precursor_chromatograms_ = rhs.precursor_chromatograms_; mrm_features_ = rhs.mrm_features_; transition_map_ = rhs.transition_map_; chromatogram_map_ = rhs.chromatogram_map_; precursor_chromatogram_map_ = rhs.precursor_chromatogram_map_; } return *this; } inline Size size() const { return chromatograms_.size(); } inline const String & getTransitionGroupID() const { return tr_gr_id_; } inline void setTransitionGroupID(const String & tr_gr_id) { tr_gr_id_ = tr_gr_id; } /// @name Transition access //@{ inline const std::vector<TransitionType> & getTransitions() const { return transitions_; } inline std::vector<TransitionType> & getTransitionsMuteable() { return transitions_; } /** Add a transition * * Transitions are internally mapped using their nativeID, * i.e. TransitionType::getNativeID. * * When querying for a transition, make sure to use this key. */ inline void addTransition(const TransitionType& transition, const String& key) { // store the index where to find the transition, using the key for lookup auto result = transition_map_.emplace(key, int(transitions_.size())); if (!result.second) // ouch: key was already used { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Internal error: Transition with nativeID was already present!", key); } transitions_.push_back(transition); } inline bool hasTransition(const String& key) const { return transition_map_.find(key) != transition_map_.end(); } inline const TransitionType& getTransition(const String& key) { OPENMS_PRECONDITION(hasTransition(key), "Cannot retrieve transitions that does not exist") OPENMS_PRECONDITION(transitions_.size() > (size_t)transition_map_[key], "Mapping needs to be accurate") return transitions_[transition_map_[key]]; } //@} /// @name (Fragment ion) chromatogram access //@{ inline std::vector<ChromatogramType>& getChromatograms() { return chromatograms_; } inline const std::vector<ChromatogramType>& getChromatograms() const { return chromatograms_; } /** Add a chromatogram * * Chromatograms are internally mapped using the provided key. * The ChromatogramType::getNativeID is a good choice. * * When querying for a chromatogram, make sure to use this key. */ inline void addChromatogram(const ChromatogramType& chromatogram, const String& key) { // store the index where to find the chromatogram, using the key for lookup auto result = chromatogram_map_.emplace(key, int(chromatograms_.size())); if (!result.second) // ouch: key was already used { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Internal error: Chromatogram with nativeID was already present!", key); } chromatograms_.push_back(chromatogram); } inline bool hasChromatogram(const String& key) const { return chromatogram_map_.find(key) != chromatogram_map_.end(); } inline ChromatogramType& getChromatogram(const String& key) { OPENMS_PRECONDITION(hasChromatogram(key), "Cannot retrieve chromatogram that does not exist") OPENMS_PRECONDITION(chromatograms_.size() > (size_t)chromatogram_map_[key], "Mapping needs to be accurate") return chromatograms_[chromatogram_map_.at(key)]; } inline const ChromatogramType& getChromatogram(const String& key) const { OPENMS_PRECONDITION(hasChromatogram(key), "Cannot retrieve chromatogram that does not exist") OPENMS_PRECONDITION(chromatograms_.size() > (size_t)chromatogram_map_.at(key), "Mapping needs to be accurate") return chromatograms_[chromatogram_map_.at(key)]; } //@} /// @name (Precursor ion) chromatogram access //@{ inline std::vector<ChromatogramType>& getPrecursorChromatograms() { return precursor_chromatograms_; } inline const std::vector<ChromatogramType>& getPrecursorChromatograms() const { return precursor_chromatograms_; } /** Add a precursor chromatogram (extracted from an MS1 map) * * Precursor chromatograms are internally mapped using the provided key, * i.e. ChromatogramType::getNativeID. * * When querying for a chromatogram, make sure to use this key. * * @param[in] chromatogram Chromatographic traces from the MS1 map to be added * @param[in] key Unique identifier of the chromatogram, e.g. its nativeID */ inline void addPrecursorChromatogram(const ChromatogramType& chromatogram, const String& key) { // store the index where to find the chromatogram, using the key for lookup auto result = precursor_chromatogram_map_.emplace(key, int(precursor_chromatograms_.size())); if (!result.second) // ouch: key was already used { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Internal error: Chromatogram with nativeID was already present!", key); } precursor_chromatograms_.push_back(chromatogram); } inline bool hasPrecursorChromatogram(const String& key) const { return precursor_chromatogram_map_.find(key) != precursor_chromatogram_map_.end(); } inline ChromatogramType & getPrecursorChromatogram(const String& key) { OPENMS_PRECONDITION(hasPrecursorChromatogram(key), "Cannot retrieve precursor chromatogram that does not exist") OPENMS_PRECONDITION(precursor_chromatograms_.size() > (size_t)precursor_chromatogram_map_.at(key), "Mapping needs to be accurate") return precursor_chromatograms_[precursor_chromatogram_map_.at(key)]; } inline const ChromatogramType & getPrecursorChromatogram(const String& key) const { OPENMS_PRECONDITION(hasPrecursorChromatogram(key), "Cannot retrieve precursor chromatogram that does not exist") OPENMS_PRECONDITION(precursor_chromatograms_.size() > (size_t)precursor_chromatogram_map_.at(key), "Mapping needs to be accurate") return precursor_chromatograms_[precursor_chromatogram_map_.at(key)]; } //@} /// @name MRM feature access (positions in RT where a peak was found across all chromatograms) //@{ inline const std::vector<MRMFeature> & getFeatures() const { return mrm_features_; } inline std::vector<MRMFeature> & getFeaturesMuteable() { return mrm_features_; } inline void addFeature(const MRMFeature & feature) { mrm_features_.push_back(feature); } inline void addFeature(MRMFeature && feature) { mrm_features_.push_back(std::move(feature)); } //@} /// @name Helper functions //@{ /// Check whether internal state is consistent, e.g. same number of chromatograms and transitions are present (no runtime overhead in release mode) inline bool isInternallyConsistent() const { OPENMS_PRECONDITION(transitions_.size() == chromatograms_.size(), "Same number of transitions as chromatograms are required") OPENMS_PRECONDITION(transition_map_.size() == chromatogram_map_.size(), "Same number of transitions as chromatograms mappings are required") OPENMS_PRECONDITION(isMappingConsistent_(), "Mapping needs to be consistent") return true; } /// Ensure that chromatogram native ids match their keys in the map inline bool chromatogramIdsMatch() const { for (std::map<String, int>::const_iterator it = chromatogram_map_.begin(); it != chromatogram_map_.end(); it++) { if (getChromatogram(it->first).getNativeID() != it->first) { return false; } } for (std::map<String, int>::const_iterator it = precursor_chromatogram_map_.begin(); it != precursor_chromatogram_map_.end(); it++) { if (getPrecursorChromatogram(it->first).getNativeID() != it->first) { return false; } } return true; } void getLibraryIntensity(std::vector<double> & result) const { for (typename TransitionsType::const_iterator it = transitions_.begin(); it != transitions_.end(); ++it) { result.push_back(it->getLibraryIntensity()); } for (Size i = 0; i < result.size(); i++) { // the library intensity should never be below zero if (result[i] < 0.0) { result[i] = 0.0; } } } MRMTransitionGroup subset(std::vector<std::string> tr_ids) const { MRMTransitionGroup transition_group_subset; transition_group_subset.setTransitionGroupID(tr_gr_id_); for (const auto& tr : transitions_) { if (std::find(tr_ids.begin(), tr_ids.end(), tr.getNativeID()) != tr_ids.end()) { if (this->hasTransition(tr.getNativeID())) { transition_group_subset.addTransition(tr, tr.getNativeID()); } if (this->hasChromatogram(tr.getNativeID())) { transition_group_subset.addChromatogram(chromatograms_[chromatogram_map_.at(tr.getNativeID())], tr.getNativeID()); } } } for (const auto& pc : precursor_chromatograms_) { // add precursor chromatograms if present transition_group_subset.addPrecursorChromatogram(pc, pc.getNativeID()); } for (const auto& tgf : mrm_features_) { MRMFeature mf; mf.setIntensity(tgf.getIntensity()); mf.setRT(tgf.getRT()); mf.MetaInfoInterface::operator=(tgf); for (const auto& tr : transitions_) { if (std::find(tr_ids.begin(), tr_ids.end(), tr.getNativeID()) != tr_ids.end()) { mf.addFeature(tgf.getFeature(tr.getNativeID()),tr.getNativeID()); } } std::vector<String> pf_ids; tgf.getPrecursorFeatureIDs(pf_ids); for (const auto& pf_id : pf_ids) { mf.addPrecursorFeature(tgf.getPrecursorFeature(pf_id), pf_id); } transition_group_subset.addFeature(mf); } return transition_group_subset; } MRMTransitionGroup subsetDependent(std::vector<std::string> tr_ids) const { MRMTransitionGroup transition_group_subset; transition_group_subset.setTransitionGroupID(tr_gr_id_); for (typename TransitionsType::const_iterator tr_it = transitions_.begin(); tr_it != transitions_.end(); ++tr_it) { if (std::find(tr_ids.begin(), tr_ids.end(), tr_it->getNativeID()) != tr_ids.end()) { transition_group_subset.addTransition(*tr_it, tr_it->getNativeID()); transition_group_subset.addChromatogram(chromatograms_[chromatogram_map_.at(tr_it->getNativeID())], tr_it->getNativeID()); } } for (std::vector< MRMFeature >::const_iterator tgf_it = mrm_features_.begin(); tgf_it != mrm_features_.end(); ++tgf_it) { transition_group_subset.addFeature(*tgf_it); } return transition_group_subset; } //@} /** @brief Returns the best feature by overall quality. For the given transition group, return the best feature as determined by the overall quality score. Requires the feature list to not be empty. */ const MRMFeature& getBestFeature() const { OPENMS_PRECONDITION(!getFeatures().empty(), "Cannot get best feature for empty transition group") // Find the feature with the highest score Size bestf = 0; double highest_score = getFeatures()[0].getOverallQuality(); for (Size it = 0; it < getFeatures().size(); it++) { if (getFeatures()[it].getOverallQuality() > highest_score) { bestf = it; highest_score = getFeatures()[it].getOverallQuality(); } } return getFeatures()[bestf]; } protected: /// Checks that the mapping between chromatograms and transitions is consistent bool isMappingConsistent_() const { if (transition_map_.size() != chromatogram_map_.size()) { return false; } for (std::map<String, int>::const_iterator it = chromatogram_map_.begin(); it != chromatogram_map_.end(); it++) { if (!hasTransition(it->first)) { return false; } } return true; } /// transition group id (peak group id) String tr_gr_id_; /// transition list TransitionsType transitions_; /// chromatogram list std::vector<ChromatogramType> chromatograms_; /// precursor chromatogram list std::vector<ChromatogramType> precursor_chromatograms_; /// feature list MRMFeatureListType mrm_features_; std::map<String, int> chromatogram_map_; std::map<String, int> precursor_chromatogram_map_; std::map<String, int> transition_map_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/KERNEL/ChromatogramPeak.h
.h
6,359
250
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <iosfwd> #include <functional> namespace OpenMS { /** @brief A 1-dimensional raw data point or peak for chromatograms. This datastructure is intended for chromatograms. @ingroup Kernel */ class OPENMS_DLLAPI ChromatogramPeak { public: /** @name Type definitions */ //@{ /// Dimension enum {DIMENSION = 1}; /// Intensity type typedef double IntensityType; /// Position type typedef DPosition<1> PositionType; /// Coordinate type typedef double CoordinateType; //@} /** @name Constructors and Destructor */ //@{ /// Default constructor inline ChromatogramPeak() : position_(), intensity_(0) {} /// Copy constructor ChromatogramPeak(const ChromatogramPeak & p) = default; /// Constructor with position and intensity inline ChromatogramPeak(const PositionType retention_time, const IntensityType intensity) : position_(retention_time), intensity_(intensity) {} /** @brief Destructor @note The destructor is non-virtual although many classes are derived from ChromatogramPeak. This is intentional, since otherwise we would "waste" space for a vtable pointer in each instance. Normally you should not derive other classes from ChromatogramPeak (unless you know what you are doing, of course). */ ~ChromatogramPeak() {} //@} /** @name Accessors */ //@{ /// Non-mutable access to the data point intensity (height) inline IntensityType getIntensity() const { return intensity_; } /// Mutable access to the data point intensity (height) inline void setIntensity(IntensityType intensity) { intensity_ = intensity; } /// Non-mutable access to RT inline CoordinateType getRT() const { return position_[0]; } /// Mutable access to RT inline void setRT(CoordinateType rt) { position_[0] = rt; } /// Alias for getRT() inline CoordinateType getPos() const { return position_[0]; } /// Alias for setRT() inline void setPos(CoordinateType pos) { position_[0] = pos; } /// Non-mutable access to the position inline PositionType const & getPosition() const { return position_; } /// Mutable access to the position inline PositionType & getPosition() { return position_; } /// Mutable access to the position inline void setPosition(PositionType const & position) { position_ = position; } //@} /// Assignment operator ChromatogramPeak & operator=(const ChromatogramPeak & rhs) = default; /// Equality operator inline bool operator==(const ChromatogramPeak& rhs) const = default; /// Equality operator inline bool operator!=(const ChromatogramPeak & rhs) const { return !(operator==(rhs)); } /** @name Comparator classes. These classes implement binary predicates that can be used to compare two peaks with respect to their intensities, positions. */ //@{ /// Comparator by intensity struct IntensityLess { inline bool operator()(ChromatogramPeak const & left, ChromatogramPeak const & right) const { return left.getIntensity() < right.getIntensity(); } inline bool operator()(ChromatogramPeak const & left, IntensityType right) const { return left.getIntensity() < right; } inline bool operator()(IntensityType left, ChromatogramPeak const & right) const { return left < right.getIntensity(); } inline bool operator()(IntensityType left, IntensityType right) const { return left < right; } }; /// Comparator by RT position. struct RTLess { inline bool operator()(const ChromatogramPeak & left, const ChromatogramPeak & right) const { return left.getRT() < right.getPos(); } inline bool operator()(ChromatogramPeak const & left, CoordinateType right) const { return left.getRT() < right; } inline bool operator()(CoordinateType left, ChromatogramPeak const & right) const { return left < right.getRT(); } inline bool operator()(CoordinateType left, CoordinateType right) const { return left < right; } }; /// Comparator by position. As this class has dimension 1, this is basically an alias for RTLess. struct PositionLess { inline bool operator()(const ChromatogramPeak & left, const ChromatogramPeak & right) const { return left.getPosition() < right.getPosition(); } inline bool operator()(const ChromatogramPeak & left, const PositionType & right) const { return left.getPosition() < right; } inline bool operator()(const PositionType & left, const ChromatogramPeak & right) const { return left < right.getPosition(); } inline bool operator()(const PositionType & left, const PositionType & right) const { return left < right; } }; //@} protected: /// The data point position PositionType position_; /// The data point intensity IntensityType intensity_; }; ///Print the contents to a stream. OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const ChromatogramPeak & point); } // namespace OpenMS // Hash function specialization for ChromatogramPeak namespace std { template<> struct hash<OpenMS::ChromatogramPeak> { std::size_t operator()(const OpenMS::ChromatogramPeak& p) const noexcept { std::size_t seed = OpenMS::hash_float(p.getRT()); OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIntensity())); return seed; } }; } // namespace std
Unknown