otbTestHelper.cxx 90.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright (C) 1999-2011 Insight Software Consortium
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
21 22 23 24


#include "otbTestHelper.h"
#include "otbMacro.h"
Guillaume Pasero's avatar
Guillaume Pasero committed
25
#include "otbStringUtils.h"
26 27 28
#include <iostream>
#include <fstream>
#include <cctype>
29
#include <algorithm>
Julien Michel's avatar
Julien Michel committed
30
#include <string>
31

32 33 34
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
35
#include "ogrsf_frmts.h"
36 37 38 39
#pragma GCC diagnostic pop
#else
#include "ogrsf_frmts.h"
#endif
40

41 42 43 44
#include "itksys/SystemTools.hxx"
#include "itksys/Directory.hxx"
#include "itksys/RegularExpression.hxx"

45 46 47 48 49
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbDifferenceImageFilter.h"
#include "otbPrintableImageFilter.h"
50
#include "otbStreamingShrinkImageFilter.h"
51 52 53
#include "otbOGRVersionProxy.h"

#include "otbConfigure.h"
54 55 56 57 58 59 60 61

#define ITK_TEST_DIMENSION_MAX 6

// OGR Headers files
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_multiproc.h"

OTB Bot's avatar
STYLE  
OTB Bot committed
62 63 64 65 66 67 68 69 70 71 72 73 74
#define otbPrintDiff(comment, refStr, testStr) \
  std::cout << "   ----    '" << comment << "' checking   ---------------------------" << std::endl; \
  std::cout << "   Base << " << refStr << std::endl; \
  std::cout << "   Test >> " << testStr << std::endl;

#define otbCheckStringValue(Comment, RefStr, TestStr, count, report) \
    { \
    std::string strRefStr(""); if (RefStr != NULL) strRefStr = RefStr; \
    std::string strTestStr(""); if (TestStr != NULL) strTestStr = TestStr; \
    if (strRefStr != strTestStr) \
      { \
      count++; \
      if (report) \
75
        { \
OTB Bot's avatar
STYLE  
OTB Bot committed
76
        otbPrintDiff(Comment, strRefStr, strTestStr); \
77
        } \
OTB Bot's avatar
STYLE  
OTB Bot committed
78 79 80 81 82 83 84 85
      } \
    }
#define otbCheckValue(Comment, Ref, Test, count, report) \
    { \
    if (Ref != Test) \
      { \
      count++; \
      if (report) \
86
        { \
OTB Bot's avatar
STYLE  
OTB Bot committed
87
        otbPrintDiff(Comment, Ref, Test); \
88
        } \
OTB Bot's avatar
STYLE  
OTB Bot committed
89 90
      } \
    }
91 92 93 94

namespace otb
{

OTB Bot's avatar
STYLE  
OTB Bot committed
95
int TestHelper::RegressionTestAllImages(const StringList& baselineFilenamesImage,
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
                                        const StringList& testFilenamesImage)
{
  int result = 0;
  StringListIt itbaselineFilenames = baselineFilenamesImage.begin();
  StringListIt itTestFilenames = testFilenamesImage.begin();
  int                                cpt(1);
  // For each couple of baseline and test file, do the comparison
  for (; (itbaselineFilenames != baselineFilenamesImage.end())
         && (itTestFilenames != testFilenamesImage.end());
       ++itbaselineFilenames, ++itTestFilenames)
    {
    std::string baselineFilenameImage = (*itbaselineFilenames);
    std::string testFilenameImage = (*itTestFilenames);

    std::map<std::string, int> baselines =
      this->RegressionTestBaselines(const_cast<char*>(baselineFilenameImage.c_str()));
    std::map<std::string, int>::reverse_iterator baseline = baselines.rbegin();
    int multiResult = 1;
    std::cout << "Number of baseline images: " << baselines.size() << std::endl;
    while (baseline != baselines.rend() && (multiResult != 0))
      {
117
      std::cout << "Testing non-regression on image: " << (baseline->first) << std::endl;
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
      this->ReportErrorsOff();
      baseline->second = this->RegressionTestImage(cpt, testFilenameImage.c_str(),
                                                        (baseline->first).c_str(),
                                                        m_ToleranceDiffValue);

      multiResult = baseline->second;
      ++baseline;
      }
    if (multiResult != 0)
      {
      baseline = baselines.rbegin();
      this->ReportErrorsOn();
      baseline->second
        = this->RegressionTestImage(cpt, testFilenameImage.c_str(),
                                         (baseline->first).c_str(),
                                         m_ToleranceDiffValue);
OTB Bot's avatar
STYLE  
OTB Bot committed
134
      }
135
    ++cpt;
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
    result += multiResult;
    }
  return result;
}

int TestHelper::RegressionTestAllMetaData(const StringList& baselineFilenamesMetaData,
                                          const StringList& testFilenamesMetaData)
{
  int result = 0;
  // Creates iterators on baseline filenames vector and test filenames vector
  StringListIt itbaselineFilenames = baselineFilenamesMetaData.begin();
  StringListIt itTestFilenames = testFilenamesMetaData.begin();
  // For each couple of baseline and test file, do the comparison
  for (; (itbaselineFilenames != baselineFilenamesMetaData.end())
         && (itTestFilenames != testFilenamesMetaData.end());
       ++itbaselineFilenames, ++itTestFilenames)
    {
    std::string baselineFilenameImage = (*itbaselineFilenames);
    std::string testFilenameImage = (*itTestFilenames);

    std::map<std::string, int> baselines =
      this->RegressionTestBaselines(const_cast<char*>(baselineFilenameImage.c_str()));
    std::map<std::string, int>::reverse_iterator baseline = baselines.rbegin();
    int multiResult = 1;
    std::cout << "Number of baseline images: " << baselines.size() << std::endl;
    while (baseline != baselines.rend() && (multiResult != 0))
      {
163
      std::cout << "Testing non-regression on image: " << (baseline->first) << std::endl;
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
      this->ReportErrorsOff();
      baseline->second = this->RegressionTestMetaData(testFilenameImage.c_str(),
                                                           (baseline->first).c_str(),
                                                           m_ToleranceDiffValue);

      multiResult = baseline->second;
      ++baseline;
      }
    if (multiResult != 0)
      {
      baseline = baselines.rbegin();
      this->ReportErrorsOn();
      baseline->second
        = this->RegressionTestMetaData(testFilenameImage.c_str(),
                                            (baseline->first).c_str(),
                                            m_ToleranceDiffValue);
      }
    result += multiResult;
    }
  return result;
}

int TestHelper::RegressionTestAllAscii(const StringList& baselineFilenamesAscii,
                                       const StringList& testFilenamesAscii,
                                       const StringList& ignoredLines)
{
  int result = 0;
  // Creates iterators on baseline filenames vector and test filenames vector
  StringListIt itbaselineFilenames = baselineFilenamesAscii.begin();
  StringListIt itTestFilenames = testFilenamesAscii.begin();
  StringListIt itIgnoredLines = ignoredLines.begin();

  // Warning message
  if (ignoredLines.size() > 0)
    {
    std::cout << "The lines containing the expressions ";
    for (; itIgnoredLines != ignoredLines.end(); ++itIgnoredLines)
      {
      std::cout << (*itIgnoredLines) << " ";
      }
    std::cout << "are not considered" << std::endl;
    }

  // For each couple of baseline and test file, do the comparison
  for (; (itbaselineFilenames != baselineFilenamesAscii.end())
         && (itTestFilenames != testFilenamesAscii.end());
       ++itbaselineFilenames, ++itTestFilenames)
    {
    std::string baselineFilenameAscii = (*itbaselineFilenames);
    std::string testFilenameAscii = (*itTestFilenames);

    std::map<std::string,
             int> baselines =
      this->RegressionTestBaselines(const_cast<char*>(baselineFilenameAscii.c_str()));
    std::map<std::string, int>::reverse_iterator baseline = baselines.rbegin();
    int multiResult = 1;
    std::cout << "Number of baseline files: " << baselines.size() << std::endl;
    while (baseline != baselines.rend() && (multiResult != 0))
      {
223
      std::cout << "Testing non-regression on file: " << (baseline->first) << std::endl;
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
      this->ReportErrorsOff();
      baseline->second = this->RegressionTestAsciiFile(testFilenameAscii.c_str(),
                                                            (baseline->first).c_str(),
                                                            m_Epsilon,
                                                            ignoredLines);

      multiResult = baseline->second;
      ++baseline;
      }
    if (multiResult != 0)
      {
      baseline = baselines.rbegin();
      this->ReportErrorsOn();
      baseline->second
        = this->RegressionTestAsciiFile(testFilenameAscii.c_str(),
                                             (baseline->first).c_str(),
                                             m_Epsilon,
                                             ignoredLines);
      }
    result += multiResult;
    }

  return result;
}

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
int TestHelper::RegressionTestAllDiff(const StringList& baselineFilenamesAscii,
                                       const StringList& testFilenamesAscii,
                                       const StringList& ignoredLines)
{
  int result = 0;
  // Creates iterators on baseline filenames vector and test filenames vector
  StringListIt itbaselineFilenames = baselineFilenamesAscii.begin();
  StringListIt itTestFilenames = testFilenamesAscii.begin();
  StringListIt itIgnoredLines = ignoredLines.begin();

  // Warning message
  if (ignoredLines.size() > 0)
    {
    std::cout << "The lines containing the expressions ";
    for (; itIgnoredLines != ignoredLines.end(); ++itIgnoredLines)
      {
      std::cout << (*itIgnoredLines) << " ";
      }
    std::cout << "are not considered" << std::endl;
    }

  // For each couple of baseline and test file, do the comparison
  for (; (itbaselineFilenames != baselineFilenamesAscii.end())
         && (itTestFilenames != testFilenamesAscii.end());
       ++itbaselineFilenames, ++itTestFilenames)
    {
    std::string baselineFilenameAscii = (*itbaselineFilenames);
    std::string testFilenameAscii = (*itTestFilenames);

    std::map<std::string,
             int> baselines =
      this->RegressionTestBaselines(const_cast<char*>(baselineFilenameAscii.c_str()));
    std::map<std::string, int>::reverse_iterator baseline = baselines.rbegin();
    int multiResult = 1;
    std::cout << "Number of baseline files: " << baselines.size() << std::endl;
    while (baseline != baselines.rend() && (multiResult != 0))
      {
286
      std::cout << "Testing non-regression on file: " << (baseline->first) << std::endl;
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
      this->ReportErrorsOff();
      baseline->second = this->RegressionTestDiffFile(testFilenameAscii.c_str(),
                                                            (baseline->first).c_str(),
                                                            m_Epsilon,
                                                            ignoredLines);

      multiResult = baseline->second;
      ++baseline;
      }
    if (multiResult != 0)
      {
      baseline = baselines.rbegin();
      this->ReportErrorsOn();
      baseline->second
        = this->RegressionTestDiffFile(testFilenameAscii.c_str(),
                                             (baseline->first).c_str(),
                                             m_Epsilon,
                                             ignoredLines);
      }
    result += multiResult;
    }

  return result;
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
int TestHelper::RegressionTestAllBinary(const StringList& baselineFilenamesBinary,
                                        const StringList& testFilenamesBinary)
{
  int result = 0;
  // Creates iterators on baseline filenames vector and test filenames vector
  StringListIt itbaselineFilenames = baselineFilenamesBinary.begin();
  StringListIt itTestFilenames = testFilenamesBinary.begin();

  // For each couple of baseline and test file, do the comparison
  for (; (itbaselineFilenames != baselineFilenamesBinary.end())
         && (itTestFilenames != testFilenamesBinary.end());
       ++itbaselineFilenames, ++itTestFilenames)
    {
    std::string baselineFilenameBinary = (*itbaselineFilenames);
    std::string testFilenameBinary = (*itTestFilenames);

    std::map<std::string,
             int> baselines =
      this->RegressionTestBaselines(const_cast<char*>(baselineFilenameBinary.c_str()));
    std::map<std::string, int>::reverse_iterator baseline = baselines.rbegin();
    int multiResult = 1;
    std::cout << "Number of baseline files: " << baselines.size() << std::endl;
    while (baseline != baselines.rend() && (multiResult != 0))
      {
336
      std::cout << "Testing non-regression on file: " << (baseline->first) << std::endl;
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
      this->ReportErrorsOff();
      baseline->second = this->RegressionTestBinaryFile(testFilenameBinary.c_str(),
                                                             (baseline->first).c_str());

      multiResult = baseline->second;
      ++baseline;
      }
    if (multiResult != 0)
      {
      baseline = baselines.rbegin();
      this->ReportErrorsOn();
      baseline->second
        = this->RegressionTestBinaryFile(testFilenameBinary.c_str(),
                                              (baseline->first).c_str());
      }
    result += multiResult;
    }

  return result;
}

int TestHelper::RegressionTestAllOgr(const StringList& baselineFilenamesOgr,
                                     const StringList& testFilenamesOgr)
{
  int result = 0;
  // Creates iterators on baseline filenames vector and test filenames vector
  StringListIt itbaselineFilenames = baselineFilenamesOgr.begin();
  StringListIt itTestFilenames = testFilenamesOgr.begin();
  // For each couple of baseline and test file, do the comparison
  for (; (itbaselineFilenames != baselineFilenamesOgr.end())
         && (itTestFilenames != testFilenamesOgr.end());
       ++itbaselineFilenames, ++itTestFilenames)
    {
    std::string baselineFilenameOgr = (*itbaselineFilenames);
    std::string testFilenameOgr = (*itTestFilenames);

    std::map<std::string,
             int> baselines =
      this->RegressionTestBaselines(const_cast<char*>(baselineFilenameOgr.c_str()));
    std::map<std::string, int>::reverse_iterator baseline = baselines.rbegin();
    int multiResult = 1;
    std::cout << "Number of baseline OGR files: " << baselines.size() << std::endl;
    while (baseline != baselines.rend() && (multiResult != 0))
      {
381
      std::cout << "Testing non-regression on OGR file: " << (baseline->first) << std::endl;
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
      this->ReportErrorsOff();
      baseline->second = this->RegressionTestOgrFile(testFilenameOgr.c_str(),
                                                          (baseline->first).c_str(),
                                                          m_ToleranceDiffValue);

      multiResult = baseline->second;
      ++baseline;
      }
    if (multiResult != 0)
      {
      baseline = baselines.rbegin();
      this->ReportErrorsOn();
      baseline->second
        = this->RegressionTestOgrFile(testFilenameOgr.c_str(),
                                           (baseline->first).c_str(),
                                           m_ToleranceDiffValue);
      }
    result += multiResult;
    }

  return result;
}


406
int TestHelper::RegressionTestAsciiFile(const char * testAsciiFileName, const char * baselineAsciiFileName,
OTB Bot's avatar
STYLE  
OTB Bot committed
407
                                        const double epsilon, std::vector<std::string> ignoredLines) const
408 409 410 411 412 413 414 415
{
  std::ifstream fluxfiletest(testAsciiFileName);
  std::ifstream fluxfileref(baselineAsciiFileName);

  std::string diffAsciiFileName(testAsciiFileName);
  diffAsciiFileName += ".diff.txt";
  std::ofstream fluxfilediff;
  if (m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
416
    {
417
    fluxfilediff.open(diffAsciiFileName);
OTB Bot's avatar
STYLE  
OTB Bot committed
418
    }
419 420 421 422 423 424 425

  std::string strfiletest;
  std::string strfileref;

  int nbdiff(0);
  int numLine(1);
  if (!fluxfiletest)
OTB Bot's avatar
STYLE  
OTB Bot committed
426 427 428
    {
    itkGenericExceptionMacro(<< "Impossible to open the test ASCII file <" << testAsciiFileName << ">.");
    }
429
  if (!fluxfileref)
OTB Bot's avatar
STYLE  
OTB Bot committed
430 431 432
    {
    itkGenericExceptionMacro(<< "Impossible to open the baseline ASCII file <" << baselineAsciiFileName << ">.");
    }
433 434 435 436

  //fill up a vector of string, in which each element is one line of the file
  std::vector<std::string> listLineFileRef;
  std::vector<std::string> listLineFileTest;
437
  while (std::getline(fluxfileref, strfileref))
OTB Bot's avatar
STYLE  
OTB Bot committed
438
    {
439
    listLineFileRef.push_back(strfileref);
OTB Bot's avatar
STYLE  
OTB Bot committed
440
    }
441 442
  fluxfileref.close();

443
  while (std::getline(fluxfiletest, strfiletest))
OTB Bot's avatar
STYLE  
OTB Bot committed
444
    {
445
    listLineFileTest.push_back(strfiletest);
OTB Bot's avatar
STYLE  
OTB Bot committed
446
    }
447 448
  fluxfiletest.close();

OTB Bot's avatar
STYLE  
OTB Bot committed
449 450
  if (m_IgnoreLineOrder)
    {
451 452
    std::sort(listLineFileRef.begin(), listLineFileRef.end());
    std::sort(listLineFileTest.begin(), listLineFileTest.end());
OTB Bot's avatar
STYLE  
OTB Bot committed
453
    }
454 455 456 457 458 459 460 461

  //These are to save up the differences
  std::vector<std::string> listStrDiffLineFileRef;
  std::vector<std::string> listStrDiffLineFileTest;

  std::vector<std::string>::iterator itRef = listLineFileRef.begin();
  std::vector<std::string>::iterator itTest = listLineFileTest.begin();
//   while (std::getline(fluxfileref, strfileref) != 0)
462
 while ((itRef != listLineFileRef.end()) && (itTest != listLineFileTest.end()))
OTB Bot's avatar
STYLE  
OTB Bot committed
463
    {
464 465 466
    strfileref = *itRef;
    strfiletest = *itTest;

467
    //otbMsgDevMacro(<< "Comparing " << strfileref << " -with- " << strfiletest);
468

469 470 471 472
    //Check is the current line should be ignored
    bool ignoreCurrentLineRef = false;
    bool ignoreCurrentLineTest = false;
    if (ignoredLines.size() > 0)
OTB Bot's avatar
STYLE  
OTB Bot committed
473
      {
474 475
      for (std::vector<std::string>::iterator itIgnoredLines = ignoredLines.begin();
           itIgnoredLines != ignoredLines.end(); ++itIgnoredLines)
OTB Bot's avatar
STYLE  
OTB Bot committed
476 477
        {
        std::string            ignoredLinesAscii = (*itIgnoredLines);
478 479
        std::string::size_type loc = strfileref.find(ignoredLinesAscii);
        if (loc != std::string::npos)
OTB Bot's avatar
STYLE  
OTB Bot committed
480
          {
481
          ignoreCurrentLineRef = true;
OTB Bot's avatar
STYLE  
OTB Bot committed
482
          }
483 484
        loc = strfiletest.find(ignoredLinesAscii);
        if (loc != std::string::npos)
OTB Bot's avatar
STYLE  
OTB Bot committed
485
          {
486
          ignoreCurrentLineTest = true;
OTB Bot's avatar
STYLE  
OTB Bot committed
487
          }
488 489 490
        }
      }

491

492
    // Ignore lines with "RTTI" and "Modified Time" inside by default : to avoid multibaseline
493 494 495
    // between Linux and Win32 plateforms
    if ((!ignoreCurrentLineRef) && (!ignoreCurrentLineTest))
      {
496
      if(isToBeIgnoredForAnyComparison(strfileref))
497
        ignoreCurrentLineRef = true;
498

499
      if(isToBeIgnoredForAnyComparison(strfiletest))
500 501
        ignoreCurrentLineTest = true;
      }
502

503 504 505 506
    //Compare the lines only if none is supposed to be ignored
    //Note: the iterator increment will take care of moving only the
    //ignored one if the order does not matter
    bool differenceFoundInCurrentLine = false;
507 508 509 510
//    if (ignoreCurrentLineRef || ignoreCurrentLineTest)
//      {
//      otbMsgDevMacro( << "* ignoring");
//      }
511
    if ((!ignoreCurrentLineRef) && (!ignoreCurrentLineTest))
OTB Bot's avatar
STYLE  
OTB Bot committed
512 513 514
      {
      differenceFoundInCurrentLine = CompareLines(strfileref, strfiletest, nbdiff, fluxfilediff, numLine,
                                                  listStrDiffLineFileRef, listStrDiffLineFileTest, epsilon);
515 516 517 518
//      if (!differenceFoundInCurrentLine)
//        {
//        otbMsgDevMacro( << "* no difference found");
//        }
OTB Bot's avatar
STYLE  
OTB Bot committed
519
      }
520

521 522 523
    if (ignoreCurrentLineRef) ++itRef;
    if (ignoreCurrentLineTest) ++itTest;

524
    if (m_IgnoreLineOrder)
OTB Bot's avatar
STYLE  
OTB Bot committed
525
      {
526 527
      if ((!ignoreCurrentLineRef) && (!ignoreCurrentLineTest))
        {
OTB Bot's avatar
STYLE  
OTB Bot committed
528
        if (differenceFoundInCurrentLine)
529
          {
OTB Bot's avatar
STYLE  
OTB Bot committed
530 531
          if (*itRef > *itTest)
            {
532 533
            fluxfilediff << "Additional line in test file: " << " : " << *itTest << std::endl;
            ++itTest;
OTB Bot's avatar
STYLE  
OTB Bot committed
534
            }
535
          else
OTB Bot's avatar
STYLE  
OTB Bot committed
536
            {
537 538
            fluxfilediff << "Additional line in ref file: " << " : " << *itTest << std::endl;
            ++itRef;
OTB Bot's avatar
STYLE  
OTB Bot committed
539
            }
540 541
          }
        else
OTB Bot's avatar
STYLE  
OTB Bot committed
542
          {
543 544
          ++itRef;
          ++itTest;
OTB Bot's avatar
STYLE  
OTB Bot committed
545
          }
546 547 548
        }
      }
    else
OTB Bot's avatar
STYLE  
OTB Bot committed
549
      {
550 551 552 553 554
		if ((!ignoreCurrentLineRef) && (!ignoreCurrentLineTest))
		{
			++itRef;
			++itTest;
		}
OTB Bot's avatar
STYLE  
OTB Bot committed
555
      }
556

OTB Bot's avatar
STYLE  
OTB Bot committed
557
    }
558 559 560 561 562

  //Here, the line by line comparison is finished and at least one (ref or test) is at the end
  //we simply output the content of the other one

  while (itRef != listLineFileRef.end())
OTB Bot's avatar
STYLE  
OTB Bot committed
563
    {
564
    strfileref = *itRef;
565
    std::stringstream buffstreamRef;
OTB Bot's avatar
STYLE  
OTB Bot committed
566
    std::string       strRef = "";
567 568 569 570 571
    buffstreamRef << strfileref;
    buffstreamRef >> strRef;
    fluxfilediff << "Additional line in ref file: " << numLine << " : " << strRef << std::endl;
    nbdiff++;
    if (m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
572
      {
573
      listStrDiffLineFileRef.push_back(strfileref);
OTB Bot's avatar
STYLE  
OTB Bot committed
574
      }
575
    ++itRef;
OTB Bot's avatar
STYLE  
OTB Bot committed
576
    }
577 578

  while (itTest != listLineFileTest.end())
OTB Bot's avatar
STYLE  
OTB Bot committed
579
    {
580
    strfiletest = *itTest;
581
    std::stringstream buffstreamTest;
OTB Bot's avatar
STYLE  
OTB Bot committed
582
    std::string       strTest = "";
583 584 585 586 587
    buffstreamTest << strfiletest;
    buffstreamTest >> strTest;
    fluxfilediff << "Additional line in test file: " << numLine << " : " << strTest << std::endl;
    nbdiff++;
    if (m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
588
      {
589
      listStrDiffLineFileTest.push_back(strfiletest);
OTB Bot's avatar
STYLE  
OTB Bot committed
590
      }
591
    ++itTest;
OTB Bot's avatar
STYLE  
OTB Bot committed
592
    }
593 594

  if (m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
595
    {
596
    fluxfilediff.close();
OTB Bot's avatar
STYLE  
OTB Bot committed
597
    }
598 599

  if (nbdiff != 0 && m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
600
    {
601 602 603 604 605 606 607 608 609 610 611 612
    std::cout << "<DartMeasurement name=\"ASCIIFileError\" type=\"numeric/int\">";
    std::cout << nbdiff;
    std::cout << "</DartMeasurement>" << std::endl;
    std::cout << "================================================================" << std::endl;
    std::cout << "baseline ASCII File : " << baselineAsciiFileName << std::endl;
    std::cout << "Test ASCII File     : " << testAsciiFileName << std::endl;
    std::cout << "Diff ASCII File     : " << diffAsciiFileName << std::endl;
    std::cout << "Tolerance value     : " << epsilon << std::endl;
    std::cout << "Tolerance max check : " << m_EpsilonBoundaryChecking << std::endl;

    //FIXME won't be intuitive for the non order case
    unsigned int numLineDiff = std::min(listStrDiffLineFileRef.size(), listStrDiffLineFileTest.size());
613
    std::cout << "Nb lines different : " << numLineDiff << std::endl;
614
    for (unsigned int i = 0; i < numLineDiff; ++i)
OTB Bot's avatar
STYLE  
OTB Bot committed
615
      {
616 617 618
      std::cout << "   -------------------------------" << std::endl;
      std::cout << "   Base << " << listStrDiffLineFileRef[i] << std::endl;
      std::cout << "   Test >> " << listStrDiffLineFileTest[i] << std::endl;
OTB Bot's avatar
STYLE  
OTB Bot committed
619
      }
620
    for (unsigned int i = numLineDiff; i < listStrDiffLineFileRef.size(); ++i)
OTB Bot's avatar
STYLE  
OTB Bot committed
621
      {
622 623
      std::cout << "   -------------------------------" << std::endl;
      std::cout << "   Base << " << listStrDiffLineFileRef[i] << std::endl;
OTB Bot's avatar
STYLE  
OTB Bot committed
624
      }
625
    for (unsigned int i = numLineDiff; i < listStrDiffLineFileTest.size(); ++i)
OTB Bot's avatar
STYLE  
OTB Bot committed
626
      {
627 628
      std::cout << "   -------------------------------" << std::endl;
      std::cout << "   Test >> " << listStrDiffLineFileTest[i] << std::endl;
OTB Bot's avatar
STYLE  
OTB Bot committed
629
      }
630 631 632 633
    }
  return (nbdiff != 0) ? 1 : 0;
}

634 635 636
int TestHelper::RegressionTestDiffFile(const char * testAsciiFileName, const char * baselineAsciiFileName,
                                        const double epsilon, StringList ignoredLines) const
{
Guillaume Pasero's avatar
Guillaume Pasero committed
637 638
  typedef std::vector<boost::iterator_range<std::string::const_iterator> > TokenListType;
  
639 640 641 642 643 644 645 646
  std::ifstream fluxfiletest(testAsciiFileName);
  std::ifstream fluxfileref(baselineAsciiFileName);

  std::string diffAsciiFileName(testAsciiFileName);
  diffAsciiFileName += ".diff.txt";
  std::ofstream fluxfilediff;
  if (m_ReportErrors)
    {
647
    fluxfilediff.open(diffAsciiFileName);
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    }

  std::string strfiletest;
  std::string strfileref;

  int nbdiff(0);
  if (!fluxfiletest)
    {
    itkGenericExceptionMacro(<< "Impossible to open the test ASCII file <" << testAsciiFileName << ">.");
    }
  if (!fluxfileref)
    {
    itkGenericExceptionMacro(<< "Impossible to open the baseline ASCII file <" << baselineAsciiFileName << ">.");
    }

  //fill up a vector of string, in which each element is one line of the file
  StringList listLineFileRef;
  StringList listLineFileTest;
  while (std::getline(fluxfileref, strfileref))
    {
    listLineFileRef.push_back(strfileref);
    }
  fluxfileref.close();

  while (std::getline(fluxfiletest, strfiletest))
    {
    listLineFileTest.push_back(strfiletest);
    }
  fluxfiletest.close();

Guillaume Pasero's avatar
Guillaume Pasero committed
678 679 680 681 682 683
  if (m_IgnoreLineOrder)
    {
    std::sort(listLineFileRef.begin(), listLineFileRef.end());
    std::sort(listLineFileTest.begin(), listLineFileTest.end());
    }

684
  //These are to save up the differences
685
  StringList listStrDiffLineFile;
686 687 688

  // filter ignored lines
  // TODO
689
  // filter lines with hexa address (isHexaPointerAddress)
690
  // use  isToBeIgnoredForAnyComparison()
691 692 693 694 695

  // Iterate over the baseline lines
  unsigned int posTest = 0;
  unsigned int posRef = 0;
  unsigned int curPosTest;
Guillaume Pasero's avatar
Guillaume Pasero committed
696 697 698 699 700
  TokenListType tokenRef;
  TokenListType tokenTest;
  TokenListType tokenTestSelected;
  std::string separators(" \t,;:=[]{}()<>");
  std::string emptyStr("");
701 702
  unsigned int nbTokenRef = 0;
  unsigned int nbTokenTest = 0;
703
  unsigned int nbTokenTestSelected = 0;
704
  bool isFirstMissingRefLine = true;
705 706 707

  for (posRef=0 ; posRef<listLineFileRef.size() ; posRef++)
    {
Guillaume Pasero's avatar
Guillaume Pasero committed
708 709
    std::string &curLineRef = listLineFileRef[posRef];
    if (!IsLineValid(curLineRef,ignoredLines))
710 711 712
      {
      continue;
      }
Guillaume Pasero's avatar
Guillaume Pasero committed
713 714 715 716 717
    boost::split(tokenRef, curLineRef, boost::is_any_of(separators));
    // remove empty tokens
    TokenListType::iterator refEndFiltered = std::remove_if(tokenRef.begin(), tokenRef.end(), IsTokenEmpty);
    tokenRef.resize(refEndFiltered-tokenRef.begin());
    nbTokenRef = tokenRef.size();
718 719 720 721 722 723 724
    if (nbTokenRef == 0)
      {
      // ignore lines without tokens
      continue;
      }
    unsigned int bestLinePos = posTest;
    int bestCommonTokens = -1;
Guillaume Pasero's avatar
Guillaume Pasero committed
725 726 727
    std::vector<unsigned int> validTestLines;
    std::vector<unsigned int> skippedTestLines;
    std::vector<unsigned int> differencesPosSelected;
728 729
    for (curPosTest = posTest ; curPosTest < listLineFileTest.size() ; curPosTest++)
      {
730 731 732 733 734
      // stop searching after 30 lines tested
      if (curPosTest > posTest + 30)
        {
        break;
        }
Guillaume Pasero's avatar
Guillaume Pasero committed
735 736
      std::string &curLineTest = listLineFileTest[curPosTest];
      if (!IsLineValid(curLineTest,ignoredLines))
737 738 739
        {
        continue;
        }
Guillaume Pasero's avatar
Guillaume Pasero committed
740 741 742 743 744
      boost::split(tokenTest, curLineTest, boost::is_any_of(separators));
      // remove empty tokens
      TokenListType::iterator testEndFiltered = std::remove_if(tokenTest.begin(), tokenTest.end(), IsTokenEmpty);
      tokenTest.resize(testEndFiltered-tokenTest.begin());
      nbTokenTest = tokenTest.size();
745 746 747 748 749
      if (nbTokenTest == 0)
        {
        // ignore lines without tokens
        continue;
        }
Guillaume Pasero's avatar
Guillaume Pasero committed
750 751 752 753 754 755 756 757 758
      //if (curPosTest == posTest)
      //  {
      //  tokenTestSelected = tokenTest;
      //  }

      // from this point : the test line is considered valid
      validTestLines.push_back(curPosTest);

      // get number of equivalent separators and tokens to find the best match
759
      int commonTokens = 0;
760 761
      int firstCommonTokens = 0;
      int firstNumericToken = -1;
Guillaume Pasero's avatar
Guillaume Pasero committed
762 763
      unsigned int commonSeparators = 0;
      std::vector<unsigned int> differencesPos;
764 765
      for (unsigned int i = 0 ; i < std::min(nbTokenRef,nbTokenTest) ; i++)
        {
Guillaume Pasero's avatar
Guillaume Pasero committed
766 767 768 769 770 771 772 773
        //------ comparing previous separator ------
        std::string sepRef("");
        std::string sepTest("");
        unsigned int endSepRef;
        unsigned int endSepTest;
        unsigned int startSepRef;
        unsigned int startSepTest;
        if (i)
774
          {
Guillaume Pasero's avatar
Guillaume Pasero committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
          startSepRef  = tokenRef[i-1].end() - curLineRef.begin();
          startSepTest = tokenTest[i-1].end() - curLineTest.begin();
          endSepRef  = tokenRef[i].begin() - curLineRef.begin();
          endSepTest = tokenTest[i].begin() - curLineTest.begin();
          }
        else
          {
          startSepRef  = 0;
          startSepTest = 0;
          endSepRef  = tokenRef[0].begin() - curLineRef.begin();
          endSepTest = tokenTest[0].begin() - curLineTest.begin();
          }
        for (unsigned int iRef=startSepRef ; iRef < endSepRef ; iRef++ )
          {
          if (curLineRef[iRef] != ' ' && curLineRef[iRef] != '\t')
            sepRef += curLineRef[iRef];
          }
        for (unsigned int iTest=startSepTest ; iTest < endSepTest ; iTest++ )
          {
          if (curLineTest[iTest] != ' ' && curLineTest[iTest] != '\t')
            sepTest += curLineTest[iTest];
          }
        if (sepRef.compare(sepTest) == 0)
          {
          commonSeparators++;
800 801 802 803 804
          }
        else
          {
          break;
          }
Guillaume Pasero's avatar
Guillaume Pasero committed
805
        // ----------- comparing current token --------------------
806 807 808 809 810 811 812 813
        bool areTokensEquivalent = false;
        // first : try direct string comparison
        if (curLineRef.compare(
              tokenRef[i].begin() - curLineRef.begin(),
              tokenRef[i].size(),
              curLineTest,
              tokenTest[i].begin() - curLineTest.begin(),
              tokenTest[i].size()) == 0)
Guillaume Pasero's avatar
Guillaume Pasero committed
814
          {
815
          areTokensEquivalent = true;
Guillaume Pasero's avatar
Guillaume Pasero committed
816
          }
817
        else
Guillaume Pasero's avatar
Guillaume Pasero committed
818
          {
819
          // examine other cases :
820
          // test if hexadecimal address
821 822 823 824 825 826 827 828 829
          bool isRefTokenHexa = isHexaPointerAddress(
                                  curLineRef,
                                  tokenRef[i].begin()-curLineRef.begin(),
                                  tokenRef[i].size());
          bool isTestTokenHexa = isHexaPointerAddress(
                                  curLineTest,
                                  tokenTest[i].begin()-curLineTest.begin(),
                                  tokenTest[i].size());
          if (isRefTokenHexa && isTestTokenHexa)
Guillaume Pasero's avatar
Guillaume Pasero committed
830
            {
831
            // these tokens are equivalent (we don't compare pointer address)
832
            areTokensEquivalent = true;
Guillaume Pasero's avatar
Guillaume Pasero committed
833 834 835
            }
          else
            {
836 837 838
            double vTest=0.;
            double vRef=0.;
            double vNorm=0.;
839 840 841
            // cast ref token
            bool isRefTokenNum = true;
            try
842
              {
843 844 845 846 847 848
              vRef = boost::lexical_cast<double>(tokenRef[i]);
              // record the first numeric token position
              if (firstNumericToken<0)
                {
                firstNumericToken = static_cast<int>(i);
                }
849
              }
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
            catch (boost::bad_lexical_cast &)
              {
              isRefTokenNum = false;
              }
            // cast test token
            bool isTestTokenNum = true;
            try
              {
              vTest = boost::lexical_cast<double>(tokenTest[i]);
              }
            catch (boost::bad_lexical_cast &)
              {
              isTestTokenNum = false;
              }
            if (isRefTokenNum && isTestTokenNum)
865
              {
866
              // test difference against epsilon
867
              vNorm = (std::abs(vRef) + std::abs(vTest)) * 0.5;
868
              if ((vNorm <= m_EpsilonBoundaryChecking) //make sure that either the test of the ref are non 0
869
                || (std::abs(vRef-vTest) <= epsilon * vNorm)) //epsilon as relative error
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
                {
                // these tokens are equivalent
                areTokensEquivalent = true;
                }
              }
            else
              {
              // test for special tokens
              for (unsigned int j=0 ; j<m_SpecialTokens.size() ; j++)
                {
                if (curLineRef.compare(
                      tokenRef[i].begin() - curLineRef.begin(),
                      tokenRef[i].size(),
                      m_SpecialTokens[j].first) == 0 &&
                    curLineTest.compare(
                      tokenTest[i].begin() - curLineTest.begin(),
                      tokenTest[i].size(),
                      m_SpecialTokens[j].second) == 0)
                  {
                  areTokensEquivalent = true;
                  break;
                  }
                }
893
              }
Guillaume Pasero's avatar
Guillaume Pasero committed
894
            }
895 896 897 898 899
          }
        if (areTokensEquivalent)
          {
          commonTokens++;
          if (differencesPos.empty())
Guillaume Pasero's avatar
Guillaume Pasero committed
900
            {
901
            firstCommonTokens++;
Guillaume Pasero's avatar
Guillaume Pasero committed
902 903
            }
          }
904 905 906 907
        else
          {
          differencesPos.push_back(i);
          }
Guillaume Pasero's avatar
Guillaume Pasero committed
908
        }
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
      // finish iteration of all tokens from reference line to detect first numeric token
      for (unsigned int i = std::min(nbTokenRef,nbTokenTest) ; i < nbTokenRef ; i++)
        {
        try
          {
          boost::lexical_cast<double>(tokenRef[i]);
          // record the first numeric token position
          if (firstNumericToken<0)
            {
            firstNumericToken = static_cast<int>(i);
            }
          }
        catch (boost::bad_lexical_cast &)
          {
          }
        }
Guillaume Pasero's avatar
Guillaume Pasero committed
925 926 927 928 929

      if (commonSeparators < std::min(nbTokenRef,nbTokenTest))
        {
        // All the separators are not equivalent : reject line
        continue;
930
        }
931 932 933 934 935 936 937
      if (firstNumericToken > firstCommonTokens)
        {
        // if there are non-numeric tokens before a numeric one, all non-numeric
        // tokens must match (we make sure to compare the same field name)
        continue;
        }
      if (firstCommonTokens > bestCommonTokens)
938
        {
939
        bestCommonTokens = firstCommonTokens;
940 941
        bestLinePos = curPosTest;
        tokenTestSelected = tokenTest;
942
        nbTokenTestSelected = nbTokenTest;
Guillaume Pasero's avatar
Guillaume Pasero committed
943 944 945 946 947 948 949 950
        differencesPosSelected = differencesPos;
        skippedTestLines.clear();
        unsigned int k=0;
        while (validTestLines[k] < curPosTest)
          {
          skippedTestLines.push_back(validTestLines[k]);
          k++;
          }
951 952
        }
      // test if lines are identic
953
      if (static_cast<unsigned int>(firstCommonTokens) == std::max(nbTokenRef,nbTokenTest))
954 955 956 957 958
        {
        break;
        }
      }

959
    // depending on the best number of common tokens ...
960
    if (bestCommonTokens <= 0)
961
      {
962
      // line not found in test
963 964 965 966 967
      if (isFirstMissingRefLine)
        {
        listStrDiffLineFile.push_back("   -------------------------------");
        isFirstMissingRefLine = false;
        }
Guillaume Pasero's avatar
Guillaume Pasero committed
968 969 970 971 972
      listStrDiffLineFile.push_back(std::string("   Base << ")+curLineRef);
      if (m_ReportErrors)
        {
        fluxfilediff << "In baseline l."<<posRef+1<<" : "<<curLineRef<< std::endl;
        }
973
      nbdiff++;
974 975 976
      }
    else
      {
Guillaume Pasero's avatar
Guillaume Pasero committed
977 978
      // record skipped lines in test file
      for (unsigned int k=0 ; k < skippedTestLines.size() ; k++)
979
        {
980
        isFirstMissingRefLine = true;
Guillaume Pasero's avatar
Guillaume Pasero committed
981 982 983 984
        if (k== 0)
          listStrDiffLineFile.push_back("   -------------------------------");
        listStrDiffLineFile.push_back(std::string("   Test >> ")+listLineFileTest[skippedTestLines[k]]);
        if (m_ReportErrors)
985
          {
Guillaume Pasero's avatar
Guillaume Pasero committed
986
          fluxfilediff << "In test     l."<<skippedTestLines[k]+1<<" : "<<listLineFileTest[skippedTestLines[k]] << std::endl;
987
          }
Guillaume Pasero's avatar
Guillaume Pasero committed
988
        nbdiff++;
989 990
        }

991
      if (bestCommonTokens < static_cast<int>(std::max(nbTokenRef,nbTokenTestSelected)))
992
        {
Guillaume Pasero's avatar
Guillaume Pasero committed
993 994 995 996 997 998
        nbdiff++;
        std::string &lineTestSelected = listLineFileTest[bestLinePos];
        // record the diff
        std::ostringstream ossBase;
        std::ostringstream ossTest;
        for (unsigned int k=0 ; k < std::min(nbTokenRef,nbTokenTestSelected) ; k++)
999
          {
Guillaume Pasero's avatar
Guillaume Pasero committed
1000
          // record the separator
1001 1002
          unsigned int sizeSepRef;
          unsigned int startSepRef;
Guillaume Pasero's avatar
Guillaume Pasero committed
1003
          if (k)
1004
            {
1005 1006
            startSepRef = tokenRef[k-1].end()-curLineRef.begin();
            sizeSepRef = tokenRef[k].begin()-tokenRef[k-1].end();
1007
            }
Guillaume Pasero's avatar
Guillaume Pasero committed
1008
          else
1009
            {
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
            startSepRef = 0;
            sizeSepRef = tokenRef[0].begin()-curLineRef.begin();
            }
          ossBase << curLineRef.substr(startSepRef, sizeSepRef);
          for (unsigned int j=0 ; j<sizeSepRef ; j++)
            {
            if (curLineRef[startSepRef+j] == '\t')
              {
              ossTest << "\t";
              }
            else
              {
              ossTest << " ";
              }
1024
            }
Guillaume Pasero's avatar
Guillaume Pasero committed
1025 1026 1027
          // record the token
          bool isTokenEquivalent = true;
          for (unsigned int t=0 ; t < differencesPosSelected.size() ; t++)
1028
            {
Guillaume Pasero's avatar
Guillaume Pasero committed
1029
            if (k == differencesPosSelected[t])
1030
              {
Guillaume Pasero's avatar
Guillaume Pasero committed
1031 1032
              isTokenEquivalent = false;
              break;
1033
              }
1034
            }
Guillaume Pasero's avatar
Guillaume Pasero committed
1035 1036 1037 1038
          if (isTokenEquivalent)
            {
            ossBase << curLineRef.substr(tokenRef[k].begin()-curLineRef.begin(),
                                         tokenRef[k].size());
1039
            ossTest << std::string(tokenRef[k].size(), '_');
Guillaume Pasero's avatar
Guillaume Pasero committed
1040
            }
1041 1042
          else
            {
Guillaume Pasero's avatar
Guillaume Pasero committed
1043 1044 1045 1046 1047 1048 1049
            unsigned int maxTokenSize = std::max(tokenRef[k].size(),tokenTestSelected[k].size());
            ossBase << curLineRef.substr(tokenRef[k].begin()-curLineRef.begin(),
                                         tokenRef[k].size())
                    << std::string(maxTokenSize - tokenRef[k].size(), ' ');
            ossTest << lineTestSelected.substr(tokenTestSelected[k].begin()-lineTestSelected.begin(),
                                               tokenTestSelected[k].size())
                    << std::string(maxTokenSize - tokenTestSelected[k].size(), ' ');
1050 1051
            }
          }
Guillaume Pasero's avatar
Guillaume Pasero committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        // process token in excess on any side
        if (nbTokenRef >= nbTokenTestSelected)
          {
          ossBase << curLineRef.substr(tokenRef[nbTokenTestSelected-1].end()-curLineRef.begin());
          if (nbTokenRef > nbTokenTestSelected)
            ossTest << "|";
          }
        else if (nbTokenRef < nbTokenTestSelected)
          {
          ossBase << "|";
          ossTest << lineTestSelected.substr(tokenTestSelected[nbTokenRef-1].end()-lineTestSelected.begin());
          }
        listStrDiffLineFile.push_back("   -------------------------------");
        listStrDiffLineFile.push_back(std::string("   Base << ")+ossBase.str());
        listStrDiffLineFile.push_back(std::string("   Test >> ")+ossTest.str());
        if (m_ReportErrors)
1068
          {
Guillaume Pasero's avatar
Guillaume Pasero committed
1069 1070
          fluxfilediff << "In baseline l."<< posRef+1 <<" : "<< ossBase.str() << std::endl;
          fluxfilediff << "In test     l."<< bestLinePos+1 << " : "<<ossTest.str() << std::endl;
1071
          }
1072
        isFirstMissingRefLine = true;
1073 1074
        }

1075
      // update posTest
Guillaume Pasero's avatar
Guillaume Pasero committed
1076
      posTest = bestLinePos + 1;
1077 1078 1079
      }
    }

Guillaume Pasero's avatar
Guillaume Pasero committed
1080 1081 1082 1083 1084 1085 1086 1087 1088
  // process remaining lines in test file
  for (curPosTest = posTest ; curPosTest < listLineFileTest.size() ; curPosTest++)
    {
    std::string &curLineTest = listLineFileTest[curPosTest];
    if (!IsLineValid(curLineTest,ignoredLines))
      {
      continue;
      }
    boost::split(tokenTest, curLineTest, boost::is_any_of(separators));
Guillaume Pasero's avatar
Guillaume Pasero committed
1089 1090 1091
    // remove empty tokens
    TokenListType::iterator testEndFiltered = std::remove_if(tokenTest.begin(), tokenTest.end(), IsTokenEmpty);
    tokenTest.resize(testEndFiltered-tokenTest.begin());
Guillaume Pasero's avatar
Guillaume Pasero committed
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    nbTokenTest = tokenTest.size();
    if (nbTokenTest == 0)
      {
      // ignore lines without tokens
      continue;
      }
    // this test line is valid
    //listStrDiffLineFile.push_back("   -------------------------------");
    listStrDiffLineFile.push_back(std::string("   Test >> ")+curLineTest);
    if (m_ReportErrors)
      {
      fluxfilediff << "In test     l."<<curPosTest+1<<" : "<<curLineTest << std::endl;
      }
    nbdiff++;
    }
  
  if (m_ReportErrors)
    {
    fluxfilediff.close();
    }

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
  if (nbdiff != 0 && m_ReportErrors)
    {
    std::cout << "<DartMeasurement name=\"ASCIIFileError\" type=\"numeric/int\">";
    std::cout << nbdiff;
    std::cout << "</DartMeasurement>" << std::endl;
    std::cout << "================================================================" << std::endl;
    std::cout << "baseline ASCII File : " << baselineAsciiFileName << std::endl;
    std::cout << "Test ASCII File     : " << testAsciiFileName << std::endl;
    std::cout << "Diff ASCII File     : " << diffAsciiFileName << std::endl;
    std::cout << "Tolerance value     : " << epsilon << std::endl;
    std::cout << "Tolerance max check : " << m_EpsilonBoundaryChecking << std::endl;
1124 1125 1126
    std::cout << "Nb lines different : " << nbdiff << std::endl;
    
    for (unsigned int i=0 ; i<listStrDiffLineFile.size() ; i++)
1127
      {
1128
      std::cout << listStrDiffLineFile[i] << std::endl;
1129 1130
      }
    }
1131
  
1132 1133 1134
  return (nbdiff != 0) ? 1 : 0;
}

Guillaume Pasero's avatar
Guillaume Pasero committed
1135 1136 1137 1138 1139
bool TestHelper::IsTokenEmpty(boost::iterator_range<std::string::const_iterator> &token)
{
  return token.empty();
}

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
int TestHelper::TokenizeLine(const std::string &line, StringList &tokens) const
{
  std::string::size_type pos;
  tokens.clear();
  std::string::size_type counter = 0;
  bool isSeparator;
  bool isToken = false;
  int curChar;
  for (pos = 0 ; pos < line.size() ; pos++)
    {
    isSeparator = true;
    curChar = (int)(line[pos]);
    // test if alphanumeric or '.' or '-' or '^' or '_' or '/'
    if (isAlphaNum(curChar) || isPoint(curChar) || isMinusSign(curChar) ||
        curChar == 94 || curChar == 95 || curChar == 47)
      {
      isSeparator = false;
      }

    if (isToken)
      {
      // already in a token
      if (isSeparator)
        {
        // end of the token : record it
        tokens.push_back(line.substr(pos-counter, counter));
        isToken = false;
        counter = 0;tokens.push_back(line.substr(pos-counter, counter));
        }
      else
        {
        // still in a token
        counter++;
        }
      }
    else
      {
      // not in a token
      if (isSeparator)
        {
        // do nothing
        }
      else
        {
        // start of a token
        isToken = true;
        counter++;
        }
      }
    }
  // handle final token
  if (isToken)
    {
    tokens.push_back(line.substr(line.size()-counter, counter));
    }

  return tokens.size();
}

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
bool TestHelper::IsLineValid(const std::string& str, const StringList &ignoredLines) const
{
  bool ret = true;
  if (isToBeIgnoredForAnyComparison(str))
    {
    ret = false;
    }
  else
    {
    for (unsigned int i=0 ; i<ignoredLines.size() ; i++)
      {
      if (str.find(ignoredLines[i]) != std::string::npos)
        {
        ret = false;
        break;
        }
      }
    }
  return ret;
}

1220 1221 1222 1223 1224 1225
/******************************************/
/******************************************/
/******************************************/

int TestHelper::RegressionTestBinaryFile(const char * testBinaryFileName, const char * baselineBinaryFileName) const
{
OTB Bot's avatar
STYLE  
OTB Bot committed
1226
  int           nbdiff(0);
1227 1228 1229
  std::ifstream fluxfiletest(testBinaryFileName, std::ifstream::binary);
  std::ifstream fluxfileref(baselineBinaryFileName, std::ifstream::binary);
  if (fluxfiletest.fail())
OTB Bot's avatar
STYLE  
OTB Bot committed
1230 1231 1232
    {
    itkGenericExceptionMacro(<< "Impossible to open the test binary file <" << testBinaryFileName << ">.");
    }
1233
  if (!fluxfileref)
OTB Bot's avatar
STYLE  
OTB Bot committed
1234
    {
1235
    itkGenericExceptionMacro(<< "Impossible to open the baseline binary file <" << baselineBinaryFileName << ">.");
OTB Bot's avatar
STYLE  
OTB Bot committed
1236
    }
1237 1238
  while (fluxfiletest.good() && fluxfileref.good())
    {
OTB Bot's avatar
STYLE  
OTB Bot committed
1239 1240
    if (fluxfiletest.get() != fluxfileref.get())
      {
1241
      nbdiff++;
OTB Bot's avatar
STYLE  
OTB Bot committed
1242
      }
1243 1244 1245 1246 1247
    }
  fluxfiletest.close();
  fluxfileref.close();

  if (nbdiff != 0 && m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
1248
    {
1249 1250 1251
    std::cout << "<DartMeasurement name=\"BINARYFileError\" type=\"numeric/int\">";
    std::cout << nbdiff;
    std::cout << "</DartMeasurement>" << std::endl;
OTB Bot's avatar
STYLE  
OTB Bot committed
1252
    }
1253 1254 1255 1256
  return (nbdiff != 0) ? 1 : 0;
}

int TestHelper::RegressionTestImage(int cpt, const char *testImageFilename, const char *baselineImageFilename,
OTB Bot's avatar
STYLE  
OTB Bot committed
1257
                                    const double toleranceDiffPixelImage) const
1258 1259 1260
{
  // Use the factory mechanism to read the test and baseline files and convert them to double

OTB Bot's avatar
STYLE  
OTB Bot committed
1261 1262
  typedef otb::VectorImage<double, 2>        ImageType;
  typedef otb::ImageFileReader<ImageType>    ReaderType;
1263 1264 1265 1266 1267

  // Read the baseline file
  ReaderType::Pointer baselineReader = ReaderType::New();
  baselineReader->SetFileName(baselineImageFilename);
  try
OTB Bot's avatar
STYLE  
OTB Bot committed
1268
    {
1269
    baselineReader->UpdateLargestPossibleRegion();
OTB Bot's avatar
STYLE  
OTB Bot committed
1270 1271 1272
    }
  catch (itk::ExceptionObject& e)
    {
1273
    itkGenericExceptionMacro(<< "Exception detected while reading "
OTB Bot's avatar
STYLE  
OTB Bot committed
1274
                             << baselineImageFilename << " : " << e.GetDescription());
1275
    return 1000;
OTB Bot's avatar
STYLE  
OTB Bot committed
1276
    }
1277 1278 1279 1280 1281

  // Read the file generated by the test
  ReaderType::Pointer testReader = ReaderType::New();
  testReader->SetFileName(testImageFilename);
  try
OTB Bot's avatar
STYLE  
OTB Bot committed
1282
    {
1283
    testReader->UpdateLargestPossibleRegion();
OTB Bot's avatar
STYLE  
OTB Bot committed
1284 1285 1286
    }
  catch (itk::ExceptionObject& e)
    {
1287
    itkGenericExceptionMacro(<< "Exception detected while reading "
OTB Bot's avatar
STYLE  
OTB Bot committed
1288
                             << testImageFilename << " : " << e.GetDescription());
1289
    return 1000;
OTB Bot's avatar
STYLE  
OTB Bot committed
1290
    }
1291 1292 1293 1294 1295 1296 1297 1298

  // The sizes of the baseline and test image must match
  ImageType::SizeType baselineSize;
  baselineSize = baselineReader->GetOutput()->GetLargestPossibleRegion().GetSize();
  ImageType::SizeType testSize;
  testSize = testReader->GetOutput()->GetLargestPossibleRegion().GetSize();

  if (baselineSize != testSize)
OTB Bot's avatar
STYLE  
OTB Bot committed
1299
    {
1300 1301 1302 1303
    std::cerr << "The size of the baseline image and Test image do not match!" << std::endl;
    std::cerr << "baseline image: " << baselineImageFilename << " has size " << baselineSize << std::endl;
    std::cerr << "Test image:     " << testImageFilename << " has size " << testSize << std::endl;
    return 1;
OTB Bot's avatar
STYLE  
OTB Bot committed
1304
    }
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

  // Now compare the two images
  typedef otb::DifferenceImageFilter<ImageType, ImageType> DiffType;
  DiffType::Pointer diff = DiffType::New();
  diff->SetValidInput(baselineReader->GetOutput());
  diff->SetTestInput(testReader->GetOutput());
  diff->SetDifferenceThreshold(toleranceDiffPixelImage);
  diff->UpdateLargestPossibleRegion();

  ImageType::PixelType status = diff->GetTotalDifference();
OTB Bot's avatar
STYLE  
OTB Bot committed
1315
  unsigned long        numberOfPixelsWithDifferences = diff->GetNumberOfPixelsWithDifferences();
1316 1317 1318

  //Write only one this message
  if (m_ReportErrors == 0)
OTB Bot's avatar
STYLE  
OTB Bot committed
1319 1320
    {
    otbGenericMsgDebugMacro(<< "RegressionTestImage DifferenceThreshold: " << toleranceDiffPixelImage);
1321
    otbGenericMsgDebugMacro(<< "Status diff->GetTotalDifference:         "
OTB Bot's avatar
STYLE  
OTB Bot committed
1322 1323
                            << status << " for " << numberOfPixelsWithDifferences << " pixel(s).");
    }
1324 1325
  // if there are discrepencies, create an diff image
  if (status.GetSquaredNorm() > 0 && m_ReportErrors)
OTB Bot's avatar
STYLE  
OTB Bot committed
1326
    {
Sébastien Dinot's avatar
STYLE  
Sébastien Dinot committed
1327
    typedef otb::PrintableImageFilter<ImageType>               RescaleType;
1328
    typedef otb::ImageFileWriter<RescaleType::OutputImageType> WriterType;
1329

1330 1331 1332 1333 1334 1335 1336
    RescaleType::Pointer rescale = RescaleType::New();
    WriterType::Pointer writer = WriterType::New();
    writer->SetInput(rescale->GetOutput());

    std::cout << "<DartMeasurement name=\"ImageError " << cpt << "\" type=\"numeric/double\">";
    std::cout << status;
    std::cout << "</DartMeasurement>" << std::endl;
1337

1338 1339 1340
    std::cout << "<DartMeasurement name=\"NumberOfPixelsWithDifferences " << cpt << "\" type=\"numeric/integer\">";
    std::cout << numberOfPixelsWithDifferences;
    std::cout << "</DartMeasurement>" << std::endl;
1341

1342 1343 1344
    std::cout << "<DartMeasurement name=\"ToleranceDiffPixelImage\" type=\"numeric/double\">";
    std::cout << toleranceDiffPixelImage;
    std::cout << "</DartMeasurement>" << std::endl;
1345

1346 1347
    diff->UpdateOutputInformation();
    ImageType::SizeType size = diff->GetOutput()->GetLargestPossibleRegion().GetSize();
1348

1349
    if( size[0]*size[1] <= m_MaxArea)
OTB Bot's avatar
STYLE  
OTB Bot committed
1350
      {