File: FuzzyStringComparator.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 (531 lines) | stat: -rw-r--r-- 20,199 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// --------------------------------------------------------------------------
//                   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: Stephan Aiche $
// $Authors: Clemens Groepl, Stephan Aiche $
// --------------------------------------------------------------------------

#include <OpenMS/CONCEPT/FuzzyStringComparator.h>
#include <OpenMS/SYSTEM/File.h>
#include <QDir>
#include <sstream>

namespace OpenMS
{

  FuzzyStringComparator::FuzzyStringComparator() :
    log_dest_(&std::cout),
    input_1_name_("input_1"),
    input_2_name_("input_2"),
    input_line_1_(),
    input_line_2_(),
    line_num_1_(0),
    line_num_2_(0),
    line_num_1_max_(-1),
    line_num_2_max_(-1),
    line_str_1_max_(),
    line_str_2_max_(),
    ratio_max_allowed_(1.0),
    ratio_max_(1.0),
    absdiff_max_allowed_(0.0),
    absdiff_max_(0.0),
    element_1_(),
    element_2_(),
    is_absdiff_small_(false),
    verbose_level_(2),
    tab_width_(8),
    first_column_(1),
    is_status_success_(true),
    use_prefix_(false),
    whitelist_(),
    whitelist_cases_()
  {
  }

  FuzzyStringComparator::~FuzzyStringComparator()
  {
  }

  void FuzzyStringComparator::reportFailure_(char const * const message) const
  {
    // We neither want this entire method be non-const nor make
    // is_status_success_ a mutable.  So lets hack around it.  (Documented in
    // class.)
    const_cast<bool &>(is_status_success_) = false;

    if (verbose_level_ >= 1)
    {
      PrefixInfo_ prefix1(input_line_1_, tab_width_, first_column_);
      PrefixInfo_ prefix2(input_line_2_, tab_width_, first_column_);

      std::string prefix;
      if (use_prefix_)
      {
        prefix = "   :|:  ";
      }

      *log_dest_ << std::boolalpha <<
      prefix << "FAILED: '" << message << "'\n" <<
      prefix << "\n" <<
      prefix << "  input:\tin1\tin2\n" <<
      prefix << "  line:\t" << line_num_1_ << '\t' << line_num_2_ << "\n" <<
      prefix << "  pos/col:\t" << input_line_1_.line_position_ << '/' << prefix1.line_column << '\t' << input_line_2_.line_position_ << '/' << prefix2.line_column << "\n" <<
      prefix << " --------------------------------\n" <<
      prefix << "  is_number:\t" << element_1_.is_number << '\t' << element_2_.is_number << "\n" <<
      prefix << "  numbers:\t" << element_1_.number << '\t' << element_2_.number << "\n" <<
      prefix << "  is_space:\t" << element_1_.is_space << '\t' << element_2_.is_space << "\n" <<
      prefix << "  is_letter:\t" << (!element_1_.is_number && !element_1_.is_space) << '\t' << (!element_2_.is_number && !element_2_.is_space) << "\n" <<
      prefix << "  letters:\t\"" << element_1_.letter << "\"\t\"" << element_2_.letter << "\"\n" <<
      prefix << "  char_codes:\t" << static_cast<UInt>(element_1_.letter) << "\t" << static_cast<UInt>(element_2_.letter) << "\n" <<
      prefix << " --------------------------------\n" <<
      prefix << "  relative_max:        " << ratio_max_ << "\n" <<
      prefix << "  relative_acceptable: " << ratio_max_allowed_ << "\n" <<
      prefix << " --------------------------------\n" <<
      prefix << "  absolute_max:        " << absdiff_max_ << "\n" <<
      prefix << "  absolute_acceptable: " << absdiff_max_allowed_ << std::endl;

      writeWhitelistCases_(prefix);

      *log_dest_
      << prefix << "\n"
      << prefix << "Offending lines:\t\t\t(tab_width = " << tab_width_ << ", first_column = " << first_column_ << ")\n"
      << prefix << "\n"
      << prefix << "in1:  " << QDir::toNativeSeparators(File::absolutePath(input_1_name_).toQString()).toStdString() << "   (line: " << line_num_1_ << ", position/column: " << input_line_1_.line_position_ << '/' << prefix1.line_column << ")\n"
      << prefix << prefix1.prefix << "!\n"
      << prefix << prefix1.prefix_whitespaces << OpenMS::String(input_line_1_.line_.str()).suffix(input_line_1_.line_.str().size() - prefix1.prefix.size()) << "\n"
      << prefix <<  "\n"
      << prefix << "in2:  " << QDir::toNativeSeparators(File::absolutePath(input_2_name_).toQString()).toStdString() << "   (line: " << line_num_2_ << ", position/column: " << input_line_2_.line_position_ << '/' << prefix2.line_column << ")\n"
      << prefix << prefix2.prefix << "!\n"
      << prefix << prefix2.prefix_whitespaces << OpenMS::String(input_line_2_.line_.str()).suffix(input_line_2_.line_.str().size() - prefix2.prefix.size()) << "\n"
      << prefix << "\n\n"
      << "Easy Access:" << "\n"
      << QDir::toNativeSeparators(File::absolutePath(input_1_name_).toQString()).toStdString() << ':' << line_num_1_ << ":" << prefix1.line_column << ":\n"
      << QDir::toNativeSeparators(File::absolutePath(input_2_name_).toQString()).toStdString() << ':' << line_num_2_ << ":" << prefix2.line_column << ":\n"
      << "\n"
#ifdef WIN32
      << "TortoiseMerge"
      << " /base:\"" << QDir::toNativeSeparators(File::absolutePath(input_1_name_).toQString()).toStdString() << "\""
      << " /mine:\"" << QDir::toNativeSeparators(File::absolutePath(input_2_name_).toQString()).toStdString() << "\""
#else
      << "diff"
      << " " << QDir::toNativeSeparators(File::absolutePath(input_1_name_).toQString()).toStdString()
      << " " << QDir::toNativeSeparators(File::absolutePath(input_2_name_).toQString()).toStdString()
#endif
      << std::endl;
    }

    // If verbose level is low, report only the first error.
    if (verbose_level_ < 3)
    {
      throw FuzzyStringComparator::AbortComparison();
    }

    return;
  } // reportFailure_()

  void FuzzyStringComparator::reportSuccess_() const
  {
    if (is_status_success_ && verbose_level_ >= 2)
    {
      std::string prefix;
      if (use_prefix_)
      {
        prefix = "   :|:  ";
      }

      *log_dest_ <<
      prefix << "PASSED.\n" <<
      prefix << '\n' <<
      prefix << "  relative_max:        " << ratio_max_ << '\n' <<
      prefix << "  relative_acceptable: " << ratio_max_allowed_ << '\n' <<
      prefix << '\n' <<
      prefix << "  absolute_max:        " << absdiff_max_ << '\n' <<
      prefix << "  absolute_acceptable: " << absdiff_max_allowed_ << std::endl;

      writeWhitelistCases_(prefix);

      *log_dest_ << prefix << std::endl;

      if (line_num_1_max_ == -1 && line_num_2_max_ == -1)
      {
        *log_dest_ <<
        prefix << "No numeric differences were found.\n" <<
        prefix << std::endl;
      }
      else
      {
        *log_dest_ <<
        prefix << "Maximum relative error was attained at these lines, enclosed in \"\":\n" <<
        prefix << '\n' <<
        QDir::toNativeSeparators(input_1_name_.c_str()).toStdString() << ':' << line_num_1_max_ << ":\n" <<
        "\"" << line_str_1_max_ << "\"\n" <<
        '\n' <<
        QDir::toNativeSeparators(input_2_name_.c_str()).toStdString() << ':' << line_num_2_max_ << ":\n" <<
        "\"" << line_str_2_max_ << "\"\n" <<
        std::endl;
      }
    }
    return;
  }

  bool FuzzyStringComparator::compareLines_(std::string const & line_str_1, std::string const & line_str_2)
  {

    for (StringList::const_iterator slit = whitelist_.begin();
         slit != whitelist_.end();
         ++slit
         )
    {
      if (line_str_1.find(*slit) != String::npos &&
          line_str_2.find(*slit) != String::npos
          )
      {
        ++whitelist_cases_[*slit];
        // *log_dest_ << "whitelist_ case: " << *slit << '\n';
        return is_status_success_;
      }
    }

    input_line_1_.setToString(line_str_1);
    input_line_2_.setToString(line_str_2);

    try
    {
      while (input_line_1_.ok() && input_line_2_.ok())
      {
        element_1_.fillFromInputLine(input_line_1_);
        element_2_.fillFromInputLine(input_line_2_);

        if (element_1_.is_number)
        {
          if (element_2_.is_number) // we are comparing numbers
          {             // check if absolute difference is small
            double absdiff = element_1_.number - element_2_.number;
            if (absdiff < 0)
            {
              absdiff = -absdiff;
            }
            if (absdiff > absdiff_max_)
            {
              absdiff_max_ = absdiff;
            }
            // If absolute difference is small, large relative errors will be
            // tolerated in the cases below.  But a large absolute difference is
            // not an error, if relative error is small.  We do not jump out of
            // the case distinction here because we want to record the relative
            // error even in case of a successful comparison.
            is_absdiff_small_ = (absdiff <= absdiff_max_allowed_);

            if (!element_1_.number) // element_1_.number_ is zero
            {
              if (!element_2_.number) // both numbers are zero
              {
                continue;
              }
              else
              {
                if (!is_absdiff_small_)
                {
                  reportFailure_("element_1_.number_ is zero, but element_2_.number_ is not");
                  continue;
                }
              }
            }
            else          // element_1_.number_ is not zero
            {
              if (!element_2_.number)
              {
                if (!is_absdiff_small_)
                {
                  reportFailure_("element_1_.number_ is not zero, but element_2_.number_ is");
                  continue;
                }
              }
              else            // both numbers are not zero
              {
                double ratio = element_1_.number / element_2_.number;
                if (ratio < 0)
                {
                  if (!is_absdiff_small_)
                  {
                    reportFailure_("numbers have different signs");
                    continue;
                  }
                }
                else              // ok, numbers have same sign, but we still need to check their ratio
                {
                  if (ratio < 1)      // take reciprocal value
                  {
                    ratio = 1.0 / ratio;
                  }
                  // by now, we are sure that ratio >= 1
                  if (ratio > ratio_max_) // update running max
                  {
                    ratio_max_ = ratio;
                    line_num_1_max_ = line_num_1_;
                    line_num_2_max_ = line_num_2_;
                    line_str_1_max_ = line_str_1;
                    line_str_2_max_ = line_str_2;
                    if (ratio_max_ > ratio_max_allowed_)
                    {
                      if (!is_absdiff_small_)
                      {
                        reportFailure_("ratio of numbers is too large");
                        continue;
                      }
                    }
                  }
                }
                // okay
                continue;
              }
            }
          }
          else
          {
            reportFailure_("input_1 is a number, but input_2 is not");
            continue;
          }
        }
        else      // input_1 is not a number
        {
          if (element_2_.is_number)
          {
            reportFailure_("input_1 is not a number, but input_2 is");
            continue;
          }
          else        // ok, both inputs are not numbers, let us compare them as characters or whitespace
          {
            if (element_1_.is_space)
            {
              if (element_2_.is_space) // ok, both inputs are whitespace
              {
                continue;
              }
              else
              {
                if (element_1_.letter == ASCII__CARRIAGE_RETURN)                   // should be 13 == ascii carriage return char
                {
                  // we skip over '\r'
                  input_line_2_.line_.clear();                   // reset status
                  input_line_2_.line_.seekg(input_line_2_.line_position_);                   // rewind to saved position
                  continue;
                  //reportFailure_("input_1 is carriage return, but input_2_ is not whitespace");
                }
                else
                {
                  reportFailure_("input_1 is whitespace, but input_2 is not");
                }
                continue;
              }
            }
            else          // input_1 is not whitespace
            {
              if (element_2_.is_space)
              {
                if (element_2_.letter == ASCII__CARRIAGE_RETURN)                   // should be 13 == ascii carriage return char
                {
                  // we skip over '\r'
                  input_line_1_.line_.clear();                   // reset status
                  input_line_1_.line_.seekg(input_line_1_.line_position_);                   // rewind to saved position
                  continue;
                  //reportFailure_("input_1 is not whitespace, but input_2 is carriage return");
                }
                else
                {
                  reportFailure_("input_1 is not whitespace, but input_2 is");
                }
                continue;
              }
              else            // both inputs are neither numbers nor whitespace, let us compare them as characters
              {
                if (element_1_.letter == element_2_.letter) // ok, same characters
                {
                  continue;
                }
                else
                {
                  reportFailure_("different letters");
                  continue;
                }
              }
            }
          }
        }

        if (is_absdiff_small_)
        {
          is_absdiff_small_ = false;
          continue;
        }

        verbose_level_ = 10000;
        reportFailure_
          ("This cannot happen.  You should never get here ... "
           "please report this bug along with the data that produced it."
          );

      }       // while ( input_line_1_ || input_line_2_ )
      if (input_line_1_.ok() && !input_line_2_.ok())
      {
        reportFailure_("line from input_2 is shorter than line from input_1");
      }
      if (!input_line_1_.ok() && input_line_2_.ok())
      {
        reportFailure_("line from input_1 is shorter than line from input_2");
      }
    }
    catch (FuzzyStringComparator::AbortComparison const &)
    {
      // *log_dest_ << "compareLines_(): Caught FuzzyStringComparator::AbortComparison\n";
    }

    return is_status_success_;
  } // compareLines_()

  bool FuzzyStringComparator::compareStrings(std::string const & lhs, std::string const & rhs)
  {
    std::istringstream input_1(lhs);
    std::istringstream input_2(rhs);

    return compareStreams(input_1, input_2);

  } // compareStrings()

  bool FuzzyStringComparator::compareStreams(std::istream & input_1, std::istream & input_2)
  {
    std::string line_str_1;
    std::string line_str_2;

    while (input_1 || input_2)
    {

      readNextLine_(input_1, line_str_1, line_num_1_);
      //std::cout << "eof: " << input_1.eof() << " failbit: " << input_1.fail() << " badbit: " << input_1.bad() << " reading " << input_1.tellg () << "chars\n";

      readNextLine_(input_2, line_str_2, line_num_2_);
      //std::cout << "eof: " << input_2.eof() << " failbit: " << input_2.fail() << " badbit: " << input_2.bad() << " reading " << input_2.tellg () << "chars\n";

      // compare the two lines of input
      if (!compareLines_(line_str_1, line_str_2) && verbose_level_ < 3)
        break;

    } // while ( input_1 || input_2 )

    reportSuccess_();

    return is_status_success_;

  } // compareStreams()

  void FuzzyStringComparator::readNextLine_(std::istream & input_stream, std::string & line_string, int & line_number) const
  {
    for (line_string.clear(); ++line_number, std::getline(input_stream, line_string); )
    {
      if (line_string.empty())
        continue;                                // shortcut
      std::string::const_iterator iter = line_string.begin();       // loop initialization
      for (; iter != line_string.end() && isspace((unsigned char)*iter); ++iter)
      {
      }
                                                                                        // skip over whitespace
      if (iter != line_string.end())
        break;                                      // line is not empty or whitespace only
    }
  }

  bool FuzzyStringComparator::compareFiles(const std::string & filename_1, const std::string & filename_2)
  {
    input_1_name_ = filename_1;
    input_2_name_ = filename_2;

    if (input_1_name_ == input_2_name_)
    {
      *log_dest_ << "Error: first and second input file have the same name.  That's cheating!\n";
      return false;
    }

    std::ifstream input_1_f;
    if (!openInputFileStream_(input_1_name_, input_1_f))
      return false;

    std::ifstream input_2_f;
    if (!openInputFileStream_(input_2_name_, input_2_f))
      return false;

    //------------------------------------------------------------
    // main loop

    compareStreams(input_1_f, input_2_f);

    return is_status_success_;

  }   // compareFiles()

  bool FuzzyStringComparator::openInputFileStream_(const std::string & filename, std::ifstream & input_stream) const
  {
    input_stream.open(filename.c_str(), std::ios::in | std::ios::binary);
    if (!input_stream)
    {
      *log_dest_ << "Error opening first input file '" << filename << "'.\n";
      return false;
    }
    input_stream.unsetf(std::ios::skipws);
    return true;
  }

  void FuzzyStringComparator::writeWhitelistCases_(const std::string & prefix) const
  {
    if (!whitelist_cases_.empty())
    {
      *log_dest_ <<
      prefix << '\n' <<
      prefix << "  whitelist cases:\n";
      Size length = 0;
      for (std::map<String, UInt>::const_iterator wlcit =
             whitelist_cases_.begin(); wlcit != whitelist_cases_.end();
           ++wlcit)
      {
        if (wlcit->first.size() > length)
          length = wlcit->first.size();
      }
      for (std::map<String, UInt>::const_iterator wlcit =
             whitelist_cases_.begin(); wlcit != whitelist_cases_.end();
           ++wlcit)
      {
        *log_dest_ <<
        prefix << "    " << std::setw(length + 3) << std::left <<
        ("\"" + wlcit->first + "\"") << std::setw(3) << std::right <<
        wlcit->second << "x\n";
      }
    }
  }

} //namespace OpenMS