Home  · Classes  · Annotated Classes  · Modules  · Members  · Namespaces  · Related Pages
DTA2DFile.h
Go to the documentation of this file.
1 // --------------------------------------------------------------------------
2 // OpenMS -- Open-Source Mass Spectrometry
3 // --------------------------------------------------------------------------
4 // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
5 // ETH Zurich, and Freie Universitaet Berlin 2002-2017.
6 //
7 // This software is released under a three-clause BSD license:
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 // * Neither the name of any author or any participating institution
14 // may be used to endorse or promote products derived from this software
15 // without specific prior written permission.
16 // For a full list of authors, refer to the file AUTHORS.
17 // --------------------------------------------------------------------------
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
22 // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25 // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // --------------------------------------------------------------------------
31 // $Maintainer: Timo Sachsenberg $
32 // $Authors: Marc Sturm $
33 // --------------------------------------------------------------------------
34 
35 #ifndef OPENMS_FORMAT_DTA2DFILE_H
36 #define OPENMS_FORMAT_DTA2DFILE_H
37 
42 
43 #include <fstream>
44 #include <iostream>
45 
46 namespace OpenMS
47 {
64  class OPENMS_DLLAPI DTA2DFile :
65  public ProgressLogger
66  {
67 private:
69 
70 public:
71 
74  DTA2DFile();
77  ~DTA2DFile();
79 
81  PeakFileOptions& getOptions();
82 
84  const PeakFileOptions& getOptions() const;
85 
95  template <typename MapType>
96  void load(const String& filename, MapType& map)
97  {
98  startProgress(0, 0, "loading DTA2D file");
99 
100  //try to open file
101  std::ifstream is(filename.c_str());
102  if (!is)
103  {
104  throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
105  }
106 
107  map.reset();
108 
109  //set DocumentIdentifier
110  map.setLoadedFileType(filename);
111  map.setLoadedFilePath(filename);
112 
113  // temporary variables to store the data in
114  std::vector<String> strings(3);
115  typename MapType::SpectrumType spec;
116  spec.setRT(-1.0); //to make sure the first RT is different from the the initialized value
118  double rt(0.0);
119  char delimiter;
120 
121  // default dimension of the data
122  Size rt_dim = 0;
123  Size mz_dim = 1;
124  Size int_dim = 2;
125 
126  //RT unit (default is seconds)
127  bool time_in_minutes = false;
128 
129  // string to store the current line in
130  String line;
131 
132  // native ID (numbers from 0)
133  UInt native_id = 0;
134 
135  // line number counter
136  Size line_number = 0;
137 
138  while (getline(is, line, '\n'))
139  {
140  ++line_number;
141  line.trim();
142 
143  if (line.empty()) continue;
144 
145  //test which delimiter is used in the line
146  if (line.has('\t'))
147  {
148  delimiter = '\t';
149  }
150  else
151  {
152  delimiter = ' ';
153  }
154 
155  //is header line
156  if (line.hasPrefix("#"))
157  {
158  line = line.substr(1).trim();
159  line.split(delimiter, strings);
160 
161  // flags to check if dimension is set correctly
162  bool rt_set = false;
163  bool mz_set = false;
164  bool int_set = false;
165 
166  //assign new order
167  for (Size i = 0; i < 3; ++i)
168  {
169  if (strings[i] == "RT" || strings[i] == "RETENTION_TIME" || strings[i] == "MASS-TO-CHARGE" || strings[i] == "IT" || strings[i] == "INTENSITY")
170  {
171  std::cerr << "Warning: This file contains the deprecated keyword '" << strings[i] << "'." << "\n";
172  std::cerr << " Please use only the new keywords SEC/MIN, MZ, INT." << "\n";
173  }
174  if ((strings[i] == "SEC" || strings[i] == "RT" || strings[i] == "RETENTION_TIME") && rt_set == false)
175  {
176  rt_dim = i;
177  rt_set = true;
178  }
179  else if ((strings[i] == "MIN") && rt_set == false)
180  {
181  rt_dim = i;
182  rt_set = true;
183  time_in_minutes = true;
184  }
185  else if ((strings[i] == "MZ" || strings[i] == "MASS-TO-CHARGE") && mz_set == false)
186  {
187  mz_dim = i;
188  mz_set = true;
189  }
190  else if ((strings[i] == "INT" || strings[i] == "IT" || strings[i] == "INTENSITY") && int_set == false)
191  {
192  int_dim = i;
193  int_set = true;
194  }
195  else
196  {
197  throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Misformatted header line!", filename);
198  }
199  }
200  continue;
201  }
202 
203  try
204  {
205  line.split(delimiter, strings);
206  if (strings.size() != 3)
207  {
208  throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\" (got " + String(strings.size()) + ", expected 3 entries)", filename);
209  }
210  p.setIntensity(strings[int_dim].toFloat());
211  p.setMZ(strings[mz_dim].toDouble());
212  rt = (strings[rt_dim].toDouble()) * (time_in_minutes ? 60.0 : 1.0);
213  }
214  // conversion to double or something else could have gone wrong
215  catch (Exception::BaseException& /*e*/)
216  {
217  throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, std::string("Bad data line (" + String(line_number) + "): \"") + line + "\"", filename);
218  }
219 
220  // Retention time changed -> new Spectrum
221  if (fabs(rt - spec.getRT()) > 0.0001)
222  {
223  if (spec.size() != 0
224  &&
225  (!options_.hasRTRange() || options_.getRTRange().encloses(DPosition<1>(spec.getRT())))) // RT restriction fulfilled
226  {
227  map.addSpectrum(spec);
228  }
229  setProgress(0);
230  spec.clear(true);
231  spec.setRT(rt);
232  spec.setNativeID(String("index=") + native_id);
233  ++native_id;
234  }
235 
236  //Skip peaks with invalid m/z or intensity value
237  if (
238  (!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(p.getMZ())))
239  &&
240  (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(p.getIntensity())))
241  )
242  {
243  spec.push_back(p);
244  }
245  }
246 
247  // add last Spectrum
248  if (
249  spec.size() != 0
250  &&
251  (!options_.hasRTRange() || options_.getRTRange().encloses(DPosition<1>(spec.getRT()))) // RT restriction fulfilled
252  )
253  {
254  map.addSpectrum(spec);
255  }
256 
257  is.close();
258  endProgress();
259  }
260 
269  template <typename MapType>
270  void store(const String& filename, const MapType& map) const
271  {
272  startProgress(0, map.size(), "storing DTA2D file");
273 
274  std::ofstream os(filename.c_str());
275  if (!os)
276  {
277  throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
278  }
279 
280  // write header
281  os << "#SEC\tMZ\tINT\n";
282 
283  // Iterate over all peaks of each spectrum and
284  // write one line for each peak of the spectrum.
285  UInt count = 0;
286  for (typename MapType::const_iterator spec = map.begin(); spec != map.end(); ++spec)
287  {
288  setProgress(count++);
289  for (typename MapType::SpectrumType::ConstIterator it = spec->begin(); it != spec->end(); ++it)
290  {
291  // Write rt, m/z and intensity.
292  os << precisionWrapper(spec->getRT()) << "\t" << precisionWrapper(it->getPos()) << "\t" << precisionWrapper(it->getIntensity()) << "\n";
293  }
294 
295  }
296  os.close();
297  endProgress();
298  }
299 
308  template <typename MapType>
309  void storeTIC(const String& filename, const MapType& map) const
310  {
311  startProgress(0, map.size(), "storing DTA2D file");
312 
313  std::ofstream os(filename.c_str());
314  if (!os)
315  {
316  throw Exception::UnableToCreateFile(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, filename);
317  }
318 
319  // write header (Always MZ=0 for chromatograms in DTA2D.)
320  os << "#SEC\tMZ\tINT\n";
321 
322  typename MapType::ChromatogramType TIC = map.getTIC();
323  for (typename MapType::ChromatogramType::ConstIterator it = TIC.begin(); it != TIC.end(); ++it)
324  {
325  // write rt and intensity.
326  os << precisionWrapper(it->getRT()) << "\t" << precisionWrapper(0) << "\t" << precisionWrapper(it->getIntensity()) << "\n";
327  }
328 
329  os.close();
330  endProgress();
331  }
332 
333  };
334 
335 } // namespace OpenMS
336 
337 #endif // OPENMS_FORMAT_DTA2DFILE_H
DTA2D File adapter.
Definition: DTA2DFile.h:64
bool has(Byte byte) const
true if String contains the byte, false otherwise
A more convenient string class.
Definition: String.h:57
bool encloses(const PositionType &position) const
Checks whether this range contains a certain point.
Definition: DRange.h:172
void reset()
Resets all internal values.
Definition: MSExperiment.h:709
void addSpectrum(const MSSpectrum &spectrum)
adds a spectrum to the list
Definition: MSExperiment.h:831
The representation of a chromatogram.
Definition: MSChromatogram.h:55
CoordinateType getMZ() const
Non-mutable access to m/z.
Definition: Peak1D.h:114
unsigned int UInt
Unsigned integer type.
Definition: Types.h:95
const DRange< 1 > & getMZRange() const
returns the MZ range
PeakFileOptions options_
Definition: DTA2DFile.h:68
Iterator begin()
Definition: MSExperiment.h:162
Base::const_iterator const_iterator
Definition: MSExperiment.h:130
bool hasRTRange() const
returns true if an RT range has been set
File not found exception.
Definition: Exception.h:524
Size size() const
Definition: MSExperiment.h:132
Main OpenMS namespace.
Definition: FeatureDeconvolution.h:47
void setMZ(CoordinateType mz)
Mutable access to m/z.
Definition: Peak1D.h:120
void setIntensity(IntensityType intensity)
Mutable access to the data point intensity (height)
Definition: Peak1D.h:111
const DRange< 1 > & getRTRange() const
returns the RT range
void setLoadedFileType(const String &file_name)
set the file_type according to the type of the file loaded from (see FileHandler::Type) preferably do...
bool hasMZRange() const
returns true if an MZ range has been set
const DRange< 1 > & getIntensityRange() const
returns the intensity range
String substr(size_t pos=0, size_t n=npos) const
Wrapper for the STL substr() method. Returns a String object with its contents initialized to a subst...
Iterator end()
Definition: MSExperiment.h:172
The representation of a 1D spectrum.
Definition: MSSpectrum.h:67
void store(const String &filename, const MapType &map) const
Stores a map in a DTA2D file.
Definition: DTA2DFile.h:270
const PrecisionWrapper< FloatingPointType > precisionWrapper(const FloatingPointType rhs)
Wrapper function that sets the appropriate precision for output temporarily. The original precision i...
Definition: PrecisionWrapper.h:97
String & trim()
removes whitespaces (space, tab, line feed, carriage return) at the beginning and the end of the stri...
A 1-dimensional raw data point or peak.
Definition: Peak1D.h:55
Exception base class.
Definition: Exception.h:90
void clear(bool clear_meta_data)
Clears all data and meta data.
void setRT(double rt)
Sets the absolute retention time (in seconds)
In-Memory representation of a mass spectrometry experiment.
Definition: MSExperiment.h:82
const MSChromatogram getTIC() const
returns the total ion chromatogram (TIC)
Definition: MSExperiment.h:900
std::vector< SpectrumType >::const_iterator ConstIterator
Non-mutable iterator.
Definition: MSExperiment.h:118
bool hasPrefix(const String &string) const
true if String begins with string, false otherwise
size_t Size
Size type e.g. used as variable which can hold result of size()
Definition: Types.h:128
bool hasIntensityRange() const
returns true if an intensity range has been set
Base class for all classes that want to report their progress.
Definition: ProgressLogger.h:55
Unable to create file exception.
Definition: Exception.h:637
void setLoadedFilePath(const String &file_name)
set the file_name_ according to absolute path of the file loaded from preferably done whilst loading ...
void setNativeID(const String &native_id)
sets the native identifier for the spectrum, used by the acquisition software.
Options for loading files containing peak data.
Definition: PeakFileOptions.h:48
void storeTIC(const String &filename, const MapType &map) const
Stores the TIC of a map in a DTA2D file.
Definition: DTA2DFile.h:309
double getRT() const
bool split(const char splitter, std::vector< String > &substrings, bool quote_protect=false) const
Splits a string into substrings using splitter as delimiter.
void load(const String &filename, MapType &map)
Loads a map from a DTA2D file.
Definition: DTA2DFile.h:96
Parse Error exception.
Definition: Exception.h:623
IntensityType getIntensity() const
Definition: Peak1D.h:109

OpenMS / TOPP release 2.3.0 Documentation generated on Tue Jan 9 2018 18:21:59 using doxygen 1.8.13