value.hpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 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 << 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 generic, observed, value.
  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 generic, derived, value.
  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. /* std::cout << "getting value of " << this->get_name() << std::endl; */
  375. if (!value_valid){
  376. update_value();
  377. value_valid = true;
  378. }
  379. return value;
  380. }
  381. };
  382. /**
  383. * A std::vector wrapper around a C-style array.
  384. * In order to make some of the higher-level Value types easier to work with,
  385. * it is a good idea to wrap all arrays in the original data source with
  386. * std::vector objects. To do this, it is necessary to supply both a Value
  387. * object containing the array itself as well as another Value object
  388. * containing the size of that array. Currently, update_value will simply copy
  389. * the contents of the array into the interally held vector.
  390. */
  391. template <typename T>
  392. class WrapperVector : public DerivedValue<std::vector<T> >{
  393. private:
  394. Value<int>* size;
  395. Value<T*>* data;
  396. void update_value(){
  397. int n = size->get_value();
  398. T* data_ref = data->get_value();
  399. this->value.assign(data_ref, data_ref+n);
  400. }
  401. public:
  402. WrapperVector(Value<int>* size, Value<T*>* data, const std::string& alias="")
  403. :DerivedValue<std::vector<T> >("vectorOf("+size->get_name()+","+data->get_name()+")", alias),
  404. size(size), data(data){ }
  405. };
  406. /**
  407. * Creates a std::pair type from a two other Value objects.
  408. */
  409. template <typename T1, typename T2>
  410. class Pair : public DerivedValue<std::pair<T1, T2> >{
  411. protected:
  412. std::pair<Value<T1>*, Value<T2>* > value_pair;
  413. void update_value(){
  414. this->value.first = value_pair.first->get_value();
  415. this->value.second = value_pair.second->get_value();
  416. }
  417. public:
  418. Pair(Value<T1> *value1, Value<T2> *value2, const std::string alias="")
  419. :DerivedValue<std::pair<T1, T2> >("pair("+value1->get_name()+","+value2->get_name()+")", alias),
  420. value_pair(value1, value2){ }
  421. };
  422. template<typename... T> class _Zip;
  423. template<>
  424. class _Zip<> {
  425. protected:
  426. int _get_size(){
  427. return std::numeric_limits<int>::max();
  428. }
  429. std::tuple<> _get_at(int idx){
  430. return std::make_tuple();
  431. }
  432. bool _verify_integrity() {
  433. return true;
  434. }
  435. std::string _get_name(){
  436. return "";
  437. }
  438. public:
  439. _Zip() { }
  440. };
  441. template<typename Head, typename... Tail>
  442. class _Zip<Head, Tail...> : private _Zip<Tail...> {
  443. protected:
  444. Value<std::vector<Head>>* head;
  445. int _get_size(){
  446. int this_size = head->get_value().size();
  447. int rest_size = _Zip<Tail...>::_get_size();
  448. return std::min(this_size, rest_size);
  449. }
  450. typename std::tuple<Head,Tail...> _get_at(int idx){
  451. auto tail_tuple = _Zip<Tail...>::_get_at(idx);
  452. return std::tuple_cat(std::make_tuple(head->get_value()[idx]),tail_tuple);
  453. }
  454. bool _verify_integrity() {
  455. return (head != nullptr) &&_Zip<Tail...>::_verify_integrity();
  456. }
  457. std::string _get_name(){
  458. return head->get_name()+","+_Zip<Tail...>::_get_name();
  459. }
  460. public:
  461. _Zip() { }
  462. _Zip(Value<std::vector<Head>>* head, Value<std::vector<Tail>>*... tail)
  463. : _Zip<Tail...>(tail...),
  464. head(head) { }
  465. };
  466. /**
  467. * Zips a series of observations together
  468. */
  469. template <typename... ArgTypes>
  470. class Zip : public DerivedValue<std::vector<std::tuple<ArgTypes...>>>,
  471. private _Zip<ArgTypes...>{
  472. protected:
  473. void update_value(){
  474. this->value.clear();
  475. int size = _Zip<ArgTypes...>::_get_size();
  476. for(int i=0; i<size; i++){
  477. this->value.push_back(_Zip<ArgTypes...>::_get_at(i));
  478. }
  479. }
  480. std::string _get_name(){
  481. return "zip("+_Zip<ArgTypes...>::_get_name()+")";
  482. }
  483. public:
  484. Zip(Value<std::vector<ArgTypes>>*... args, const std::string& alias)
  485. :DerivedValue<std::vector<std::tuple<ArgTypes...>>>("", alias),
  486. _Zip<ArgTypes...>(args...) {
  487. this->set_name(_get_name());
  488. }
  489. };
  490. template<typename> class MapOver; // undefined
  491. template <typename Ret, typename... ArgTypes>
  492. class MapOver<Ret(ArgTypes...)> : public DerivedValue<std::vector<Ret>>{
  493. private:
  494. Function<Ret(ArgTypes...)>& fn;
  495. Zip<ArgTypes...>* arg;
  496. void update_value(){
  497. this->value.clear();
  498. for(auto tup : arg->get_value()){
  499. this->value.push_back(call(fn,tup));
  500. }
  501. }
  502. public:
  503. MapOver(Function<Ret(ArgTypes...)>& fn, Zip<ArgTypes...>* arg, const std::string& alias)
  504. :DerivedValue<std::vector<Ret>>("map_over("+fn.get_name()+":"+arg->get_name()+")", alias),
  505. fn(fn), arg(arg){ }
  506. };
  507. /**
  508. * Takes a set of four Value<std::vector<T> > objects and a function of four Ts
  509. * and returns a std::vector<R>. This is used in, for instance, calculating the
  510. * energy of a set of particles when one has separate arrays containing pt,
  511. * eta, phi, and mass. These arrays are first wrapped up in VectorWrappers and
  512. * then passes along with a function to calculate the energy into a ZipMapFour.
  513. * The result of this calculation is a new vector containing the energy for
  514. * each particle. Note that if the input vectors are not all the same size,
  515. * calculations are only performed up to the size of the shortest.
  516. * \see MiniTreeDataSet
  517. * \todo find way to implement for arbitrary number(and possibly type) of
  518. * vector inputs.
  519. */
  520. template <typename R, typename T>
  521. class ZipMapFour : public DerivedValue<std::vector<R> >{
  522. private:
  523. Function<R(T, T, T, T)>& f;
  524. Value<std::vector<T> >* v1;
  525. Value<std::vector<T> >* v2;
  526. Value<std::vector<T> >* v3;
  527. Value<std::vector<T> >* v4;
  528. void update_value(){
  529. std::vector<T> v1_val = v1->get_value();
  530. std::vector<T> v2_val = v2->get_value();
  531. std::vector<T> v3_val = v3->get_value();
  532. std::vector<T> v4_val = v4->get_value();
  533. int n;
  534. std::tie(n, std::ignore) = std::minmax({v1_val.size(), v2_val.size(), v3_val.size(), v4_val.size()});
  535. this->value.resize(n);
  536. for (int i=0; i<n; i++){
  537. this->value[i] = f(v1_val[i], v2_val[i], v3_val[i], v4_val[i]);
  538. }
  539. }
  540. public:
  541. ZipMapFour(Function<R(T, T, T, T)>& f,
  542. Value<std::vector<T> >* v1, Value<std::vector<T> >* v2,
  543. Value<std::vector<T> >* v3, Value<std::vector<T> >* v4, const std::string alias)
  544. :DerivedValue<std::vector<R> >("zipmap("+f.get_name()+":"+v1->get_name()+","+v2->get_name()+","+
  545. v3->get_name()+","+v4->get_name()+")", alias),
  546. f(f), v1(v1), v2(v2), v3(v3), v4(v4) { }
  547. ZipMapFour(Function<R(T, T, T, T)>& f,
  548. const std::string& label1, const std::string& label2,
  549. const std::string& label3, const std::string& label4, const std::string alias)
  550. :ZipMapFour(f,
  551. dynamic_cast<Value<std::vector<T> >*>(GenValue::get_value(label1)),
  552. dynamic_cast<Value<std::vector<T> >*>(GenValue::get_value(label2)),
  553. dynamic_cast<Value<std::vector<T> >*>(GenValue::get_value(label3)),
  554. dynamic_cast<Value<std::vector<T> >*>(GenValue::get_value(label4)),
  555. alias){ }
  556. };
  557. /**
  558. * Returns the count of elements in the input vector passing a test function.
  559. */
  560. template<typename T>
  561. class Count : public DerivedValue<int>{
  562. private:
  563. Function<bool(T)>& selector;
  564. Value<std::vector<T> >* v;
  565. void update_value(){
  566. value = 0;
  567. for(auto val : v->get_value()){
  568. if(selector(val))
  569. value++;
  570. }
  571. }
  572. public:
  573. Count(Function<bool(T)>& selector, Value<std::vector<T>>* v, const std::string alias)
  574. :DerivedValue<int>("count("+selector.get_name()+":"+v->get_name()+")", alias),
  575. selector(selector), v(v) { }
  576. };
  577. /**
  578. * Reduce a Value of type vector<T> to just a T.
  579. * This is useful functionality to model, for instance, calculating the maximum
  580. * element of a vector, or a the mean. See child classes for specific
  581. * implementations.
  582. */
  583. template <typename T>
  584. class Reduce : public DerivedValue<T>{
  585. private:
  586. Function<T(std::vector<T>)>& reduce;
  587. void update_value(){
  588. this->value = reduce(v->get_value());
  589. }
  590. protected:
  591. Value<std::vector<T> >* v;
  592. public:
  593. Reduce(Function<T(std::vector<T>)>& reduce, Value<std::vector<T> >* v, const std::string alias)
  594. :DerivedValue<T>("reduceWith("+reduce.get_name()+":"+v->get_name()+")", alias),
  595. reduce(reduce), v(v) { }
  596. };
  597. /**
  598. * Find and return the maximum value of a vector.
  599. */
  600. template <typename T>
  601. class Max : public Reduce<T>{
  602. public:
  603. Max(Value<std::vector<T>>* v, const std::string alias)
  604. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("max",
  605. FUNC(([](std::vector<T> vec){
  606. return *std::max_element(vec.begin(), vec.end());}))),
  607. v, alias) { }
  608. };
  609. /**
  610. * Find and return the minimum value of a vector.
  611. */
  612. template <typename T>
  613. class Min : public Reduce<T>{
  614. public:
  615. Min(Value<std::vector<T>>* v, const std::string alias)
  616. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("min",
  617. FUNC(([](std::vector<T> vec){
  618. return *std::min_element(vec.begin(), vec.end());}))),
  619. v, alias) { }
  620. };
  621. /**
  622. * Calculate the mean value of a vector.
  623. */
  624. template <typename T>
  625. class Mean : public Reduce<T>{
  626. public:
  627. Mean(Value<std::vector<T>>* v, const std::string alias)
  628. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("mean",
  629. FUNC(([](std::vector<T> vec){
  630. int n = 0; T sum = 0;
  631. for (T e : vec){ n++; sum += e; }
  632. return n>0 ? sum / n : 0; }))),
  633. v, alias) { }
  634. };
  635. /**
  636. * Calculate the range of the values in a vector
  637. */
  638. template <typename T>
  639. class Range : public Reduce<T>{
  640. public:
  641. Range(Value<std::vector<T>>* v, const std::string alias)
  642. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("range",
  643. FUNC(([](std::vector<T> vec){
  644. auto minmax = std::minmax_element(vec.begin(), vec.end());
  645. return (*minmax.second) - (*minmax.first); }))),
  646. v, alias) { }
  647. };
  648. /**
  649. * Extract the element at a specific index from a vector.
  650. */
  651. template <typename T>
  652. class ElementOf : public Reduce<T>{
  653. public:
  654. ElementOf(Value<int>* index, Value<std::vector<T>>* v, const std::string alias)
  655. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("elementOf",
  656. FUNC(([index](std::vector<T> vec){return vec[index->get_value()];}))),
  657. v, alias) { }
  658. };
  659. /**
  660. * Similar to Reduce, but returns a pair of a T and an int.
  661. * This is useful if you need to know where in the vector exists the element
  662. * being returned.
  663. */
  664. template <typename T>
  665. class ReduceIndex : public DerivedValue<std::pair<T, int> >{
  666. private:
  667. Function<std::pair<T,int>(std::vector<T>)>& reduce;
  668. Value<std::vector<T> >* v;
  669. void update_value(){
  670. this->value = reduce(v->get_value());
  671. }
  672. public:
  673. ReduceIndex(Function<std::pair<T,int>(std::vector<T>)>& reduce, Value<std::vector<T> >* v, const std::string alias="")
  674. :DerivedValue<T>("reduceIndexWith("+reduce.get_name()+":"+v->get_name()+")", alias),
  675. reduce(reduce), v(v) { }
  676. };
  677. /**
  678. * Find and return the maximum value of a vector and its index.
  679. */
  680. template <typename T>
  681. class MaxIndex : public ReduceIndex<T>{
  682. public:
  683. MaxIndex(Value<std::vector<T>>* v, const std::string alias="")
  684. :ReduceIndex<T>(GenFunction::register_function<T(std::vector<T>)>("maxIndex",
  685. FUNC(([](std::vector<T> vec){
  686. auto elptr = std::max_element(vec.begin(), vec.end());
  687. return std::pair<T,int>(*elptr, int(elptr-vec.begin())); }))),
  688. v, alias) { }
  689. };
  690. /**
  691. * Find and return the minimum value of a vector and its index.
  692. */
  693. template <typename T>
  694. class MinIndex : public ReduceIndex<T>{
  695. public:
  696. MinIndex(Value<std::vector<T>>* v, const std::string alias="")
  697. :ReduceIndex<T>(GenFunction::register_function<T(std::vector<T>)>("minIndex",
  698. FUNC(([](std::vector<T> vec){
  699. auto elptr = std::min_element(vec.begin(), vec.end());
  700. return std::pair<T,int>(*elptr, int(elptr-vec.begin())); }))),
  701. v, alias) { }
  702. };
  703. /**
  704. * A generic value owning only a function object.
  705. * All necessary values upon which this value depends must be bound to the
  706. * function object.
  707. */
  708. template <typename T>
  709. class BoundValue : public DerivedValue<T>{
  710. protected:
  711. Function<T()>& f;
  712. void update_value(){
  713. this->value = f();
  714. }
  715. public:
  716. BoundValue(Function<T()>& f, const std::string alias="")
  717. :DerivedValue<T>(f.get_name()+"(<bound>)", alias),
  718. f(f) { }
  719. };
  720. /**
  721. * A Value of a pointer. The pointer is constant, however the data the pointer
  722. * points to is variable.
  723. */
  724. template <typename T>
  725. class PointerValue : public DerivedValue<T*>{
  726. protected:
  727. void update_value(){ }
  728. public:
  729. PointerValue(const std::string& name, T* ptr, const std::string alias="")
  730. :DerivedValue<T*>(name, alias){
  731. this->value = ptr;
  732. }
  733. };
  734. /**
  735. * A Value which always returns the same value, supplied in the constructor.
  736. */
  737. template <typename T>
  738. class ConstantValue : public DerivedValue<T>{
  739. protected:
  740. void update_value(){ }
  741. public:
  742. ConstantValue(const std::string& name, T const_value, const std::string alias="")
  743. :DerivedValue<T>("const::"+name, alias),
  744. Value<T>::value(const_value) { }
  745. };
  746. }
  747. #endif // value_hpp