Chebyshev
Unit testing for scientific software
Loading...
Searching...
No Matches
prec.h
Go to the documentation of this file.
1
5
6#ifndef CHEBYSHEV_PREC_H
7#define CHEBYSHEV_PREC_H
8
9#include <string>
10#include <vector>
11#include <map>
12#include <iostream>
13#include <memory>
14#include <mutex>
15#include <thread>
16
18#include "./core/output.h"
19#include "./core/random.h"
20#include "./prec/estimator.h"
21#include "./prec/fail.h"
22
23
24namespace chebyshev {
25
27namespace prec {
28
29
33
35 std::string moduleName = "unknown";
36
39
42
45
47 std::vector<std::string> outputFiles {};
48
50 std::vector<std::string> estimateColumns = {
51 "name", "meanErr", "rmsErr", "maxErr", "failed"
52 };
53
56 std::vector<std::string> estimateOutputFiles {};
57
59 std::vector<std::string> equationColumns = {
60 "name", "difference", "tolerance", "failed"
61 };
62
65 std::vector<std::string> equationOutputFiles {};
66
70 std::map<std::string, bool> pickedTests {};
71
77 bool multithreading = true;
78
79 };
80
81
85 private:
86
88 std::map<std::string, std::vector<estimate_result>> estimateResults {};
89
91 std::mutex estimateMutex;
92
94 std::vector<std::thread> estimateThreads;
95
97 std::map<std::string, std::vector<equation_result>> equationResults {};
98
100 bool wasTerminated {false};
101
102 public:
103
106
109 std::shared_ptr<output::output_context> output;
110
113 std::shared_ptr<random::random_context> random;
114
115
121 inline void setup(
122 const std::string& moduleName,
123 int argc = 0, const char** argv = nullptr) {
124
125 // Initialize other modules
127 output = std::make_shared<output::output_context>();
128 random = std::make_shared<random::random_context>();
129
130 // Initialize list of picked tests
131 if(argc && argv)
132 for (int i = 1; i < argc; ++i)
133 settings.pickedTests[argv[i]] = true;
134
135 output->info("Starting precision testing of the " + moduleName + " module ...");
136
137 settings.moduleName = moduleName;
138 wasTerminated = false;
139 }
140
141
145 inline void terminate(bool exit = false) {
146
147 // Ensure all test cases have been executed
148 this->wait_results();
149 // std::lock_guard<std::mutex> lock(estimateMutex);
150
151 unsigned int totalTests = 0;
152 unsigned int failedTests = 0;
153
154 for (const auto& pair : estimateResults) {
155 for (const auto& testCase : pair.second) {
156 totalTests++;
157 failedTests += testCase.failed ? 1 : 0;
158 }
159 }
160
161 for (const auto& pair : equationResults) {
162 for (const auto& testCase : pair.second) {
163 totalTests++;
164 failedTests += testCase.failed ? 1 : 0;
165 }
166 }
167
168
169 // Ensure that an output file is specified
170 if( output->settings.outputToFile &&
171 !output->settings.outputFiles.size() &&
172 !settings.estimateOutputFiles.size() &&
173 !settings.equationOutputFiles.size() &&
174 !settings.outputFiles.size()) {
175
176 settings.outputFiles = { settings.moduleName + "_results" };
177 }
178
179
180 // Print test results
181 std::vector<std::string> outputFiles;
182
183 // Print estimate results
184 outputFiles = settings.outputFiles;
185 outputFiles.insert(
186 outputFiles.end(),
187 settings.estimateOutputFiles.begin(),
188 settings.estimateOutputFiles.end()
189 );
190
191 output->print_results(
192 estimateResults, settings.estimateColumns, outputFiles
193 );
194
195
196 // Print equation results
197 outputFiles = settings.outputFiles;
198 outputFiles.insert(
199 outputFiles.end(),
200 settings.equationOutputFiles.begin(),
201 settings.equationOutputFiles.end()
202 );
203
204 output->print_results(
205 equationResults, settings.equationColumns, outputFiles
206 );
207
208
209 // Print overall test results
210 double percent = totalTests > 0 ? (failedTests / (double) totalTests) * 100 : 0;
211
212 output->info("Finished testing " + settings.moduleName);
213 output->info(
214 std::to_string(totalTests) + " total tests, " + std::to_string(failedTests) +
215 " failed (" + std::to_string(percent).substr(0, 4) + "%)"
216 );
217
218 if (totalTests == 0)
219 output->warn("No tests were executed!");
220
221 if(exit) {
222 output->terminate();
223 std::exit(failedTests);
224 }
225
226 wasTerminated = true;
227 }
228
229
234 prec_context(const std::string& moduleName, int argc, const char** argv) {
235 setup(moduleName, argc, argv);
236 }
237
238
241 if (!wasTerminated)
242 terminate();
243 }
244
245
248
249 std::lock_guard<std::mutex> lock(estimateMutex);
250 estimateResults = other.estimateResults;
251 equationResults = other.equationResults;
252 settings = other.settings;
253 output = other.output;
254 random = other.random;
255 }
256
257
259 inline prec_context& operator=(const prec_context& other) {
260
261 std::lock_guard<std::mutex> lock(estimateMutex);
262 estimateResults = other.estimateResults;
263 equationResults = other.equationResults;
264 settings = other.settings;
265 output = other.output;
266 random = other.random;
267
268 return *this;
269 }
270
271
280 template <
281 typename R, typename ...Args,
282 typename Function1 = std::function<R(Args...)>,
283 typename Function2 = Function1
284 >
285 inline void estimate(
286 const std::string& name,
287 Function1 funcApprox,
288 Function2 funcExpected,
290
291 // Skip the test case if any tests have been picked
292 // and this one was not picked.
293 if(settings.pickedTests.size())
294 if(settings.pickedTests.find(name) == settings.pickedTests.end())
295 return;
296
297 output->debug("Running estimate case: " + name);
298
299 auto task = [this, name, funcApprox, funcExpected, opt]() {
300
301 // Use the estimator to estimate error integrals.
302 auto res = opt.estimator(funcApprox, funcExpected, opt);
303
304 res.name = name;
305 res.domain = opt.domain;
306 res.tolerance = opt.tolerance;
307 res.quiet = opt.quiet;
308 res.iterations = opt.iterations;
309
310 // Use the fail function to determine whether the test failed.
311 res.failed = opt.fail(res);
312
313 std::lock_guard<std::mutex> lock(estimateMutex);
314 estimateResults[name].push_back(res);
315 };
316
317 if (settings.multithreading)
318 estimateThreads.emplace_back(task);
319 else
320 task();
321 }
322
323
337 template <
338 typename R, typename ...Args,
339 typename Function1 = std::function<R(Args...)>,
340 typename Function2 = Function1
341 >
342 inline void estimate(
343 const std::string& name,
344 Function1 funcApprox,
345 Function2 funcExpected,
346 std::vector<interval> domain,
347 prec_t tolerance, unsigned int iterations,
350 bool quiet = false) {
351
352 estimate_options<R, Args...> opt {};
353 opt.domain = domain;
354 opt.tolerance = tolerance;
355 opt.iterations = iterations;
356 opt.fail = fail;
357 opt.estimator = estimator;
358 opt.quiet = quiet;
359
360 estimate(name, funcApprox, funcExpected, opt);
361 }
362
363
378 inline void estimate(
379 const std::string& name,
380 EndoFunction<double> funcApprox,
381 EndoFunction<double> funcExpected,
382 interval domain,
383 prec_t tolerance = get_nan(),
384 unsigned int iterations = 0,
387 bool quiet = false) {
388
389 if (tolerance != tolerance)
390 tolerance = settings.defaultTolerance;
391
392 if (iterations == 0)
393 iterations = settings.defaultIterations;
394
396 opt.domain = { domain };
397 opt.tolerance = tolerance;
398 opt.iterations = iterations;
399 opt.fail = fail;
400 opt.estimator = estimator;
401 opt.quiet = quiet;
402
403 estimate(name, funcApprox, funcExpected, opt);
404 }
405
406
413 template <
414 typename Type, typename Identity = EndoFunction<Type>
415 >
416 inline void identity(
417 const std::string& name,
418 Identity id,
419 const estimate_options<Type, Type>& opt) {
420
421 // Apply the identity function
422 EndoFunction<Type> funcApprox = [id](Type x) -> Type {
423 return id(x);
424 };
425
426 // And compare it to the identity
427 EndoFunction<Type> funcExpected = [](Type x) -> Type {
428 return x;
429 };
430
431 estimate(name, funcApprox, funcExpected, opt);
432 }
433
434
442 template <
443 typename Type, typename Involution = EndoFunction<Type>
444 >
445 inline void involution(
446 const std::string& name,
447 Involution invol,
448 const estimate_options<Type, Type>& opt) {
449
450 // Apply the involution two times
451 EndoFunction<Type> funcApprox = [invol](Type x) -> Type {
452 return invol(invol(x));
453 };
454
455 // And compare it to the identity
456 EndoFunction<Type> funcExpected = [](Type x) -> Type {
457 return x;
458 };
459
460 estimate(name, funcApprox, funcExpected, opt);
461 }
462
463
471 template <
472 typename Type, typename Involution = EndoFunction<Type>
473 >
474 inline void idempotence(
475 const std::string& name,
476 Involution idem,
477 const estimate_options<Type, Type>& opt) {
478
479 // Apply the idem two times
480 EndoFunction<Type> funcApprox = [idem](Type x) -> Type {
481 return idem(idem(x));
482 };
483
484 // And compare it to the identity
485 EndoFunction<Type> funcExpected = [idem](Type x) -> Type {
486 return idem(x);
487 };
488
489 estimate(name, funcApprox, funcExpected, opt);
490 }
491
492
504 template <
505 typename OutputType, typename InputType = OutputType,
506 typename Homogeneous = std::function<OutputType(InputType)>
507 >
508 inline void homogeneous(
509 const std::string& name,
510 Homogeneous hom,
512 OutputType zero_element = OutputType(0.0)) {
513
514 // Apply the homogeneous function
515 std::function<OutputType(InputType)> funcApprox =
516 [=](InputType x) -> OutputType {
517 return hom(x);
518 };
519
520 // And compare it to the zero element
521 std::function<OutputType(InputType)> funcExpected =
522 [=](InputType x) -> OutputType {
523 return zero_element;
524 };
525
526 estimate(name, funcApprox, funcExpected, opt);
527 }
528
529
537 template<typename Type = double>
538 inline void equals(
539 const std::string& name,
540 const Type& evaluated, const Type& expected,
542
543 // Skip the test case if any tests have been picked
544 // and this one was not picked.
545 if(settings.pickedTests.size())
546 if(settings.pickedTests.find(name) == settings.pickedTests.end())
547 return;
548
549 output->debug("Running equation case: " + name);
550
551 equation_result res {};
552 prec_t diff = opt.distance(evaluated, expected);
553
554 // Mark the test as failed if the
555 // distance between the two values
556 // is bigger than the tolerance.
557 res.failed = (diff > opt.tolerance) || (diff != diff);
558
559 res.name = name;
560 res.difference = diff;
561 res.tolerance = opt.tolerance;
562 res.quiet = opt.quiet;
563
564 // Register the result of the equation by name
565 equationResults[name].push_back(res);
566 }
567
568
578 template<typename Type = double>
579 inline void equals(
580 const std::string& name,
581 const Type& evaluated, const Type& expected,
582 prec_t tolerance,
584 bool quiet = false) {
585
587 opt.tolerance = tolerance;
588 opt.distance = distance;
589 opt.quiet = quiet;
590
591 equals(name, evaluated, expected, opt);
592 }
593
594
603 inline void equals(
604 const std::string& name,
605 prec_t evaluated, prec_t expected,
606 prec_t tolerance = get_nan(),
607 bool quiet = false) {
608
609 if (tolerance != tolerance)
610 tolerance = settings.defaultTolerance;
611
612 // Skip the test case if any tests have been picked
613 // and this one was not picked.
614 if(settings.pickedTests.size())
615 if(settings.pickedTests.find(name) == settings.pickedTests.end())
616 return;
617
618 output->debug("Running equation case: " + name);
619
620 equation_result res {};
621 prec_t diff = distance::absolute(evaluated, expected);
622
623 // Mark the test as failed if the
624 // distance between the two values
625 // is bigger than the tolerance or is NaN.
626 res.failed = (diff > tolerance) || (diff != diff);
627
628 res.name = name;
629 res.difference = diff;
630 res.tolerance = tolerance;
631 res.quiet = quiet;
632
633 res.evaluated = evaluated;
634 res.expected = expected;
635
636 // Register the result of the equation by name
637 equationResults[name].push_back(res);
638 }
639
640
648 template<typename Type>
649 inline void equals(
650 const std::string& name,
651 std::vector<std::array<Type, 2>> values,
652 prec_t tolerance = get_nan(),
653 bool quiet = false) {
654
655 if (tolerance != tolerance)
656 tolerance = settings.defaultTolerance;
657
658 // Skip the test case if any tests have been picked
659 // and this one was not picked.
660 if(settings.pickedTests.size())
661 if(settings.pickedTests.find(name) == settings.pickedTests.end())
662 return;
663
664 for (const auto& v : values)
665 equals(name, v[0], v[1], tolerance, quiet);
666 }
667
668
670 inline void wait_results() {
671
672 for (auto& t : estimateThreads)
673 if (t.joinable())
674 t.join();
675
676 estimateThreads.clear();
677 }
678
679
685 inline std::vector<estimate_result> get_estimate(const std::string& name) {
686
687 this->wait_results();
688
689 return estimateResults[name];
690 }
691
692
698 inline estimate_result get_estimate(const std::string& name, unsigned int i) {
699
700 this->wait_results();
701
702 return estimateResults[name].at(i);
703 }
704
705
707 inline std::vector<equation_result> get_equation(const std::string& name) {
708 return equationResults[name];
709 }
710
711
713 inline equation_result get_equation(const std::string& name, unsigned int i) {
714 return equationResults[name].at(i);
715 }
716
717 };
718
719
725 prec_context make_context(const std::string& moduleName,
726 int argc = 0, const char** argv = nullptr) {
727
728 return prec_context(moduleName, argc, argv);
729 }
730
731
732}}
733
734#endif
Precision testing context, handling precision test cases.
Definition prec.h:84
void equals(const std::string &name, const Type &evaluated, const Type &expected, equation_options< Type > opt)
Test an equivalence up to a tolerance, with the given options (e.g.
Definition prec.h:538
std::shared_ptr< random::random_context > random
Random module settings for the context, dynamically allocated and possibly shared between multiple co...
Definition prec.h:113
void equals(const std::string &name, std::vector< std::array< Type, 2 > > values, prec_t tolerance=get_nan(), bool quiet=false)
Evaluate multiple pairs of values for equivalence up to the given tolerance (e.g.
Definition prec.h:649
void setup(const std::string &moduleName, int argc=0, const char **argv=nullptr)
Setup the precision testing module.
Definition prec.h:121
void idempotence(const std::string &name, Involution idem, const estimate_options< Type, Type > &opt)
Precision testing of an endofunction which is idempotent.
Definition prec.h:474
equation_result get_equation(const std::string &name, unsigned int i)
Get a single result of equation testing by label and index.
Definition prec.h:713
std::vector< equation_result > get_equation(const std::string &name)
Get the results of equation testing by label.
Definition prec.h:707
prec_context(const std::string &moduleName, int argc, const char **argv)
Construct a precision testing context.
Definition prec.h:234
void equals(const std::string &name, prec_t evaluated, prec_t expected, prec_t tolerance=get_nan(), bool quiet=false)
Test an equivalence up to a tolerance, with the given options (e.g.
Definition prec.h:603
estimate_result get_estimate(const std::string &name, unsigned int i)
Get a single result of error estimation by label and index.
Definition prec.h:698
void estimate(const std::string &name, EndoFunction< double > funcApprox, EndoFunction< double > funcExpected, interval domain, prec_t tolerance=get_nan(), unsigned int iterations=0, FailFunction fail=fail::fail_on_max_err(), Estimator< double, double > estimator=estimator::quadrature1D< double >(), bool quiet=false)
Estimate error integrals over a real function of real variable, with respect to an exact function.
Definition prec.h:378
void homogeneous(const std::string &name, Homogeneous hom, const estimate_options< OutputType, InputType > &opt, OutputType zero_element=OutputType(0.0))
Precision testing of an function which is homogeneous over the domain.
Definition prec.h:508
prec_settings settings
Settings for the precision testing context.
Definition prec.h:105
prec_context(const prec_context &other)
Custom copy constructor to avoid copying std::mutex.
Definition prec.h:247
void estimate(const std::string &name, Function1 funcApprox, Function2 funcExpected, estimate_options< R, Args... > opt)
Estimate error integrals over a function with respect to an exact function, with the given options.
Definition prec.h:285
void involution(const std::string &name, Involution invol, const estimate_options< Type, Type > &opt)
Precision testing of an endofunction which is an involution.
Definition prec.h:445
prec_context & operator=(const prec_context &other)
Custom assignment operator to avoid copying std::mutex.
Definition prec.h:259
void wait_results()
Wait for all concurrent test cases to finish execution.
Definition prec.h:670
void estimate(const std::string &name, Function1 funcApprox, Function2 funcExpected, std::vector< interval > domain, prec_t tolerance, unsigned int iterations, FailFunction fail, Estimator< R, Args... > estimator, bool quiet=false)
Estimate error integrals over a function with respect to an exact function.
Definition prec.h:342
void identity(const std::string &name, Identity id, const estimate_options< Type, Type > &opt)
Precision testing of an endofunction which is equivalent to the identity.
Definition prec.h:416
void equals(const std::string &name, const Type &evaluated, const Type &expected, prec_t tolerance, DistanceFunction< Type > distance, bool quiet=false)
Test an equivalence up to a tolerance, with the given options (e.g.
Definition prec.h:579
void terminate(bool exit=false)
Terminate the precision testing module.
Definition prec.h:145
~prec_context()
Destructor for the context, automatically terminates the module.
Definition prec.h:240
std::shared_ptr< output::output_context > output
Output module settings for the context, dynamically allocated and possibly shared between multiple co...
Definition prec.h:109
std::vector< estimate_result > get_estimate(const std::string &name)
Get the results of error estimation by label.
Definition prec.h:685
#define CHEBYSHEV_PREC_ITER
Default number of function evaluations in precision testing.
Definition common.h:12
#define CHEBYSHEV_PREC_TOLERANCE
Default tolerance in precision testing.
Definition common.h:17
long double prec_t
Floating-point type of higher precision, used in computations, such as error estimation.
Definition common.h:42
Default precision estimators.
Default fail functions.
Distance functions for use in prec_context::equals().
prec_t absolute(Type a, Type b)
Absolute distance between two values which have an ordering with respect to zero.
Definition distance.h:21
Precision estimators.
auto quadrature1D()
Use Simpson's quadrature scheme to approximate error integrals for univariate real functions (endofun...
Definition estimator.h:30
Fail functions for use in prec::estimate.
auto fail_on_max_err()
Default fail function which marks the test as failed if the maximum error on the domain is bigger tha...
Definition fail.h:34
General namespace of the framework.
Definition benchmark.h:22
std::function< Type(Type)> EndoFunction
An endofunction is a function which has the same type of input and output, such as a real function of...
Definition common.h:60
constexpr FloatType get_nan()
Get a quiet NaN of the specified floating point type.
Definition common.h:65
The output module, with formatting capabilities.
prec_context make_context(const std::string &moduleName, int argc=0, const char **argv=nullptr)
Construct a precision testing context with the given parameters.
Definition prec.h:725
Structures for precision testing.
std::function< bool(const estimate_result &)> FailFunction
A function which determines whether an estimation failed.
Definition prec_structures.h:66
typename estimate_options< R, Args... >::Estimator_t Estimator
Generic precision estimator function signature.
Definition prec_structures.h:162
std::function< prec_t(Type, Type)> DistanceFunction
Distance function between two elements.
Definition prec_structures.h:71
The pseudorandom number generation and sampling module.
Structure holding options for equivalence evaluation.
Definition prec_structures.h:199
bool quiet
Print to standard output or not.
Definition prec_structures.h:211
prec_t tolerance
Tolerance on the absolute difference.
Definition prec_structures.h:202
DistanceFunction< T > distance
Distance function to measure the distance between the expected and evaluated value.
Definition prec_structures.h:206
A structure holding the result of an evaluation.
Definition prec_structures.h:167
bool failed
Whether the test failed.
Definition prec_structures.h:189
bool quiet
Print to standard output or not.
Definition prec_structures.h:192
std::string name
Identifying name of the function or test case.
Definition prec_structures.h:170
prec_t evaluated
Evaluated value.
Definition prec_structures.h:173
prec_t difference
Evaluated difference between expected and evaluated values.
Definition prec_structures.h:179
prec_t expected
Expected value.
Definition prec_structures.h:176
prec_t tolerance
Tolerance on the absolute difference.
Definition prec_structures.h:186
A structure holding the options for precision estimation.
Definition prec_structures.h:77
FailFunction fail
The function to determine whether the test failed (defaults to fail::fail_on_max_err).
Definition prec_structures.h:105
prec_t tolerance
The tolerance to use to determine whether the test failed.
Definition prec_structures.h:98
unsigned int iterations
Number of function evaluations to use.
Definition prec_structures.h:101
std::vector< interval > domain
The domain of estimation.
Definition prec_structures.h:86
Estimator_t estimator
The precision estimator to use (defaults to a dummy estimator).
Definition prec_structures.h:90
bool quiet
Whether to show the test result or not.
Definition prec_structures.h:110
A structure holding the result of precision estimation.
Definition prec_structures.h:25
An interval on the real numbers.
Definition interval.h:16
Settings for the precision testing module, used in prec_context.
Definition prec.h:32
std::map< std::string, bool > pickedTests
Target tests marked for execution, can be picked by passing test case names by command line (all test...
Definition prec.h:70
prec_t defaultTolerance
Default tolerance on max absolute error.
Definition prec.h:44
bool multithreading
Whether to use multithreading for the execution of accuracy estimation tasks (defaults to true).
Definition prec.h:77
std::string moduleName
Name of the module being tested.
Definition prec.h:35
std::vector< std::string > estimateOutputFiles
The files to write estimate results to (if empty, all results are output to a generic file).
Definition prec.h:56
std::vector< std::string > equationOutputFiles
The files to write equation results to (if empty, all results are output to a generic file).
Definition prec.h:65
FailFunction defaultFailFunction
Default fail function.
Definition prec.h:41
std::vector< std::string > outputFiles
The files to write all precision testing results to.
Definition prec.h:47
unsigned int defaultIterations
Default number of iterations for integral quadrature.
Definition prec.h:38
std::vector< std::string > estimateColumns
Default columns to print for precision estimates.
Definition prec.h:50
std::vector< std::string > equationColumns
Default columns to print for equations.
Definition prec.h:59