File: InternalCalibration.C

package info (click to toggle)
openms 1.11.1-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 436,688 kB
  • ctags: 150,907
  • sloc: cpp: 387,126; xml: 71,547; python: 7,764; ansic: 2,626; php: 2,499; sql: 737; ruby: 342; sh: 325; makefile: 128
file content (242 lines) | stat: -rw-r--r-- 11,226 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// --------------------------------------------------------------------------
//                   OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of any author or any participating institution
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Alexandra Zerck $
// $Authors: $
// --------------------------------------------------------------------------


#include <OpenMS/FILTERING/CALIBRATION/InternalCalibration.h>
#include <OpenMS/ANALYSIS/ID/IDMapper.h>
#include <stdio.h>

namespace OpenMS
{

  InternalCalibration::InternalCalibration() :
    DefaultParamHandler("InternalCalibration"),
    ProgressLogger(),
    trafo_(TransformationDescription::DataPoints())
  {
    defaults_.setValue("mz_tolerance", 1., "Allowed tolerance between peak and reference m/z.");
    defaults_.setMinFloat("mz_tolerance", 0.);
    defaults_.setValue("mz_tolerance_unit", "Da", "Unit for mz_tolerance.");
    defaults_.setValidStrings("mz_tolerance_unit", StringList::create("Da,ppm"));
    defaults_.setValue("rt_tolerance", 10, "Allowed tolerance between peak and reference rt.");
    // defaults_.setValue("hires:percentage",30,"Percentage of spectra a signal has to appear in to be considered as background signal.");
    defaultsToParam_();
  }

  void InternalCalibration::checkReferenceIds_(std::vector<PeptideIdentification> & pep_ids)
  {
    for (Size p_id = 0; p_id < pep_ids.size(); ++p_id)
    {
      if (pep_ids[p_id].getHits().size() > 1)
      {
        throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, "InternalCalibration: Your Id-file contains PeptideIdentifications with more than one hit, use the IDFilter to select only the best hits.");
      }
      if (!pep_ids[p_id].metaValueExists("RT"))
      {
        throw Exception::MissingInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__, "InternalCalibration: meta data value 'RT' missing for peptide identification!");
      }
      if (!pep_ids[p_id].metaValueExists("MZ"))
      {
        throw Exception::MissingInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__, "InternalCalibration: meta data value 'MZ' missing for peptide identification!");
      }
    }
  }

  void InternalCalibration::makeLinearRegression_(std::vector<DoubleReal> & observed_masses, std::vector<DoubleReal> & theoretical_masses)
  {
    if (observed_masses.size() != theoretical_masses.size())
    {
      throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Number of observed and theoretical masses must agree.");
    }
#ifdef DEBUG_CALIBRATION
    std::ofstream out("calibration_regression.txt");
    std::vector<DoubleReal> rel_errors(observed_masses.size(), 0.);
    // determine rel error in ppm for the two reference masses
    for (Size ref_peak = 0; ref_peak < observed_masses.size(); ++ref_peak)
    {
      rel_errors[ref_peak] = (theoretical_masses[ref_peak] - observed_masses[ref_peak]) / theoretical_masses[ref_peak] * 1e6;

      out << observed_masses[ref_peak] << "\t" << rel_errors[ref_peak] << "\n";
      std::cout << observed_masses[ref_peak] << " " << theoretical_masses[ref_peak] << std::endl;
      // std::cout << observed_masses[ref_peak]<<"\t"<<rel_errors[ref_peak]<<std::endl;
    }
#endif

    TransformationDescription::DataPoints data;
    for (Size i = 0; i < observed_masses.size(); ++i)
    {
      data.push_back(std::make_pair(observed_masses[i],
                                    theoretical_masses[i]));
    }

    trafo_ = TransformationDescription(data);
    trafo_.fitModel("linear", Param());

#ifdef DEBUG_CALIBRATION
    //          std::cout <<"\n\n---------------------------------\n\n"<< "after calibration "<<std::endl;
    for (Size i = 0; i < observed_masses.size(); ++i)
    {
      DoubleReal new_mass = trafo_.apply(observed_masses[i]);

      DoubleReal rel_error = (theoretical_masses[i] - (new_mass)) / theoretical_masses[i] * 1e6;
      std::cout << observed_masses[i] << "\t" << rel_error << std::endl;
    }
#endif
  }

  void InternalCalibration::calibrateMapGlobally(const FeatureMap<> & feature_map, FeatureMap<> & calibrated_feature_map,
                                                 String trafo_file_name)
  {
    // check if the ids
    checkReferenceIds_(feature_map);
    // first collect theoretical and observed m/z values
    std::vector<DoubleReal> observed_masses;
    std::vector<DoubleReal> theoretical_masses;
    for (Size f = 0; f < feature_map.size(); ++f)
    {
      // if more than one peptide id exists for this feature we can't use it as reference
      if (feature_map[f].getPeptideIdentifications().size() > 1)
        continue;
      if (!feature_map[f].getPeptideIdentifications().empty())
      {
        Int charge = feature_map[f].getPeptideIdentifications()[0].getHits()[0].getCharge();
        DoubleReal theo_mass = feature_map[f].getPeptideIdentifications()[0].getHits()[0].getSequence().getMonoWeight(Residue::Full, charge) / (DoubleReal)charge;
        theoretical_masses.push_back(theo_mass);
        observed_masses.push_back(feature_map[f].getMZ());
#ifdef DEBUG_CALIBRATION
        std::cout << feature_map[f].getRT() << " " << feature_map[f].getMZ() << " " << theo_mass << std::endl;
        std::cout << feature_map[f].getPeptideIdentifications()[0].getHits().size() << std::endl;
        std::cout << feature_map[f].getPeptideIdentifications()[0].getHits()[0].getSequence() << std::endl;
        std::cout << feature_map[f].getPeptideIdentifications()[0].getHits()[0].getCharge() << std::endl;
#endif
      }
    }
    // then make the linear regression
    makeLinearRegression_(observed_masses, theoretical_masses);
    // apply transformation
    applyTransformation_(feature_map, calibrated_feature_map);
    if (trafo_file_name != "")
    {
      TransformationXMLFile().store(trafo_file_name, trafo_);
    }
  }

  void InternalCalibration::calibrateMapGlobally(const FeatureMap<> & feature_map, FeatureMap<> & calibrated_feature_map, std::vector<PeptideIdentification> & ref_ids, String trafo_file_name)
  {
    checkReferenceIds_(ref_ids);

    calibrated_feature_map = feature_map;
    // clear the ids
    for (Size f = 0; f < calibrated_feature_map.size(); ++f)
    {
      calibrated_feature_map[f].getPeptideIdentifications().clear();
    }

    // map the reference ids onto the features
    IDMapper mapper;
    Param param;
    param.setValue("rt_tolerance", (DoubleReal)param_.getValue("rt_tolerance"));
    param.setValue("mz_tolerance", param_.getValue("mz_tolerance"));
    param.setValue("mz_measure", param_.getValue("mz_tolerance_unit"));
    mapper.setParameters(param);
    std::vector<ProteinIdentification> vec;
    mapper.annotate(calibrated_feature_map, ref_ids, vec);

    // calibrate
    calibrateMapGlobally(calibrated_feature_map, calibrated_feature_map, trafo_file_name);

    // copy the old ids
    calibrated_feature_map.setUnassignedPeptideIdentifications(feature_map.getUnassignedPeptideIdentifications());
    for (Size f = 0; f < feature_map.size(); ++f)
    {
      calibrated_feature_map[f].getPeptideIdentifications().clear();
      if (!feature_map[f].getPeptideIdentifications().empty())
      {
        calibrated_feature_map[f].setPeptideIdentifications(feature_map[f].getPeptideIdentifications());
      }
    }
  }

  void InternalCalibration::applyTransformation_(const FeatureMap<> & feature_map, FeatureMap<> & calibrated_feature_map)
  {
    calibrated_feature_map = feature_map;
    for (Size f = 0; f < feature_map.size(); ++f)
    {
      DoubleReal mz = feature_map[f].getMZ();
      mz = trafo_.apply(mz);
      calibrated_feature_map[f].setMZ(mz);

      // apply transformation to convex hulls and subordinates
      for (Size s = 0; s < calibrated_feature_map[f].getSubordinates().size(); ++s)
      {
        // subordinates
        DoubleReal mz = calibrated_feature_map[f].getSubordinates()[s].getMZ();
        mz = trafo_.apply(mz);
        calibrated_feature_map[f].getSubordinates()[s].setMZ(mz);
      }
      for (Size s = 0; s < calibrated_feature_map[f].getConvexHulls().size(); ++s)
      {
        // convex hulls
        std::vector<DPosition<2> > point_vec = calibrated_feature_map[f].getConvexHulls()[s].getHullPoints();
        calibrated_feature_map[f].getConvexHulls()[s].clear();
        for (Size p = 0; p < point_vec.size(); ++p)
        {
          DoubleReal mz = point_vec[p][1];
          mz = trafo_.apply(mz);
          point_vec[p][1] = mz;
        }
        calibrated_feature_map[f].getConvexHulls()[s].setHullPoints(point_vec);
      }
    }
  }

  void InternalCalibration::checkReferenceIds_(const FeatureMap<> & feature_map)
  {
    Size num_ids = 0;
    for (Size f = 0; f < feature_map.size(); ++f)
    {
      if (!feature_map[f].getPeptideIdentifications().empty() && feature_map[f].getPeptideIdentifications()[0].getHits().size() > 1)
      {
        throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, "InternalCalibration: Your feature map contains PeptideIdentifications with more than one hit, use the IDFilter to select only the best hits before you map the ids to the feature map.");
      }
      else if (!feature_map[f].getPeptideIdentifications().empty())
        ++num_ids;
    }
    if (num_ids < 2)
    {
      throw Exception::InvalidParameter(__FILE__, __LINE__, __PRETTY_FUNCTION__, "InternalCalibration: Your feature map contains less than two PeptideIdentifications, can't perform a linear regression on your data.");
    }
  }

}