6 #ifndef DISMEC_COMMON_H
7 #define DISMEC_COMMON_H
11 #include "spdlog/fmt/fmt.h"
23 #define THROW_ERROR(...) THROW_EXCEPTION(std::runtime_error, __VA_ARGS__)
34 inline long parse_long(
const char*
string,
const char** out) {
35 char* out_ptr =
nullptr;
36 long result = std::strtol(
string, &out_ptr, 10);
53 const char* start = feature_part;
54 while(*feature_part) {
55 const char* result =
nullptr;
57 long index =
parse_long(feature_part, &result);
58 if (result == feature_part) {
61 bool is_error = [&](){
62 for(
const char* scan = feature_part; *scan; ++scan) {
63 if(!std::isspace(*scan)) {
72 THROW_ERROR(
"Error parsing feature. Missing feature index.");
73 }
else if(*result !=
':') {
75 }
else if(errno != 0) {
76 THROW_ERROR(
"Error parsing feature index. Errno={}: '{}'", errno, strerror(errno));
80 char* after_feature =
nullptr;
81 double value = std::strtod(result+1, &after_feature);
82 if(result + 1 == after_feature) {
83 THROW_ERROR(
"Error parsing feature: Missing feature value.");
84 }
else if(errno != 0) {
85 THROW_ERROR(
"Error parsing feature value. Errno={}: '{}'", errno, strerror(errno));
88 feature_part = after_feature;
89 callback(index, value);
98 std::ostream&
write_vector_as_text(std::ostream& stream,
const Eigen::Ref<const DenseRealVector>& data);
110 void binary_dump(std::streambuf& target,
const T* begin,
const T* end) {
111 static_assert(std::is_pod_v<T>,
"Can only binary dump POD types");
112 std::streamsize num_bytes = (end - begin) * ssizeof<T>;
113 auto wrote = target.sputn(
reinterpret_cast<const char*
>(begin), num_bytes);
114 if(num_bytes != wrote) {
115 THROW_ERROR(
"Expected to write {} bytes, but wrote only {}", num_bytes, wrote);
121 static_assert(std::is_pod_v<T>,
"Can only binary load POD types");
122 std::streamsize num_bytes = (end - begin) * ssizeof<T>;
123 auto read = target.sgetn(
reinterpret_cast<char*
>(begin), num_bytes);
124 if(num_bytes != read) {
125 THROW_ERROR(
"Expected to read {} bytes, but got only {}", num_bytes, read);
std::string print_char(char c)
std::ostream & write_vector_as_text(std::ostream &stream, const Eigen::Ref< const DenseRealVector > &data)
Writes the given vector as space-separated human-readable numbers.
std::istream & read_vector_from_text(std::istream &stream, Eigen::Ref< DenseRealVector > data)
Reads the given vector as space-separated human-readable numbers.
void binary_dump(std::streambuf &target, const T *begin, const T *end)
MatrixHeader parse_header(const std::string &content)
void binary_load(std::streambuf &target, T *begin, T *end)
LoLBinarySparse read_binary_matrix_as_lol(std::istream &source)
long parse_long(const char *string, const char **out)
void parse_sparse_vector_from_text(const char *feature_part, F &&callback)
parses sparse features given in index:value text format.
Binary Sparse Matrix in List-of-Lists format.
std::vector< std::vector< long > > NonZeros