value.hpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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. namespace detail {
  61. template<typename T, int N, bool Done, typename... TYPES>
  62. struct _HomoTuple {
  63. typedef _HomoTuple<T, N, sizeof...(TYPES)+1==N, TYPES..., T> stype;
  64. typedef typename stype::type type;
  65. };
  66. template<typename T, int N, typename... TYPES>
  67. struct _HomoTuple<T, N, true, TYPES...> {
  68. typedef std::tuple<TYPES...> type;
  69. };
  70. }
  71. template<typename T, int N>
  72. struct HomoTuple {
  73. typedef detail::_HomoTuple<T, N, N==0> stype;
  74. typedef typename stype::type type;
  75. };
  76. namespace detail {
  77. // Convert array into a tuple
  78. template<typename Array, std::size_t... I>
  79. decltype(auto) a2t_impl(const Array& a, std::index_sequence<I...>){
  80. return std::make_tuple(a[I]...);
  81. }
  82. }
  83. /**
  84. * Converts a std::vector to a std::tuple.
  85. */
  86. template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
  87. decltype(auto) a2t(const std::array<T, N>& a){
  88. return detail::a2t_impl(a, Indices());
  89. }
  90. namespace detail {
  91. template <class F, class Tuple, std::size_t... I>
  92. constexpr decltype(auto) call_impl(F &&f, Tuple &&t, std::index_sequence<I...>){
  93. return std::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...);
  94. }
  95. }
  96. template <class F, class Tuple>
  97. constexpr decltype(auto) call(F &&f, Tuple &&t){
  98. return detail::call_impl(
  99. std::forward<F>(f), std::forward<Tuple>(t),
  100. std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>{});
  101. }
  102. namespace detail{
  103. template <typename T, int N, int I>
  104. struct t2s_impl{
  105. public:
  106. static std::string cvt(typename HomoTuple<T,N>::type& tup, std::function<std::string(T)>& f){
  107. std::stringstream ss;
  108. ss << f(std::get<N-I>(tup)) << ", " << t2s_impl<T, N, I+1>::cvt(tup, f);
  109. return ss.str();
  110. }
  111. };
  112. template <typename T, int N>
  113. struct t2s_impl<T, N, 0>{
  114. public:
  115. static std::string cvt(typename HomoTuple<T,N>::type&, std::function<std::string(T)>&){
  116. return "";
  117. }
  118. };
  119. }
  120. template <typename T, int N>
  121. std::string t2s(typename HomoTuple<T,N>::type& tup, std::function<std::string(T)>& f){
  122. return detail::t2s_impl<T, N, N>(tup, f);
  123. }
  124. template<typename> class Function; // undefined
  125. /**
  126. * Parent class to all Function classes. Holds a class-level collection of all
  127. * created function objects.
  128. */
  129. class GenFunction {
  130. private:
  131. std::string name;
  132. std::string impl;
  133. protected:
  134. inline static bool in_register_function=false;
  135. public:
  136. /**
  137. * Static mapping of functions from their name to the object wrapper of
  138. * the function.
  139. */
  140. inline static std::map<const std::string, GenFunction*> function_registry;
  141. GenFunction(const std::string& name, const std::string& impl)
  142. :name(name),
  143. impl(impl){ }
  144. virtual ~GenFunction() { };
  145. std::string& get_name(){
  146. return name;
  147. }
  148. std::string& get_impl(){
  149. return impl;
  150. }
  151. /**
  152. * Attempt to invoke clang-format for the purpose of printing out
  153. * nicely formatted functions to the log file. If clang-format is not
  154. * present, this function just passes through the code unmodified.
  155. */
  156. static std::string format_code(const std::string& code){
  157. std::stringstream code_out("");
  158. std::string command("echo \""+code+"\" | clang-format");
  159. char buffer[255];
  160. FILE *stream = popen(command.c_str(), "r");
  161. while (fgets(buffer, 255, stream) != NULL)
  162. code_out << buffer;
  163. if (pclose(stream) == 0)
  164. return code_out.str();
  165. else
  166. return code;
  167. }
  168. static std::string summary(){
  169. std::stringstream ss;
  170. ss << "The following functions have been registered" << std::endl;
  171. for(auto p : function_registry){
  172. if (p.second == nullptr) continue;
  173. ss << "FUNCTION::" << p.second->name << "@" << p.second << std::endl;
  174. ss << format_code(p.second->impl);
  175. }
  176. return ss.str();
  177. }
  178. template <typename T>
  179. static Function<T>& register_function(const std::string& name, std::function<T> f, const std::string& impl){
  180. in_register_function = true;
  181. Function<T>* func;
  182. if (GenFunction::function_registry[name] != nullptr){
  183. func = dynamic_cast<Function<T>*>(GenFunction::function_registry[name]);
  184. if (func == nullptr){
  185. ERROR("Trying to register function which has already been registered with a different type");
  186. }
  187. } else {
  188. func = new Function<T>(name, impl, f);
  189. GenFunction::function_registry[name] = func;
  190. }
  191. in_register_function = false;
  192. return *func;
  193. }
  194. template <typename T>
  195. static Function<T>& lookup_function(const std::string& name){
  196. if (GenFunction::function_registry[name] == nullptr){
  197. CRITICAL("Function \"" << name << "\" not previously registered", -1);
  198. } else {
  199. Function<T>* func = dynamic_cast<Function<T>*>(GenFunction::function_registry[name]);
  200. if (func == nullptr){
  201. CRITICAL("Function \"" << name << "\" request and register have mismatched types", -1);
  202. }
  203. return *GenFunction::function_registry[name];
  204. }
  205. }
  206. };
  207. /**
  208. * In order to enable proper provenance tracking, and at the same time keep
  209. * the ability to embed functions into values, the Function class should be
  210. * used. It is simply a wrapper around a std::function that also has a name.
  211. * This name is used when generating the name of values that use the function.
  212. * A function name is automatically prepended with "func::" to explicitly state
  213. * that the value is the result of a computation encoded within the function
  214. * object, and not from some other Value object. Unfortunately, it is up to the
  215. * user to find where that function is defined in the source code to inspect
  216. * what it is doing. But hopefully this isn't too onerous by just using grep.
  217. */
  218. template <typename R, typename... ArgTypes>
  219. class Function<R(ArgTypes...)> : public GenFunction {
  220. private:
  221. std::function<R(ArgTypes...)> f;
  222. public:
  223. Function(const std::string& name, const std::string& impl, std::function<R(ArgTypes...)> f)
  224. :GenFunction(name, impl), f(f){
  225. if (!in_register_function) {
  226. WARNING("Don't instantiate Function objects directly! Use GenFunction::register_function instead.");
  227. }
  228. }
  229. Function(const std::string& name, std::function<R(ArgTypes...)> f)
  230. :Function(name, "N/A", f){ }
  231. ~Function() { }
  232. R operator()(ArgTypes ...args){
  233. return f(args...);
  234. }
  235. };
  236. #define FUNC(f) f, #f
  237. /**
  238. * A type-agnostic value.
  239. * It is necessary to create a type-agnostic parent class to Value so that
  240. * it is possible to handle collections of them. GenValue also provides the
  241. * rest of the type-independent interface to Value.
  242. */
  243. class GenValue;
  244. typedef std::map<std::string, GenValue*> ValueSet;
  245. class GenValue{
  246. private:
  247. /**
  248. * The name of the value.
  249. * This is used to allow for dynamic lookup of
  250. * values based on their name via GenValue::get_value.
  251. */
  252. std::string name;
  253. protected:
  254. /**
  255. * Mark the internal value as invalid. This is needed for DerivedValue
  256. * to force a recalculation of the internal value when a new
  257. * observation is loaded into memory. It is called automatically for
  258. * all GenValue objects when reset is called.
  259. */
  260. bool value_valid;
  261. void _reset(){
  262. this->value_valid = false;
  263. }
  264. /**
  265. * A static mapping containing all created Value objects.
  266. * Every value object must have a unique name, and this name is used as
  267. * a key in values to that object. This is used to enable more dynamic
  268. * creation of objects as well as avoiding the uneccesary passing of
  269. * pointers.
  270. */
  271. inline static std::map<const std::string, GenValue*> values;
  272. /**
  273. * Composite value names are typically nested. This makes complex
  274. * values have rather unwieldy names. Therefore, one can declare
  275. * aliases which allow for more human-usable names to be used. When a
  276. * value is requested by name, an alias with that value takes precidence
  277. * over a name with that value.
  278. */
  279. inline static std::map<const std::string, GenValue*> aliases;
  280. bool logging_enabled;
  281. public:
  282. GenValue(const std::string& name, const std::string& alias)
  283. :name(name),
  284. value_valid(false),
  285. logging_enabled(false){
  286. INFO("Registered value: \"" << name << "\" with alias: \"" << alias << "\"");
  287. values[name] = this;
  288. if (alias != "")
  289. GenValue::alias(alias, this);
  290. }
  291. const std::string& get_name(){
  292. return name;
  293. }
  294. void set_name(const std::string& new_name){
  295. values[name] = nullptr;
  296. name = new_name;
  297. values[name] = this;
  298. }
  299. /**
  300. * If logging is enabled for this value, this function should be
  301. * implemented to format the value to a string and place it as an INFO
  302. * entry in the log file. Useful for debugging, but may produce alot of
  303. * output.
  304. */
  305. virtual void log() = 0;
  306. static void reset(){
  307. for (auto val : values){
  308. if (val.second != nullptr){
  309. val.second->_reset();
  310. }
  311. }
  312. }
  313. static GenValue* get_value(const std::string& name){
  314. if (aliases[name] != nullptr)
  315. return aliases[name];
  316. else
  317. return values[name];
  318. }
  319. static void alias(const std::string& name, GenValue* value){
  320. if (aliases[name] != nullptr){
  321. WARNING("WARNING: alias \"" << name << "\" overrides previous entry.");
  322. }
  323. aliases[name] = value;
  324. }
  325. static GenValue* alias(const std::string& name){
  326. if (values[name] != nullptr){
  327. WARNING("Alias \"" << name << "\" does not exist.");
  328. }
  329. return aliases[name];
  330. }
  331. static std::string summary(){
  332. std::stringstream ss;
  333. ss << "The following values have been created:" << std::endl;
  334. for (auto value : values){
  335. if (value.second == nullptr) continue;
  336. ss << "\tVALUE::\"" << value.first << "\" at address " << value.second << std::endl;
  337. }
  338. ss << "And these aliases:" << std::endl;
  339. for (auto alias : aliases){
  340. std::string orig("VOID");
  341. if (alias.second == nullptr) continue;
  342. for (auto value : values){
  343. if (alias.second == value.second){
  344. orig = value.second->get_name();
  345. break;
  346. }
  347. }
  348. ss << "\tALIAS::\"" << alias.first << "\" referring to \"" << orig << "\"" << std::endl;
  349. }
  350. return ss.str();
  351. }
  352. friend std::ostream& operator<<(std::ostream& os, const GenValue& gv);
  353. };
  354. std::ostream& operator<<(std::ostream& os, GenValue& gv){
  355. os << gv.get_name();
  356. return os;
  357. }
  358. /**
  359. * A templated value.
  360. * In order to facilitate run-time creation of analysis routines, it is
  361. * necessary to have some ability to get and store *values*. Values can either
  362. * be directly taken from some original data source (i.e. ObservedValue), or
  363. * they can be a function of some other set of values (i.e. DerivedValue). They
  364. * template class T of Value<T> is the type of thing that is returned upon
  365. * calling get_value().
  366. */
  367. template <typename T>
  368. class Value : public GenValue{
  369. protected:
  370. std::function<std::string(T)> value_to_string;
  371. public:
  372. Value(const std::string& name, const std::string& alias="")
  373. :value_to_string([](T){return "";}),
  374. GenValue(name, alias){ }
  375. /** Calculate, if necessary, and return the value held by this object.
  376. */
  377. virtual T& get_value() = 0;
  378. void enable_logging(const std::function<std::string(T)>& value_to_string = [](T){return "";}){
  379. logging_enabled = true;
  380. this->value_to_string = value_to_string;
  381. }
  382. void disable_logging(){
  383. logging_enabled = false;
  384. }
  385. };
  386. /**
  387. * A value supplied by the dataset, not derived.
  388. * An ObservedValue is the interface to your dataset. Upon creation, an
  389. * ObservedValue is given a pointer to an object of type T. When an observation
  390. * is loaded into memory, the value at the location referenced by that pointer
  391. * must be updated with the associated data from that observation. This is the
  392. * responsibility of whatever DataSet implementation is being used. This object
  393. * then will read that data and return it when requested.
  394. */
  395. template <typename T>
  396. class ObservedValue : public Value<T>{
  397. private:
  398. T *val_ref;
  399. public:
  400. ObservedValue(const std::string& name, T* val_ref, const std::string& alias="")
  401. :Value<T>(name, alias),
  402. val_ref(val_ref){ }
  403. void log(){
  404. if(this->logging_enabled){
  405. INFO(this->get_name() << ": " << this->value_to_string(*val_ref));
  406. }
  407. }
  408. static std::string fmt_name(const std::string& name){
  409. return name;
  410. }
  411. T& get_value(){
  412. if (!this->value_valid){
  413. this->value_valid = true;
  414. this->log();
  415. }
  416. return *val_ref;
  417. }
  418. };
  419. /**
  420. * A Value derived from some other Values, not directly from the dataset.
  421. * A DerivedValue is generally defined as some function of other Value objects.
  422. * For example, a Pair is a function of two other Value objects that makes a
  423. * pair of them. Note that these other Value objects are free to be either
  424. * ObservedValues or other DerivedValues.
  425. *
  426. * It is desireable from a performance standpoint that each DerivedValue be
  427. * calculated no more than once per observation. Therefore, when a get_value is
  428. * called on a DerivedValue, it first checks whether the value that it holds is
  429. * **valid**, meaning it has already been calculated for this observation. If
  430. * so, it simply returns the value. If not, the update_value function is called
  431. * to calculate the value. and then the newly calculated value is marked as
  432. * valid and returned.
  433. */
  434. template <typename T>
  435. class DerivedValue : public Value<T>{
  436. protected:
  437. T value;
  438. /**
  439. * Updates the internal value.
  440. * This function should be overridden by any child class to do the
  441. * actual work of updating value based on whatever rules the class
  442. * chooses. Normally, this consists of geting the values from some
  443. * associated Value objects, doing some calculation on them, and
  444. * storing the result in value.
  445. */
  446. virtual void update_value() = 0;
  447. public:
  448. DerivedValue(const std::string& name, const std::string& alias="")
  449. :Value<T>(name, alias){ }
  450. void log(){
  451. if(this->logging_enabled){
  452. INFO(this->get_name() << ": " << this->value_to_string(value));
  453. }
  454. }
  455. T& get_value(){
  456. /* if (this->logging_enabled){ */
  457. /* std::cout << "Getting value for " << this->get_name() << std::endl; */
  458. /* } */
  459. if (!this->value_valid){
  460. /* if (this->logging_enabled){ */
  461. /* std::cout << "Updating value for " << this->get_name() << std::endl; */
  462. /* } */
  463. update_value();
  464. this->value_valid = true;
  465. this->log();
  466. }
  467. return value;
  468. }
  469. };
  470. /**
  471. * A std::vector wrapper around a C-style array.
  472. * In order to make some of the higher-level Value types easier to work with,
  473. * it is a good idea to wrap all arrays in the original data source with
  474. * std::vector objects. To do this, it is necessary to supply both a Value
  475. * object containing the array itself as well as another Value object
  476. * containing the size of that array. Currently, update_value will simply copy
  477. * the contents of the array into the interally held vector.
  478. */
  479. template <typename T>
  480. class WrapperVector : public DerivedValue<std::vector<T> >{
  481. private:
  482. Value<int>* size;
  483. Value<T*>* data;
  484. void update_value(){
  485. int n = size->get_value();
  486. T* data_ref = data->get_value();
  487. this->value.assign(data_ref, data_ref+n);
  488. }
  489. public:
  490. static std::string fmt_name(Value<int>* size, Value<T*>* data){
  491. return "wrapper_vector("+size->get_name()+","+data->get_name()+")";
  492. }
  493. WrapperVector(Value<int>* size, Value<T*>* data, const std::string& alias="")
  494. :DerivedValue<std::vector<T> >(fmt_name(size,data), alias),
  495. size(size), data(data){ }
  496. };
  497. /**
  498. * Creates a std::pair type from a two other Value objects.
  499. */
  500. template <typename T1, typename T2>
  501. class Pair : public DerivedValue<std::pair<T1, T2> >{
  502. protected:
  503. std::pair<Value<T1>*, Value<T2>* > value_pair;
  504. void update_value(){
  505. this->value.first = value_pair.first->get_value();
  506. this->value.second = value_pair.second->get_value();
  507. }
  508. public:
  509. static std::string fmt_name(Value<T1> *value1, Value<T2> *value2){
  510. return "pair("+value1->get_name()+","+value2->get_name()+")";
  511. }
  512. Pair(Value<T1> *value1, Value<T2> *value2, const std::string alias="")
  513. :DerivedValue<std::pair<T1, T2> >(fmt_name(value1, value2), alias),
  514. value_pair(value1, value2){ }
  515. };
  516. template<typename... T> class _Zip;
  517. template<>
  518. class _Zip<> {
  519. protected:
  520. int _get_size(){
  521. return std::numeric_limits<int>::max();
  522. }
  523. std::tuple<> _get_at(int){
  524. return std::make_tuple();
  525. }
  526. std::string _get_name(){
  527. return "";
  528. }
  529. public:
  530. _Zip() { }
  531. };
  532. template<typename Head, typename... Tail>
  533. class _Zip<Head, Tail...> : private _Zip<Tail...> {
  534. protected:
  535. Value<std::vector<Head>>* head;
  536. int _get_size(){
  537. int this_size = head->get_value().size();
  538. int rest_size = _Zip<Tail...>::_get_size();
  539. return std::min(this_size, rest_size);
  540. }
  541. typename std::tuple<Head,Tail...> _get_at(int idx){
  542. auto tail_tuple = _Zip<Tail...>::_get_at(idx);
  543. return std::tuple_cat(std::make_tuple(head->get_value()[idx]),tail_tuple);
  544. }
  545. std::string _get_name(){
  546. return head->get_name()+","+_Zip<Tail...>::_get_name();
  547. }
  548. public:
  549. _Zip() { }
  550. _Zip(Value<std::vector<Head>>* head, Value<std::vector<Tail>>*... tail)
  551. : _Zip<Tail...>(tail...),
  552. head(head) { }
  553. };
  554. namespace impl {
  555. std::string zip_fmt_name(){
  556. return "";
  557. }
  558. template<typename Head>
  559. std::string zip_fmt_name(Value<std::vector<Head>>* head){
  560. return head->get_name();
  561. }
  562. template<typename Head1, typename Head2, typename... Tail>
  563. std::string zip_fmt_name(Value<std::vector<Head1>>* head1, Value<std::vector<Head2>>* head2, Value<std::vector<Tail>>*... tail){
  564. return head1->get_name() + "," + zip_fmt_name<Head2, Tail...>(head2, tail...);
  565. }
  566. }
  567. /**
  568. * Zips a series of vectors together. Can be combined with Map to
  569. * yield a Value whose elements are individually a function of the
  570. * corresponding elements of the vectors that were zipped together. For those
  571. * familiar with python, it accompilishes the same thing as
  572. * @code{.py}
  573. * xs = [1,2,3,4]
  574. * ys = [10,20,30,40]
  575. * print(list(map(lambda t:t[0]+t[1],zip(xs,ys))))
  576. * @endcode
  577. * which outputs
  578. * @code
  579. * [11, 22, 33, 44]
  580. * @endcode
  581. */
  582. template <typename... ArgTypes>
  583. class Zip : public DerivedValue<std::vector<std::tuple<ArgTypes...>>>,
  584. private _Zip<ArgTypes...>{
  585. protected:
  586. void update_value(){
  587. this->value.clear();
  588. int size = _Zip<ArgTypes...>::_get_size();
  589. for(int i=0; i<size; i++){
  590. this->value.push_back(_Zip<ArgTypes...>::_get_at(i));
  591. }
  592. }
  593. public:
  594. static std::string fmt_name(Value<std::vector<ArgTypes>>*... args){
  595. return "zip("+zip_fmt_name(args...)+")";
  596. }
  597. Zip(Value<std::vector<ArgTypes>>*... args, const std::string& alias)
  598. :DerivedValue<std::vector<std::tuple<ArgTypes...>>>(fmt_name(args...), alias),
  599. _Zip<ArgTypes...>(args...) { }
  600. };
  601. template<typename> class Map; // undefined
  602. /**
  603. * Maps a function over an input vector. The input vector must be a vector of
  604. * tuples, where the the elements of the tuple match the arguments of the
  605. * function. For example if the function takes two floats as arguments, the
  606. * tuple should contain two floats. The Value object required by Map will
  607. * typically be created as a Zip.
  608. */
  609. template <typename Ret, typename... ArgTypes>
  610. class Map<Ret(ArgTypes...)> : public DerivedValue<std::vector<Ret>>{
  611. private:
  612. typedef Value<std::vector<std::tuple<ArgTypes...>>> arg_type;
  613. Function<Ret(ArgTypes...)>& fn;
  614. arg_type* arg;
  615. void update_value(){
  616. this->value.clear();
  617. for(auto tup : arg->get_value()){
  618. this->value.push_back(call(fn,tup));
  619. }
  620. }
  621. public:
  622. static std::string fmt_name(Function<Ret(ArgTypes...)>& fn, arg_type* arg){
  623. return "map("+fn.get_name()+":"+arg->get_name()+")";
  624. }
  625. Map(Function<Ret(ArgTypes...)>& fn, arg_type* arg, const std::string& alias)
  626. :DerivedValue<std::vector<Ret>>(fmt_name(fn, arg), alias),
  627. fn(fn), arg(arg){ }
  628. };
  629. template<typename... T> class _Tuple;
  630. template<>
  631. class _Tuple<> {
  632. protected:
  633. std::tuple<> _get_value(){
  634. return std::make_tuple();
  635. }
  636. public:
  637. _Tuple() { }
  638. };
  639. template<typename Head, typename... Tail>
  640. class _Tuple<Head, Tail...> : private _Tuple<Tail...> {
  641. protected:
  642. Value<Head>* head;
  643. typename std::tuple<Head,Tail...> _get_value(){
  644. auto tail_tuple = _Tuple<Tail...>::_get_value();
  645. return std::tuple_cat(std::make_tuple(head->get_value()),tail_tuple);
  646. }
  647. public:
  648. _Tuple() { }
  649. _Tuple(Value<Head>* head, Value<Tail>*... tail)
  650. : _Tuple<Tail...>(tail...),
  651. head(head) { }
  652. };
  653. namespace impl {
  654. std::string tuple_fmt_name(){
  655. return "";
  656. }
  657. template<typename Head>
  658. std::string tuple_fmt_name(Value<Head>* head){
  659. return head->get_name();
  660. }
  661. template<typename Head1, typename Head2, typename... Tail>
  662. std::string tuple_fmt_name(Value<Head1>* head1, Value<Head2>* head2, Value<Tail>*... tail){
  663. return head1->get_name() + "," + tuple_fmt_name<Head2, Tail...>(head2, tail...);
  664. }
  665. }
  666. /**
  667. * Takes a series of Value objects and bundles them together into a std::tuple
  668. * object. Typically, this is most usefull when one wants to apply a function
  669. * to a few values and store the result. This class can be used in conjunction
  670. * with Apply to achieve this.
  671. */
  672. template <typename... ArgTypes>
  673. class Tuple : public DerivedValue<std::tuple<ArgTypes...>>,
  674. private _Tuple<ArgTypes...>{
  675. protected:
  676. void update_value(){
  677. this->value = _Tuple<ArgTypes...>::_get_value();
  678. }
  679. public:
  680. static std::string fmt_name(Value<ArgTypes>*... args){
  681. return "tuple("+impl::tuple_fmt_name(args...)+")";
  682. }
  683. Tuple(Value<ArgTypes>*... args, const std::string& alias)
  684. :DerivedValue<std::tuple<ArgTypes...>>(fmt_name(args...), alias),
  685. _Tuple<ArgTypes...>(args...) { }
  686. };
  687. /**
  688. * Gets the Nth element from a tuple value
  689. */
  690. template <size_t N, typename... ArgTypes>
  691. class DeTup : public DerivedValue<typename std::tuple_element<N, std::tuple<ArgTypes...>>::type>{
  692. Value<std::tuple<ArgTypes...>> tup;
  693. protected:
  694. void update_value(){
  695. this->value = std::get<N>(tup->get_value());
  696. }
  697. public:
  698. static std::string fmt_name(Value<std::tuple<ArgTypes...>>* tup){
  699. return "detup("+tup->get_name()+")";
  700. }
  701. DeTup(Value<std::tuple<ArgTypes...>>* tup, const std::string& alias)
  702. :DerivedValue<typename std::tuple_element<N, std::tuple<ArgTypes...>>::type>(fmt_name(tup), alias),
  703. tup(tup) { }
  704. };
  705. /**
  706. * Creates a vector of extracting the Nth value from each entry in a vector of
  707. * tuples.
  708. */
  709. template <size_t N, typename... ArgTypes>
  710. class DeTupVector : public DerivedValue<std::vector<typename std::tuple_element<N, std::tuple<ArgTypes...>>::type>>{
  711. Value<std::vector<std::tuple<ArgTypes...>>>* tup;
  712. protected:
  713. void update_value(){
  714. this->value.clear();
  715. for( auto& t : tup->get_value()){
  716. this->value.push_back(std::get<N>(t));
  717. }
  718. }
  719. public:
  720. static std::string fmt_name(Value<std::vector<std::tuple<ArgTypes...>>>* tup){
  721. return "detup_vec("+tup->get_name()+")";
  722. }
  723. DeTupVector(Value<std::vector<std::tuple<ArgTypes...>>>* tup, const std::string& alias)
  724. :DerivedValue<std::vector<typename std::tuple_element<N, std::tuple<ArgTypes...>>::type>>(fmt_name(tup), alias),
  725. tup(tup) { }
  726. };
  727. template<typename> class Apply; // undefined
  728. /**
  729. * Applies a function to a tuple of values and returns a value. This will
  730. * typically be called with a Tuple object as an argument.
  731. */
  732. template <typename Ret, typename... ArgTypes>
  733. class Apply<Ret(ArgTypes...)> : public DerivedValue<Ret>{
  734. private:
  735. Function<Ret(ArgTypes...)>& fn;
  736. Value<std::tuple<ArgTypes...>>* arg;
  737. void update_value(){
  738. auto &tup = arg->get_value();
  739. this->value = call(fn, tup);
  740. }
  741. public:
  742. static std::string fmt_name(Function<Ret(ArgTypes...)>& fn, Value<std::tuple<ArgTypes...>>* arg){
  743. return "apply("+fn.get_name()+":"+arg->get_name()+")";
  744. }
  745. Apply(Function<Ret(ArgTypes...)>& fn, Value<std::tuple<ArgTypes...>>* arg, const std::string& alias)
  746. :DerivedValue<Ret>(fmt_name(fn,arg), alias),
  747. fn(fn), arg(arg){ }
  748. };
  749. /**
  750. * Returns the count of elements in the input vector passing a test function.
  751. */
  752. template<typename T>
  753. class Count : public DerivedValue<int>{
  754. private:
  755. Function<bool(T)>& selector;
  756. Value<std::vector<T> >* v;
  757. void update_value(){
  758. value = 0;
  759. for(auto val : v->get_value()){
  760. if(selector(val))
  761. value++;
  762. }
  763. }
  764. public:
  765. static std::string fmt_name(Function<bool(T)>& selector, Value<std::vector<T>>* v){
  766. return "count("+selector.get_name()+":"+v->get_name()+")";
  767. }
  768. Count(Function<bool(T)>& selector, Value<std::vector<T>>* v, const std::string alias)
  769. :DerivedValue<int>(fmt_name(selector,v), alias),
  770. selector(selector), v(v) { }
  771. };
  772. /**
  773. * Returns the elements in a vector that pass a test function.
  774. */
  775. template<typename T>
  776. class Filter : public DerivedValue<std::vector<T>>{
  777. private:
  778. Function<bool(T)>& filter;
  779. Value<std::vector<T> >* v;
  780. void update_value(){
  781. this->value.clear();
  782. for(auto val : v->get_value()){
  783. if(this->filter(val))
  784. this->value.push_back(val);
  785. }
  786. }
  787. public:
  788. static std::string fmt_name(Function<bool(T)>& filter, Value<std::vector<T>>* v){
  789. return "filter("+filter.get_name()+":"+v->get_name()+")";
  790. }
  791. Filter(Function<bool(T)>& filter, Value<std::vector<T>>* v, const std::string alias)
  792. :DerivedValue<std::vector<T>>(fmt_name(filter,v), alias),
  793. filter(filter), v(v) { }
  794. };
  795. /**
  796. * Returns the elements in a vector that pass a test function. The elements on
  797. * the vector must be tuples. Typically this will be used in conjunction with
  798. * Zip and Map.
  799. */
  800. template<typename... ArgTypes>
  801. class TupFilter : public DerivedValue<std::vector<std::tuple<ArgTypes...>>>{
  802. private:
  803. typedef std::vector<std::tuple<ArgTypes...>> value_type;
  804. Function<bool(ArgTypes...)>& filter;
  805. Value<value_type>* arg;
  806. void update_value(){
  807. this->value.clear();
  808. for(auto val : arg->get_value()){
  809. if(call(filter,val))
  810. this->value.push_back(val);
  811. }
  812. }
  813. public:
  814. static std::string fmt_name(Function<bool(ArgTypes...)>& filter, Value<value_type>* arg){
  815. return "tup_filter("+filter.get_name()+":"+arg->get_name()+")";
  816. }
  817. TupFilter(Function<bool(ArgTypes...)>& filter, Value<value_type>* arg, const std::string alias)
  818. :DerivedValue<value_type>(fmt_name(filter, arg), alias),
  819. filter(filter), arg(arg) { }
  820. };
  821. /**
  822. * Reduce a Value of type vector<T> to just a T.
  823. * This is useful functionality to model, for instance, calculating the maximum
  824. * element of a vector, or a the mean. See child classes for specific
  825. * implementations.
  826. */
  827. template <typename T>
  828. class Reduce : public DerivedValue<T>{
  829. private:
  830. Function<T(std::vector<T>)>& reduce;
  831. void update_value(){
  832. this->value = reduce(v->get_value());
  833. }
  834. protected:
  835. Value<std::vector<T> >* v;
  836. public:
  837. Reduce(Function<T(std::vector<T>)>& reduce, Value<std::vector<T> >* v, const std::string alias)
  838. :DerivedValue<T>("reduceWith("+reduce.get_name()+":"+v->get_name()+")", alias),
  839. reduce(reduce), v(v) { }
  840. };
  841. /**
  842. * Find and return the maximum value of a vector.
  843. */
  844. template <typename T>
  845. class Max : public Reduce<T>{
  846. public:
  847. static std::string fmt_name(Value<std::vector<T>>* v){
  848. return "max("+v->get_name()+")";
  849. }
  850. Max(Value<std::vector<T>>* v, const std::string alias)
  851. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("max",
  852. FUNC(([](std::vector<T> vec){
  853. return *std::max_element(vec.begin(), vec.end());}))),
  854. v, alias) { }
  855. };
  856. /**
  857. * Find and return the minimum value of a vector.
  858. */
  859. template <typename T>
  860. class Min : public Reduce<T>{
  861. public:
  862. static std::string fmt_name(Value<std::vector<T>>* v){
  863. return "min("+v->get_name()+")";
  864. }
  865. Min(Value<std::vector<T>>* v, const std::string alias)
  866. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("min",
  867. FUNC(([](std::vector<T> vec){
  868. return *std::min_element(vec.begin(), vec.end());}))),
  869. v, alias) { }
  870. };
  871. /**
  872. * Calculate the mean value of a vector.
  873. */
  874. template <typename T>
  875. class Mean : public Reduce<T>{
  876. public:
  877. static std::string fmt_name(Value<std::vector<T>>* v){
  878. return "mean("+v->get_name()+")";
  879. }
  880. Mean(Value<std::vector<T>>* v, const std::string alias)
  881. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("mean",
  882. FUNC(([](std::vector<T> vec){
  883. int n = 0; T sum = 0;
  884. for (T e : vec){ n++; sum += e; }
  885. return n>0 ? sum / n : 0; }))),
  886. v, alias) { }
  887. };
  888. /**
  889. * Calculate the range of the values in a vector
  890. */
  891. template <typename T>
  892. class Range : public Reduce<T>{
  893. public:
  894. static std::string fmt_name(Value<std::vector<T>>* v){
  895. return "range("+v->get_name()+")";
  896. }
  897. Range(Value<std::vector<T>>* v, const std::string alias)
  898. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("range",
  899. FUNC(([](std::vector<T> vec){
  900. auto minmax = std::minmax_element(vec.begin(), vec.end());
  901. return (*minmax.second) - (*minmax.first); }))),
  902. v, alias) { }
  903. };
  904. /**
  905. * Extract the element at a specific index from a vector.
  906. */
  907. template <typename T>
  908. class ElementOf : public Reduce<T>{
  909. public:
  910. ElementOf(Value<int>* index, Value<std::vector<T>>* v, const std::string alias)
  911. :Reduce<T>(GenFunction::register_function<T(std::vector<T>)>("elementOf",
  912. FUNC(([index](std::vector<T> vec){return vec[index->get_value()];}))),
  913. v, alias) { }
  914. };
  915. /**
  916. * Similar to Reduce, but returns a pair of a T and an int.
  917. * This is useful if you need to know where in the vector exists the element
  918. * being returned.
  919. */
  920. template <typename T>
  921. class ReduceIndex : public DerivedValue<std::pair<T, int> >{
  922. private:
  923. Function<std::pair<T,int>(std::vector<T>)>& reduce;
  924. Value<std::vector<T> >* v;
  925. void update_value(){
  926. this->value = reduce(v->get_value());
  927. }
  928. public:
  929. ReduceIndex(Function<std::pair<T,int>(std::vector<T>)>& reduce, Value<std::vector<T> >* v, const std::string alias="")
  930. :DerivedValue<T>("reduceIndexWith("+reduce.get_name()+":"+v->get_name()+")", alias),
  931. reduce(reduce), v(v) { }
  932. };
  933. /**
  934. * Find and return the maximum value of a vector and its index.
  935. */
  936. template <typename T>
  937. class MaxIndex : public ReduceIndex<T>{
  938. public:
  939. MaxIndex(Value<std::vector<T>>* v, const std::string alias="")
  940. :ReduceIndex<T>(GenFunction::register_function<T(std::vector<T>)>("maxIndex",
  941. FUNC(([](std::vector<T> vec){
  942. auto elptr = std::max_element(vec.begin(), vec.end());
  943. return std::pair<T,int>(*elptr, int(elptr-vec.begin())); }))),
  944. v, alias) { }
  945. };
  946. /**
  947. * Find and return the minimum value of a vector and its index.
  948. */
  949. template <typename T>
  950. class MinIndex : public ReduceIndex<T>{
  951. public:
  952. MinIndex(Value<std::vector<T>>* v, const std::string alias="")
  953. :ReduceIndex<T>(GenFunction::register_function<T(std::vector<T>)>("minIndex",
  954. FUNC(([](std::vector<T> vec){
  955. auto elptr = std::min_element(vec.begin(), vec.end());
  956. return std::pair<T,int>(*elptr, int(elptr-vec.begin())); }))),
  957. v, alias) { }
  958. };
  959. /**
  960. * Find combinations of items from an input vector
  961. */
  962. template <typename T, int Size>
  963. class Combinations : public DerivedValue<std::vector<typename HomoTuple<T,Size>::type>>{
  964. private:
  965. Value<std::vector<T>>* val;
  966. typedef typename HomoTuple<T,Size>::type tuple_type;
  967. void update_value(){
  968. auto& v = val->get_value();
  969. int data_size = v.size();
  970. this->value.clear();
  971. std::vector<bool> selector(data_size);
  972. std::fill(selector.begin(), selector.begin()+std::min({Size,data_size}), true);
  973. do {
  974. std::array<T, Size> perm;
  975. int idx = 0;
  976. for (int i=0; i<data_size; i++){
  977. if (selector[i]){
  978. perm[idx] = v[i];
  979. idx++;
  980. if (idx == Size) break;
  981. }
  982. }
  983. this->value.push_back(a2t(perm)); //!!!
  984. } while(std::prev_permutation(selector.begin(), selector.end()));
  985. }
  986. public:
  987. static std::string fmt_name(Value<std::vector<T>>* val){
  988. std::stringstream ss;
  989. ss << "combinations(" << Size << "," << val->get_name() << ")";
  990. return ss.str();
  991. }
  992. Combinations(Value<std::vector<T>>* val, const std::string alias="")
  993. :DerivedValue<std::vector<tuple_type>>(fmt_name(val), alias),
  994. val(val) { }
  995. };
  996. /**
  997. * Calculate the cartesian product of two input vectors
  998. */
  999. template <typename FST, typename SND>
  1000. class CartProduct : public DerivedValue<std::vector<std::tuple<FST,SND>>>{
  1001. private:
  1002. Value<std::vector<FST>>* val1;
  1003. Value<std::vector<SND>>* val2;
  1004. void update_value(){
  1005. this->value.clear();
  1006. auto& v1 = val1->get_value();
  1007. auto& v2 = val2->get_value();
  1008. for(int i=0; i<v1.size(); i++){
  1009. for(int j=0; j<v2.size(); j++){
  1010. this->value.push_back(std::tuple<FST,SND>(v1[i],v2[j]));
  1011. }
  1012. }
  1013. }
  1014. static std::string calc_name(Value<std::vector<FST>>* val1, Value<std::vector<SND>>* val2){
  1015. std::stringstream ss;
  1016. ss << "cartProduct("
  1017. << val1->get_name() << ", " << val2->get_name()
  1018. << ")";
  1019. return ss.str();
  1020. }
  1021. public:
  1022. static std::string fmt_name(Value<std::vector<FST>>* val1, Value<std::vector<SND>>* val2){
  1023. return "cartProduct("+val1->get_name()+", "+val2->get_name()+")";
  1024. }
  1025. CartProduct(Value<std::vector<FST>>* val1, Value<std::vector<SND>>* val2, const std::string alias="")
  1026. :DerivedValue<std::vector<std::tuple<FST,SND>>>(calc_name(val1, val2), alias),
  1027. val1(val1), val2(val2) { }
  1028. };
  1029. /**
  1030. * A generic value owning only a function object.
  1031. * All necessary values upon which this value depends must be bound to the
  1032. * function object.
  1033. */
  1034. template <typename T>
  1035. class BoundValue : public DerivedValue<T>{
  1036. protected:
  1037. Function<T()>& f;
  1038. void update_value(){
  1039. this->value = f();
  1040. }
  1041. public:
  1042. BoundValue(Function<T()>& f, const std::string alias="")
  1043. :DerivedValue<T>(f.get_name()+"(<bound>)", alias),
  1044. f(f) { }
  1045. };
  1046. /**
  1047. * A Value of a pointer. The pointer is constant, however the data the pointer
  1048. * points to is variable.
  1049. */
  1050. template <typename T>
  1051. class PointerValue : public DerivedValue<T*>{
  1052. protected:
  1053. void update_value(){ }
  1054. public:
  1055. PointerValue(const std::string& name, T* ptr, const std::string alias="")
  1056. :DerivedValue<T*>(name, alias){
  1057. this->value = ptr;
  1058. }
  1059. };
  1060. /**
  1061. * A Value which always returns the same value, supplied in the constructor.
  1062. */
  1063. template <typename T>
  1064. class ConstantValue : public DerivedValue<T>{
  1065. protected:
  1066. void update_value(){ }
  1067. public:
  1068. ConstantValue(const std::string& name, T const_value, const std::string alias="")
  1069. :DerivedValue<T>("const::"+name, alias),
  1070. Value<T>::value(const_value) { }
  1071. };
  1072. }
  1073. #endif // value_hpp