GLAMERDOC++
Gravitational Lensing Code Library
Loading...
Searching...
No Matches
utilities_slsim.h
1#ifndef _UTILITIES_H
2#define _UTILITIES_H
3
4#include "standard.h"
5#include <typeinfo>
6#include <vector>
7#include <map>
8#include <string>
9#include <stdexcept>
10#include <algorithm>
11#include <utility>
12#include <iterator>
13#include <cstdlib>
14#include <random>
15//#if __cplusplus >= 201103L
16#include <typeindex>
17#include <dirent.h>
18#include <unistd.h>
19#include <sys/stat.h>
20#include <sys/types.h>
21#include <boost/variant.hpp>
22#include <set>
23#include <iomanip>
24#include <thread>
25
26namespace Utilities
27{
29template<class T>
30T to_numeric(const std::string &str) {
31 return std::stoi(str);
32};
33template<>
34inline long to_numeric<long>(const std::string &str) {
35 try{
36 return std::stol(str);
37 }catch(...){
38 return -500;
39 }
40};
41template<>
42inline int to_numeric<int>(const std::string &str) {
43 return std::stoi(str);
44 try{
45 return std::stoi(str);
46 }catch(...){
47 return -500;
48 }
49};
50template<>
51inline float to_numeric<float>(const std::string &str) {
52 return std::stof(str);
53 try{
54 return std::stof(str);
55 }catch(...){
56 return -500;
57 }
58};
59template<>
60inline double to_numeric<double>(const std::string &str) {
61 try{
62 return std::stod(str);
63 }catch(...){
64 return -500;
65 }
66};
67//********************************************************
68
69template <typename T>
70bool AlwaysTrue(T t){return true;}
71
72template <typename T>
73bool AlwaysFalse(T t){return false;}
74
75template <typename T>
76T vec_sum(const std::vector<T> &v){
77 double sum=0.0;
78 for(const T &a : v) sum += a;
79 return sum;
80}
81
82// this is not for the user
83namespace detail
84{
85//#if __cplusplus < 201103L
86//class type_index
87//{
88//public:
89// type_index(const std::type_info& type) : t(type) {}
90// inline bool operator<(const type_index& rhs) const { return t.before(rhs.t); }
91//
92//private:
93// const std::type_info& t;
94//};
95//#else
96using std::type_index;
97//#endif
98}
99
100template <class T>
101void Matrix(T **matrix, long rows, long cols){
102 matrix = new T*[rows];
103 matrix[0] = new T[rows*cols];
104 for (long i = 1; i < rows; ++i)
105 matrix[i] = matrix[0] + i * cols;
106}
107
108template <class T>
109void free_Matrix(T **matrix, long rows, long){
110 if (rows) delete[] matrix[0];
111 delete []matrix;
112}
113
114PosType **PosTypeMatrix(size_t rows, size_t cols);
115void free_PosTypeMatrix(PosType **matrix, size_t rows, size_t cols);
116PosType **PosTypeMatrix(long rows1,long rows2, long cols1, long cols2);
117void free_PosTypeMatrix(PosType **matrix, long rows1,long rows2, long cols1, long cols2);
118
120template<typename T>
121class D3Matrix{
122public:
123 D3Matrix(size_t xsize,size_t ysize,size_t zsize)
124 :xn(xsize),yn(ysize),zn(zsize){
125 array = new T[xn*yn*zn];
126 }
127 ~D3Matrix(){
128 delete[] array;
129 }
130
131 T& operator()(size_t i,size_t j,size_t k){
132 return array[i + j*xn + k*xn*yn];
133 }
134
135 T& operator()(size_t m){
136 return array[m];
137 }
138
139 size_t xindex(size_t m){
140 return m % (xn);
141 }
142 size_t yindex(size_t m){
143 return (m % (xn*yn) ) / xn;
144 }
145
146 size_t zindex(size_t m){
147 return m / (xn*yn);
148 }
149
150private:
151 size_t xn;
152 size_t yn;
153 size_t zn;
154 T *array;
155};
156
157
159template<typename T>
160class D2Matrix{
161
162public:
163 D2Matrix(size_t xsize,size_t ysize)
164 :xn(xsize),yn(ysize){
165 array = new T[xn*yn];
166 }
167 ~D2Matrix(){
168 delete[] array;
169 }
170
171 T& operator()(size_t i,size_t j){
172 return array[i + j*xn];
173 }
174
175 T& operator()(size_t m){
176 return array[m];
177 }
178
179 size_t xindex(size_t m){
180 return m % xn;
181 }
182 size_t yindex(size_t m){
183 return m / xn;
184 }
185
186
187private:
188 size_t xn;
189 size_t yn;
190 T *array;
191};
192
198template <typename T>
199class SymmetricMatrix{
200 std::vector<T> v;
201 int n;
202 int m;
203public:
204 SymmetricMatrix(int n):n(n){
205 v.resize(n*(n+1)/2);
206 m = 2*n-1;
207 }
208 T& operator()(int i,int j){
209 //long k = j + (2*n-1-i)*i/2 ;
210 //size_t k = (i <= j ) ? j + (2*n-1-i)*i/2 : i + (2*n-1-j)*j/2;
211 size_t k = (i <= j ) ? j + (m-i)*i/2 : i + (m-j)*j/2;
212 //assert(k>=0);
213 //assert(k < v.size());
214 return v[ k ];
215 }
216 T& operator[](size_t k){
217 return v[ k ];
218 }
219
220 int size(){return n;}
221
223 size_t oned_index(int i,int j){
224 return (i <= j ) ? j + (m-i)*i/2 : i + (m-j)*j/2;
225 }
226};
227
228
270template<typename BaseT>
272{
273public: /* iterators */
274 template<typename ValueT = BaseT> // TODO: needs to check subclass type
275 class iterator
276 {
277 private:
278 typedef typename std::vector<BaseT*>::iterator base_iterator;
279 base_iterator it;
280
281 public:
282 typedef ValueT value_type;
283 typedef ValueT* pointer;
284 typedef const ValueT* const_pointer;
285 typedef ValueT& reference;
286 typedef const ValueT& const_reference;
287 typedef typename base_iterator::difference_type difference_type;
288 typedef typename base_iterator::iterator_category iterator_category;
289
290 iterator() {}
291 iterator(base_iterator i) : it(i) {}
292 iterator(const iterator& other) : it(other.it) {}
293
294 iterator& operator=(const iterator& rhs) { it = rhs.it; return *this; }
295
296 reference operator*() { return (reference)(**it); }
297
298 //const reference operator*() const { return (const reference)(**it); }
299
300 pointer operator->() { return (pointer)(*it); }
301 const_pointer operator->() const { return (const_pointer)(*it); }
302
303 iterator& operator++() { ++it; return *this; }
304 iterator operator++(int) { iterator tmp(*this); ++it; return tmp; }
305 iterator& operator--() { --it; return *this; }
306 iterator operator--(int) { iterator tmp(*this); --it; return tmp; }
307
308 bool operator==(const iterator& rhs) const { return (it == rhs.it); }
309 bool operator!=(const iterator& rhs) const { return (it != rhs.it); }
310
311 iterator& operator+=(difference_type n) { it += n; return *this; }
312 iterator& operator-=(difference_type n) { it -= n; return *this; }
313
314 reference operator[](difference_type n) { return (reference)*it[n]; }
315
316 //const reference operator[](difference_type n) const { return (const reference)*it[n]; }
317
318 friend iterator operator+(const iterator& i, difference_type n) { return iterator(i.it + n); }
319 friend iterator operator+(difference_type n, const iterator& i) { return iterator(i.it + n); }
320 friend iterator operator-(const iterator& i, difference_type n) { return iterator(i.it - n); }
321 friend iterator operator-(difference_type n, const iterator& i) { return iterator(i.it - n); }
322
323 friend difference_type operator-(const iterator& b, const iterator& a) { return (b.it - a.it); }
324
325 friend bool operator<(const iterator&a, const iterator& b) { return (a.it < b.it); }
326 friend bool operator>(const iterator&a, const iterator& b) { return (a.it > b.it); }
327 friend bool operator<=(const iterator&a, const iterator& b) { return (a.it <= b.it); }
328 friend bool operator>=(const iterator&a, const iterator& b) { return (a.it >= b.it); }
329 };
330
331public:
334 {
335 }
336
339 {
340 clear();
341 }
342
345 {
346 using std::swap;
347
348 swap(a.items, b.items);
349 swap(a.tmap, b.tmap);
350 }
351
354 {
355 // copy-and-swap idiom
356 swap(*this, rhs);
357 return *this;
358 }
359
361 template<typename SubclassT>
362 void copy_back(const SubclassT& obj)
363 {
364 // make sure this is a subclass of BaseT
365 check_subclass(obj);
366
367 // copy the object
368 SubclassT* copy = new SubclassT(obj);
369
370 // add the copy of the object to the list of items
371 items.push_back(copy);
372
373 // add the copy to type map
374 tmap[typeid(SubclassT)].push_back(copy);
375 }
376
377
379 void pop_back()
380 {
381 // get very last element
382 BaseT* back = items.back();
383
384 // remove from the vector in the type map
385 tmap[back->type()].pop_back();
386
387 // remove from items
388 items.pop_back();
389
390 // delete from memory
391 delete back;
392 }
393
395 template<typename SubclassT>
396 void pop_back()
397 {
398 // search for vector belonging to SubclassT
399 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
400 if(found == tmap.end())
401 return;
402
403 // pop from vector for type
404 found->second.pop_back();
405
406 // go through list of all items from back, until item of correct type is found
407 for(typename base_container::reverse_iterator it = items.rbegin(); it != items.rend(); ++it)
408 {
409 if((*it)->type() == typeid(SubclassT))
410 {
411 // remove the item
412 delete (*it);
413 items.erase(it);
414 return;
415 }
416 }
417 }
418
420 void clear()
421 {
422 for(std::size_t i = 0, n = items.size(); i < n; ++i)
423 delete items[i];
424 items.clear();
425 tmap.clear();
426 }
427
429 template<typename SubclassT>
430 void clear()
431 {
432 // search for vector belonging to SubclassT
433 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
434 if(found == tmap.end())
435 return;
436
437 base_container& titems = found.second;
438
439 // delete items from vector for subclass
440 for(std::size_t i = 0, n = titems.size(); i < n; ++i)
441 delete titems[i];
442
443 // remove items for subclass
444 tmap.erase(found);
445
446 // erase items matching type
447 items.erase(std::remove_if(items.begin(), items.end(), is_type<SubclassT>), items.end());
448 }
449
451 BaseT* data()
452 {
453 return items.data();
454 }
455
457 const BaseT* data() const
458 {
459 return items.data();
460 }
461
463 template<typename SubclassT>
464 bool type(std::size_t i)
465 {
466 return is_type<SubclassT>(items[i]);
467 }
468
470 BaseT& operator[](std::size_t i)
471 {
472 return *items[i];
473 }
474
476 const BaseT& operator[](std::size_t i) const
477 {
478 return *items[i];
479 }
480
482 BaseT& get(std::size_t i)
483 {
484 return *items[i];
485 }
486
488 const BaseT& get(std::size_t i) const
489 {
490 return *items[i];
491 }
492
494 template<typename SubclassT>
495 SubclassT& get(std::size_t i)
496 {
497 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
498 if(found == tmap.end())
499 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
500 return (SubclassT&)*found->second[i];
501 }
502
504 template<typename SubclassT>
505 const SubclassT& get(std::size_t i) const
506 {
507 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
508 if(found == tmap.end())
509 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
510 return (const SubclassT&)*found->second[i];
511 }
512
514 BaseT& at(std::size_t i)
515 {
516 return *items.at(i);
517 }
518
520 const BaseT& at(std::size_t i) const
521 {
522 return *items.at(i);
523 }
524
529 template<typename SubclassT>
530 SubclassT& at(std::size_t i)
531 {
532 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
533 if(found == tmap.end())
534 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
535 return (SubclassT&)*found->second.at(i);
536 }
537
539 template<typename SubclassT>
540 const SubclassT& at(std::size_t i) const
541 {
542 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
543 if(found == tmap.end())
544 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
545 return (const SubclassT&)*found->second.at(i);
546 }
547
549 std::size_t size() const
550 {
551 return items.size();
552 }
553
555 template<typename SubclassT>
556 std::size_t size() const
557 {
558 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
559 if(found == tmap.end())
560 return 0;
561 return found->second.size();
562 }
563
565 bool empty() const
566 {
567 return items.empty();
568 }
569
571 template<typename SubclassT>
572 bool empty() const
573 {
574 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
575 if(found == tmap.end())
576 return true;
577
578 return found->second.empty();
579 }
580
582 iterator<> begin()
583 {
584 return iterator<>(items.begin());
585 }
586
588 iterator<> end()
589 {
590 return iterator<>(items.end());
591 }
592
594 template<typename SubclassT>
595 iterator<SubclassT> begin()
596 {
597 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
598 if(found == tmap.end())
599 return iterator<SubclassT>(items.end());
600 return iterator<SubclassT>(found->second.begin());
601 }
602
604 template<typename SubclassT>
605 iterator<SubclassT> end()
606 {
607 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
608 if(found == tmap.end())
609 return iterator<SubclassT>(items.end());
610 return iterator<SubclassT>(found->second.end());
611 }
612
613private:
615 MixedVector(const MixedVector<BaseT>& other);
616
617 typedef std::vector<BaseT*> base_container;
618
619 inline static void check_subclass(const BaseT&) {}
620
621 template<typename SubclassT>
622 inline static bool is_type(const BaseT* obj) { return (typeid(*obj) == typeid(SubclassT)); }
623
624 base_container items;
625
626 typedef std::map<detail::type_index, base_container> tmap_t;
627 tmap_t tmap;
628};
629
631template<typename BaseT>
632class MixedVector<BaseT*>
633{
634public: /* iterators */
635 template<typename ValueT = BaseT*> // TODO: needs to check subclass pointer type
636 class iterator
637 {
638 private:
639 typedef typename std::vector<BaseT*>::iterator base_iterator;
640 base_iterator it;
641
642 public:
643 typedef typename std::vector<ValueT>::iterator::value_type value_type;
644 typedef typename std::vector<ValueT>::iterator::pointer pointer;
645 typedef typename std::vector<ValueT>::iterator::reference reference;
646 typedef typename base_iterator::difference_type difference_type;
647 typedef typename base_iterator::iterator_category iterator_category;
648
649 iterator() {}
650 iterator(base_iterator i) : it(i) {}
651 iterator(const iterator& other) : it(other.it) {}
652
653 iterator& operator=(const iterator& rhs) { it = rhs.it; return *this; }
654
655 reference operator*() { return (reference)*it; }
656 const reference operator*() const { return (const reference)*it; }
657
658 iterator& operator++() { ++it; return *this; }
659 iterator operator++(int) { iterator tmp(*this); ++it; return tmp; }
660 iterator& operator--() { --it; return *this; }
661 iterator operator--(int) { iterator tmp(*this); --it; return tmp; }
662
663 bool operator==(const iterator& rhs) const { return (it == rhs.it); }
664 bool operator!=(const iterator& rhs) const { return (it != rhs.it); }
665
666 iterator& operator+=(difference_type n) { it += n; return *this; }
667 iterator& operator-=(difference_type n) { it -= n; return *this; }
668
669 pointer operator[](difference_type n) { return (pointer)it[n]; }
670 const pointer operator[](difference_type n) const { return (const pointer)it[n]; }
671
672 friend iterator operator+(const iterator& i, difference_type n) { return iterator(i.it + n); }
673 friend iterator operator+(difference_type n, const iterator& i) { return iterator(i.it + n); }
674 friend iterator operator-(const iterator& i, difference_type n) { return iterator(i.it - n); }
675 friend iterator operator-(difference_type n, const iterator& i) { return iterator(i.it - n); }
676
677 friend difference_type operator-(const iterator& b, const iterator& a) { return (b.it - a.it); }
678
679 friend bool operator<(const iterator&a, const iterator& b) { return (a.it < b.it); }
680 friend bool operator>(const iterator&a, const iterator& b) { return (a.it > b.it); }
681 friend bool operator<=(const iterator&a, const iterator& b) { return (a.it <= b.it); }
682 friend bool operator>=(const iterator&a, const iterator& b) { return (a.it >= b.it); }
683 };
684
685public:
688 {
689 }
690
693 : items(other.items), tmap(other.tmap)
694 {
695 }
696
699 {
700 clear();
701 }
702
705 {
706 using std::swap;
707
708 swap(a.items, b.items);
709 swap(a.tmap, b.tmap);
710 }
711
714 {
715 // copy-and-swap idiom
716 swap(*this, rhs);
717 return *this;
718 }
719
721 BaseT& back()
722 {
723 return items.back();
724 }
725
727 const BaseT& back() const
728 {
729 return items.back();
730 }
731
733 void push_back(BaseT* obj)
734 {
735 // make sure this is a subclass of BaseT
736 check_subclass(obj);
737
738 // add the copy of the object pointer to the list of items
739 items.push_back(obj);
740
741 // add the copy to type map
742 tmap[typeid(*obj)].push_back(obj);
743 }
744
746 void pop_back()
747 {
748 // get very last element
749 BaseT* back = items.back();
750
751 // remove from the vector in the type map
752 tmap[typeid(*back)].pop_back();
753
754 // remove from items
755 items.pop_back();
756
757 delete back; // delete object
758 }
759
761 template<typename SubclassT>
762 void pop_back()
763 {
764 // search for vector belonging to SubclassT
765 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
766 if(found == tmap.end())
767 return;
768
769 // pop from vector for type
770 found->second.pop_back();
771
772 // go through list of all items from back, until item of correct type is found
773 for(typename std::vector<BaseT*>::reverse_iterator it = items.rbegin(); it != items.rend(); ++it)
774 {
775 if(typeid(**it) == typeid(SubclassT))
776 {
777 // remove the item
778 delete(*it);
779 items.erase(it);
780 return;
781 }
782 }
783 }
784
786 void clear()
787 {
788 while(!empty()) pop_back();
789 }
790
792 template<typename SubclassT>
793 void clear()
794 {
795 // remove vector for subclass
796 tmap.erase(typeid(SubclassT));
797
798 // erase items matching type
799 items.erase(std::remove_if(items.begin(), items.end(), is_type<SubclassT>), items.end());
800 }
801
803 BaseT** data()
804 {
805 return items.data();
806 }
807
809 const BaseT** data() const
810 {
811 return items.data();
812 }
813
815 template<typename SubclassT>
816 bool type(std::size_t i)
817 {
818 return is_type<SubclassT>(items[i]);
819 }
820
822 BaseT* operator[](std::size_t i) const
823 {
824 return items[i];
825 }
826
828 BaseT* get(std::size_t i)
829 {
830 return items[i];
831 }
832
834 const BaseT* get(std::size_t i) const
835 {
836 return items[i];
837 }
838
840 template<typename SubclassT>
841 SubclassT* get(std::size_t i)
842 {
843 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
844 if(found == tmap.end())
845 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
846 return (SubclassT*)found->second[i];
847 }
848
850 template<typename SubclassT>
851 const SubclassT* get(std::size_t i) const
852 {
853 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
854 if(found == tmap.end())
855 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
856 return (const SubclassT*)found->second[i];
857 }
858
860 BaseT* at(std::size_t i)
861 {
862 return items.at(i);
863 }
864
866 const BaseT* at(std::size_t i) const
867 {
868 return items.at(i);
869 }
870
875 template<typename SubclassT>
876 SubclassT* at(std::size_t i)
877 {
878 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
879 if(found == tmap.end())
880 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
881 return (SubclassT*)found->second.at(i);
882 }
883
885 template<typename SubclassT>
886 const SubclassT* at(std::size_t i) const
887 {
888 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
889 if(found == tmap.end())
890 throw std::out_of_range(std::string() + "type " + typeid(SubclassT).name() + " not in vector");
891 return (const SubclassT*)found->second.at(i);
892 }
893
895 std::size_t size() const
896 {
897 return items.size();
898 }
899
901 template<typename SubclassT>
902 std::size_t size() const
903 {
904 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
905 if(found == tmap.end())
906 return 0;
907 return found->second.size();
908 }
909
911 bool empty() const
912 {
913 return items.empty();
914 }
915
917 template<typename SubclassT>
918 bool empty() const
919 {
920 typename tmap_t::const_iterator found = tmap.find(typeid(SubclassT));
921 if(found == tmap.end())
922 return true;
923
924 return found->second.empty();
925 }
926
928 iterator<> begin()
929 {
930 return iterator<>(items.begin());
931 }
932
934 iterator<> end()
935 {
936 return iterator<>(items.end());
937 }
938
940 template<typename SubclassT>
941 iterator<SubclassT> begin()
942 {
943 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
944 if(found == tmap.end())
945 return iterator<SubclassT>(items.end());
946 return iterator<SubclassT>(found->second.begin());
947 }
948
950 template<typename SubclassT>
951 iterator<SubclassT> end()
952 {
953 typename tmap_t::iterator found = tmap.find(typeid(SubclassT));
954 if(found == tmap.end())
955 return iterator<SubclassT>(items.end());
956 return iterator<SubclassT>(found->second.end());
957 }
958
959private:
960 inline void check_subclass(const BaseT*) {}
961
962 template<typename SubclassT>
963 inline static bool is_type(const BaseT* obj) { return (typeid(*obj) == typeid(SubclassT)); }
964
965 typedef std::vector<BaseT*> base_container;
966
967 base_container items;
968
969 typedef std::map<detail::type_index, base_container> tmap_t;
970 tmap_t tmap;
971};
972
973template<class BaseT>
974std::size_t lower_bound(std::vector<BaseT*>& items, PosType target){
975 std::size_t ju,jm,jl;
976
977 if(items.size() == 0) return 0;
978
979 jl=0;
980 ju=items.size()-1;
981 while (ju-jl > 1) {
982 jm=(ju+jl) >> 1;
983 if(items[jm]->compareZ(target))
984 jl=jm;
985 else
986 ju=jm;
987 }
988 return jl;
989}
990
992template<typename Container>
993void delete_container(Container& c) { while(!c.empty()) delete c.back(), c.pop_back(); }
994
1004public:
1006 PosType x_min
1007 ,PosType y_min
1008 ,PosType my_range
1009 ,PosType smallsize
1010 ):
1011 range(my_range)
1012 {
1013 xo[0] = x_min;
1014 xo[1] = y_min;
1015 n = (int)(range/smallsize+1);
1016 }
1017
1018 int xy2d (int x, int y);
1019 int xy2d (PosType x, PosType y);
1020 void d2xy(int d, int *x, int *y);
1021 void d2xy(int d, PosType *x, PosType *y);
1022
1023private:
1024 int n;
1025 PosType xo[2],range;
1026 void rot(int s,int *x, int *y, int rx, int ry);
1027};
1028
1029template<typename T>
1030T between(const T& x, const T& l, const T& u)
1031{
1032 return std::max(l, std::min(u, x));
1033}
1034
1035#ifdef ENABLE_CLANG
1037class RandomNumbers{
1038public:
1039
1040 RandomNumbers(unsigned int seed);
1041 ~RandomNumbers(void);
1042
1043 PosType operator()(void);
1045 PosType gauss(){return norm_dist(rand_gen);}
1046private:
1047
1048 std::normal_distribution<> norm_dist;
1049 std::mt19937 rand_gen;
1050};
1051#endif
1052
1059class RandomNumbers_NR{
1060public:
1061
1062 RandomNumbers_NR(long seed);
1063 // sets seed from clock
1064 RandomNumbers_NR();
1065
1066 PosType operator()(void);
1068 PosType gauss(){
1069 ++calls;
1070 if(count){
1071 do{
1072 u = 2*ran2() - 1;
1073 v = 2*ran2() - 1;
1074 s = u*u +v*v;
1075 }while( s > 1.0 || s == 0.0);
1076
1077 s = sqrt(-2*log(s)/s);
1078 count = false;
1079 return s*u;
1080 }else{
1081 count = true;
1082 return s*v;
1083 }
1084 };
1085
1086 int poisson(double lam){
1087 if(lam > 200){
1088 return std::max<long>(std::lround( gauss()*sqrt(lam) + lam ) ,0);
1089 }
1090 double L = exp(-lam),p=1;
1091 int k = 0;
1092 do{
1093 ++k;
1094 p *= operator()();
1095 }while(p>L);
1096
1097 return k-1;
1098 }
1099
1100// int poisson(double lam){
1101//
1102// int step = 500;
1103// double Lam = lam,p=1;
1104// int k = 0;
1105// do{
1106// ++k;
1107// p *= operator()();
1108// while(p<1 && Lam>0){
1109// if(Lam > step){
1110// p *= exp(step);
1111// Lam -= step;
1112// }else{
1113// p *= exp(Lam);
1114// Lam=0;
1115// }
1116// }
1117// }while(p>1);
1118//
1119// return k-1;
1120// }
1121
1122 size_t calls = 0;
1123
1124 long getseed(){return firstseed;}
1125private:
1126 long idum;
1127 PosType ran2(void);
1128
1129 int IM1;
1130 int IM2;
1131 PosType AM;
1132 //int IMM1 = (IM1-1);
1133 int IA1;
1134 int IA2;
1135 int IQ1;
1136 int IQ2;
1137 int IR1;
1138 int IR2;
1139 int NDIV;
1140 PosType EPS;
1141 PosType RNMX;
1142
1143 long idum2;
1144 long iy;
1145 long iv[32];
1146 bool count;
1147 PosType u,v,s;
1148 long firstseed;
1149
1150};
1151
1153template <typename T, typename R>
1155 std::vector<T> &vec
1156 ,R &ran
1157){
1158
1159 size_t ran_t;
1160 if(vec.size() < 2) return;
1161 for (size_t i = vec.size()-1; i>0; --i) {
1162 ran_t = (size_t)(ran()*(i+1));
1163 //swap(tmp,vec[ran_t]);
1164 std::swap(vec[ran_t],vec[i]);
1165 //swap(vec[i],tmp);
1166 }
1167}
1168
1170template <typename T>
1171void sort_indexes(const std::vector<T> &v
1172 ,std::vector<size_t> &index
1173) {
1174
1175 // initialise original index locations
1176 index.resize(v.size());
1177 for (size_t i = 0; i != index.size(); ++i) index[i] = i;
1178
1179 // sort indexes based on comparing values in v
1180 std::sort(index.begin(), index.end(),[&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
1181}
1182
1183template <typename T>
1184void sort_indexes(const T *v
1185 ,std::vector<size_t> &index
1186 ,size_t N) {
1187
1188 // initialise original index locations
1189 index.resize(N);
1190
1191 for (size_t i = 0; i != index.size(); ++i) index[i] = i;
1192
1193 // sort indexes based on comparing values in v
1194 std::sort(index.begin(), index.end(),
1195 [v](size_t i1, size_t i2) {return v[i1] < v[i2];});
1196}
1197
1199template <typename T>
1200void sort_indexes_decending(const std::vector<T> &v
1201 ,std::vector<size_t> &index
1202) {
1203
1204 // initialise original index locations
1205 index.resize(v.size());
1206 for (size_t i = 0; i != index.size(); ++i) index[i] = i;
1207
1208 // sort indexes based on comparing values in v
1209 std::sort(index.begin(), index.end(),
1210 [&v](size_t i1, size_t i2) {return v[i1] > v[i2];});
1211}
1212
1218template <typename R>
1219class ShuffledIndex{
1220public:
1221 ShuffledIndex(size_t N,R &ran){
1222 if(N == 0) throw std::invalid_argument("N=0");
1223
1224 for(size_t i=0 ; i<N ; ++i) index[i] = i;
1225 index.resize(N);
1226 Utilities::shuffle(index,ran);
1227 index_internal = 0;
1228 }
1229
1231 size_t operator*(){return index[index_internal];}
1233 size_t operator++(int){
1234 size_t tmp = index[index_internal];
1235 if(index_internal == index.size()){
1236 index_internal = 0;
1237 }else{
1238 ++index_internal;
1239 }
1240 return tmp;
1241 }
1242
1243 size_t operator++(){
1244 if(index_internal == index.size()){
1245 index_internal = 0;
1246 }else{
1247 ++index_internal;
1248 }
1249 return index[index_internal];
1250 }
1251
1253 void reshuffle(R &ran){
1254 Utilities::shuffle(index,ran);
1255 index_internal = 0;
1256 }
1257
1258private:
1259 std::vector<size_t> index;
1260 size_t index_internal;
1261};
1262
1263
1264// reorders vec according to index p
1265template <typename T>
1266void apply_permutation(
1267 T *vec,
1268 const std::vector<std::size_t>& p)
1269{
1270 std::vector<T> copy(p.size());
1271
1272 for(std::size_t i = 0; i < p.size(); ++i){
1273 copy[i] = vec[i];
1274 }
1275
1276 for(std::size_t i = 0; i < p.size(); ++i){
1277 vec[i] = copy[p[i]];
1278 }
1279}
1280
1281template <typename T>
1282void apply_permutation(
1283 std::vector<T>& vec,
1284 const std::vector<std::size_t>& p)
1285{
1286 apply_permutation(vec.data(),p);
1287}
1288
1293void powerspectrum2d(
1294 std::valarray<double> const &aa
1295 ,std::valarray<double> const &bb
1296 ,long nx
1297 ,long ny
1298 ,double boxlx
1299 ,double boxly
1300 ,std::vector<double> &ll
1301 ,std::vector<double> &Pl
1302 ,double zeropaddingfactor
1303 );
1304
1305void powerspectrum2d(
1306 std::valarray<double> &aa
1307 ,long nx
1308 ,long ny
1309 ,double boxlx
1310 ,double boxly
1311 ,std::vector<double> &ll
1312 ,std::vector<double> &Pl
1313);
1314
1316 std::valarray<double> &aa
1317 ,long nx
1318 ,long ny
1319 ,double boxlx
1320 ,double boxly
1321 ,const std::vector<double> &ll
1322 ,std::vector<double> &Pl
1323 ,std::vector<double> &llave
1324);
1325
1326void powerspectrum2d(
1327 std::valarray<float> const &aa
1328 ,std::valarray<float> const &bb
1329 ,long nx
1330 ,long ny
1331 ,double boxlx
1332 ,double boxly
1333 ,std::vector<double> &ll
1334 ,std::vector<double> &Pl
1335 ,double zeropaddingfactor
1336 );
1337
1338void powerspectrum2d(
1339 std::valarray<float> &aa
1340 ,long nx
1341 ,long ny
1342 ,double boxlx
1343 ,double boxly
1344 ,std::vector<double> &ll
1345 ,std::vector<double> &Pl
1346);
1347
1349 std::valarray<float> &aa
1350 ,int nx
1351 ,int ny
1352 ,double boxlx
1353 ,double boxly
1354 ,const std::vector<double> &ll
1355 ,std::vector<double> &Pl
1356 ,std::vector<double> &llave
1357);
1358
1360int GetNThreads();
1361
1363namespace IO{
1364
1365inline bool file_exists (const std::string& name) {
1366 struct stat buffer;
1367 return (stat (name.c_str(), &buffer) == 0);
1368}
1369
1370 template <class T>
1372 std::string filename
1373 ,std::vector<T> &x
1374 ,int skiplines = 0
1375 ,bool verbose = false
1376 ){
1377
1378 x.clear();
1379
1380 std::ifstream file_in(filename.c_str());
1381 std::string myline;
1382 std::string space = " ";
1383 T myt1;
1384
1385 std::string strg;
1386 std::stringstream buffer;
1387
1388 if(!file_in){
1389 std::cout << "Can't open file " << filename << std::endl;
1390 ERROR_MESSAGE();
1391 throw std::runtime_error(" Cannot open file.");
1392 }
1393
1394 std::cout << "Reading from " << filename << std::endl;
1395 size_t i=0;
1396 while(i < skiplines){
1397 getline(file_in,myline);
1398 ++i;
1399 }
1400 while(file_in.peek() == '#'){
1401 file_in.ignore(10000,'\n');
1402 ++i;
1403 }
1404 std::cout << "skipped "<< i << " comment lines in " << filename << std::endl;
1405
1406 size_t pos;
1407 // read in data
1408 while(getline(file_in,myline)){
1409
1410 if(myline[0] == '#'){
1411 std::cout << "skipped line " << i << std::endl;
1412 continue;
1413 }
1414
1415 pos= myline.find_first_not_of(space);
1416 myline.erase(0,pos);
1417
1418 buffer << myline;
1419 buffer >> myt1;
1420 if(verbose) std::cout << myt1 << " ";
1421 x.push_back(myt1);
1422
1423 strg.clear();
1424 buffer.clear();
1425 myline.clear();
1426
1427 }
1428 std::cout << "Read " << x.size() << " lines from " << filename << std::endl;
1429 }
1430
1433template <class T1,class T2>
1435 std::string filename
1436 ,std::vector<T1> &x
1437 ,std::vector<T2> &y
1438 ,std::string delineator = " "
1439 ,int skiplines = 0
1440 ,bool verbose = false
1441
1442 ){
1443
1444 x.clear();
1445 y.clear();
1446
1447 std::ifstream file_in(filename.c_str());
1448 std::string myline;
1449 std::string space = " ";
1450 T1 myt1;
1451 T2 myt2;
1452
1453 std::string strg;
1454 std::stringstream buffer;
1455
1456 if(!file_in){
1457 std::cout << "Can't open file " << filename << std::endl;
1458 ERROR_MESSAGE();
1459 throw std::runtime_error(" Cannot open file.");
1460 }
1461
1462 std::cout << "Reading caustic information from " << filename << std::endl;
1463 size_t i=0;
1464 while(i < skiplines){
1465 getline(file_in,myline);
1466 ++i;
1467 }
1468 while(file_in.peek() == '#'){
1469 file_in.ignore(10000,'\n');
1470 ++i;
1471 }
1472 std::cout << "skipped "<< i << " comment lines in " << filename << std::endl;
1473
1474 size_t pos;
1475 // read in data
1476 while(getline(file_in,myline)){
1477
1478 if(myline[0] == '#'){
1479 std::cout << "skipped line " << i << std::endl;
1480 continue;
1481 }
1482
1483 pos= myline.find_first_not_of(space);
1484 myline.erase(0,pos);
1485
1486
1487 pos = myline.find(delineator);
1488 strg.assign(myline,0,pos);
1489 buffer << strg;
1490 buffer >> myt1;
1491 if(verbose) std::cout << myt1 << " ";
1492 x.push_back(myt1);
1493
1494 myline.erase(0,pos+1);
1495 pos= myline.find_first_not_of(space);
1496 myline.erase(0,pos);
1497
1498 strg.clear();
1499 buffer.clear();
1500
1501 pos = myline.find(space);
1502 strg.assign(myline,0,pos);
1503 buffer << strg;
1504 buffer >> myt2;
1505 if(verbose) std::cout << myt2 << std::endl;
1506 y.push_back(myt2);
1507
1508 strg.clear();
1509 buffer.clear();
1510 myline.clear();
1511
1512 }
1513 std::cout << "Read " << x.size() << " lines from " << filename << std::endl;
1514}
1515
1517template <class T1,class T2,class T3>
1519 std::string filename
1520 ,std::vector<T1> &x
1521 ,std::vector<T2> &y
1522 ,std::vector<T3> &z
1523 ,std::string delineator = " "
1524 ,bool verbose = false
1525
1526 ){
1527
1528
1529 assert(0); // Untested!!!!
1530 x.clear();
1531 y.clear();
1532 z.clear();
1533
1534 std::ifstream file_in(filename.c_str());
1535 std::string myline;
1536 std::string space = " ";
1537 T1 myt1;
1538 T2 myt2;
1539 T3 myt3;
1540
1541 std::string strg;
1542 std::stringstream buffer;
1543
1544 if(!file_in){
1545 std::cout << "Can't open file " << filename << std::endl;
1546 ERROR_MESSAGE();
1547 throw std::runtime_error(" Cannot open file.");
1548 }
1549
1550 std::cout << "Reading caustic information from " << filename << std::endl;
1551 size_t i=0;
1552 while(file_in.peek() == '#'){
1553 file_in.ignore(10000,'\n');
1554 ++i;
1555 }
1556 std::cout << "skipped "<< i << " comment lines in " << filename << std::endl;
1557
1558 size_t pos;
1559 // read in data
1560 while(getline(file_in,myline)){
1561
1562 if(myline[0] == '#'){
1563 std::cout << "skipped line " << i << std::endl;
1564 continue;
1565 }
1566
1567 pos= myline.find_first_not_of(space);
1568 myline.erase(0,pos);
1569
1570
1571 pos = myline.find(delineator);
1572 strg.assign(myline,0,pos);
1573 buffer << strg;
1574 buffer >> myt1;
1575 if(verbose) std::cout << myt1 << " ";
1576 x.push_back(myt1);
1577
1578 myline.erase(0,pos+1);
1579 pos= myline.find_first_not_of(space);
1580 myline.erase(0,pos);
1581
1582 strg.clear();
1583 buffer.clear();
1584
1585 // ******************
1586
1587
1588 pos = myline.find(space);
1589 strg.assign(myline,0,pos);
1590 buffer << strg;
1591 buffer >> myt2;
1592 if(verbose) std::cout << myt2 << std::endl;
1593 y.push_back(myt2);
1594
1595 myline.erase(0,pos+1);
1596 pos= myline.find_first_not_of(space);
1597 myline.erase(0,pos);
1598
1599 strg.clear();
1600 buffer.clear();
1601
1602 // ******************
1603 pos = myline.find(space);
1604 strg.assign(myline,0,pos);
1605 buffer << strg;
1606 buffer >> myt3;
1607 if(verbose) std::cout << myt3 << std::endl;
1608 y.push_back(myt3);
1609
1610 strg.clear();
1611 buffer.clear();
1612 myline.clear();
1613
1614 }
1615 std::cout << "Read " << x.size() << " lines from " << filename << std::endl;
1616}
1617
1618int NumberOfEntries(const std::string &string,char deliniator);
1619
1621int CountColumns(std::string filename
1622 ,char comment_char = '#'
1623 ,char deliniator = ' '
1624);
1625
1629void ReadFileNames(
1630 std::string dir
1631 ,const std::string filespec
1632 ,std::vector<std::string> & filenames
1633 ,bool verbose);
1634
1636bool check_directory(std::string dir);
1638bool make_directories(const std::string &root_dir);
1639
1640
1650template <typename T>
1651void ReadASCII(std::vector<T> &data
1652 ,std::string filename
1653 ,int &columns
1654 ,int &rows
1655 ,char comment_char = '#'
1656 ,int skiplines = 0
1657 ,size_t MaxNrows = std::numeric_limits<size_t>::max()
1658 ,bool verbose = true){
1659
1660 std::ifstream file(filename);
1661 // find number of particles
1662 if (!file.is_open()){
1663 std::cerr << "file " << filename << " cann't be opened." << std::endl;
1664 throw std::runtime_error("no file");
1665 }
1666
1667
1668 data.empty();
1669
1670 std::string line;
1671 columns = 0;
1672 rows = 0;
1673 size_t first_data_line;
1674
1675 // skip over first lines
1676 int i=0;
1677 while(i < skiplines){
1678 std::getline(file,line);
1679 if(!file) break; // probably EOF
1680 ++i;
1681 }
1682
1683 // read comment lines and first data line
1684 do{
1685 first_data_line = file.tellg();
1686 std::getline(file,line);
1687 if(!file) break; // probably EOF
1688 }while(line[0] == comment_char);
1689
1690 columns = NumberOfEntries(line,' ');
1691
1692 file.seekg(first_data_line); // move back to first data line
1693
1694 std::copy(std::istream_iterator<T>(file),
1695 std::istream_iterator<T>(),
1696 std::back_inserter(data));
1697
1698 rows = data.size()/columns;
1699 if(verbose){
1700 std::cout << "Read " << rows << " rows of " << columns << " columns from file " << filename << std::endl;
1701 }
1702}
1703
1720
1721template <typename T>
1722int ReadCSVnumerical1(std::string filename
1723 ,std::vector<std::vector<T> > &data
1724 ,std::vector<std::string> &column_names
1725 ,size_t MaxNumber = 100000000
1726 ,char comment_char = '#'
1727 ,char deliniator = ','
1728 ,std::string replace = "\\N"
1729 ,std::function<bool(std::vector<T> &)> accept = [](std::vector<T> &v){return true;}
1730 ){
1731
1732 bool verbose = false;
1733
1734 std::ifstream file(filename);
1735 // find number of particles
1736 if (!file.is_open()){
1737 std::cerr << "file " << filename << " cann't be opened." << std::endl;
1738 throw std::runtime_error("no file");
1739 }
1740
1741 int count_preamble=0;
1742 std::string line;
1743 // read comment lines and first data line
1744 do{
1745 std::getline(file,line);
1746 ++count_preamble;
1747 if(!file) break; // probably EOF
1748 }while(line[0] == comment_char);
1749
1750 // read the names
1751 std::stringstream lineStream(line);
1752 std::string cell;
1753 column_names.empty();
1754 while(std::getline(lineStream,cell, deliniator))
1755 {
1756 column_names.push_back(cell);
1757 }
1758 // This checks for a trailing comma with no data after it.
1759 if (!lineStream && cell.empty())
1760 {
1761 column_names.push_back("");
1762 }
1763
1764 if(verbose){ // print column names
1765 int i = 0;
1766 for(auto st : column_names){
1767 std::cout << i++ << " " << st << std::endl;
1768 }
1769 }
1770
1771 int ncolumns = NumberOfEntries(line,deliniator);
1772
1773 // check if any of the columns are strings
1774 std::getline(file,line);
1775 {
1776 size_t n=0,m = 0,i=0;
1777 do{
1778 m = line.find(",",n);
1779 cell = line.substr(n,m-n);
1781 cell.erase(remove_if(cell.begin(),cell.end(), isspace), cell.end());
1782 n = m+1;
1783 ++i;
1784 }while(m != std::string::npos);
1785 }
1786
1787 // count number of data line
1788 size_t number_of_data_lines = 1;
1789 while(std::getline(file, line) && number_of_data_lines < MaxNumber ) ++number_of_data_lines;
1790
1791 //std::vector<std::vector<T> > tmp_data(columns,std::vector<T>(number_of_data_lines));
1792 std::vector<std::vector<T> > tmp_data(ncolumns,std::vector<T>(0));
1793 swap(data,tmp_data);
1794 std::vector<T> tmp_row(ncolumns);
1795
1797 //file.seekg(std::ios::beg);
1798 file.clear();
1799 file.close();
1800 file.open(filename);
1801 for(int i=0; i < count_preamble; ++i){
1802 file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
1803 }
1804
1805 size_t rows = 0;
1806 while(std::getline(file,line) && rows < MaxNumber){
1807 // read the names
1808 std::stringstream lineStream(line);
1809 std::string cell;
1810
1811 int i=0;
1812 while(std::getline(lineStream,cell,deliniator))
1813 {
1814 if(cell==replace) cell='0';
1815
1817 cell.erase(remove_if(cell.begin(),cell.end(), isspace), cell.end());
1818 //data[i].push_back(to_numeric<T>(cell));
1819 //data[i][rows] = to_numeric<T>(cell);
1820 tmp_row[i] = to_numeric<T>(cell);
1821 i = (i+1)%ncolumns;
1822 }
1823 if(accept(tmp_row)){
1824 ++rows;
1825 for(int i=0 ; i < ncolumns ; ++i) data[i].push_back(tmp_row[i]);
1826 }
1827 }
1828 return 1;
1829}
1830
1834
1835template <typename T>
1836size_t ReadCSVrange(std::string filename
1837 ,std::vector<std::vector<T> > &ranges
1838 ,std::vector<std::string> &column_names
1839 ,size_t MaxNumber = 100000000
1840 ,char comment_char = '#'
1841 ,char deliniator = ','
1842 ,std::string replace = "\\N"
1843 ,std::function<bool(std::vector<T> &)> accept = [](std::vector<T> &v){return true;}
1844){
1845
1846 bool verbose = false;
1847
1848 std::ifstream file(filename);
1849 // find number of particles
1850 if (!file.is_open()){
1851 std::cerr << "file " << filename << " cann't be opened." << std::endl;
1852 throw std::runtime_error("no file");
1853 }
1854
1855 int count_preamble=0;
1856 std::string line;
1857 // read comment lines and first data line
1858 do{
1859 std::getline(file,line);
1860 ++count_preamble;
1861 if(!file) break; // probably EOF
1862 }while(line[0] == comment_char);
1863
1864 // read the names
1865 std::stringstream lineStream(line);
1866 std::string cell;
1867 column_names.empty();
1868 while(std::getline(lineStream,cell, ','))
1869 {
1870 column_names.push_back(cell);
1871 }
1872 // This checks for a trailing comma with no data after it.
1873 if (!lineStream && cell.empty())
1874 {
1875 column_names.push_back("");
1876 }
1877
1878 if(verbose){ // print colum names
1879 int i = 0;
1880 for(auto st : column_names){
1881 std::cout << i++ << " " << st << std::endl;
1882 }
1883 }
1884
1885 int columns = NumberOfEntries(line,deliniator);
1886
1887 std::vector<std::vector<T> > tmp_ranges(columns,std::vector<T>(2));
1888 swap(ranges,tmp_ranges);
1889 std::vector<T> tmp_row(columns);
1890
1892 //file.seekg(std::ios::beg);
1893 file.clear();
1894 file.close();
1895 file.open(filename);
1896 for(int i=0; i < count_preamble; ++i){
1897 file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
1898 }
1899 //std::getline(file,line);
1900
1901 size_t rows = 0;
1902 while(std::getline(file,line) && rows < MaxNumber){
1903 // read the names
1904 std::stringstream lineStream(line);
1905 std::string cell;
1906
1907 int i=0;
1908 while(std::getline(lineStream,cell,deliniator))
1909 {
1910 if(cell==replace) cell='0';
1911
1913 cell.erase(remove_if(cell.begin(),cell.end(), isspace), cell.end());
1914 tmp_row[i] = to_numeric<T>(cell);
1915 i = (i+1)%columns;
1916 }
1917 if(accept(tmp_row)){
1918 if(rows==0){
1919 for(int j=0 ; j < columns ; ++j){
1920 ranges[j][0] = tmp_row[j];
1921 ranges[j][1] = tmp_row[j];
1922
1923 }
1924 }else{
1925 for(int j=0 ; j < columns ; ++j){
1926 if(ranges[j][0] > tmp_row[j]) ranges[j][0] = tmp_row[j];
1927 if(ranges[j][1] < tmp_row[j]) ranges[j][1] = tmp_row[j];
1928 }
1929 }
1930 ++rows;
1931 }
1932 }
1933 return rows;
1934}
1935
1950
1951template <typename T>
1952int ReadCSVnumerical2(std::string filename
1953 ,std::vector<std::vector<T> > &data
1954 ,std::vector<std::string> &column_names
1955 ,size_t Nmax = 1000000
1956 ,char comment_char = '#'
1957 ,char deliniator = ','
1958 ,bool header = true
1959 ,std::string reject = ""
1960){
1961
1962
1963 std::ifstream file(filename);
1964
1965 if (!file.is_open()){
1966 std::cerr << "file " << filename << " cann't be opened." << std::endl;
1967 throw std::runtime_error("no file");
1968 }
1969 std::string line;
1970 // read comment lines and first data line
1971 do{
1972 std::getline(file,line);
1973 if(!file) break; // probably EOF
1974 }while(line[0] == comment_char);
1975
1976 // read the names
1977 std::stringstream lineStream(line);
1978 std::string cell;
1979 column_names.empty();
1980 long ii = 0;
1981
1982 if(header){
1983 while(std::getline(lineStream,cell,deliniator))
1984 {
1985 column_names.push_back(cell);
1986 }
1987
1988 // This checks for a trailing comma with no data after it.
1989 if (!lineStream && cell.empty())
1990 {
1991 column_names.push_back("");
1992 }
1993 }else{
1994
1995 while(std::getline(lineStream,cell,deliniator))
1996 {
1997 column_names.push_back(cell);
1998 }
1999
2000 data.emplace_back(column_names.size());
2001 int i=0;
2002 for(auto a : column_names){
2004 cell.erase(remove_if(cell.begin(),cell.end(), isspace), cell.end());
2005 data.back()[i++] = to_numeric<T>(a);
2006 }
2007 ++ii;
2008 }
2009
2010 int columns = NumberOfEntries(line,deliniator);
2011
2012 for(auto &v : data ) v.empty();
2013
2014 while(std::getline(file,line) && ii < Nmax){
2015
2016 data.emplace_back(columns);
2017
2018 // read the numbers
2019 std::stringstream lineStream(line);
2020 std::string cell;
2021
2022 int i=0;
2023 while(std::getline(lineStream,cell, deliniator))
2024 {
2025 assert(i < columns);
2026 cell.erase(remove_if(cell.begin(),cell.end(), isspace), cell.end());
2027 if(cell == reject){
2028 data.pop_back();
2029 --ii;
2030 break;
2031 }else{
2032 data.back()[i] = to_numeric<T>(cell);
2033 ++i;
2034 }
2035 }
2036 ++ii;
2037 }
2038
2039 return 1;
2040}
2041
2059
2060template<typename T>
2061void writeCSV(const std::string filename
2062 ,const std::vector<std::string> header
2063 ,std::vector<T *> &data
2064){
2065
2066 std::ofstream s(filename + ".csv");
2067
2068 long ncol = header.size();
2069 assert(ncol == data.size() );
2070 for(int i = 0 ; i < header.size()-1 ; ++i){
2071 s << header[i] << ",";
2072 }
2073 s << header.back() << std::endl;
2074
2075 size_t nrow = data[0]->size();
2076 for(auto v : data) assert(nrow == v->size() );
2077
2078 for(size_t j = 0 ; j < nrow ; ++j){
2079 for(int i = 0 ; i < ncol-1 ; ++i){
2080 s << data[i]->operator[](j) << ",";
2081 }
2082 s << data.back()->operator[](j) << "\n";
2083 }
2084}
2085
2086/*** \brief A class for reading and then looking up objects from a CSV catalog.
2087
2088 The constructor will read in the whole catalog and sort it into Nxbins X-bins. Each
2089 X-bin is then sorted by Y.
2090
2091 The find(x,y) function will set the current value to a galaxy with a x within the
2092 x-bin of x and a y close to y. The other information in the row of the csv file for
2093 this entry can then be read.
2094
2095 */
2096class XYcsvLookUp{
2097public:
2098 XYcsvLookUp(std::string datafile
2099 ,std::string Xlabel
2100 ,std::string Ylabel
2101 ,int Nxbins
2102 ,size_t MaxNumber = 1000000
2103 ,bool verbose = false);
2104 XYcsvLookUp(
2105 std::string datafile
2106 ,std::string Xlabel
2107 ,std::string Ylabel
2108 ,std::vector<double> Xbins
2109 ,size_t MaxNumber = 1000000
2110 ,bool verbose = false);
2111
2113 std::vector<double> find(double x,double y);
2114
2116 double operator[](std::string label) const;
2117
2119 double operator[](int i) const{
2120 return (*current)[i];
2121 }
2123 double getX() const {
2124 return (*current)[Xindex];
2125 }
2127 double getY() const {
2128 return (*current)[Yindex];
2129 }
2131 std::vector<double> record() const{
2132 return *current;
2133 }
2135 std::vector<double> operator*() const {
2136 return *current;
2137 }
2138
2139 void operator++(){
2140 if(current != data.end() ) ++current;
2141 }
2142 void operator--(){
2143 if(current != data.begin() ) --current;
2144 }
2146 std::vector<std::string> labels() const{
2147 return column_names;
2148 }
2149
2150 double Xmin() const {return xmin;}
2151 double Xmax() const {return xmax;}
2153 double Ymin(double x) const;
2155 double Ymax(double x) const;
2156
2157 void printcurrent(){
2158 int i = 0;
2159 for(auto label : column_names){
2160 std::cout << label << " : " << (*current)[i++] << std::endl;
2161 }
2162 }
2163
2164private:
2165 int Xindex;
2166 int Yindex;
2167 double xmax;
2168 double xmin;
2169 std::vector<std::vector<double> >::iterator current;
2170 std::vector<std::vector<std::vector<double> >::iterator> borders;
2171 std::vector<std::vector<double> > data;
2172 std::vector<std::string> column_names;
2173 std::vector<double> Xborders;
2174 size_t NinXbins;
2175 std::string filename;
2176};
2177} // Utilities::IO
2178
2180void splitstring(std::string &line,std::vector<std::string> &vec,const std::string &delimiter);
2181
2190template< typename T>
2192public:
2193 DataFrame(std::string datafile
2194 ,size_t MaxNumber = 1000000
2195 ,char comment_char = '#'
2196 ,char deliniator = ','
2197 ,std::string replace = "\\N"
2198 ,std::function<bool(std::vector<T> &)> accept = [](std::vector<T> &v){return true;}
2199 ):filename(datafile){
2200 input(datafile,MaxNumber,comment_char,deliniator,replace,accept);
2201 };
2202
2203 DataFrame(){};
2204
2205 void input(std::string datafile
2206 ,size_t MaxNumber = 1000000
2207 ,char comment_char = '#'
2208 ,char deliniator = ','
2209 ,std::string replace = "\\N"
2210 ,std::function<bool(std::vector<T> &)> accept = [](std::vector<T> &v){return true;}
2211 ){
2212 filename = datafile;
2213 Utilities::IO::ReadCSVnumerical1(datafile,data,column_names,MaxNumber,'#',',',replace,accept);
2214 for(int i=0 ; i<column_names.size() ; ++i) datamap[column_names[i]] = i;
2215 };
2216
2218 void pop(std::string colname){
2219
2220 int i=datamap[colname];
2221
2222 swap(column_names[i],column_names.back());
2223 column_names.pop_back();
2224 swap(data[i],data.back());
2225 data.pop_back();
2226
2227 datamap.empty();
2228 for(int i=0 ; i<column_names.size() ; ++i) datamap[column_names[i]] = i;
2229 }
2230
2232 std::vector<T>& operator[](const std::string &label){
2233 if(datamap.find(label) == datamap.end()){
2234 std::cerr << "No label - " << label << " - in " << filename <<std::endl;
2235 throw std::invalid_argument("no label");
2236 }
2237 return data[datamap[label]];
2238 //for(auto c : column_names ) std::cout << c << " ";
2239 //std::cout << std::endl;
2240 //throw std::invalid_argument(label + " was not one of the columns of the galaxy data file :" + filename);
2241 };
2242
2244 void add_column(const std::string &name,const std::vector<T> &vec){
2245 if(vec.size() != data[0].size()){
2246 std::cerr << "Added column to DataFrame needs to have the same size." << std::endl;
2247 throw std::invalid_argument("wrong size");
2248 }
2249 column_names.push_back(name);
2250 data.push_back(vec);
2251 data[name] = data.size()-1;
2252 };
2253
2255 std::vector<T>& operator[](int i){
2256 return data[i];
2257 };
2258
2260 std::vector<std::string> labels() const{
2261 return column_names;
2262 };
2263
2264 // sort by one of the columns
2265 void sortby(std::string name){
2266 std::vector<size_t> index(data[0].size());
2267 size_t N = index.size();
2268 for(size_t i=0 ; i<N ; ++i) index[i] = i;
2269
2270 sort_indexes(data[datamap[name]],index);
2271 std::vector<T> tmp_v(N);
2272
2273 for(size_t j=0 ; j<data.size() ; ++j){
2274 for(size_t i=0 ; i<N ; ++i){
2275 tmp_v[i] = data[j][index[i]];
2276 }
2277 swap(data[j],tmp_v);
2278 }
2279 }
2280
2281 // shuffle order of rows
2282 void shuffle(Utilities::RandomNumbers_NR &ran){
2283 std::vector<size_t> index(data[0].size());
2284 size_t N = index.size();
2285 for(size_t i=0 ; i<N ; ++i) index[i] = i;
2286 Utilities::shuffle(index, ran);
2287
2288 std::vector<T> tmp_v(N);
2289
2290 for(size_t j=0 ; j<data.size() ; ++j){
2291 for(size_t i=0 ; i<N ; ++i){
2292 tmp_v[i] = data[j][index[i]];
2293 }
2294 swap(data[j],tmp_v);
2295 }
2296 }
2297
2298 size_t number_of_rows(){return data[0].size();}
2299 size_t number_of_columns(){return data.size();}
2300
2301 std::vector<std::vector<T> > data;
2302private:
2303 std::map<std::string,int> datamap;
2304 std::vector<std::string> column_names;
2305 std::string filename;
2306};
2307
2308// this is a summation algorithm that maintains percision for large sequences of numbers
2309template <typename T>
2310double KleinSum(std::vector<T> &input){
2311 double s = 0.0,cs = 0.0,ccs = 0.0,c,cc;
2312 size_t n = input.size();
2313 for(size_t i = 0 ; i<n ; ++i){
2314 double t = s + input[i];
2315 if( abs(s) >= abs(input[i]) ){
2316 c = (s - t) + input[i];
2317 }else{
2318 c = (input[i] - t) + s;
2319 }
2320 s = t;
2321 t = cs + c;
2322 if( abs(cs) >= abs(c) ){
2323 cc = (cs - t) + c;
2324 }else{
2325 cc = (c - t) + cs;
2326 }
2327 cs = t;
2328 ccs = ccs + cc;
2329 }
2330 return s + cs + ccs;
2331}
2332
2333
2334template <typename T,typename F>
2335double PairWiseSum(T *begin,T *end,F value){
2336 double sum = 0;
2337 size_t n = end - begin;
2338 if(n <= 10){
2339 for(T* p=begin ; p != end ; ++p){
2340 sum += value(p);
2341 }
2342 }else{
2343 sum = PairWiseSum<T,F>(begin,begin + n/2,value) + PairWiseSum<T,F>(begin + n/2,end,value);
2344 }
2345 return sum;
2346}
2347
2349template <typename T>
2350double PairWiseSum(T *begin,T *end){
2351 double sum = 0;
2352 size_t n = end - begin;
2353 if(n <= 10){
2354 for(T* p=begin ; p != end ; ++p){
2355 sum += *p;
2356 }
2357 }else{
2358 sum = PairWiseSum(begin,begin + n/2) + PairWiseSum(begin + n/2,end);
2359 }
2360 return sum;
2361}
2362
2364template <typename T>
2365double PairWiseSum(std::vector<T> &v){
2366 return PairWiseSum(v.data(),v.data() + v.size());
2367}
2368
2370template <typename T,typename F>
2371double PairWiseSum(std::vector<T> &v,F value){
2372 return PairWiseSum(v.data(),v.data() + v.size(),value);
2373}
2374
2376template <typename T>
2377class SUMMER{
2378
2379public:
2380
2381 SUMMER():batch(1000),n(0),ntotal(0),current(0.0){};
2382 SUMMER(size_t batchsize)
2383 :batch(batchsize),n(0),current(0.0),ntotal(0){};
2384
2386 void operator+=(T x){
2387 ++n;
2388 current += x;
2389 ++ntotal;
2390 if(n % batch == 0){
2391 v.push_back(current);
2392 n=0;
2393 current = 0;
2394 }
2395 }
2396
2399 if(v.size() ==0 ) return 0;
2400 v.push_back(current);
2401 return Utilities::PairWiseSum(v);
2402 }
2403
2405 void reset(){
2406 std::vector<T> dump;
2407 std::swap(v,dump);
2408 n = ntotal = 0;
2409 current = 0;
2410 }
2411
2414 return ntotal;
2415 }
2416
2417private:
2418 size_t batch;
2419 size_t n;
2420 size_t ntotal;
2421 T current;
2422 std::vector<T> v;
2423};
2424
2425/*
2426This is 1F2(a,b,c:x)
2427
2428 Note convergence restrictions: abs(x) < 1 and c not a negative integer or zero
2429*/
2430template <typename T = double>
2431double hypergeometric( T a, T b, T c, T x )
2432{
2433
2434 if(abs(x) > 1 ){
2435 throw std::invalid_argument("out of bounds");
2436 }
2437 const double TOLERANCE = 1.0e-10;
2438 double term = a * b * x / c;
2439 double value = 1.0 + term;
2440 int n = 1;
2441
2442 while ( abs( term ) > TOLERANCE )
2443 {
2444 a++, b++, c++, n++;
2445 term *= a * b * x / c / n;
2446 value += term;
2447 }
2448
2449 return value;
2450}
2451
2452class LOGPARAMS{
2453
2454public:
2455 typedef boost::variant<int,size_t,long,float,double,std::string,bool> MULTITYPE;
2456 typedef std::map<std::string,MULTITYPE> LINE;
2457 typedef std::map<std::string,std::vector<double> > VLINE;
2458 typedef std::map<std::string,std::vector<bool> > BLINE;
2459
2460private:
2461 time_t to;
2462
2463 LINE lines;
2464 VLINE vlines;
2465 BLINE blines;
2466 std::string filename;
2467 std::string blanck_val;
2468public:
2469
2470 LOGPARAMS(std::string file,std::string blanck_value = "0"):filename(file),blanck_val(blanck_value){
2471 time(&to);
2472 };
2473
2474 ~LOGPARAMS(){
2475 print_file(filename);
2476 }
2477
2478 void operator()(std::string label,MULTITYPE v){lines[label] = v;}
2479 void operator()(std::string label,const std::vector<double> &v){vlines[label] = v;}
2480 void operator()(std::string label,const std::vector<bool> &v){blines[label] = v;}
2481 void operator()(std::string label){lines[label] = "-----";}
2482
2483
2484 MULTITYPE operator[](std::string label){return lines[label];}
2485 void setlogfile(std::string name){filename = name;}
2486
2487 void print(){
2488 for(auto a : lines){
2489 std::cout << std::left << std::setw(25) << a.first << " " << a.second << std::endl;
2490 }
2491 for(auto a : vlines){
2492 std::cout << std::left << std::setw(25) << a.first << " : ";
2493 for(double x : a.second ) std::cout << x << " ";
2494 std::cout << std::endl;
2495 }
2496 for(auto a : blines){
2497 std::cout << std::left << a.first << " : ";
2498 for(double x : a.second ) std::cout << x << " ";
2499 std::cout << std::endl;
2500 }
2501 time_t now = time(0);
2502 std::cout << "log has existed for " << difftime(now,to)/60 << " min" << std::endl;
2503 }
2504
2505 void print_to_file(){
2506 print_file(filename);
2507 }
2508
2509 void print_file(std::string filename){
2510 //printrow(std::cout, it->first, it->second, comment->second);
2511
2512 std::ofstream logfile(filename);
2513 time_t now = time(0);
2514 struct tm date = *localtime(&now);
2515 logfile << date.tm_hour << ":" << date.tm_min << " " << date.tm_mday << "/" << date.tm_mon << "/" << date.tm_year + 1900 << std::endl;
2516 logfile << "log has existed for " << difftime(now,to)/60 << " min" << std::endl;
2517 for(auto a : lines){
2518 logfile << std::left << std::setw(23) << a.first << " " << a.second << std::endl;
2519 }
2520 for(auto a : vlines){
2521 logfile << std::left << std::setw(23) << a.first << " : ";
2522 for(double x : a.second ) logfile << x << " ";
2523 logfile << std::endl;
2524 }
2525 for(auto a : blines){
2526 logfile << std::left << a.first << " : ";
2527 for(double x : a.second ) logfile << x << " ";
2528 logfile << std::endl;
2529 }
2530 }
2531
2532};
2533
2534
2535class LOGDATA{
2536
2537public:
2538 typedef boost::variant<int,long,size_t,float,double,std::string,bool> MULTITYPE;
2539 typedef std::map<std::string,MULTITYPE> LINE;
2540
2541private:
2542 std::vector<LINE> lines;
2543 std::string filename;
2544 std::string blank_val;
2545 std::vector<std::string> header;
2546 long nbatch;
2547 int precision;
2548 long last_line_printed;
2549 long nlabels;
2550 std::set<std::string> labels;
2551
2552 std::map<std::string,std::string> label_comments;
2553
2554 long nprints;
2555
2556 void append_file(){
2557
2558 const long default_precision = std::cout.precision();
2559 std::ofstream logfile;
2560 logfile.open(filename,std::ios_base::app);
2561
2562 size_t n=labels.size();
2563 if(n == nlabels && last_line_printed > 0){
2564 std::cout << std::setprecision(precision);
2565 for(size_t j=last_line_printed ; j<lines.size() ; ++j ){
2566 int i=0;
2567 for(auto &label : labels){
2568 try{
2569 if(label == "ID"){
2570 logfile << std::setprecision(17) << lines[j].at(label);
2571 std::cout << std::setprecision(precision);
2572 }else if(label == "RA" || label == "DEC" ){
2573 logfile << std::setprecision(8) << lines[j].at(label) ;
2574 std::cout << std::setprecision(precision);
2575 }else{
2576 logfile << std::setprecision(precision) << lines[j].at(label) ;
2577 }
2578 if(i<n-1) logfile << ",";
2579 }catch(std::exception& e){
2580 logfile << std::setprecision(precision) << blank_val ;
2581 if(i<n-1) logfile << ",";
2582 }
2583 ++i;
2584 }
2585 logfile << std::endl;
2586 }
2587 std::cout << std::setprecision(default_precision);
2588
2589 last_line_printed = lines.size();
2590 }else{
2591 // number of labels has changed print from the beginning
2592 print_to_file();
2593 }
2594 }
2595
2596public:
2597
2598 LOGDATA(std::string file
2599 ,std::string blanck_value = "0"
2600 ,long Nbatch=1000
2601 ):filename(file),blank_val(blanck_value)
2602 ,nbatch(Nbatch),precision(std::cout.precision())
2603 ,last_line_printed(0),nlabels(0),nprints(0){
2604 print_to_file();
2605 };
2606
2607 ~LOGDATA(){print_to_file();}
2608
2609 std::string output_file(){return filename;}
2610
2611 void set_precision(int p){
2612 precision = p;
2613 }
2614
2615 // current number of columns
2616 size_t ncol(){return labels.size();}
2617 // names of columns
2618 std::set<std::string> names = labels;
2619
2620 void print_to_file(){
2621
2622 const int default_precision = std::cout.precision();
2623 //std::cout << std::setprecision(12);
2624
2625 if(lines.size() == 0 ) return;
2626
2627 std::ofstream logfile(filename);
2628
2629 time_t now = time(0);
2630 struct tm date = *localtime(&now);
2631 logfile << "# " << date.tm_hour << ":" << date.tm_min << " " << date.tm_mday << "/" << date.tm_mon << "/" << date.tm_year + 1900 << std::endl;
2632 for(std::string &s : header){
2633 logfile << "# " << s << std::endl;
2634 }
2635
2636 // print comments on labels
2637 {
2638 int i=1;
2639 for(auto &label : labels){
2640 auto it = label_comments.find(label);
2641 if(it == label_comments.end() ){
2642 logfile << "# " << i << " " << label << " : no comment" << std::endl;
2643 }else{
2644 logfile << "# " << i << " " << it->first << " : " << it->second << std::endl;
2645 }
2646 ++i;
2647 }
2648 }
2649 size_t i=0;
2650 nlabels = labels.size();
2651 for(auto &label : labels){
2652 logfile << label;
2653 if(i<nlabels-1) logfile << ",";
2654 ++i;
2655 }
2656 logfile << std::endl;
2657
2658 std::cout << std::setprecision(precision);
2659 for(LINE &line : lines){
2660 i=0;
2661 for(auto &label : labels){
2662 try{
2663 if(label == "ID"){
2664 logfile << std::setprecision(17) << line.at(label) ;
2665 std::cout << std::setprecision(precision);
2666 }else if(label == "RA" || label == "DEC" ){
2667 logfile << std::setprecision(8) << line.at(label) ;
2668 std::cout << std::setprecision(precision);
2669 }else{
2670 logfile << std::setprecision(precision) << line.at(label);
2671 }
2672 if(i<nlabels-1) logfile << ",";
2673 }catch(std::exception& e){
2674 logfile << std::setprecision(precision) << blank_val;
2675 if(i<nlabels-1) logfile << ",";
2676 }
2677 ++i;
2678 }
2679 logfile << std::endl;
2680 }
2681 std::cout << std::setprecision(default_precision);
2682
2683 last_line_printed = lines.size();
2684 ++nprints;
2685 }
2686
2688 void add(const LINE &line){
2689 for (auto itr = line.begin(); itr != line.end(); ++itr) labels.insert(itr->first);
2690 lines.push_back(line);
2691 if(lines.size() % nbatch == 0) append_file();
2692 }
2693
2695 void replace(const LINE &line){
2696 for (auto itr = line.begin(); itr != line.end(); ++itr) labels.insert(itr->first);
2697 lines.back() = line;
2698 }
2699
2701 void header_comment(const std::string &s){
2702 header.push_back(s);
2703 }
2704
2706 void label_description(const std::string &name
2707 ,const std::string &description
2708 ){
2709 label_comments[name] = description;
2710 }
2711};
2712
2713// /// alternative to std::thread that counts threads
2714// template<class Function, class ... Args >
2715// class MyThread
2716// {
2717// private:
2718// std::thread thread_;
2719//
2720// static long count;
2721// static long unjoined;
2722//
2723// public:
2724// MyThread(Function&& f,Args&&... args)
2725// {
2726// if(count > 20) throw std::runtime_error("too many threads");
2727// thread_ = std::thread(std::forward<Function>(f),std::forward<Args>(args)...);
2728// ++count;
2729// ++unjoined;
2730// }
2731//
2732// ~MyThread(){
2733// --count;
2734// }
2735//
2736// void join(){
2737// thread_.join();
2738// --unjoined;
2739// }
2740//
2741//
2742// };
2743
2744
2749
2750template <typename T>
2751std::valarray<T> AdaptiveSmooth(const std::valarray<T> &map_in,size_t Nx,size_t Ny,T value){
2752
2753 std::valarray<T> map_out(map_in.size());
2754 long r,area;
2755 T val;
2756 for(long i=0;i<Nx;++i){
2757 for(long j=0;j<Ny;++j){
2758 r = 0;
2759 val = map_in[i+j*Nx];
2760 while(val < value && r < std::min(Nx, Ny) ){
2761
2762 area = 0;
2763 val = 0;
2764 long imin,imax,jmin,jmax;
2765
2766 imin = (i-r < 0) ? 0 : i-r;
2767 imax = (i+r > Nx-1) ? Nx-1 : i+r;
2768
2769 jmin = (j-r < 0) ? 0 : j-r;
2770 jmax = (j+r > Ny-1) ? Ny-1 : j+r;
2771
2772
2773 for(long ii=imin;ii<=imax;++ii){
2774 for(long jj=jmin;jj<=jmax;++jj){
2775 if( (ii-i)*(ii-i) + (jj-j)*(jj-j) < r){
2776 val += map_in[ii+jj*Nx];
2777 ++area;
2778 }
2779 }
2780 }
2781 ++r;
2782 }
2783
2784 map_out[i+j*Nx] = val/area;
2785 }
2786 }
2787
2788 return map_out;
2789 }
2790} // Utilities
2791
2792//#endif
2793
2794
2795#endif
std::vector< T > & operator[](const std::string &label)
returns column by name
Definition utilities_slsim.h:2232
void input(std::string datafile, size_t MaxNumber=1000000, char comment_char='#', char deliniator=',', std::string replace="\\N", std::function< bool(std::vector< T > &)> accept=[](std::vector< T > &v){return true;})
Definition utilities_slsim.h:2205
std::vector< T > & operator[](int i)
returns column by number
Definition utilities_slsim.h:2255
std::vector< std::string > labels() const
returns labels of the columns from the data file
Definition utilities_slsim.h:2260
void pop(std::string colname)
remove a column
Definition utilities_slsim.h:2218
void add_column(const std::string &name, const std::vector< T > &vec)
add a column to the data frame. This does a copy.
Definition utilities_slsim.h:2244
DataFrame(std::string datafile, size_t MaxNumber=1000000, char comment_char='#', char deliniator=',', std::string replace="\\N", std::function< bool(std::vector< T > &)> accept=[](std::vector< T > &v){return true;})
Definition utilities_slsim.h:2193
HilbertCurve(PosType x_min, PosType y_min, PosType my_range, PosType smallsize)
Definition utilities_slsim.h:1005
int xy2d(int x, int y)
convert (x,y) to d
Definition utilities.cpp:291
void d2xy(int d, int *x, int *y)
convert d to (x,y)
Definition utilities.cpp:303
BaseT * at(std::size_t i)
indexed access with bounds checking
Definition utilities_slsim.h:860
friend void swap(MixedVector< BaseT * > &a, MixedVector< BaseT * > &b)
swap two MixedVectors
Definition utilities_slsim.h:704
void push_back(BaseT *obj)
add an object of type SubclassT to the vector, this does not copy the object but will delete is when ...
Definition utilities_slsim.h:733
const SubclassT * get(std::size_t i) const
indexed access for type SubclassT (const)
Definition utilities_slsim.h:851
SubclassT * at(std::size_t i)
Templated indexing operator for elements of a specific derived class. The index runs 0 ....
Definition utilities_slsim.h:876
std::size_t size() const
number of elements of a specific type
Definition utilities_slsim.h:902
bool type(std::size_t i)
Checks if element i is of the derived type SubclassT.
Definition utilities_slsim.h:816
void clear()
clear all elements of a given type
Definition utilities_slsim.h:793
iterator< SubclassT > end()
get iterator to last of items of type SubclassT
Definition utilities_slsim.h:951
void pop_back()
pop element from back of vector
Definition utilities_slsim.h:746
void pop_back()
erase the last element of a specific type
Definition utilities_slsim.h:762
void clear()
clear all elements
Definition utilities_slsim.h:786
iterator begin()
get iterator to first of all items
Definition utilities_slsim.h:928
iterator end()
get iterator to last of all items
Definition utilities_slsim.h:934
const SubclassT * at(std::size_t i) const
Templated indexing operator for elements of a specific derived class (const).
Definition utilities_slsim.h:886
BaseT * get(std::size_t i)
indexed access
Definition utilities_slsim.h:828
std::size_t size() const
number of all elements
Definition utilities_slsim.h:895
MixedVector()
default constructor
Definition utilities_slsim.h:687
BaseT ** data()
direct access to underlying array
Definition utilities_slsim.h:803
const BaseT * at(std::size_t i) const
indexed access with bounds checking (const)
Definition utilities_slsim.h:866
BaseT & back()
back of list
Definition utilities_slsim.h:721
BaseT * operator[](std::size_t i) const
Indexing operator for all elements in form of a reference to the base class.
Definition utilities_slsim.h:822
const BaseT & back() const
back of list
Definition utilities_slsim.h:727
const BaseT * get(std::size_t i) const
indexed access (const)
Definition utilities_slsim.h:834
SubclassT * get(std::size_t i)
indexed access for type SubclassT
Definition utilities_slsim.h:841
const BaseT ** data() const
direct access to underlying array (const)
Definition utilities_slsim.h:809
~MixedVector()
destroy the vector and all contained items
Definition utilities_slsim.h:698
bool empty() const
check if vector of items of type SubclassT is empty
Definition utilities_slsim.h:918
MixedVector< BaseT * > & operator=(MixedVector< BaseT * > rhs)
assign one MixedVector to another
Definition utilities_slsim.h:713
iterator< SubclassT > begin()
get iterator to first of items of type SubclassT
Definition utilities_slsim.h:941
bool empty() const
check if vector of items is empty
Definition utilities_slsim.h:911
MixedVector(const MixedVector< BaseT * > &other)
copy constructor
Definition utilities_slsim.h:692
A container that can hold mixed objects all derived from a base class and retains the ability to acce...
Definition utilities_slsim.h:272
void pop_back()
erase the last element of a specific type
Definition utilities_slsim.h:396
bool empty() const
check if vector of items of type SubclassT is empty
Definition utilities_slsim.h:572
MixedVector()
default constructor
Definition utilities_slsim.h:333
std::size_t size() const
number of all elements
Definition utilities_slsim.h:549
MixedVector< BaseT > & operator=(MixedVector< BaseT > rhs)
assign one MixedVector to another
Definition utilities_slsim.h:353
const BaseT & operator[](std::size_t i) const
Indexing operator for all elements (const).
Definition utilities_slsim.h:476
friend void swap(MixedVector< BaseT > &a, MixedVector< BaseT > &b)
swap two MixedVectors
Definition utilities_slsim.h:344
BaseT * data()
direct access to underlying array
Definition utilities_slsim.h:451
void pop_back()
pop element from back of vector
Definition utilities_slsim.h:379
SubclassT & get(std::size_t i)
indexed access for type SubclassT
Definition utilities_slsim.h:495
~MixedVector()
destroy the vector and all contained items
Definition utilities_slsim.h:338
BaseT & get(std::size_t i)
indexed access
Definition utilities_slsim.h:482
void clear()
clear all elements
Definition utilities_slsim.h:420
bool type(std::size_t i)
Checks if element i is of the derived type SubclassT.
Definition utilities_slsim.h:464
iterator begin()
get iterator to first of all items
Definition utilities_slsim.h:582
const BaseT & get(std::size_t i) const
indexed access (const)
Definition utilities_slsim.h:488
void copy_back(const SubclassT &obj)
add a copy of an object of type SubclassT to the vector, in contrast push_back() deos not copy and wi...
Definition utilities_slsim.h:362
const BaseT * data() const
direct access to underlying array (const)
Definition utilities_slsim.h:457
bool empty() const
check if vector of items is empty
Definition utilities_slsim.h:565
BaseT & at(std::size_t i)
indexed access with bounds checking
Definition utilities_slsim.h:514
const SubclassT & at(std::size_t i) const
Templated indexing operator for elements of a specific derived class (const).
Definition utilities_slsim.h:540
SubclassT & at(std::size_t i)
Templated indexing operator for elements of a specific derived class. The index runs 0 ....
Definition utilities_slsim.h:530
std::size_t size() const
number of elements of a specific type
Definition utilities_slsim.h:556
const BaseT & at(std::size_t i) const
indexed access with bounds checking (const)
Definition utilities_slsim.h:520
const SubclassT & get(std::size_t i) const
indexed access for type SubclassT (const)
Definition utilities_slsim.h:505
iterator< SubclassT > begin()
get iterator to first of items of type SubclassT
Definition utilities_slsim.h:595
void clear()
clear all elements of a given type
Definition utilities_slsim.h:430
BaseT & operator[](std::size_t i)
Indexing operator for all elements.
Definition utilities_slsim.h:470
iterator< SubclassT > end()
get iterator to last of items of type SubclassT
Definition utilities_slsim.h:605
iterator end()
get iterator to last of all items
Definition utilities_slsim.h:588
PosType operator()(void)
return a uniform random number between 0 and 1
Definition utilities.cpp:429
long getseed()
total number of calls
Definition utilities_slsim.h:1124
PosType gauss()
generates a Gaussian distributed number with unit variance by polar Box-Muller transform
Definition utilities_slsim.h:1068
void operator+=(T x)
add another number
Definition utilities_slsim.h:2386
size_t total_number()
returns the number of numbers that have been added
Definition utilities_slsim.h:2413
T operator*()
returns the current total
Definition utilities_slsim.h:2398
void reset()
reset to start over, frees memory
Definition utilities_slsim.h:2405
size_t operator*()
return the index number
Definition utilities_slsim.h:1231
size_t operator++(int)
goto the next number
Definition utilities_slsim.h:1233
size_t operator++()
goto the next number
Definition utilities_slsim.h:1243
void reshuffle(R &ran)
get a new random order
Definition utilities_slsim.h:1253
size_t oned_index(int i, int j)
convertion from 2d to 1d index
Definition utilities_slsim.h:223
namespace for input/output utilities
Definition utilities_slsim.h:1363
bool make_directories(const std::string &root_dir)
make a directory if it doesn't exist
Definition utilities.cpp:564
void ReadASCII(std::vector< T > &data, std::string filename, int &columns, int &rows, char comment_char='#', int skiplines=0, size_t MaxNrows=std::numeric_limits< size_t >::max(), bool verbose=true)
This function will read in all the numbers from a multi-column ,space seporated ASCII data file.
Definition utilities_slsim.h:1651
void read3columnfile(std::string filename, std::vector< T1 > &x, std::vector< T2 > &y, std::vector< T3 > &z, std::string delineator=" ", bool verbose=false)
Read in data from an ASCII file with three columns.
Definition utilities_slsim.h:1518
void read2columnfile(std::string filename, std::vector< T1 > &x, std::vector< T2 > &y, std::string delineator=" ", int skiplines=0, bool verbose=false)
Read in data from an ASCII file with two columns.
Definition utilities_slsim.h:1434
int ReadCSVnumerical1(std::string filename, std::vector< std::vector< T > > &data, std::vector< std::string > &column_names, size_t MaxNumber=100000000, char comment_char='#', char deliniator=',', std::string replace="\\N", std::function< bool(std::vector< T > &)> accept=[](std::vector< T > &v){return true;})
Read numerical data from a csv file with a header.
Definition utilities_slsim.h:1722
int ReadCSVnumerical2(std::string filename, std::vector< std::vector< T > > &data, std::vector< std::string > &column_names, size_t Nmax=1000000, char comment_char='#', char deliniator=',', bool header=true, std::string reject="")
Read numerical data from a csv file with a header.
Definition utilities_slsim.h:1952
size_t ReadCSVrange(std::string filename, std::vector< std::vector< T > > &ranges, std::vector< std::string > &column_names, size_t MaxNumber=100000000, char comment_char='#', char deliniator=',', std::string replace="\\N", std::function< bool(std::vector< T > &)> accept=[](std::vector< T > &v){return true;})
Definition utilities_slsim.h:1836
void writeCSV(const std::string filename, const std::vector< std::string > header, std::vector< T * > &data)
write a CSV data file for some data vectors
Definition utilities_slsim.h:2061
bool check_directory(std::string dir)
returns true if director exists and false if it doesn't
Definition utilities.cpp:556
int CountColumns(std::string filename, char comment_char='#', char deliniator=' ')
Count the number of columns in a ASCII data file.
Definition utilities.cpp:614
void read1columnfile(std::string filename, std::vector< T > &x, int skiplines=0, bool verbose=false)
Definition utilities_slsim.h:1371
void ReadFileNames(std::string dir, const std::string filespec, std::vector< std::string > &filenames, bool verbose)
Reads the file names in a directory that contain a specific sub string.
Definition utilities.cpp:574
Definition utilities.h:39
T to_numeric(const std::string &str)
convert a string to a numerical value of various types
Definition utilities_slsim.h:30
std::valarray< T > AdaptiveSmooth(const std::valarray< T > &map_in, size_t Nx, size_t Ny, T value)
Smooth a 2 dimensional map stored in a valarray with a density dependent kernel.
Definition utilities_slsim.h:2751
void powerspectrum2d(std::valarray< double > const &aa, std::valarray< double > const &bb, long nx, long ny, double boxlx, double boxly, std::vector< double > &ll, std::vector< double > &Pl, double zeropaddingfactor)
Calculates power spectrum from a 2d map or the cross-power spectrum between two 2d maps.
Definition utilities.cpp:839
void sort_indexes(const std::vector< T > &v, std::vector< size_t > &index)
Find the indexes that sort a vector in asending order.
Definition utilities_slsim.h:1171
void shuffle(std::vector< T > &vec, R &ran)
Shuffles a vector into a random order.
Definition utilities_slsim.h:1154
void delete_container(Container &c)
delete the objects that are pointed to in a container of pointers
Definition utilities_slsim.h:993
void splitstring(std::string &line, std::vector< std::string > &vec, const std::string &delimiter)
split string into vector of seporate strings that were seporated by
Definition utilities.cpp:828
void powerspectrum2dprebin(std::valarray< double > &aa, long nx, long ny, double boxlx, double boxly, const std::vector< double > &ll, std::vector< double > &Pl, std::vector< double > &llave)
Definition utilities.cpp:454
void range(std::vector< T > vec, T &max, T &min)
find the maximum and minimum of a vector
Definition utilities.h:247
void sort_indexes_decending(const std::vector< T > &v, std::vector< size_t > &index)
Find the indexes that sort a vector in descending order.
Definition utilities_slsim.h:1200
int GetNThreads()
returns the compiler variable N_THREADS that is maximum number of threads to be used.
Definition utilities.cpp:553