-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.cpp
388 lines (310 loc) · 15 KB
/
setup.cpp
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
/**
* @file setup.cpp
* @brief Definitions of the functions to read settings from file, launch the calculations and save the results
* @author Enrico Pedretti
* @date 2023-09-03
*/
#include <diagmc/setup.h>
#include <diagmc/simulation.h>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include <stdlib.h>
#include <exception>
#include <string>
#include <vector>
#include <cmath>
#include <limits>
using json = nlohmann::json;
//defaults for optional settings parameters
#define N_THERMALIZATION_STEPS_DEFAULT 0
#define INITIAL_S0_DEFAULT 1
#define SAMPLES_PER_POINT_DEFAULT 1
#define NEW_SEED std::chrono::system_clock::now().time_since_epoch().count()
void check_required_keys_presence(const json & settings, std::vector<std::string> list_of_keys)
{
//loop over list of keys, checking if each is contained in settings, terminate the program if not present
for (auto key : list_of_keys)
{
if(!settings.contains(key))
{
std::cerr << "Error: missing " << key << " in settings.json." << std::endl;
exit(EXIT_FAILURE);
}
}
}
std::vector<double> range_generator(const json & settings, std::string which)
{
//vector to store the list of values of the 'which' parameter
std::vector<double> range_vector;
//case where min, max and step keys are present for the 'which' parameter
if (settings.contains(which+"_min") && settings.contains(which+"_max") && settings.contains(which+"_step"))
{
double min_value = settings[which+"_min"];
double max_value = settings[which+"_max"];
double step = settings[which+"_step"];
//linearly spaced values between min, and max, spaced by step
for (double x = min_value; x <= max_value; x += step)
range_vector.push_back(x);
}
else if (settings.contains(which)) //case where only a single value of the parameter is specified
{
range_vector.push_back(settings[which]); //in this case the vector contains a single value
}
else //no values of the necessary parameter: terminate program
{
std::cerr << "Error: missing " << which << " in settings.json. "<< std::endl;
exit(EXIT_FAILURE);
}
return range_vector;
}
std::vector<double> log_range_generator(const json & settings, std::string which)
{
//vector to store the list of values of the 'which' parameter
std::vector<double> range_vector;
//case where min, max and step keys are present for the 'which' parameter
if (settings.contains(which+"_min") && settings.contains(which+"_max") && settings.contains(which+"_points_per_decade"))
{
double min_value = settings[which+"_min"];
double max_value = settings[which+"_max"];
double points_per_decade = settings[which+"_points_per_decade"];
double logmin = std::log10(min_value);
double logmax = std::log10(max_value);
double number_of_decades = logmax - logmin; //e.g. log10(10^8) - log10(10^3) = 8 - 3 = 5 decades
double logstep = 1. / points_per_decade; //distance between two subsequent points in logscale
//log10-spaced values between min, and max, spaced by logstep, corresponding to the desired points_per_decade
for (int n = 0; n <= number_of_decades / logstep; ++n)
range_vector.push_back(std::pow(10, logmin + n * logstep)); //go back to linear scale
}
else if (settings.contains(which)) //case where only a single value of the parameter is specified
{
range_vector.push_back(settings[which]); //in this case the vector contains a single value
}
else //no values of the necessary parameter: terminate program
{
std::cerr << "Error: incorrect/missing " << which << " in settings.json. "<< std::endl;
exit(EXIT_FAILURE);
}
return range_vector;
}
void print_progress_bar(double progress)
{
int barWidth = 70; //number of chars for the progress bar
std::cout << "[";
int current_position = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i <= current_position) std::cout << "="; //full char if inside completed part
else std::cout << " "; //empty char for the non-completed portion
}
std::cout << "] " << int(progress * 100.0) << "%\r"; //carriage return to overwrite line
std::cout.flush();
}
json read_settings(std::string filename)
{
//open read-only filestream to read settings file
std::ifstream filestream(filename);
//check that file was opened correctly, terminate program otherwise
if (!filestream) {
std::cerr << "Unable to open the settings.json file. Make sure that it is present in the same folder of the executable." << std::endl;
filestream.close();
exit(EXIT_FAILURE);
}
json settings; //dictionary-like object to parse and store the settings read from file
//try to parse the json file, terminate program if fail
try {
settings = json::parse(filestream);
filestream.close();
}
catch(const std::exception & e)
{
std::cerr << "Error while parsing settings.json." << e.what() << std::endl;
filestream.close();
exit(EXIT_FAILURE);
}
//Check on main dictionary key. Terminate program if there is any error
//here only CALC_TYPE is checked, since it is needed to determine which function to call
//specific checks for required keys are then performed inside each function
if(!settings.contains("CALC_TYPE"))
{
std::cerr << "Error: missing CALC_TYPE in settings.json." << std::endl;
exit(EXIT_FAILURE);
}
if(settings["CALC_TYPE"] != "single" && settings["CALC_TYPE"] != "sweep" && settings["CALC_TYPE"] != "convergence-test")
{
std::cerr << "Error: invalid CALC_TYPE argument in settings.json. Expected 'single'/'sweep'/'convergence-test', but "<< settings["CALC_TYPE"] << "was provided." << std::endl;
exit(EXIT_FAILURE);
}
std::cout<<"Simulation settings read from file.\n";
return settings;
}
void single_run(const json & settings)
{
//PARAMETERS#################################################################
//check presence of required keys in settings.json
check_required_keys_presence( settings,
{
"beta",
"H",
"GAMMA",
"N_total_steps",
"output_file"
}
);
//assign default values to optional keys if not present in settings.json
int initial_s0 = settings.contains("initial_s0") ? (int) settings["initial_s0"] : INITIAL_S0_DEFAULT;
unsigned long long N_thermalization_steps = settings.contains("N_thermalization_steps") ? (unsigned long long) settings["N_thermalization_steps"] : N_THERMALIZATION_STEPS_DEFAULT;
unsigned long long int update_choice_seed = settings.contains("update_choice_seed") ? int(settings["update_choice_seed"]) : NEW_SEED;
unsigned long long int diagram_seed = settings.contains("diagram_seed") ? int(settings["diagram_seed"]) : NEW_SEED;
//############################################################################
//open file stream to write results in output file, write the header row containing the titles of the columns
std::ofstream output_file_stream(static_cast<std::string>(settings["output_file"]));
output_file_stream << SingleRunResults::ostream_output_header();
//SIMULATION#################################################################
std::cout<<"Running single run simulation...\n";
//execute single run simulation, and print results to terminal standard output
SingleRunResults results = run_simulation(
settings["beta"],
initial_s0,
settings["H"],
settings["GAMMA"],
settings["N_total_steps"],
N_thermalization_steps,
update_choice_seed,
diagram_seed
);
output_file_stream << results;
output_file_stream.close();
//for single run, also print summary on console standard output
results.print_results();
//############################################################################
}
void sweep(const json & settings)
{
//PARAMETERS#################################################################
//check existence of required keys in settings.json
check_required_keys_presence( settings,
{
"N_total_steps",
"output_file"
}
);
//generates linearly-spaced list of values for the sweep parameters, based on min, max and step
std::vector<double> beta_values = range_generator(settings, "beta");
std::vector<double> H_values = range_generator(settings, "H");
std::vector<double> GAMMA_values = range_generator(settings, "GAMMA");
unsigned long long N_total_steps = settings["N_total_steps"];
//assign default values to optional keys if not present in settings.json
int initial_s0 = settings.contains("initial_s0") ? (int) settings["initial_s0"] : INITIAL_S0_DEFAULT;
unsigned long long N_thermalization_steps = settings.contains("N_thermalization_steps") ? (unsigned long long) settings["N_thermalization_steps"] : N_THERMALIZATION_STEPS_DEFAULT;
int samples_per_point = settings.contains("samples_per_point") ? int(settings["samples_per_point"]) : SAMPLES_PER_POINT_DEFAULT;
//############################################################################
//open file stream to write results in output file, write the header row containing the titles of the columns
std::ofstream output_file_stream(static_cast<std::string>(settings["output_file"]));
output_file_stream << SingleRunResults::ostream_output_header();
//SIMULATION###################################################################
std::cout<<"Running sweep simulation...\n";
//calculates parameters for progress bar, and prints it on standard output
int total_number_of_runs = beta_values.size() * H_values.size() * GAMMA_values.size() * samples_per_point;
int current_run = 0;
print_progress_bar(current_run/total_number_of_runs);
//nested for loop for the sweep, running every combination of beta, H and GAMMA
for (auto beta : beta_values)
{
for(auto H : H_values)
{
for (auto GAMMA : GAMMA_values)
{
//avoid GAMMA = 0, since it is not allowed: use a value extremely close to 0
if(std::abs(GAMMA) < std::numeric_limits<double>::epsilon()) GAMMA = 1e-10;
//possibility to run multiple times for the same combination of parameters, useful to compute average and stddev
for(int i = 0; i < samples_per_point; ++i)
{
//launch run for the specific combination of parameters
SingleRunResults results = run_simulation(beta, initial_s0, H, GAMMA, N_total_steps, N_thermalization_steps);
output_file_stream << results; //immediately write results on file, to avoid losing data if program is interrupted
//update progress bar
++current_run;
print_progress_bar( (double) current_run/total_number_of_runs);
}
}
}
}
std::cout<<std::endl<<"Sweep completed.\n";
output_file_stream.close();
//###############################################################################
}
void convergence_test(const json & settings)
{
//PARAMETERS#################################################################
//check existence of required keys in settings.json
check_required_keys_presence( settings,
{
"beta",
"H",
"GAMMA",
"output_file"
}
);
//generates log-spaced list of values for the sweep parameters, based on min, max and step
std::vector<double> N_total_steps_values = log_range_generator(settings, "N_total_steps");
std::vector<double> N_thermalization_steps_values;
//assign default values to optional keys if not present in settings.json
int initial_s0 = settings.contains("initial_s0") ? (int) settings["initial_s0"] : 1;
if( !settings.contains("N_thermalization_steps") && !settings.contains("N_thermalization_step_max")) N_thermalization_steps_values = {0};
else N_thermalization_steps_values = log_range_generator(settings, "N_thermalization_steps");
unsigned long long int update_choice_seed = settings.contains("update_choice_seed") ? int(settings["update_choice_seed"]) : NEW_SEED;
unsigned long long int diagram_seed = settings.contains("diagram_seed") ? int(settings["diagram_seed"]) : NEW_SEED;
//############################################################################
//open file stream to write results in output file, write the header row containing the titles of the columns
std::ofstream output_file_stream(static_cast<std::string>(settings["output_file"]));
output_file_stream << SingleRunResults::ostream_output_header();
//SIMULATION#################################################################
std::cout<<"Running convergence test...\n";
//calculates parameters for progress bar, and prints it on standard output
int total_number_of_runs = N_total_steps_values.size() * N_thermalization_steps_values.size();
int current_run = 0;
print_progress_bar(current_run/total_number_of_runs);
//nested for loop for the sweep, running every combination of N_total_steps, and N_thermalization_steps
for (auto N_total_steps : N_total_steps_values)
{
for(auto N_thermalization_steps : N_thermalization_steps_values)
{
//launch run for the specific combination of parameters
SingleRunResults results = run_simulation(
settings["beta"],
initial_s0,
settings["H"],
settings["GAMMA"],
N_total_steps,
N_thermalization_steps,
update_choice_seed,
diagram_seed
);
output_file_stream << results; //immediately write results on file, to avoid losing data if program is interrupted
//update progress bar
++current_run;
print_progress_bar( (double) current_run/total_number_of_runs);
}
}
std::cout<<std::endl<<"Convergence test completed.\n";
output_file_stream.close();
//############################################################################
}
void launch_calculations(std::string settings_filename)
{
//read settings from json file, and store it in a json object (dictionary-like)
json settings = read_settings(settings_filename);
//select which kind of calculation to run, based on what was specified in the settings file
if(settings["CALC_TYPE"] == "single" )
{
single_run(settings);
}
else if (settings["CALC_TYPE"] == "sweep")
{
sweep(settings);
}
else if (settings["CALC_TYPE"] == "convergence-test")
{
convergence_test(settings);
}
}