NGen
Loading...
Searching...
No Matches
bmi_utilities.hpp
1#ifndef NGEN_BMI_UTILITIES_HPP
2#define NGEN_BMI_UTILITIES_HPP
3
4#include <algorithm>
5#include <cstdint>
6#include <iterator>
7#include <memory>
8#include <stdexcept>
9#include <string>
10#include <string_view>
11#include <utility>
12#include <vector>
13#include <boost/type_index.hpp>
14#include "bmi/Bmi_Adapter.hpp"
15#include "utilities/bmi_primitive_type.hpp"
16
17/*
18 * Typed access to BMI model variables.
19 *
20 * A BMI adapter reports a variable in three ways the standard does not tie together: a type, as a
21 * string; a size, as a count of bytes; and a buffer or pointer carrying no type at all. Reading or
22 * writing one therefore means choosing a C++ type, sizing a buffer, and trusting the two agree.
23 *
24 * A type name is resolved once, to a primitive_type (see bmi_primitive_type.hpp), and that is what
25 * is passed around after.
26 *
27 * Prefer the helpers below to calling Bmi_Adapter::GetValue() or GetValuePtr() and casting the
28 * result:
29 *
30 * GetValue<T>() read a variable, or one item of it, converted to T
31 * GetValuePtr<T>() borrow the model's own storage, typed
32 * get_value_as_type() build a value in the variable's declared type
33 * get_values_as_type() build a buffer in the variable's declared type
34 * resolve_var_type() the primitive_type to address a variable as, checked against its item size
35 *
36 * The raw adapter calls stay public -- the adapters implement them, and a caller may genuinely want
37 * bytes -- but they are not the ordinary way to read or write a variable.
38 */
39
40namespace models {
41 namespace bmi {
42
55 inline primitive_type resolve_var_type(Bmi_Adapter &model, std::string_view name)
56 {
57 // The adapter calls take the name as a std::string, by value, so make one and hand it on.
58 std::string var_name(name);
59 const size_t item_size = static_cast<size_t>(model.GetVarItemsize(var_name));
60 const std::string reported = model.GetVarType(std::move(var_name));
61 const primitive_type type = model.get_primitive_type(reported, item_size);
62 // Every buffer is sized from the item size and addressed as the type, so a disagreement reads or
63 // writes past the end -- undetectable afterwards, so refuse up front.
64 if (size_of(type) != item_size) {
65 throw std::runtime_error("Cannot use variable '" + std::string(name) + "' of model '" +
66 model.get_model_name() + "': its type '" + reported + "' is " +
67 std::to_string(size_of(type)) +
68 " bytes, but the model reports an item size of " +
69 std::to_string(item_size) + " bytes.");
70 }
71 return type;
72 }
73
74 namespace helper {
75
87 template<typename TO, typename FROM>
88 static inline std::vector<TO> make_vector(const FROM* data, const size_t& count){
89 //Let Return Value Optimization (move semantics) help here (no copy of vector)
90 return std::vector<TO>(data, data+count);
91 }
92
93 }
94
108 template <typename T, typename Iterator>
109 std::shared_ptr<T> as_c_array(Iterator begin, Iterator end){
110 //Make a shared pointer large enough to hold all elements
111 //This is a CONTIGUOUS array of type T
112 //Must provide a custom deleter to delete the array
113 std::shared_ptr<T> ptr( new T[std::distance(begin, end)], [](T *p) { delete[] p; } );
114 std::transform(begin, end, ptr.get(), [](auto const& in){ return static_cast<T>(in); });
115 return ptr;
116 }
117
127 template <typename Iterator>
128 std::shared_ptr<void> get_values_as_type(primitive_type type, Iterator begin, Iterator end)
129 {
130 return with_primitive_type(type, [&]<typename T>() -> std::shared_ptr<void> {
131 return as_c_array<T>(begin, end);
132 });
133 }
134
143 template<typename T>
144 std::shared_ptr<void> get_value_as_type(primitive_type type, T value)
145 {
146 return with_primitive_type(type, [&]<typename U>() -> std::shared_ptr<void> {
147 return std::make_shared<U>(static_cast<U>(value));
148 });
149 }
150
169 template <typename T>
170 T *GetValuePtr(Bmi_Adapter &model, const std::string &name)
171 {
172 const size_t item_size = static_cast<size_t>(model.GetVarItemsize(name));
173 if (item_size != sizeof(T)) {
174 throw std::runtime_error("Cannot get pointer to variable " + name + " of model " +
175 model.get_model_name() + " as a " + std::to_string(sizeof(T)) +
176 " byte type; its items are " + std::to_string(item_size) + " bytes.");
177 }
178 return static_cast<T *>(model.GetValuePtr(name));
179 }
180
190 template <typename T>
191 std::vector<T> GetValue(Bmi_Adapter& model, const std::string& name) {
192 //TODO make model const ref
193 int total_mem = model.GetVarNbytes(name);
194 int item_size = model.GetVarItemsize(name);
195 if( total_mem == 0 || item_size == 0){
196 // Early stop if no items to be returned (also prevents possible divide by 0 computing num_items)
197 // Becuase this function is used by others which assume the return value to have AT LEAST
198 // 1 value, then this is a terminal error. This happens when the BMI model hasn't properly
199 // initialized/allocated/set the value to something meaningful. This can happen, for example,
200 // with grid data if the variables themselves are dynamically allocated based on grid properties
201 // but the grid is 0, then we essentially get a sentinal pointer with no data in it.
202 // one possible way to handle this would be to ensure a single element vector with NaN were returned here
203 // but since this function has to deal with both int and floating point types, that isn't possible
204 // because int has not NaN representation. So the best we can do at this point is raise a runtime exception
205 throw std::runtime_error("Unable to get value of variable "+name+". Model "+ model.get_model_name() +
206 " reports no valid items (Nbytes = "+std::to_string(total_mem) +
207 ", Itemsize = "+std::to_string(item_size)+".");
208 }
209 int num_items = total_mem/item_size;
210 //Determine what type we need to cast from, before the model writes into a buffer sized by it
211 primitive_type type;
212 try {
213 type = resolve_var_type(model, name);
214 } catch (const unknown_bmi_type& e) {
215 // The shared table knows the type name, but not what was being read or as what.
216 throw std::runtime_error("Unable to get value of variable " + name + " of model " +
217 model.get_model_name() + " as " +
218 boost::typeindex::type_id<T>().pretty_name() +
219 ": no logic for converting variable type " + e.type_name);
220 }
221
222 //C++ form of malloc
223 void* data = ::operator new(total_mem); //Possible to allocate 0 bytes...
224 // Use smart pointer to ensure cleanup on throw/out of scope...
225 // This works, and is relatively cheap since the lambda is stateless, only one instance should be created.
226 auto sptr = std::shared_ptr<void>(data, [](void *p) { ::operator delete(p); });
227 //Delegate to specific adapter's GetValue()
228 //Note, may be able to optimize this furthur using GetValuePtr
229 //which would avoid copying in the BMI model and copying again here
230 model.GetValue(name, data);
231
232 return with_primitive_type(type, [&]<typename S>() -> std::vector<T> {
233 return helper::make_vector<T>(static_cast<const S*>(data), num_items);
234 });
235 }
236
251 template <typename T>
252 T GetValue(Bmi_Adapter& model, const std::string& name, int index) {
253 const int item_size = model.GetVarItemsize(name);
254 const int num_items = item_size > 0 ? model.GetVarNbytes(name) / item_size : 0;
255 if (index < 0 || index >= num_items) {
256 throw std::out_of_range("Cannot get item " + std::to_string(index) + " of variable " + name +
257 " of model " + model.get_model_name() + ", which has " +
258 std::to_string(num_items) + " items.");
259 }
260
261 primitive_type type;
262 try {
263 type = resolve_var_type(model, name);
264 } catch (const unknown_bmi_type& e) {
265 throw std::runtime_error("Unable to get value of variable " + name + " of model " +
266 model.get_model_name() + " as " +
267 boost::typeindex::type_id<T>().pretty_name() +
268 ": no logic for converting variable type " + e.type_name);
269 }
270
271 return with_primitive_type(type, [&]<typename S>() -> T {
272 S item;
273 model.GetValueAtIndices(name, &item, &index, 1);
274 return static_cast<T>(item);
275 });
276 }
277 }
278}
279
280#endif //NGEN_BMI_UTILITIES_HPP
virtual std::string GetVarType(std::string name)=0
virtual void * GetValuePtr(std::string name)=0
virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count)=0
virtual void GetValue(std::string name, void *dest)=0
virtual int GetVarItemsize(std::string name)=0
virtual int GetVarNbytes(std::string name)=0
Abstract adapter interface for C++ classes to interact with the essential aspects of external models ...
Definition Bmi_Adapter.hpp:17
std::string get_model_name()
Get the model name.
Definition Bmi_Adapter.cpp:124
virtual primitive_type get_primitive_type(std::string_view external_type_name, const size_t item_size)
Resolve a type name the backing model reports to a models::bmi::primitive_type.
Definition Bmi_Adapter.hpp:84
static std::vector< TO > make_vector(const FROM *data, const size_t &count)
make a vector of type
Definition bmi_utilities.hpp:88
Definition deserialization.hpp:40
std::vector< T > GetValue(Bmi_Adapter &model, const std::string &name)
Copy values from a BMI model adapter and box them into a vector.
Definition bmi_utilities.hpp:191
T * GetValuePtr(Bmi_Adapter &model, const std::string &name)
Get a pointer to a model variable's own storage, addressed as.
Definition bmi_utilities.hpp:170
auto with_primitive_type(primitive_type type, F &&f)
Call f with the C++ type that type denotes.
Definition bmi_primitive_type.hpp:172
std::shared_ptr< void > get_value_as_type(primitive_type type, T value)
Gets a single value, casted based on type then returned as a typeless (void) pointer.
Definition bmi_utilities.hpp:144
std::shared_ptr< T > as_c_array(Iterator begin, Iterator end)
Template function for copying iterator range into contiguous array.
Definition bmi_utilities.hpp:109
primitive_type
The type of one item of a BMI variable, independent of how any language spells it.
Definition bmi_primitive_type.hpp:50
primitive_type resolve_var_type(Bmi_Adapter &model, std::string_view name)
Resolve the type to address a model's variable as, checked against its item size.
Definition bmi_utilities.hpp:55
std::shared_ptr< void > get_values_as_type(primitive_type type, Iterator begin, Iterator end)
Gets values in iterator range, casted based on type then returned as typeless (void) pointer.
Definition bmi_utilities.hpp:128
constexpr size_t size_of(primitive_type type)
The size in bytes of one item of type.
Definition bmi_primitive_type.hpp:85
Definition AbstractCLibBmiAdapter.hpp:6
Thrown when a BMI type name has no C++ type behind it.
Definition bmi_primitive_type.hpp:26
std::string type_name
Definition bmi_primitive_type.hpp:31