tmain.cpp - numeric - C++ library with numerical algorithms | |
git clone git://src.adamsgaard.dk/numeric | |
Log | |
Files | |
Refs | |
LICENSE | |
--- | |
tmain.cpp (2348B) | |
--- | |
1 #include <iostream> | |
2 #include <cstdio> // For fscanf | |
3 #include <armadillo> | |
4 #include <vector> | |
5 #include "header.h" | |
6 #include "lsfit.h" | |
7 | |
8 int main(int argc, char* argv[]) | |
9 { | |
10 // Namespace declarations | |
11 using std::cout; | |
12 | |
13 // Check that a data file is given as an input argument | |
14 if (argc < 2 || argc > 3) { | |
15 cout << "Usage: " << argv[0] << " <input file> [output file]\n" | |
16 << "If 'output file' is not specified, output data " | |
17 << "will be written to stdout.\n" | |
18 << "Example: " << argv[0] << " data.A.txt\n"; | |
19 return 1; | |
20 } | |
21 | |
22 FILE *fin; // File pointer | |
23 | |
24 // Check that the input file exists and can be read | |
25 if ((fin = fopen(argv[1], "r")) == NULL) { | |
26 cout << "Error while reading " << argv[1] << '\n'; | |
27 return 1; | |
28 } | |
29 | |
30 // First, count the number of newline characters | |
31 // for preallocation purposes | |
32 Lengthtype n = 0; | |
33 int c; | |
34 while ((c = getc(fin)) != EOF) { | |
35 if (c == '\n') | |
36 ++n; | |
37 } | |
38 fclose(fin); | |
39 cout << "Input file \"" << argv[1] << "\" consists of n=" | |
40 << n << " data points.\n"; | |
41 | |
42 // Allocate input data structures | |
43 arma::Col<Floattype> x = arma::Col<Floattype> (n); | |
44 arma::Col<Floattype> y = arma::Col<Floattype> (n); | |
45 arma::Col<Floattype> delta_y = arma::Col<Floattype> (n); | |
46 | |
47 // Read data into memory | |
48 if ((fin = fopen(argv[1], "r")) == NULL) { | |
49 cout << "Error while reading " << argv[1] << '\n'; | |
50 return 1; | |
51 } | |
52 float x_tmp, y_tmp, delta_y_tmp; | |
53 for (Lengthtype i=0; i<n; ++i) { | |
54 fscanf(fin, "%f %f %f", &x_tmp, &y_tmp, &delta_y_tmp); | |
55 x(i) = x_tmp; | |
56 y(i) = y_tmp; | |
57 delta_y(i) = delta_y_tmp; | |
58 } | |
59 fclose(fin); | |
60 | |
61 // Perform least-squares fit with LSfit class | |
62 LSfit lsfit(x, y, delta_y); | |
63 | |
64 // Evaluate fit at a fine resolution | |
65 const unsigned int res = 100; | |
66 Floattype x_min = x.min(); | |
67 cout << "x_min = " << x_min; | |
68 Floattype x_max = x.max(); | |
69 cout << ", x_max = " << x_max << '\n'; | |
70 std::vector<Floattype> xo (res); | |
71 std::vector<Floattype> yo (res); | |
72 for (unsigned int i=0; i<res; ++i) { | |
73 xo[i] = x_min + (x_max - x_min) * ((Floattype)i/res); | |
74 yo[i] = lsfit.eval(xo[i]); | |
75 } | |
76 | |
77 // Write to file if specified in as command line arguments | |
78 if (argc == 3) { | |
79 write_output(xo, yo, argv[2]); | |
80 } else { | |
81 for (unsigned int i=0; i<res; ++i) { | |
82 cout << xo[i] << '\t' << yo[i] << '\n'; | |
83 } | |
84 } | |
85 | |
86 | |
87 // Return successfully | |
88 return 0; | |
89 } |