Files
karl/include/simulation/jansson_additionals.h
T

123 lines
3.0 KiB
C++
Executable File

#ifndef JANSSON_ADDITIONALS_H
#define JANSSON_ADDITIONALS_H
#include <math.h>
#include <sstream>
#include <string>
#include <vector>
#include "blitz/array.h"
#include "jansson.h"
#include "simulation/errors.h"
#include "simulation/unit_converter.h"
typedef std::vector<std::string> json_path;
inline json_t* json_object_by_path(json_t* object, const json_path& path) {
json_t* j_obj = object;
for (auto str : path) {
j_obj = json_object_get(j_obj, str.c_str());
}
return j_obj;
}
inline double json_double(json_t* object, double default_value = 0.) {
if (object) {
return json_real_value(object);
} else {
return default_value;
}
}
inline int json_int(json_t* object, int default_value = 0) {
if (object) {
return std::floor(json_real_value(object));
} else {
return default_value;
}
}
inline std::string json_string(json_t* object, std::string default_value = "") {
if (object) {
if (json_string_value(object)) {
return std::string(json_string_value(object));
} else {
return default_value;
}
} else {
return default_value;
}
}
inline bool json_bool(json_t* object, bool default_value = false) {
if (object) {
return (json_string(object) == "true");
} else {
return default_value;
}
}
template <int s>
blitz::TinyVector<double, s> json_blitz_vector(json_t* object) {
blitz::TinyVector<double, s> vector;
size_t index;
json_t* value;
json_t* array = json_object_by_path(object, {"vector"});
size_t size = json_array_size(array);
if (size != s) {
std::stringstream error_message;
error_message << "The provided vector has size: " << size
<< ", but is stated as size " << s;
ERROR(error_message.str());
}
json_array_foreach(array, index, value) {
vector(index) = json_double(value);
}
return vector;
}
inline std::vector<double> json_vector(json_t* object) {
std::vector<double> vector;
size_t index;
json_t* value;
json_array_foreach(object, index, value) {
vector.push_back(json_double(value));
}
return vector;
}
inline json_path json_path_get(json_t* object) {
json_path path;
json_t* value;
size_t index;
json_array_foreach(object, index, value) {
path.push_back(json_string(value));
}
return path;
}
inline json_path json_path_append(const json_path& path,
const json_path& append) {
json_path result = path;
for (auto a : append) {
result.push_back(a);
}
return result;
}
inline double json_read_length(json_t* object, std::string output_unit = "m") {
double value = json_double(json_object_by_path(object, {"value"}));
std::string unit = json_string(json_object_by_path(object, {"unit"}));
return unitConvertion::length(value, unit, output_unit);
}
inline double json_read_energy(json_t* object, std::string output_unit = "eV") {
double value = json_double(json_object_by_path(object, {"value"}));
std::string unit = json_string(json_object_by_path(object, {"unit"}));
return unitConvertion::energy(value, unit, output_unit);
}
#endif /* JANSSON_ADDITIONALS_H */