value.hpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. /**
  2. * @file
  3. * @author Caleb Fangmeier <caleb@fangmeier.tech>
  4. * @version 0.1
  5. *
  6. * @section LICENSE
  7. *
  8. *
  9. * MIT License
  10. *
  11. * Copyright (c) 2017 Caleb Fangmeier
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in all
  21. * copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. * SOFTWARE.
  30. *
  31. * @section DESCRIPTION
  32. * This header defines a set of generic classes that wrap up "values". In
  33. * essence, a Value<T> object is just something that contains a value of type T
  34. * and can provide it when requested. The usefulness stems from composing
  35. * values together with calculations. This enables very clear dependency
  36. * mapping and a way to know clearly how every value was arrived at. This could
  37. * be used to, for example, automatically generate commentary for plots that
  38. * explain the exect calculation used to create it. Or easily making a series
  39. * of plots contrasting different values that have been composed slightly
  40. * differently.
  41. */
  42. #ifndef value_hpp
  43. #define value_hpp
  44. #include <iomanip>
  45. #include <iostream>
  46. #include <sstream>
  47. #include <utility>
  48. #include <algorithm>
  49. #include <map>
  50. #include <limits>
  51. #include <vector>
  52. #include <tuple>
  53. #include <initializer_list>
  54. #include <functional>
  55. #include "log.hpp"
  56. /**
  57. * The namespace containing all filval classes and functions.
  58. */
  59. namespace fv{
  60. template <typename F, typename TUPLE, bool Done, int Total, int... N>
  61. struct call_impl
  62. {
  63. static auto call(F& f, TUPLE && t)
  64. {
  65. return call_impl<F, TUPLE, Total == 1 + sizeof...(N), Total, N..., sizeof...(N)>::call(f, std::forward<TUPLE>(t));
  66. }
  67. };
  68. template <typename F, typename TUPLE, int Total, int... N>
  69. struct call_impl<F, TUPLE, true, Total, N...>
  70. {
  71. static auto call(F& f, TUPLE && t)
  72. {
  73. return f(std::get<N>(std::forward<TUPLE>(t))...);
  74. }
  75. };
  76. /**
  77. * This calls a function of type F with the contents of the tuple as separate arguments.
  78. * \see http://stackoverflow.com/questions/10766112/c11-i-can-go-from-multiple-args-to-tuple-but-can-i-go-from-tuple-to-multiple
  79. */
  80. template <typename F, typename TUPLE>
  81. auto call(F& f, TUPLE && t)
  82. {
  83. typedef typename std::decay<TUPLE>::type ttype;
  84. return call_impl<F, TUPLE, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value>::call(f, std::forward<TUPLE>(t));
  85. }
  86. template<typename> class Function; // undefined
  87. /**
  88. * Parent class to all Function classes. Holds a class-level collection of all
  89. * created function objects.
  90. */
  91. class GenFunction {
  92. private:
  93. std::string name;
  94. std::string impl;
  95. protected:
  96. inline static bool in_register_function=false;
  97. public:
  98. /**
  99. * Static mapping of functions from their name to the object wrapper of
  100. * the function.
  101. */
  102. inline static std::map<const std::string, GenFunction*> function_registry;
  103. GenFunction(const std::string& name, const std::string& impl)
  104. :name(name),
  105. impl(impl){ }
  106. virtual ~GenFunction() { };
  107. std::string& get_name(){
  108. return name;
  109. }
  110. /**
  111. * Attempt to invoke clang-format for the purpose of printing out
  112. * nicely formatted functions to the log file. If clang-format is not
  113. * present, this function just passes through the code unmodified.
  114. */
  115. static std::string format_code(const std::string& code){
  116. std::stringstream code_out("");
  117. std::string command("echo \""+code+"\" | clang-format");
  118. char buffer[255];
  119. FILE *stream = popen(command.c_str(), "r");
  120. while (fgets(buffer, 255, stream) != NULL)
  121. code_out << buffer;
  122. if (pclose(stream) == 0)
  123. return code_out.str();
  124. else
  125. return code;
  126. }
  127. static std::string summary(){
  128. std::stringstream ss;
  129. ss << "The following functions have been registered" << std::endl;
  130. for(auto p : function_registry){
  131. if (p.second == nullptr) continue;
  132. ss << "-->" << p.second->name << "@" << p.second << std::endl;
  133. ss << format_code(p.second->impl);
  134. }
  135. return ss.str();
  136. }
  137. template <typename T>
  138. static Function<T>& register_function(const std::string& name, std::function<T> f, const std::string& impl){
  139. in_register_function = true;
  140. Function<T>* func;
  141. if (GenFunction::function_registry[name] != nullptr){
  142. func = dynamic_cast<Function<T>*>(GenFunction::function_registry[name]);
  143. if (func == nullptr){
  144. ERROR("Trying to register function which has already been registered with a different type");
  145. }
  146. } else {
  147. func = new Function<T>(name, impl, f);
  148. GenFunction::function_registry[name] = func;
  149. }
  150. in_register_function = false;
  151. return *func;
  152. }
  153. };
  154. /**
  155. * In order to enable proper provenance tracking, and at the same time keep
  156. * the ability to embed functions into values, the Function class should be
  157. * used. It is simply a wrapper around a std::function that also has a name.
  158. * This name is used when generating the name of values that use the function.
  159. * A function name is automatically prepended with "func::" to explicitly state
  160. * that the value is the result of a computation encoded within the function
  161. * object, and not from some other Value object. Unfortunately, it is up to the
  162. * user to find where that function is defined in the source code to inspect
  163. * what it is doing. But hopefully this isn't too onerous by just using grep.
  164. */
  165. template <typename R, typename... ArgTypes>
  166. class Function<R(ArgTypes...)> : public GenFunction {
  167. private:
  168. std::function<R(ArgTypes...)> f;
  169. public:
  170. Function(const std::string& name, const std::string& impl, std::function<R(ArgTypes...)> f)
  171. :GenFunction(name, impl), f(f){
  172. if (!in_register_function) {
  173. WARNING("Don't instantiate Function objects directly! Use GenFunction::register_function instead.");
  174. }
  175. }
  176. Function(const std::string& name, std::function<R(ArgTypes...)> f)
  177. :Function(name, "N/A", f){ }
  178. ~Function() { }
  179. R operator()(ArgTypes ...args){
  180. return f(args...);
  181. }
  182. };
  183. #define FUNC(f) f, #f
  184. /**
  185. * A type-agnostic value.
  186. * It is necessary to create a type-agnostic parent class to Value so that
  187. * it is possible to handle collections of them. GenValue also provides the
  188. * rest of the type-independent interface to Value.
  189. */
  190. class GenValue;
  191. typedef std::map<std::string, GenValue*> ValueSet;
  192. class GenValue{
  193. private:
  194. /**
  195. * The name of the value.
  196. * This is used to allow for dynamic lookup of
  197. * values based on their name via GenValue::get_value.
  198. */
  199. std::string name;
  200. protected:
  201. /**
  202. * Mark the internal value as invalid. This is needed for DerivedValue
  203. * to force a recalculation of the internal value when a new
  204. * observation is loaded into memory. It is called automatically for
  205. * all GenValue objects when reset is called.
  206. */
  207. virtual void _reset() = 0;
  208. /**
  209. * A static mapping containing all created Value objects.
  210. * Every value object must have a unique name, and this name is used as
  211. * a key in values to that object. This is used to enable more dynamic
  212. * creation of objects as well as avoiding the uneccesary passing of
  213. * pointers.
  214. */
  215. inline static std::map<const std::string, GenValue*> values;
  216. /**
  217. * Composite value names are typically nested. This makes complex
  218. * values have rather unwieldy names. Therefore, one can declare
  219. * aliases which allow for more human-usable names to be used. When a
  220. * value is requested by name, an alias with that value takes precidence
  221. * over a name with that value.
  222. */
  223. inline static std::map<const std::string, GenValue*> aliases;
  224. public:
  225. GenValue(const std::string& name, const std::string& alias)
  226. :name(name){
  227. values[name] = this;
  228. if (alias != "")
  229. GenValue::alias(alias, this);
  230. }
  231. const std::string& get_name(){
  232. return name;
  233. }
  234. void set_name(const std::string& new_name){
  235. values[name] = nullptr;
  236. name = new_name;
  237. values[name] = this;
  238. }
  239. static void reset(){
  240. for (auto val : values){
  241. if (val.second != nullptr){
  242. val.second->_reset();
  243. }
  244. }
  245. }
  246. static GenValue* get_value(const std::string& name){
  247. if (aliases[name] != nullptr)
  248. return aliases[name];
  249. else if (values[name] != nullptr)
  250. return values[name];
  251. else{
  252. ERROR("Could not find alias or value \"" << name << "\". I'll tell you the ones I know about." << std::endl
  253. << summary());
  254. CRITICAL("Aborting... :(",-1);
  255. }
  256. }
  257. static void alias(const std::string& name, GenValue* value){
  258. if (aliases[name] != nullptr){
  259. WARNING("WARNING: alias \"" << name << "\" overrides previous entry.");
  260. }
  261. aliases[name] = value;
  262. }
  263. static GenValue* alias(const std::string& name){
  264. if (values[name] != nullptr){
  265. WARNING("Alias \"" << name << "\" does not exist.");
  266. }
  267. return aliases[name];
  268. }
  269. static std::string summary(){
  270. std::stringstream ss;
  271. ss << "The following values have been created: " << std::endl;
  272. for (auto value : values){
  273. if (value.second == nullptr) continue;
  274. ss << "\t\"" << value.first << "\" at address " << value.second << std::endl;
  275. }
  276. ss << "And these aliases:" << std::endl;
  277. for (auto alias : aliases){
  278. std::string orig("VOID");
  279. if (alias.second == nullptr) continue;
  280. for (auto value : values){
  281. if (alias.second == value.second){
  282. orig = value.second->get_name();
  283. break;
  284. }
  285. }
  286. ss << "\t\"" << alias.first << "\" referring to \"" << orig << "\"" << std::endl;
  287. }
  288. return ss.str();
  289. }
  290. friend std::ostream& operator<<(std::ostream& os, const GenValue& gv);
  291. };
  292. std::ostream& operator<<(std::ostream& os, GenValue& gv){
  293. os << gv.get_name();
  294. return os;
  295. }
  296. /**
  297. * A generic value.
  298. * In order to facilitate run-time creation of analysis routines, it is
  299. * necessary to have some ability to get and store *values*. Values can either
  300. * be directly taken from some original data source (i.e. ObservedValue), or
  301. * they can be a function of some other set of values (i.e. DerivedValue). They
  302. * template class T of Value<T> is the type of thing that is returned upon
  303. * calling get_value().
  304. */
  305. template <typename T>
  306. class Value : public GenValue{
  307. public:
  308. Value(const std::string& name, const std::string& alias="")
  309. :GenValue(name, alias){ }
  310. /** Calculate, if necessary, and return the value held by this object.
  311. */
  312. virtual T& get_value() = 0;
  313. };
  314. /**
  315. * A value supplied by the dataset, not derived.
  316. * An ObservedValue is the interface to your dataset. Upon creation, an
  317. * ObservedValue is given a pointer to an object of type T. When an observation
  318. * is loaded into memory, the value at the location referenced by that pointer
  319. * must be updated with the associated data from that observation. This is the
  320. * responsibility of whatever DataSet implementation is being used. This object
  321. * then will read that data and return it when requested.
  322. */
  323. template <typename T>
  324. class ObservedValue : public Value<T>{
  325. private:
  326. T *val_ref;
  327. void _reset(){ }
  328. public:
  329. ObservedValue(const std::string& name, T* val_ref, const std::string& alias="")
  330. :Value<T>(name, alias),
  331. val_ref(val_ref){ }
  332. T& get_value(){
  333. return *val_ref;
  334. }
  335. };
  336. /**
  337. * A Value derived from some other Values, not directly from the dataset.
  338. * A DerivedValue is generally defined as some function of other Value objects.
  339. * For example, a Pair is a function of two other Value objects that makes a
  340. * pair of them. Note that these other Value objects are free to be either
  341. * ObservedValues or other DerivedValues.
  342. *
  343. * It is desireable from a performance standpoint that each DerivedValue be
  344. * calculated no more than once per observation. Therefore, when a get_value is
  345. * called on a DerivedValue, it first checks whether the value that it holds is
  346. * **valid**, meaning it has already been calculated for this observation. If
  347. * so, it simply returns the value. If not, the update_value function is called
  348. * to calculate the value. and then the newly calculated value is marked as
  349. * valid and returned.
  350. */
  351. template <typename T>
  352. class DerivedValue : public Value<T>{
  353. private:
  354. void _reset(){
  355. value_valid = false;
  356. }
  357. protected:
  358. T value;
  359. bool value_valid;
  360. /**
  361. * Updates the internal value.
  362. * This function should be overridden by any child class to do the
  363. * actual work of updating value based on whatever rules the class
  364. * chooses. Normally, this consists of geting the values from some
  365. * associated Value objects, doing some calculation on them, and
  366. * storing the result in value.
  367. */
  368. virtual void update_value() = 0;
  369. public:
  370. DerivedValue(const std::string& name, const std::string& alias="")
  371. :Value<T>(name, alias),
  372. value_valid(false) { }
  373. T& get_value(){
  374. if (!value_valid){
  375. update_value();
  376. value_valid = true;
  377. }
  378. return value;
  379. }
  380. };
  381. /**
  382. * A std::vector wrapper around a C-style array.
  383. * In order to make some of the higher-level Value types easier to work with,
  384. * it is a good idea to wrap all arrays in the original data source with
  385. * std::vector objects. To do this, it is necessary to supply both a Value
  386. * object containing the array itself as well as another Value object
  387. * containing the size of that array. Currently, update_value will simply copy
  388. * the contents of the array into the interally held vector.
  389. */
  390. template <typename T>
  391. class WrapperVector : public DerivedValue<std::vector<T> >{
  392. private:
  393. Value<int>* size;
  394. Value<T*>* data;
  395. void update_value(){
  396. int n = size->get_value();
  397. T* data_ref = data->get_value();
  398. this->value.assign(data_ref, data_ref+n);
  399. }
  400. public:
  401. WrapperVector(Value<int>* size, Value<T*>* data, const std::string& alias="")
  402. :DerivedValue<std::vector<T> >("vectorOf("+size->get_name()+","+data->get_name()+")", alias),
  403. size(size), data(data){ }
  404. };
  405. /**
  406. * Creates a std::pair type from a two other Value objects.
  407. */
  408. template <typename T1, typename T2>
  409. class Pair : public DerivedValue<std::pair<T1, T2> >{
  410. protected:
  411. std::pair<Value<T1>*, Value<T2>* > value_pair;
  412. void update_value(){
  413. this->value.first = value_pair.first->get_value();
  414. this->value.second = value_pair.second->get_value();
  415. }
  416. public:
  417. Pair(Value<T1> *value1, Value<T2> *value2, const std::string alias="")
  418. :DerivedValue<std::pair<T1, T2> >("pair("+value1->get_name()+","+value2->get_name()+")", alias),
  419. value_pair(value1, value2){ }
  420. };
  421. template<typename... T> class _Zip;
  422. template<>
  423. class _Zip<> {
  424. protected:
  425. int _get_size(){
  426. return std::numeric_limits<int>::max();
  427. }
  428. std::tuple<> _get_at(int idx){
  429. return std::make_tuple();
  430. }
  431. std::string _get_name(){
  432. return "";
  433. }
  434. public:
  435. _Zip() { }
  436. };
  437. template<typename Head, typename... Tail>
  438. class _Zip<Head, Tail...> : private _Zip<Tail...> {
  439. protected:
  440. Value<std::vector<Head>>* head;
  441. int _get_size(){
  442. int this_size = head->get_value().size();
  443. int rest_size = _Zip<Tail...>::_get_size();
  444. return std::min(this_size, rest_size);
  445. }
  446. typename std::tuple<Head,Tail...> _get_at(int idx){
  447. auto tail_tuple = _Zip<Tail...>::_get_at(idx);
  448. return std::tuple_cat(std::make_tuple(head->get_value()[idx]),tail_tuple);
  449. }
  450. std::string _get_name(){
  451. return head->get_name()+","+_Zip<Tail...>::_get_name();
  452. }
  453. public:
  454. _Zip() { }
  455. _Zip(Value<std::vector<Head>>* head, Value<std::vector<Tail>>*... tail)
  456. : _Zip<Tail...>(tail...),
  457. head(head) { }
  458. };
  459. /**
  460. * Zips a series of vectors together. Can be combined with Map to
  461. * yield a Value whose elements are individually a function of the
  462. * corresponding elements of the vectors that were zipped together. For those
  463. * familiar with python, it accompilishes the same thing as
  464. * @code{.py}
  465. * xs = [1,2,3,4]
  466. * ys = [10,20,30,40]
  467. * print(list(map(lambda t:t[0]+t[1],zip(xs,ys))))
  468. * @endcode
  469. * which outputs
  470. * @code
  471. * [11, 22, 33, 44]
  472. * @endcode
  473. */
  474. template <typename... ArgTypes>
  475. class Zip : public DerivedValue<std::vector<std::tuple<ArgTypes...>>>,
  476. private _Zip<ArgTypes...>{
  477. protected:
  478. void update_value(){
  479. this->value.clear();
  480. int size = _Zip<ArgTypes...>::_get_size();
  481. for(int i=0; i<size; i++){
  482. this->value.push_back(_Zip<ArgTypes...>::_get_at(i));
  483. }
  484. }
  485. std::string _get_name(){
  486. return "zip("+_Zip<ArgTypes...>::_get_name()+")";
  487. }
  488. public:
  489. Zip(Value<std::vector<ArgTypes>>*... args, const std::string& alias)
  490. :DerivedValue<std::vector<std::tuple<ArgTypes...>>>("", alias),
  491. _Zip<ArgTypes...>(args...) {
  492. this->set_name(_get_name());
  493. }
  494. };
  495. template<typename> class Map; // undefined
  496. /**
  497. * Maps a function over an input vector. The input vector must be a vector of
  498. * tuples, where the the elements of the tuple match the arguments of the
  499. * function. For example if the function takes two floats as arguments, the
  500. * tuple should contain two floats. The Value object required by Map will
  501. * typically be created as a Zip.
  502. */
  503. template <typename Ret, typename... ArgTypes>
  504. class Map<Ret(ArgTypes...)> : public DerivedValue<std::vector<Ret>>{
  505. private:
  506. Function<Ret(ArgTypes...)>& fn;
  507. Zip<ArgTypes...>* arg;
  508. void update_value(){
  509. this->value.clear();
  510. for(auto tup : arg->get_value()){
  511. this->value.push_back(call(fn,tup));
  512. }
  513. }
  514. public:
  515. Map(Function<Ret(ArgTypes...)>& fn, Zip<ArgTypes...>* arg, const std::string& alias)
  516. :DerivedValue<std::vector<Ret>>("map("+fn.get_name()+":"+arg->get_name()+")", alias),
  517. fn(fn), arg(arg){ }
  518. };
  519. template<typename... T> class _Tuple;
  520. template<>
  521. class _Tuple<> {
  522. protected:
  523. std::tuple<> _get_value(){
  524. return std::make_tuple();
  525. }
  526. std::string _get_name(){
  527. return "";
  528. }
  529. public:
  530. _Tuple() { }
  531. };
  532. template<typename Head, typename... Tail>
  533. class _Tuple<Head, Tail...> : private _Tuple<Tail...> {
  534. protected:
  535. Value<Head>* head;
  536. typename std::tuple<Head,Tail...> _get_value(){
  537. auto tail_tuple = _Tuple<Tail...>::_get_value();
  538. return std::tuple_cat(std::make_tuple(head->get_value()),tail_tuple);
  539. }
  540. std::string _get_name(){
  541. return head->get_name()+","+_Tuple<Tail...>::_get_name();
  542. }
  543. public:
  544. _Tuple() { }
  545. _Tuple(Value<Head>* head, Value<Tail>*... tail)
  546. : _Tuple<Tail...>(tail...),
  547. head(head) { }
  548. };
  549. /**
  550. * Takes a series of Value objects and bundles them together into a std::tuple
  551. * object. Typically, this is most usefull when one wants to apply a function
  552. * to a few values and store the result. This class can be used in conjunction
  553. * with Apply to achieve this.
  554. */
  555. template <typename... ArgTypes>
  556. class Tuple : public DerivedValue<std::tuple<ArgTypes...>>,
  557. private _Tuple<ArgTypes...>{
  558. protected:
  559. void update_value(){
  560. this->value = _Tuple<ArgTypes...>::_get_value();
  561. }
  562. std::string _get_name(){
  563. return "tuple("+_Tuple<ArgTypes...>::_get_name()+")";
  564. }
  565. public:
  566. Tuple(Value<ArgTypes>*... args, const std::string& alias)
  567. :DerivedValue<std::tuple<ArgTypes...>>("", alias),
  568. _Tuple<ArgTypes...>(args...) {
  569. this->set_name(_get_name());
  570. }
  571. };
  572. template<typename> class Apply; // undefined
  573. /**
  574. * Applies a function to a tuple of values and returns a value. This will
  575. * typically be called with a Tuple object as an argument.
  576. */
  577. template <typename Ret, typename... ArgTypes>
  578. class Apply<Ret(ArgTypes...)> : public DerivedValue<Ret>{
  579. private:
  580. Function<Ret(ArgTypes...)>& fn;
  581. Tuple<ArgTypes...>* arg;
  582. void update_value(){
  583. auto &tup = arg->get_value();
  584. this->value = call(fn, tup);
  585. }
  586. public:
  587. Apply(Function<Ret(ArgTypes...)>& fn, Tuple<ArgTypes...>* arg, const std::string& alias)
  588. :DerivedValue<Ret>("apply("+fn.get_name()+":"+arg->get_name()+")", alias),
  589. fn(fn), arg(arg){ }
  590. };
  591. /**
  592. * Returns the count of elements in the input vector passing a test function.
  593. */
  594. template<typename T>
  595. class Count : public DerivedValue<int>{
  596. private:
  597. Function<bool(T)>& selector;
  598. Value<std::vector<T> >* v;
  599. void update_value(){
  600. value = 0;
  601. for(auto val : v->get_value()){
  602. if(selector(val))
  603. value++;
  604. }
  605. }
  606. public:
  607. Count(Function<bool(T)>& selector, Value<std::vector<T>>* v, const std::string alias)
  608. :DerivedValue<int>("count("+selector.get_name()+":"+v->get_name()+")", alias),
  609. selector(selector), v(v) { }
  610. };
  611. /**
  612. * Reduce a Value of type vector<T> to just a T.
  613. * This is useful functionality to model, for instance, calculating the maximum
  614. * element of a vector, or a the mean. See child classes for specific
  615. * implementations.
  616. */
  617. template <typename T>
  618. class Reduce : public DerivedValue<T>{
  619. private:
  620. Function<T(std::vector<T>)>& reduce;
  621. void update_value(){
  622. this->value = reduce(v->get_value());
  623. }
  624. protected:
  625. Value<std::vector<T> >* v;
  626. public:
  627. Reduce(Function<T(std::vector<T>)>& reduce, Value<std::vector<T> >* v, const std::string alias)
  628. :DerivedValue<T>("reduceWith("+reduce.get_name()+":"+v->get_name()+")", alias),
  629. reduce(reduce), v(v) { }
  630. };
  631. /**
  632. * Find and return the maximum value of a vector.
  633. */
  634. template <typename T>
  635. class Max : public Reduce<T>{
  636. public:
  637. Max(Value<std::vector<T>>* v, const std::string alias)
  638. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("max",
  639. FUNC(([](std::vector<T> vec){
  640. return *std::max_element(vec.begin(), vec.end());}))),
  641. v, alias) { }
  642. };
  643. /**
  644. * Find and return the minimum value of a vector.
  645. */
  646. template <typename T>
  647. class Min : public Reduce<T>{
  648. public:
  649. Min(Value<std::vector<T>>* v, const std::string alias)
  650. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("min",
  651. FUNC(([](std::vector<T> vec){
  652. return *std::min_element(vec.begin(), vec.end());}))),
  653. v, alias) { }
  654. };
  655. /**
  656. * Calculate the mean value of a vector.
  657. */
  658. template <typename T>
  659. class Mean : public Reduce<T>{
  660. public:
  661. Mean(Value<std::vector<T>>* v, const std::string alias)
  662. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("mean",
  663. FUNC(([](std::vector<T> vec){
  664. int n = 0; T sum = 0;
  665. for (T e : vec){ n++; sum += e; }
  666. return n>0 ? sum / n : 0; }))),
  667. v, alias) { }
  668. };
  669. /**
  670. * Calculate the range of the values in a vector
  671. */
  672. template <typename T>
  673. class Range : public Reduce<T>{
  674. public:
  675. Range(Value<std::vector<T>>* v, const std::string alias)
  676. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("range",
  677. FUNC(([](std::vector<T> vec){
  678. auto minmax = std::minmax_element(vec.begin(), vec.end());
  679. return (*minmax.second) - (*minmax.first); }))),
  680. v, alias) { }
  681. };
  682. /**
  683. * Extract the element at a specific index from a vector.
  684. */
  685. template <typename T>
  686. class ElementOf : public Reduce<T>{
  687. public:
  688. ElementOf(Value<int>* index, Value<std::vector<T>>* v, const std::string alias)
  689. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("elementOf",
  690. FUNC(([index](std::vector<T> vec){return vec[index->get_value()];}))),
  691. v, alias) { }
  692. };
  693. /**
  694. * Similar to Reduce, but returns a pair of a T and an int.
  695. * This is useful if you need to know where in the vector exists the element
  696. * being returned.
  697. */
  698. template <typename T>
  699. class ReduceIndex : public DerivedValue<std::pair<T, int> >{
  700. private:
  701. Function<std::pair<T,int>(std::vector<T>)>& reduce;
  702. Value<std::vector<T> >* v;
  703. void update_value(){
  704. this->value = reduce(v->get_value());
  705. }
  706. public:
  707. ReduceIndex(Function<std::pair<T,int>(std::vector<T>)>& reduce, Value<std::vector<T> >* v, const std::string alias="")
  708. :DerivedValue<T>("reduceIndexWith("+reduce.get_name()+":"+v->get_name()+")", alias),
  709. reduce(reduce), v(v) { }
  710. };
  711. /**
  712. * Find and return the maximum value of a vector and its index.
  713. */
  714. template <typename T>
  715. class MaxIndex : public ReduceIndex<T>{
  716. public:
  717. MaxIndex(Value<std::vector<T>>* v, const std::string alias="")
  718. :ReduceIndex<T>(GenFunction::register_function<T(std::vector<T>)>("maxIndex",
  719. FUNC(([](std::vector<T> vec){
  720. auto elptr = std::max_element(vec.begin(), vec.end());
  721. return std::pair<T,int>(*elptr, int(elptr-vec.begin())); }))),
  722. v, alias) { }
  723. };
  724. /**
  725. * Find and return the minimum value of a vector and its index.
  726. */
  727. template <typename T>
  728. class MinIndex : public ReduceIndex<T>{
  729. public:
  730. MinIndex(Value<std::vector<T>>* v, const std::string alias="")
  731. :ReduceIndex<T>(GenFunction::register_function<T(std::vector<T>)>("minIndex",
  732. FUNC(([](std::vector<T> vec){
  733. auto elptr = std::min_element(vec.begin(), vec.end());
  734. return std::pair<T,int>(*elptr, int(elptr-vec.begin())); }))),
  735. v, alias) { }
  736. };
  737. /**
  738. * A generic value owning only a function object.
  739. * All necessary values upon which this value depends must be bound to the
  740. * function object.
  741. */
  742. template <typename T>
  743. class BoundValue : public DerivedValue<T>{
  744. protected:
  745. Function<T()>& f;
  746. void update_value(){
  747. this->value = f();
  748. }
  749. public:
  750. BoundValue(Function<T()>& f, const std::string alias="")
  751. :DerivedValue<T>(f.get_name()+"(<bound>)", alias),
  752. f(f) { }
  753. };
  754. /**
  755. * A Value of a pointer. The pointer is constant, however the data the pointer
  756. * points to is variable.
  757. */
  758. template <typename T>
  759. class PointerValue : public DerivedValue<T*>{
  760. protected:
  761. void update_value(){ }
  762. public:
  763. PointerValue(const std::string& name, T* ptr, const std::string alias="")
  764. :DerivedValue<T*>(name, alias){
  765. this->value = ptr;
  766. }
  767. };
  768. /**
  769. * A Value which always returns the same value, supplied in the constructor.
  770. */
  771. template <typename T>
  772. class ConstantValue : public DerivedValue<T>{
  773. protected:
  774. void update_value(){ }
  775. public:
  776. ConstantValue(const std::string& name, T const_value, const std::string alias="")
  777. :DerivedValue<T>("const::"+name, alias),
  778. Value<T>::value(const_value) { }
  779. };
  780. }
  781. #endif // value_hpp