libpappsomspp
Library for mass spectrometry
utils.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * Copyright (c) 2015 Olivier Langella <Olivier.Langella@moulon.inra.fr>.
3  *
4  * This file is part of the PAPPSOms++ library.
5  *
6  * PAPPSOms++ is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * PAPPSOms++ is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with PAPPSOms++. If not, see <http://www.gnu.org/licenses/>.
18  *
19  * Contributors:
20  * Olivier Langella <Olivier.Langella@moulon.inra.fr> - initial API and
21  *implementation
22  ******************************************************************************/
23 
24 /////////////////////// StdLib includes
25 #include <cmath>
26 #include <iomanip>
27 
28 
29 /////////////////////// Qt includes
30 #include <QDebug>
31 #include <QFile>
32 #include <QTextStream>
33 
34 
35 /////////////////////// Local includes
36 #include "utils.h"
37 #include "types.h"
39 #include "trace/trace.h"
40 
41 
42 namespace pappso
43 {
44 
45 
46 QRegularExpression Utils::xyMassDataFormatRegExp =
47  QRegularExpression("^(\\d*\\.?\\d+)([^\\d^\\.^-]+)(-?\\d*\\.?\\d*[e-]?\\d*)");
48 
49 QRegularExpression Utils::endOfLineRegExp = QRegularExpression("^\\s+$");
50 
51 const QString
53 {
54  int size = log10(num);
55  size += 97;
56  QString base(size);
57  base.append(QString().setNum(num));
58  return (base);
59 }
60 
61 
62 void
63 Utils::writeLexicalOrderedString(QTextStream *p_out, unsigned int num)
64 {
65  *p_out << (char)(log10(num) + 97) << num;
66 }
67 
68 
69 //! Determine the number of zero decimals between the decimal point and the
70 //! first non-zero decimal.
71 /*!
72  * 0.11 would return 0 (no empty decimal)
73  * 2.001 would return 2
74  * 1000.0001254 would return 3
75  *
76  * \param value the value to be analyzed
77  * \return the number of '0' decimals between the decimal separator '.' and
78  * the first non-0 decimal
79  */
80 int
82 {
83  int intPart = static_cast<int>(value);
84 
85  double decimalPart = value - intPart;
86 
87  int count = -1;
88 
89  while(1)
90  {
91  ++count;
92 
93  decimalPart *= 10;
94 
95  if(decimalPart > 1)
96  return count;
97  }
98 
99  return count;
100 }
101 
102 
104 Utils::roundToDecimals(pappso_double value, int decimal_places)
105 {
106  if(decimal_places < 0)
107  return value;
108 
109  return ceil((value * pow(10, decimal_places)) - 0.49) /
110  pow(10, decimal_places);
111 }
112 
113 
114 long long int
116 {
117  pappso::pappso_double test_decimal = 100000000000;
118  if(sizeof(int *) == 4)
119  { // 32bits
120  test_decimal = 100000000;
121  }
122  return (floor(input * test_decimal));
123 }
124 
125 
126 std::string
127 Utils::toUtf8StandardString(const QString &text)
128 {
129  std::string env_backup = setlocale(LC_ALL, "");
130 
131  // struct lconv *lc_backup = localeconv();
132  // qDebug() << __FILE__ << "@" << __LINE__ << __FUNCTION__ << "()"
133  //<< "env_backup=" << env_backup.c_str() << "lc_backup->decimal_point"
134  //<< lc_backup->decimal_point;
135 
136  // Force locale to be "C".
137  setlocale(LC_ALL, "C");
138 
139  // Now perform the conversion.
140  QByteArray byte_array = text.toUtf8();
141  std::string stdText = "";
142 
143  for(char c : byte_array)
144  {
145  stdText += c;
146  }
147 
148  // Set back the locale to the backed-up one.
149  setlocale(LC_ALL, env_backup.c_str());
150 
151  return stdText;
152 }
153 
154 
155 bool
156 Utils::writeToFile(const QString &text, const QString &file_name)
157 {
158 
159  QFile file(file_name);
160 
161  if(file.open(QFile::WriteOnly | QFile::Truncate))
162  {
163 
164  QTextStream out(&file);
165 
166  out << text;
167 
168  out.flush();
169  file.close();
170 
171  return true;
172  }
173 
174  return false;
175 }
176 
177 
178 bool
179 Utils::appendToFile(const QString &text, const QString &file_name)
180 {
181 
182  QFile file(file_name);
183 
184  if(file.open(QFile::WriteOnly | QFile::Append))
185  {
186 
187  QTextStream out(&file);
188 
189  out << text;
190 
191  out.flush();
192  file.close();
193 
194  return true;
195  }
196 
197  return false;
198 }
199 
200 
201 std::size_t
202 Utils::extractScanNumberFromMzmlNativeId(const QString &spectrum_native_id)
203 {
204  qDebug() << " " << spectrum_native_id;
205  QStringList native_id_list = spectrum_native_id.split("=");
206  if(native_id_list.size() < 2)
207  {
208  throw ExceptionNotFound(
209  QObject::tr("scan number not found in mzML native id %1")
210  .arg(spectrum_native_id));
211  }
212  else
213  {
214  /** TODO activate this in a future release to ensure scan number
215  for(auto i = 0; i < native_id_list.size(); i += 2)
216  {
217  if(native_id_list[i] == "scan")
218  {
219  return native_id_list[i + 1].toULong();
220  }
221  }
222 
223  throw ExceptionNotFound(
224  QObject::tr("scan number not found in mzML native id %1")
225  .arg(spectrum_native_id));
226 
227 */
228  return native_id_list.back().toULong();
229  }
230  return 0;
231 }
232 
233 
234 QString
235 Utils::pointerToString(const void *const pointer)
236 {
237  return QString("%1").arg(
238  (quintptr)pointer, QT_POINTER_SIZE * 2, 16, QChar('0'));
239 }
240 
241 
242 //! Tell if both double values, are equal within the double representation
243 //! capabilities of the platform.
244 bool
245 Utils::almostEqual(double value1, double value2, int decimalPlaces)
246 {
247  // QString value1String = QString("%1").arg(value1,
248  // 0, 'f', 60);
249  // QString value2String = QString("%1").arg(value2,
250  // 0, 'f', 60);
251 
252  // qWarning() << __FILE__ << __LINE__ << __FUNCTION__
253  //<< "value1:" << value1String << "value2:" << value2String;
254 
255  // The machine epsilon has to be scaled to the magnitude of the values used
256  // and multiplied by the desired precision in ULPs (units in the last place)
257  // (decimal places).
258 
259  double valueSum = std::abs(value1 + value2);
260  // QString valueSumString = QString("%1").arg(valueSum,
261  // 0, 'f', 60);
262 
263  double valueDiff = std::abs(value1 - value2);
264  // QString valueDiffString = QString("%1").arg(valueDiff,
265  // 0, 'f', 60);
266 
267  double epsilon = std::numeric_limits<double>::epsilon();
268  // QString epsilonString = QString("%1").arg(epsilon,
269  // 0, 'f', 60);
270 
271  double scaleFactor = epsilon * valueSum * decimalPlaces;
272  // QString scaleFactorString = QString("%1").arg(scaleFactor,
273  // 0, 'f', 60);
274 
275  // qWarning() << "valueDiff:" << valueDiffString << "valueSum:" <<
276  // valueSumString <<
277  //"epsilon:" << epsilonString << "scaleFactor:" << scaleFactorString;
278 
279  bool res = valueDiff < scaleFactor
280  // unless the result is subnormal:
281  || valueDiff < std::numeric_limits<double>::min();
282 
283  // qWarning() << __FILE__ << __LINE__ << __FUNCTION__
284  //<< "returning res:" << res;
285 
286  return res;
287 }
288 
289 
290 double
292 {
293  return std::nextafter(value, value + 1);
294 }
295 
296 
297 QString
299  const QString &msg, std::chrono::system_clock::time_point chrono_time)
300 {
301 
302  time_t tt;
303 
304  tt = std::chrono::system_clock::to_time_t(chrono_time);
305 
306  QString debug_text =
307  QString("%1 - %2\n").arg(msg).arg(QString::fromLatin1(ctime(&tt)));
308 
309  return debug_text;
310 }
311 
312 
313 QString
315  const QString &msg,
316  std::chrono::system_clock::time_point chrono_start,
317  std::chrono::system_clock::time_point chrono_finish)
318 {
319  QString debug_text =
320  QString(
321  "%1 %2 min = %3 s = %4 ms = %5 "
322  "µs\n")
323  .arg(msg)
324  .arg(std::chrono::duration_cast<std::chrono::minutes>(chrono_finish -
325  chrono_start)
326  .count())
327  .arg(std::chrono::duration_cast<std::chrono::seconds>(chrono_finish -
328  chrono_start)
329  .count())
330  .arg(std::chrono::duration_cast<std::chrono::milliseconds>(chrono_finish -
331  chrono_start)
332  .count())
333  .arg(std::chrono::duration_cast<std::chrono::microseconds>(chrono_finish -
334  chrono_start)
335  .count());
336 
337  return debug_text;
338 }
339 
340 
341 std::vector<double>
343  std::size_t &error_count)
344 {
345 
346  QStringList string_list =
347  text.split(QRegularExpression("[\\s]+"), QString::SkipEmptyParts);
348 
349  // qDebug() << "string list:" << string_list;
350 
351  std::vector<double> double_vector;
352 
353  for(int iter = 0; iter < string_list.size(); ++iter)
354  {
355  QString current_string = string_list.at(iter);
356 
357  bool ok = false;
358 
359  double current_double = current_string.toDouble(&ok);
360 
361  if(!current_double && !ok)
362  {
363  ++error_count;
364  continue;
365  }
366 
367  double_vector.push_back(current_double);
368  }
369 
370  return double_vector;
371 }
372 
373 
374 std::vector<std::size_t>
376  std::size_t &error_count)
377 {
378  // qDebug() << "Parsing text:" << text;
379 
380  QStringList string_list =
381  text.split(QRegularExpression("[\\s]+"), QString::SkipEmptyParts);
382 
383  // qDebug() << "string list size:" << string_list.size()
384  //<< "values:" << string_list;
385 
386  std::vector<std::size_t> sizet_vector;
387 
388  for(int iter = 0; iter < string_list.size(); ++iter)
389  {
390  QString current_string = string_list.at(iter);
391 
392  bool ok = false;
393 
394  std::size_t current_sizet = current_string.toUInt(&ok);
395 
396  if(!current_sizet && !ok)
397  {
398  ++error_count;
399  continue;
400  }
401 
402  sizet_vector.push_back(current_sizet);
403  }
404 
405  return sizet_vector;
406 }
407 
408 
409 } // namespace pappso
static std::size_t extractScanNumberFromMzmlNativeId(const QString &spectrum_native_id)
Definition: utils.cpp:202
static QString chronoTimePointDebugString(const QString &msg, std::chrono::system_clock::time_point chrono_time=std::chrono::system_clock::now())
Definition: utils.cpp:298
static QString pointerToString(const void *const pointer)
Definition: utils.cpp:235
static pappso_double roundToDecimals(pappso_double value, int decimal_places)
Definition: utils.cpp:104
static bool almostEqual(double value1, double value2, int decimalPlaces=10)
Definition: utils.cpp:245
static std::vector< double > splitMzStringToDoubleVectorWithSpaces(const QString &text, std::size_t &error_count)
Definition: utils.cpp:342
static double nearestGreater(double value)
Definition: utils.cpp:291
static std::string toUtf8StandardString(const QString &text)
Definition: utils.cpp:127
static bool appendToFile(const QString &text, const QString &file_name)
Definition: utils.cpp:179
static QString chronoIntervalDebugString(const QString &msg, std::chrono::system_clock::time_point chrono_start, std::chrono::system_clock::time_point chrono_finish=std::chrono::system_clock::now())
Definition: utils.cpp:314
static bool writeToFile(const QString &text, const QString &file_name)
Definition: utils.cpp:156
static std::vector< std::size_t > splitSizetStringToSizetVectorWithSpaces(const QString &text, std::size_t &error_count)
Definition: utils.cpp:375
static QRegularExpression xyMassDataFormatRegExp
Definition: utils.h:53
static const QString getLexicalOrderedString(unsigned int num)
Definition: utils.cpp:52
static void writeLexicalOrderedString(QTextStream *p_out, unsigned int num)
Definition: utils.cpp:63
static int zeroDecimalsInValue(pappso_double value)
0.11 would return 0 (no empty decimal) 2.001 would return 2 1000.0001254 would return 3
Definition: utils.cpp:81
static QRegularExpression endOfLineRegExp
Regular expression that tracks the end of line in text files.
Definition: utils.h:62
static long long int roundToDecimal32bitsAsLongLongInt(pappso::pappso_double input)
Definition: utils.cpp:115
tries to keep as much as possible monoisotopes, removing any possible C13 peaks and changes multichar...
Definition: aa.cpp:39
double pappso_double
A type definition for doubles.
Definition: types.h:48
This header contains all the type re-definitions and all the global variables definitions used in the...