root/applications/robust/robustlib.h @ 1343

Revision 1343, 79.2 kB (checked in by sindj, 13 years ago)

Importance sampling. JS

Line 
1/*!
2  \file
3  \brief Robust Bayesian auto-regression model
4  \author Jan Sindelar.
5*/
6
7#ifndef ROBUST_H
8#define ROBUST_H
9
10#include <stat/exp_family.h>
11#include <itpp/itbase.h>
12#include <itpp/base/random.h>
13#include <map>
14#include <limits>
15#include <vector>
16#include <list>
17#include <set>
18#include <algorithm>
19       
20using namespace bdm;
21using namespace std;
22using namespace itpp;
23
24const double max_range = 10;//numeric_limits<double>::max()/10e-10;
25
26/// An enumeration of possible actions performed on the polyhedrons. We can merge them or split them.
27enum actions {MERGE, SPLIT};
28
29// Forward declaration of polyhedron, vertex and emlig
30class polyhedron;
31class vertex;
32class emlig;
33
34/*
35class t_simplex
36{
37public:
38        set<vertex*> minima;
39
40        set<vertex*> simplex;
41
42        t_simplex(vertex* origin_vertex)
43        {
44                simplex.insert(origin_vertex);
45                minima.insert(origin_vertex);
46        }
47};*/
48
49/// A class representing a single condition that can be added to the emlig. A condition represents data entries in a statistical model.
50class condition
51{       
52public:
53        /// Value of the condition representing the data
54        vec value;     
55
56        /// Mulitplicity of the given condition may represent multiple occurences of same data entry.
57        int multiplicity;
58
59        /// Default constructor of condition class takes the value of data entry and creates a condition with multiplicity 1 (first occurence of the data).
60        condition(vec value)
61        {
62                this->value = value;
63                multiplicity = 1;
64        }
65};
66
67class simplex
68{
69       
70
71public:
72
73        set<vertex*> vertices;
74
75        double probability;
76
77        vector<multimap<double,double>> positive_gamma_parameters;
78
79        vector<multimap<double,double>> negative_gamma_parameters;
80
81        double positive_gamma_sum;
82
83        double negative_gamma_sum;
84
85        double min_beta;
86       
87
88        simplex(set<vertex*> vertices)
89        {
90                this->vertices.insert(vertices.begin(),vertices.end());
91                probability = 0;
92        }
93
94        simplex(vertex* vertex)
95        {
96                this->vertices.insert(vertex);
97                probability = 0;
98        }
99
100        void clear_gammas()
101        {
102                positive_gamma_parameters.clear();
103                negative_gamma_parameters.clear();             
104               
105                positive_gamma_sum = 0;
106                negative_gamma_sum = 0;
107
108                min_beta = numeric_limits<double>::max();
109        }
110
111        void insert_gamma(int order, double weight, double beta)
112        {
113                if(weight>=0)
114                {
115                        while(positive_gamma_parameters.size()<order+1)
116                        {
117                                multimap<double,double> map;
118                                positive_gamma_parameters.push_back(map);
119                        }
120
121                        positive_gamma_sum += weight;
122
123                        positive_gamma_parameters[order].insert(pair<double,double>(weight,beta));             
124                }
125                else
126                {
127                        while(negative_gamma_parameters.size()<order+1)
128                        {
129                                multimap<double,double> map;
130                                negative_gamma_parameters.push_back(map);
131                        }
132
133                        negative_gamma_sum -= weight;
134
135                        negative_gamma_parameters[order].insert(pair<double,double>(-weight,beta));
136                }
137
138                if(beta < min_beta)
139                {
140                        min_beta = beta;
141                }
142        }
143};
144
145
146/// A class describing a single polyhedron of the split complex. From a collection of such classes a Hasse diagram
147/// of the structure in the exponent of a Laplace-Inverse-Gamma density will be created.
148class polyhedron
149{
150        /// A property having a value of 1 usually, with higher value only if the polyhedron arises as a coincidence of
151        /// more than just the necessary number of conditions. For example if a newly created line passes through an already
152        /// existing point, the points multiplicity will rise by 1.
153        int multiplicity;       
154
155        /// A property representing the position of the polyhedron related to current condition with relation to which we
156        /// are splitting the parameter space (new data has arrived). This property is setup within a classification procedure and
157        /// is only valid while the new condition is being added. It has to be reset when new condition is added and new classification
158        /// has to be performed.
159        int split_state;
160
161        /// A property representing the position of the polyhedron related to current condition with relation to which we
162        /// are merging the parameter space (data is being deleted usually due to a moving window model which is more adaptive and
163        /// steps in for the forgetting in a classical Gaussian AR model). This property is setup within a classification procedure and
164        /// is only valid while the new condition is being removed. It has to be reset when new condition is removed and new classification
165        /// has to be performed.
166        int merge_state;
167
168                       
169
170public:
171        /// A pointer to the multi-Laplace inverse gamma distribution this polyhedron belongs to.
172        emlig* my_emlig;
173
174        /// A list of polyhedrons parents within the Hasse diagram.
175        list<polyhedron*> parents;
176
177        /// A list of polyhedrons children withing the Hasse diagram.
178        list<polyhedron*> children;
179
180        /// All the vertices of the given polyhedron
181        set<vertex*> vertices;
182
183        /// The conditions that gave birth to the polyhedron. If some of them is removed, the polyhedron ceases to exist.
184        set<condition*> parentconditions;
185
186        /// A list used for storing children that lie in the positive region related to a certain condition
187        list<polyhedron*> positivechildren;
188
189        /// A list used for storing children that lie in the negative region related to a certain condition
190        list<polyhedron*> negativechildren;
191
192        /// Children intersecting the condition
193        list<polyhedron*> neutralchildren;
194
195        /// A set of grandchildren of the polyhedron that when new condition is added lie exactly on the condition hyperplane. These grandchildren
196        /// behave differently from other grandchildren, when the polyhedron is split. New grandchild is not necessarily created on the crossection of
197        /// the polyhedron and new condition.
198        set<polyhedron*> totallyneutralgrandchildren;
199
200        /// A set of children of the polyhedron that when new condition is added lie exactly on the condition hyperplane. These children
201        /// behave differently from other children, when the polyhedron is split. New child is not necessarily created on the crossection of
202        /// the polyhedron and new condition.
203        set<polyhedron*> totallyneutralchildren;
204
205        /// Reverse relation to the totallyneutralgrandchildren set is needed for merging of already existing polyhedrons to keep
206        /// totallyneutralgrandchildren list up to date.
207        set<polyhedron*> grandparents;
208
209        /// Vertices of the polyhedron classified as positive related to an added condition. When the polyhderon is split by the new condition,
210        /// these vertices will belong to the positive part of the splitted polyhedron.
211        set<vertex*> positiveneutralvertices;
212
213        /// Vertices of the polyhedron classified as negative related to an added condition. When the polyhderon is split by the new condition,
214        /// these vertices will belong to the negative part of the splitted polyhedron.
215        set<vertex*> negativeneutralvertices;
216
217        /// A bool specifying if the polyhedron lies exactly on the newly added condition or not.
218        bool totally_neutral;
219
220        /// When two polyhedrons are merged, there always exists a child lying on the former border of the polyhedrons. This child manages the merge
221        /// of the two polyhedrons. This property gives us the address of the mediator child.
222        polyhedron* mergechild;
223
224        /// If the polyhedron serves as a mergechild for two of its parents, we need to have the address of the parents to access them. This
225        /// is the pointer to the positive parent being merged.
226        polyhedron* positiveparent;
227
228        /// If the polyhedron serves as a mergechild for two of its parents, we need to have the address of the parents to access them. This
229        /// is the pointer to the negative parent being merged.
230        polyhedron* negativeparent;     
231
232        /// Adressing withing the statistic. Next_poly is a pointer to the next polyhedron in the statistic on the same level (if this is a point,
233        /// next_poly will be a point etc.).
234        polyhedron* next_poly;
235
236        /// Adressing withing the statistic. Prev_poly is a pointer to the previous polyhedron in the statistic on the same level (if this is a point,
237        /// next_poly will be a point etc.).
238        polyhedron* prev_poly;
239
240        /// A property counting the number of messages obtained from children within a classification procedure of position of the polyhedron related
241        /// an added/removed condition. If the message counter reaches the number of children, we know the polyhedrons' position has been fully classified.
242        int message_counter;
243
244        /// List of triangulation polyhedrons of the polyhedron given by their relative vertices.
245        set<simplex*> triangulation;
246
247        /// A list of relative addresses serving for Hasse diagram construction.
248        list<int> kids_rel_addresses;
249
250        /// Default constructor
251        polyhedron()
252        {
253                multiplicity = 1;
254
255                message_counter = 0;
256
257                totally_neutral = NULL;
258
259                mergechild = NULL;             
260        }
261       
262        /// Setter for raising multiplicity
263        void raise_multiplicity()
264        {
265                multiplicity++;
266        }
267
268        /// Setter for lowering multiplicity
269        void lower_multiplicity()
270        {
271                multiplicity--;
272        }
273
274        int get_multiplicity()
275        {
276                return multiplicity;
277        }
278       
279        /// An obligatory operator, when the class is used within a C++ STL structure like a vector
280        int operator==(polyhedron polyhedron2)
281        {
282                return true;
283        }
284
285        /// An obligatory operator, when the class is used within a C++ STL structure like a vector
286        int operator<(polyhedron polyhedron2)
287        {
288                return false;
289        }
290
291       
292        /// A setter of state of current polyhedron relative to the action specified in the argument. The three possible states of the
293        /// polyhedron are -1 - NEGATIVE, 0 - NEUTRAL, 1 - POSITIVE. Neutral state means that either the state has been reset or the polyhedron is
294        /// ready to be split/merged.
295        int set_state(double state_indicator, actions action)
296        {
297                switch(action)
298                {
299                        case MERGE:
300                                merge_state = (int)sign(state_indicator);
301                                return merge_state;                     
302                        case SPLIT:
303                                split_state = (int)sign(state_indicator);
304                                return split_state;             
305                }
306        }
307
308        /// A getter of state of current polyhedron relative to the action specified in the argument. The three possible states of the
309        /// polyhedron are -1 - NEGATIVE, 0 - NEUTRAL, 1 - POSITIVE. Neutral state means that either the state has been reset or the polyhedron is
310        /// ready to be split/merged.
311        int get_state(actions action)
312        {
313                switch(action)
314                {
315                        case MERGE:
316                                return merge_state;                     
317                        break;
318                        case SPLIT:
319                                return split_state;
320                        break;
321                }
322        }
323
324        /// Method for obtaining the number of children of given polyhedron.
325        int number_of_children()
326        {
327                return children.size();
328        }
329
330        /// A method for triangulation of given polyhedron.
331        double triangulate(bool should_integrate);     
332};
333
334
335/// A class for representing 0-dimensional polyhedron - a vertex. It will be located in the bottom row of the Hasse
336/// diagram representing a complex of polyhedrons. It has its coordinates in the parameter space.
337class vertex : public polyhedron
338{
339        /// A dynamic array representing coordinates of the vertex
340        vec coordinates;
341
342public:
343        /// A property specifying the value of the density (ted nevim, jestli je to jakoby log nebo ne) above the vertex.
344        double function_value;
345
346        /// Default constructor
347        vertex();
348
349        /// Constructor of a vertex from a set of coordinates
350        vertex(vec coordinates)
351        {
352                this->coordinates   = coordinates;
353
354                vertices.insert(this);
355
356                simplex* vert_simplex = new simplex(vertices);         
357
358                triangulation.insert(vert_simplex);
359        }
360
361        /// A method that widens the set of coordinates of given vertex. It is used when a complex in a parameter
362        /// space of certain dimension is established, but the dimension is not known when the vertex is created.
363        void push_coordinate(double coordinate)
364        {
365                coordinates  = concat(coordinates,coordinate);         
366        }
367
368        /// A method obtaining the set of coordinates of a vertex. These coordinates are not obtained as a pointer
369        /// (not given by reference), but a new copy is created (they are given by value).
370        vec get_coordinates()
371        {
372                return coordinates;
373        }
374               
375};
376
377
378/// A class representing a polyhedron in a top row of the complex. Such polyhedron has a condition that differen   tiates
379/// it from polyhedrons in other rows.
380class toprow : public polyhedron
381{
382       
383public:
384        double probability;
385
386        vertex* minimal_vertex;
387
388        /// A condition used for determining the function of a Laplace-Inverse-Gamma density resulting from Bayesian estimation
389        vec condition_sum;
390
391        int condition_order;
392
393        /// Default constructor
394        toprow(){};
395
396        /// Constructor creating a toprow from the condition
397        toprow(condition *condition, int condition_order)
398        {
399                this->condition_sum   = condition->value;
400                this->condition_order = condition_order;
401        }
402
403        toprow(vec condition_sum, int condition_order)
404        {
405                this->condition_sum   = condition_sum;
406                this->condition_order = condition_order;
407        }
408
409        double integrate_simplex(simplex* simplex, char c);
410
411};
412
413
414
415
416
417
418
419class c_statistic
420{
421
422public:
423        polyhedron* end_poly;
424        polyhedron* start_poly;
425
426        vector<polyhedron*> rows;
427
428        vector<polyhedron*> row_ends;
429
430        c_statistic()
431        {
432                end_poly   = new polyhedron();
433                start_poly = new polyhedron();
434        };
435
436        void append_polyhedron(int row, polyhedron* appended_start, polyhedron* appended_end)
437        {
438                if(row>((int)rows.size())-1)
439                {
440                        if(row>rows.size())
441                        {
442                                throw new exception("You are trying to append a polyhedron whose children are not in the statistic yet!");
443                                return;
444                        }
445
446                        rows.push_back(end_poly);
447                        row_ends.push_back(end_poly);
448                }
449
450                // POSSIBLE FAILURE: the function is not checking if start and end are connected
451
452                if(rows[row] != end_poly)
453                {
454                        appended_start->prev_poly = row_ends[row];
455                        row_ends[row]->next_poly = appended_start;                     
456                                               
457                }
458                else if((row>0 && rows[row-1]!=end_poly)||row==0)
459                {
460                        appended_start->prev_poly = start_poly;
461                        rows[row]= appended_start;                     
462                }
463                else
464                {
465                        throw new exception("Wrong polyhedron insertion into statistic: missing intermediary polyhedron!");
466                }
467
468                appended_end->next_poly = end_poly;
469                row_ends[row] = appended_end;
470        }
471
472        void append_polyhedron(int row, polyhedron* appended_poly)
473        {
474                append_polyhedron(row,appended_poly,appended_poly);
475        }
476
477        void insert_polyhedron(int row, polyhedron* inserted_poly, polyhedron* following_poly)
478        {               
479                if(following_poly != end_poly)
480                {
481                        inserted_poly->next_poly = following_poly;
482                        inserted_poly->prev_poly = following_poly->prev_poly;
483
484                        if(following_poly->prev_poly == start_poly)
485                        {
486                                rows[row] = inserted_poly;
487                        }
488                        else
489                        {                               
490                                inserted_poly->prev_poly->next_poly = inserted_poly;                                                           
491                        }
492
493                        following_poly->prev_poly = inserted_poly;
494                }
495                else
496                {
497                        this->append_polyhedron(row, inserted_poly);
498                }               
499       
500        }
501
502
503       
504
505        void delete_polyhedron(int row, polyhedron* deleted_poly)
506        {
507                if(deleted_poly->prev_poly != start_poly)
508                {
509                        deleted_poly->prev_poly->next_poly = deleted_poly->next_poly;
510                }
511                else
512                {
513                        rows[row] = deleted_poly->next_poly;
514                }
515
516                if(deleted_poly->next_poly!=end_poly)
517                {
518                        deleted_poly->next_poly->prev_poly = deleted_poly->prev_poly;
519                }
520                else
521                {
522                        row_ends[row] = deleted_poly->prev_poly;
523                }
524
525               
526
527                deleted_poly->next_poly = NULL;
528                deleted_poly->prev_poly = NULL;                                 
529        }
530
531        int size()
532        {
533                return rows.size();
534        }
535
536        polyhedron* get_end()
537        {
538                return end_poly;
539        }
540
541        polyhedron* get_start()
542        {
543                return start_poly;
544        }
545
546        int row_size(int row)
547        {
548                if(this->size()>row && row>=0)
549                {
550                        int row_size = 0;
551                       
552                        for(polyhedron* row_poly = rows[row]; row_poly!=end_poly; row_poly=row_poly->next_poly)
553                        {
554                                row_size++;
555                        }
556
557                        return row_size;
558                }
559                else
560                {
561                        throw new exception("There is no row to obtain size from!");
562                }
563        }
564};
565
566
567class my_ivec : public ivec
568{
569public:
570        my_ivec():ivec(){};
571
572        my_ivec(ivec origin):ivec()
573        {
574                this->ins(0,origin);
575        }
576
577        bool operator>(const my_ivec &second) const
578        {
579                return max(*this)>max(second);
580               
581                /*
582                int size1 = this->size();
583                int size2 = second.size();             
584                 
585                int counter1 = 0;
586                while(0==0)
587                {
588                        if((*this)[counter1]==0)
589                        {
590                                size1--;
591                        }
592                       
593                        if((*this)[counter1]!=0)
594                                break;
595
596                        counter1++;
597                }
598
599                int counter2 = 0;
600                while(0==0)
601                {
602                        if(second[counter2]==0)
603                        {
604                                size2--;
605                        }
606                       
607                        if(second[counter2]!=0)
608                                break;
609
610                        counter2++;
611                }
612
613                if(size1!=size2)
614                {
615                        return size1>size2;
616                }
617                else
618                {
619                        for(int i = 0;i<size1;i++)
620                        {
621                                if((*this)[counter1+i]!=second[counter2+i])
622                                {
623                                        return (*this)[counter1+i]>second[counter2+i];
624                                }
625                        }
626
627                        return false;
628                }*/
629        }
630
631       
632        bool operator==(const my_ivec &second) const
633        {
634                return max(*this)==max(second);
635               
636                /*
637                int size1 = this->size();
638                int size2 = second.size();             
639                 
640                int counter = 0;
641                while(0==0)
642                {
643                        if((*this)[counter]==0)
644                {
645                        size1--;
646                }
647                       
648                if((*this)[counter]!=0)
649                        break;
650
651                counter++;
652                }
653
654                counter = 0;
655                while(0==0)
656                {
657                        if(second[counter]==0)
658                        {
659                                size2--;
660                        }
661                       
662                        if(second[counter]!=0)
663                                break;
664
665                        counter++;
666                }
667
668                if(size1!=size2)
669                {
670                        return false;
671                }
672                else
673                {
674                        for(int i=0;i<size1;i++)
675                        {
676                                if((*this)[size()-1-i]!=second[second.size()-1-i])
677                                {
678                                        return false;
679                                }
680                        }
681
682                        return true;
683                }*/
684        }
685
686        bool operator<(const my_ivec &second) const
687        {
688                return !(((*this)>second)||((*this)==second));
689        }
690
691        bool operator!=(const my_ivec &second) const
692        {
693                return !((*this)==second);
694        }
695
696        bool operator<=(const my_ivec &second) const
697        {
698                return !((*this)>second);
699        }
700
701        bool operator>=(const my_ivec &second) const
702        {
703                return !((*this)<second);
704        }
705
706        my_ivec right(my_ivec original)
707        {
708               
709        }
710};
711
712
713
714
715
716
717
718//! Conditional(e) Multicriteria-Laplace-Inverse-Gamma distribution density
719class emlig // : eEF
720{
721
722        /// A statistic in a form of a Hasse diagram representing a complex of convex polyhedrons obtained as a result
723        /// of data update from Bayesian estimation or set by the user if this emlig is a prior density
724       
725
726        vector<list<polyhedron*>> for_splitting;
727               
728        vector<list<polyhedron*>> for_merging;
729
730        list<condition*> conditions;
731
732        double normalization_factor;
733
734       
735
736        void alter_toprow_conditions(condition *condition, bool should_be_added)
737        {
738                for(polyhedron* horiz_ref = statistic.rows[statistic.size()-1];horiz_ref!=statistic.get_end();horiz_ref=horiz_ref->next_poly)
739                {
740                        set<vertex*>::iterator vertex_ref = horiz_ref->vertices.begin();
741
742                        do
743                        {
744                                vertex_ref++;
745                        }
746                        while((*vertex_ref)->parentconditions.find(condition)==(*vertex_ref)->parentconditions.end());
747
748                        double product = (*vertex_ref)->get_coordinates()*condition->value;
749
750                        if(should_be_added)
751                        {
752                                ((toprow*) horiz_ref)->condition_order++;
753
754                                if(product>0)
755                                {
756                                        ((toprow*) horiz_ref)->condition_sum += condition->value;
757                                }
758                                else
759                                {
760                                        ((toprow*) horiz_ref)->condition_sum -= condition->value;
761                                }
762                        }
763                        else
764                        { 
765                                ((toprow*) horiz_ref)->condition_order--;
766
767                                if(product<0)                   
768                                {
769                                        ((toprow*) horiz_ref)->condition_sum += condition->value;
770                                }
771                                else
772                                {
773                                        ((toprow*) horiz_ref)->condition_sum -= condition->value;
774                                }
775                        }                               
776                }
777        }
778
779
780
781        void send_state_message(polyhedron* sender, condition *toadd, condition *toremove, int level)
782        {                       
783
784                bool shouldmerge    = (toremove != NULL);
785                bool shouldsplit    = (toadd != NULL);
786               
787                if(shouldsplit||shouldmerge)
788                {
789                        for(list<polyhedron*>::iterator parent_iterator = sender->parents.begin();parent_iterator!=sender->parents.end();parent_iterator++)
790                        {
791                                polyhedron* current_parent = *parent_iterator;
792
793                                current_parent->message_counter++;
794
795                                bool is_last  = (current_parent->message_counter == current_parent->number_of_children());
796                                bool is_first = (current_parent->message_counter == 1);
797
798                                if(shouldmerge)
799                                {
800                                        int child_state  = sender->get_state(MERGE);
801                                        int parent_state = current_parent->get_state(MERGE);
802
803                                        if(parent_state == 0||is_first)
804                                        {
805                                                parent_state = current_parent->set_state(child_state, MERGE);                                           
806                                        }                                       
807
808                                        if(child_state == 0)
809                                        {
810                                                if(current_parent->mergechild == NULL)
811                                                {
812                                                        current_parent->mergechild = sender;
813                                                }                                                       
814                                        }                                       
815
816                                        if(is_last)
817                                        {                                               
818                                                if(parent_state == 1)
819                                                {
820                                                        ((toprow*)current_parent)->condition_sum-=toremove->value;
821                                                        ((toprow*)current_parent)->condition_order--;
822                                                }
823
824                                                if(parent_state == -1)
825                                                {
826                                                        ((toprow*)current_parent)->condition_sum+=toremove->value;
827                                                        ((toprow*)current_parent)->condition_order--;
828                                                }
829                                               
830                                                if(current_parent->mergechild != NULL)
831                                                {
832                                                        if(current_parent->mergechild->get_multiplicity()==1)
833                                                        {
834                                                                if(parent_state > 0)
835                                                                {                                                       
836                                                                        current_parent->mergechild->positiveparent = current_parent;                                                   
837                                                                }
838
839                                                                if(parent_state < 0)
840                                                                {                                                       
841                                                                        current_parent->mergechild->negativeparent = current_parent;                                                   
842                                                                }
843                                                        }                                                       
844                                                }                                               
845                                                else
846                                                {
847                                                        //current_parent->set_state(0,MERGE);   
848
849                                                        if(level == number_of_parameters - 1)
850                                                        {
851                                                                toprow* cur_par_toprow = ((toprow*)current_parent);
852                                                                cur_par_toprow->probability = 0.0;
853                                                               
854                                                                //set<simplex*> new_triangulation;
855
856                                                                for(set<simplex*>::iterator s_ref = current_parent->triangulation.begin();s_ref!=current_parent->triangulation.end();s_ref++)
857                                                                {
858                                                                        double cur_prob = cur_par_toprow->integrate_simplex((*s_ref),'C');
859                                                                       
860                                                                        cur_par_toprow->probability += cur_prob;
861
862                                                                        //new_triangulation.insert(pair<double,set<vertex*>>(cur_prob,(*t_ref).second));
863                                                                }
864
865                                                                cur_par_toprow->my_emlig->normalization_factor += cur_par_toprow->probability;
866
867                                                                //current_parent->triangulation.clear();
868                                                                //current_parent->triangulation.insert(new_triangulation.begin(),new_triangulation.end());
869                                                        }
870                                                }
871
872                                                if(parent_state == 0)
873                                                {
874                                                        for_merging[level+1].push_back(current_parent);
875                                                        //current_parent->parentconditions.erase(toremove);
876                                                }                                               
877
878                                                                                               
879                                        }                                       
880                                }
881
882                                if(shouldsplit)
883                                {
884                                        current_parent->totallyneutralgrandchildren.insert(sender->totallyneutralchildren.begin(),sender->totallyneutralchildren.end());
885                                       
886                                        for(set<polyhedron*>::iterator tot_child_ref = sender->totallyneutralchildren.begin();tot_child_ref!=sender->totallyneutralchildren.end();tot_child_ref++)
887                                        {
888                                                (*tot_child_ref)->grandparents.insert(current_parent);
889                                        }
890
891                                        if(current_parent->totally_neutral == NULL)
892                                        {
893                                                current_parent->totally_neutral = sender->totally_neutral;
894                                        }
895                                        else
896                                        {
897                                                current_parent->totally_neutral = current_parent->totally_neutral && sender->totally_neutral;
898                                        }
899
900                                        switch(sender->get_state(SPLIT))
901                                        {
902                                        case 1:
903                                                current_parent->positivechildren.push_back(sender);
904                                                current_parent->positiveneutralvertices.insert(sender->vertices.begin(),sender->vertices.end());
905                                        break;
906                                        case 0:
907                                                current_parent->neutralchildren.push_back(sender);
908                                                current_parent->positiveneutralvertices.insert(sender->positiveneutralvertices.begin(),sender->positiveneutralvertices.end());
909                                                current_parent->negativeneutralvertices.insert(sender->negativeneutralvertices.begin(),sender->negativeneutralvertices.end());                                         
910
911                                                if(sender->totally_neutral)
912                                                {
913                                                        current_parent->totallyneutralchildren.insert(sender);
914                                                }
915                                                       
916                                        break;
917                                        case -1:
918                                                current_parent->negativechildren.push_back(sender);
919                                                current_parent->negativeneutralvertices.insert(sender->vertices.begin(),sender->vertices.end());
920                                        break;
921                                        }
922
923                                        if(is_last)
924                                        {                                               
925                                               
926                                                if((current_parent->negativechildren.size()>0&&current_parent->positivechildren.size()>0)
927                                                                                                        ||(current_parent->neutralchildren.size()>0&&current_parent->totallyneutralchildren.empty()))
928                                                {
929                                                        for_splitting[level+1].push_back(current_parent);                                               
930                                                               
931                                                        current_parent->set_state(0, SPLIT);
932                                                }
933                                                else
934                                                {
935                                                        if(current_parent->negativechildren.size()>0)
936                                                        {
937                                                                current_parent->set_state(-1, SPLIT);
938
939                                                                ((toprow*)current_parent)->condition_sum-=toadd->value;
940                                                                       
941                                                        }
942                                                        else if(current_parent->positivechildren.size()>0)
943                                                        {
944                                                                current_parent->set_state(1, SPLIT);
945
946                                                                ((toprow*)current_parent)->condition_sum+=toadd->value;                                                                 
947                                                        }
948                                                        else
949                                                        {
950                                                                current_parent->raise_multiplicity();                                                           
951                                                        }
952
953                                                        ((toprow*)current_parent)->condition_order++;
954
955                                                        if(level == number_of_parameters - 1)
956                                                        {
957                                                                toprow* cur_par_toprow = ((toprow*)current_parent);
958                                                                cur_par_toprow->probability = 0.0;
959                                                                       
960                                                                //map<double,set<vertex*>> new_triangulation;
961                                                               
962                                                                for(set<simplex*>::iterator s_ref = current_parent->triangulation.begin();s_ref!=current_parent->triangulation.end();s_ref++)
963                                                                {
964                                                                        double cur_prob = cur_par_toprow->integrate_simplex((*s_ref),'C');
965                                                                       
966                                                                        cur_par_toprow->probability += cur_prob;
967
968                                                                        //new_triangulation.insert(pair<double,set<vertex*>>(cur_prob,(*t_ref).second));
969                                                                }
970
971                                                                cur_par_toprow->my_emlig->normalization_factor += cur_par_toprow->probability;
972
973                                                                //current_parent->triangulation.clear();
974                                                                //current_parent->triangulation.insert(new_triangulation.begin(),new_triangulation.end());
975                                                        }
976
977                                                        if(current_parent->mergechild == NULL)
978                                                        {
979                                                                current_parent->positivechildren.clear();
980                                                                current_parent->negativechildren.clear();
981                                                                current_parent->neutralchildren.clear();
982                                                                //current_parent->totallyneutralchildren.clear();
983                                                                current_parent->totallyneutralgrandchildren.clear();
984                                                                // current_parent->grandparents.clear();
985                                                                current_parent->positiveneutralvertices.clear();
986                                                                current_parent->negativeneutralvertices.clear();
987                                                                current_parent->totally_neutral = NULL;
988                                                                current_parent->kids_rel_addresses.clear();
989                                                        }                                                       
990                                                }
991                                        }
992                                }
993
994                                if(is_last)
995                                {
996                                        current_parent->mergechild = NULL;
997                                        current_parent->message_counter = 0;
998
999                                        send_state_message(current_parent,toadd,toremove,level+1);
1000                                }
1001                       
1002                        }
1003
1004                        sender->totallyneutralchildren.clear();                 
1005                }               
1006        }
1007       
1008public: 
1009        c_statistic statistic;
1010
1011        vertex* minimal_vertex;
1012
1013        double min_ll;
1014
1015        vector<multiset<my_ivec>> correction_factors;
1016
1017        int number_of_parameters;
1018
1019        /// A default constructor creates an emlig with predefined statistic representing only the range of the given
1020        /// parametric space, where the number of parameters of the needed model is given as a parameter to the constructor.
1021        emlig(int number_of_parameters)
1022        {       
1023                this->number_of_parameters = number_of_parameters;
1024
1025                create_statistic(number_of_parameters);
1026
1027                min_ll = numeric_limits<double>::max();
1028        }
1029
1030        /// A constructor for creating an emlig when the user wants to create the statistic by himself. The creation of a
1031        /// statistic is needed outside the constructor. Used for a user defined prior distribution on the parameters.
1032        emlig(c_statistic statistic)
1033        {
1034                this->statistic = statistic;   
1035
1036                min_ll = numeric_limits<double>::max();
1037        }
1038
1039        void step_me(int marker)
1040        {
1041               
1042                for(int i = 0;i<statistic.size();i++)
1043                {
1044                        //int zero = 0;
1045                        //int one  = 0;
1046                        //int two  = 0;
1047
1048                        for(polyhedron* horiz_ref = statistic.rows[i];horiz_ref!=statistic.get_end();horiz_ref=horiz_ref->next_poly)
1049                        {
1050                               
1051                                /*
1052                                if(i==statistic.size()-1)
1053                                {
1054                                        cout << ((toprow*)horiz_ref)->condition_sum << "   " << ((toprow*)horiz_ref)->probability << endl;
1055                                        cout << "Order:" << ((toprow*)horiz_ref)->condition_order << endl;
1056                                }
1057                                */
1058
1059                                cout << "Stepped." << endl;
1060                               
1061                                /*
1062                                if(i==0)
1063                                {
1064                                        cout << ((vertex*)horiz_ref)->get_coordinates() << endl;
1065                                }
1066                                */
1067
1068                                /*
1069                                char* string = "Checkpoint";
1070
1071
1072                                if((*horiz_ref).parentconditions.size()==0)
1073                                {
1074                                        zero++;
1075                                }
1076                                else if((*horiz_ref).parentconditions.size()==1)
1077                                {
1078                                        one++;                                 
1079                                }
1080                                else
1081                                {
1082                                        two++;
1083                                }
1084                                */
1085                               
1086                        }
1087                }
1088               
1089
1090                /*
1091                list<vec> table_entries;
1092                for(polyhedron* horiz_ref = statistic.rows[statistic.size()-1];horiz_ref!=statistic.row_ends[statistic.size()-1];horiz_ref=horiz_ref->next_poly)
1093                {
1094                        toprow *current_toprow = (toprow*)(horiz_ref);
1095                        for(list<set<vertex*>>::iterator tri_ref = current_toprow->triangulation.begin();tri_ref!=current_toprow->triangulation.end();tri_ref++)
1096                        {
1097                                for(set<vertex*>::iterator vert_ref = (*tri_ref).begin();vert_ref!=(*tri_ref).end();vert_ref++)
1098                                {
1099                                        vec table_entry = vec();
1100                                       
1101                                        table_entry.ins(0,(*vert_ref)->get_coordinates()*current_toprow->condition.get(1,current_toprow->condition.size()-1)-current_toprow->condition.get(0,0));
1102                                       
1103                                        table_entry.ins(0,(*vert_ref)->get_coordinates());
1104
1105                                        table_entries.push_back(table_entry);
1106                                }
1107                        }                       
1108                }
1109
1110                unique(table_entries.begin(),table_entries.end());
1111
1112                               
1113               
1114                for(list<vec>::iterator entry_ref = table_entries.begin();entry_ref!=table_entries.end();entry_ref++)
1115                {
1116                        ofstream myfile;
1117                        myfile.open("robust_data.txt", ios::out | ios::app);
1118                        if (myfile.is_open())
1119                        {
1120                                for(int i = 0;i<(*entry_ref).size();i++)
1121                                {
1122                                        myfile << (*entry_ref)[i] << ";";
1123                                }
1124                                myfile << endl;
1125                       
1126                                myfile.close();
1127                        }
1128                        else
1129                        {
1130                                cout << "File problem." << endl;
1131                        }
1132                }
1133                */
1134               
1135
1136                return;
1137        }
1138
1139        int statistic_rowsize(int row)
1140        {
1141                return statistic.row_size(row);
1142        }
1143
1144        void add_condition(vec toadd)
1145        {
1146                vec null_vector = "";
1147
1148                add_and_remove_condition(toadd, null_vector);
1149        }
1150
1151
1152        void remove_condition(vec toremove)
1153        {               
1154                vec null_vector = "";
1155
1156                add_and_remove_condition(null_vector, toremove);
1157       
1158        }
1159
1160        void add_and_remove_condition(vec toadd, vec toremove)
1161        {
1162                //step_me(0);
1163                normalization_factor = 0;
1164                min_ll = numeric_limits<double>::max();
1165
1166                bool should_remove = (toremove.size() != 0);
1167                bool should_add    = (toadd.size() != 0);
1168
1169                for_splitting.clear();
1170                for_merging.clear();
1171
1172                for(int i = 0;i<statistic.size();i++)
1173                {
1174                        list<polyhedron*> empty_split;
1175                        list<polyhedron*> empty_merge;
1176
1177                        for_splitting.push_back(empty_split);
1178                        for_merging.push_back(empty_merge);
1179                }
1180
1181                list<condition*>::iterator toremove_ref = conditions.end();
1182                bool condition_should_be_added = should_add;
1183
1184                for(list<condition*>::iterator ref = conditions.begin();ref!=conditions.end();ref++)
1185                {
1186                        if(should_remove)
1187                        {
1188                                if((*ref)->value == toremove)
1189                                {
1190                                        if((*ref)->multiplicity>1)
1191                                        {
1192                                                (*ref)->multiplicity--;
1193
1194                                                alter_toprow_conditions(*ref,false);
1195
1196                                                should_remove = false;
1197                                        }
1198                                        else
1199                                        {
1200                                                toremove_ref = ref;                                                     
1201                                        }
1202                                }
1203                        }
1204
1205                        if(should_add)
1206                        {
1207                                if((*ref)->value == toadd)
1208                                {
1209                                        (*ref)->multiplicity++;
1210
1211                                        alter_toprow_conditions(*ref,true);
1212
1213                                        should_add = false;
1214
1215                                        condition_should_be_added = false;
1216                                }                               
1217                        }
1218                }       
1219
1220                condition* condition_to_remove = NULL;
1221
1222                if(toremove_ref!=conditions.end())
1223                {
1224                        condition_to_remove = *toremove_ref;
1225                        conditions.erase(toremove_ref);                 
1226                }
1227
1228                condition* condition_to_add = NULL;
1229
1230                if(condition_should_be_added)
1231                {
1232                        condition* new_condition = new condition(toadd);
1233                       
1234                        conditions.push_back(new_condition);
1235                        condition_to_add = new_condition;
1236                }               
1237               
1238                for(polyhedron* horizontal_position = statistic.rows[0];horizontal_position!=statistic.get_end();horizontal_position=horizontal_position->next_poly)
1239                {               
1240                        vertex* current_vertex = (vertex*)horizontal_position;
1241                       
1242                        if(should_add||should_remove)
1243                        {
1244                                vec appended_coords = current_vertex->get_coordinates();
1245                                appended_coords.ins(0,-1.0);                           
1246
1247                                if(should_add)
1248                                {
1249                                        double local_condition = 0;// = toadd*(appended_coords.first/=appended_coords.second);
1250
1251                                        local_condition = appended_coords*toadd;
1252
1253                                        current_vertex->set_state(local_condition,SPLIT);
1254
1255                                        /// \TODO There should be a rounding error tolerance used here to insure we are not having too many points because of rounding error.
1256                                        if(local_condition == 0)
1257                                        {
1258                                                current_vertex->totally_neutral = true;
1259
1260                                                current_vertex->raise_multiplicity();
1261
1262                                                current_vertex->negativeneutralvertices.insert(current_vertex);
1263                                                current_vertex->positiveneutralvertices.insert(current_vertex);
1264                                        }
1265                                        else
1266                                        {
1267                                                current_vertex->totally_neutral = false;
1268                                        }
1269                                }
1270                       
1271                                if(should_remove)
1272                                {                                       
1273                                        set<condition*>::iterator cond_ref;
1274                                       
1275                                        for(cond_ref = current_vertex->parentconditions.begin();cond_ref!=current_vertex->parentconditions.end();cond_ref++)
1276                                        {
1277                                                if(*cond_ref == condition_to_remove)
1278                                                {
1279                                                        break;
1280                                                }
1281                                        }
1282
1283                                        if(cond_ref!=current_vertex->parentconditions.end())
1284                                        {
1285                                                current_vertex->parentconditions.erase(cond_ref);
1286                                                current_vertex->set_state(0,MERGE);
1287                                                for_merging[0].push_back(current_vertex);
1288                                        }
1289                                        else
1290                                        {
1291                                                double local_condition = toremove*appended_coords;
1292                                                current_vertex->set_state(local_condition,MERGE);
1293                                        }
1294                                }                               
1295                        }
1296
1297                        send_state_message(current_vertex, condition_to_add, condition_to_remove, 0);           
1298                       
1299                }
1300
1301               
1302               
1303                if(should_remove)
1304                {
1305                        /*
1306                        for(int i = 0;i<for_merging.size();i++)
1307                        {
1308                                for(list<polyhedron*>::iterator merge_ref = for_merging[i].begin();merge_ref!=for_merging[i].end();merge_ref++)
1309                                {
1310                                        cout << (*merge_ref)->get_state(MERGE) << ",";
1311                                }
1312
1313                                cout << endl;
1314                        }
1315                        */
1316
1317                        cout << "Merging." << endl;
1318
1319                        set<vertex*> vertices_to_be_reduced;                   
1320                       
1321                        int k = 1;
1322
1323                        for(vector<list<polyhedron*>>::iterator vert_ref = for_merging.begin();vert_ref<for_merging.end();vert_ref++)
1324                        {
1325                                for(list<polyhedron*>::reverse_iterator merge_ref = vert_ref->rbegin();merge_ref!=vert_ref->rend();merge_ref++)
1326                                {
1327                                        if((*merge_ref)->get_multiplicity()>1)
1328                                        {
1329                                                if(k==1)
1330                                                {
1331                                                        vertices_to_be_reduced.insert((vertex*)(*merge_ref));
1332                                                }
1333                                                else
1334                                                {
1335                                                        (*merge_ref)->lower_multiplicity();
1336                                                }
1337                                        }
1338                                        else
1339                                        {
1340                                                toprow* current_positive = (toprow*)(*merge_ref)->positiveparent;
1341                                                toprow* current_negative = (toprow*)(*merge_ref)->negativeparent;
1342
1343                                                //current_positive->condition_sum -= toremove;
1344                                                //current_positive->condition_order--;
1345
1346                                                current_positive->parentconditions.erase(condition_to_remove);
1347                                               
1348                                                current_positive->children.insert(current_positive->children.end(),current_negative->children.begin(),current_negative->children.end());
1349                                                current_positive->children.remove(*merge_ref);
1350
1351                                                for(list<polyhedron*>::iterator child_ref = current_negative->children.begin();child_ref!=current_negative->children.end();child_ref++)
1352                                                {
1353                                                        (*child_ref)->parents.remove(current_negative);
1354                                                        (*child_ref)->parents.push_back(current_positive);                                                                                                     
1355                                                }
1356
1357                                                // current_positive->parents.insert(current_positive->parents.begin(),current_negative->parents.begin(),current_negative->parents.end());
1358                                                // unique(current_positive->parents.begin(),current_positive->parents.end());
1359
1360                                                for(list<polyhedron*>::iterator parent_ref = current_negative->parents.begin();parent_ref!=current_negative->parents.end();parent_ref++)
1361                                                {
1362                                                        (*parent_ref)->children.remove(current_negative);
1363
1364                                                        switch(current_negative->get_state(SPLIT))
1365                                                        {
1366                                                        case -1:
1367                                                                (*parent_ref)->negativechildren.remove(current_negative);
1368                                                                break;
1369                                                        case 0:
1370                                                                (*parent_ref)->neutralchildren.remove(current_negative);                                                               
1371                                                                break;
1372                                                        case 1:
1373                                                                (*parent_ref)->positivechildren.remove(current_negative);
1374                                                                break;
1375                                                        }
1376                                                        //(*parent_ref)->children.push_back(current_positive);
1377                                                }
1378
1379                                                if(current_positive->get_state(SPLIT)!=0&&current_negative->get_state(SPLIT)==0)
1380                                                {
1381                                                        for(list<polyhedron*>::iterator parent_ref = current_positive->parents.begin();parent_ref!=current_positive->parents.end();parent_ref++)
1382                                                        {
1383                                                                if(current_positive->get_state(SPLIT)==1)
1384                                                                {
1385                                                                        (*parent_ref)->positivechildren.remove(current_positive);
1386                                                                }
1387                                                                else
1388                                                                {
1389                                                                        (*parent_ref)->negativechildren.remove(current_positive);
1390                                                                }
1391
1392                                                                (*parent_ref)->neutralchildren.push_back(current_positive);
1393                                                        }
1394
1395                                                        current_positive->set_state(0,SPLIT);
1396                                                        for_splitting[k].push_back(current_positive);
1397                                                }
1398                                               
1399                                                if((current_positive->get_state(SPLIT)==0&&!current_positive->totally_neutral)||(current_negative->get_state(SPLIT)==0&&!current_negative->totally_neutral))
1400                                                {
1401                                                        current_positive->negativechildren.insert(current_positive->negativechildren.end(),current_negative->negativechildren.begin(),current_negative->negativechildren.end());                                               
1402                                                       
1403                                                        current_positive->positivechildren.insert(current_positive->positivechildren.end(),current_negative->positivechildren.begin(),current_negative->positivechildren.end());
1404                                                                                                       
1405                                                        current_positive->neutralchildren.insert(current_positive->neutralchildren.end(),current_negative->neutralchildren.begin(),current_negative->neutralchildren.end());
1406                                               
1407                                                        switch((*merge_ref)->get_state(SPLIT))
1408                                                        {
1409                                                        case -1:
1410                                                                current_positive->negativechildren.remove(*merge_ref);
1411                                                                break;
1412                                                        case 0:
1413                                                                current_positive->neutralchildren.remove(*merge_ref);
1414                                                                break;
1415                                                        case 1:
1416                                                                current_positive->positivechildren.remove(*merge_ref);
1417                                                                break;
1418                                                        }
1419
1420                                                        /*
1421                                                        current_positive->totallyneutralchildren.insert(current_negative->totallyneutralchildren.begin(),current_negative->totallyneutralchildren.end());
1422                                                       
1423                                                        current_positive->totallyneutralchildren.erase(*merge_ref);
1424                                                        */
1425
1426                                                        current_positive->totallyneutralgrandchildren.insert(current_negative->totallyneutralgrandchildren.begin(),current_negative->totallyneutralgrandchildren.end());
1427
1428                                                        current_positive->negativeneutralvertices.insert(current_negative->negativeneutralvertices.begin(),current_negative->negativeneutralvertices.end());
1429                                                        current_positive->positiveneutralvertices.insert(current_negative->positiveneutralvertices.begin(),current_negative->positiveneutralvertices.end());
1430                                                }
1431                                                else
1432                                                {
1433                                                        if(!current_positive->totally_neutral)
1434                                                        {
1435                                                                current_positive->positivechildren.clear();
1436                                                                current_positive->negativechildren.clear();
1437                                                                current_positive->neutralchildren.clear();
1438                                                                // current_positive->totallyneutralchildren.clear();
1439                                                                current_positive->totallyneutralgrandchildren.clear();                                                         
1440                                                                current_positive->positiveneutralvertices.clear();
1441                                                                current_positive->negativeneutralvertices.clear();
1442                                                                current_positive->totally_neutral = NULL;
1443                                                                current_positive->kids_rel_addresses.clear();                                                           
1444                                                        }
1445                                               
1446                                                }
1447
1448                                                                                               
1449                                               
1450                                                current_positive->vertices.insert(current_negative->vertices.begin(),current_negative->vertices.end());
1451                                               
1452                                               
1453                                                for(set<vertex*>::iterator vert_ref = (*merge_ref)->vertices.begin();vert_ref!=(*merge_ref)->vertices.end();vert_ref++)
1454                                                {
1455                                                        if((*vert_ref)->get_multiplicity()==1)
1456                                                        {
1457                                                                current_positive->vertices.erase(*vert_ref);
1458                                                               
1459                                                                if((current_positive->get_state(SPLIT)==0&&!current_positive->totally_neutral)||(current_negative->get_state(SPLIT)==0&&!current_negative->totally_neutral))
1460                                                                {
1461                                                                        current_positive->negativeneutralvertices.erase(*vert_ref);
1462                                                                        current_positive->positiveneutralvertices.erase(*vert_ref);
1463                                                                }
1464                                                        }
1465                                                }
1466                                               
1467                                                if(current_negative->get_state(SPLIT)==0&&!current_negative->totally_neutral)
1468                                                {
1469                                                        for_splitting[k].remove(current_negative);     
1470                                                }
1471
1472                                                if(current_positive->totally_neutral)
1473                                                {
1474                                                        if(!current_negative->totally_neutral)
1475                                                        {
1476                                                                for(set<polyhedron*>::iterator grand_ref = current_positive->grandparents.begin();grand_ref!=current_positive->grandparents.end();grand_ref++)
1477                                                                {
1478                                                                        (*grand_ref)->totallyneutralgrandchildren.erase(current_positive);
1479                                                                }                                                               
1480                                                        }
1481                                                        else
1482                                                        {
1483                                                                for(set<polyhedron*>::iterator grand_ref = current_negative->grandparents.begin();grand_ref!=current_negative->grandparents.end();grand_ref++)
1484                                                                {
1485                                                                        (*grand_ref)->totallyneutralgrandchildren.erase(current_negative);
1486                                                                        (*grand_ref)->totallyneutralgrandchildren.insert(current_positive);
1487                                                                }                                                               
1488                                                        }
1489                                                }
1490                                                else
1491                                                {
1492                                                        if(current_negative->totally_neutral)
1493                                                        {
1494                                                                for(set<polyhedron*>::iterator grand_ref = current_negative->grandparents.begin();grand_ref!=current_negative->grandparents.end();grand_ref++)
1495                                                                {
1496                                                                        (*grand_ref)->totallyneutralgrandchildren.erase(current_negative);                                                                     
1497                                                                }
1498                                                        }                                                       
1499                                                }
1500
1501                                                current_positive->grandparents.clear();
1502
1503                                               
1504                                               
1505                                                current_positive->totally_neutral = (current_positive->totally_neutral && current_negative->totally_neutral);
1506
1507                                                current_positive->my_emlig->normalization_factor += current_positive->triangulate(k==for_splitting.size()-1);
1508                                               
1509                                                statistic.delete_polyhedron(k,current_negative);
1510
1511                                                delete current_negative;
1512
1513                                                for(list<polyhedron*>::iterator child_ref = (*merge_ref)->children.begin();child_ref!=(*merge_ref)->children.end();child_ref++)
1514                                                {
1515                                                        (*child_ref)->parents.remove(*merge_ref);
1516                                                }
1517
1518                                                /*
1519                                                for(list<polyhedron*>::iterator parent_ref = (*merge_ref)->parents.begin();parent_ref!=(*merge_ref)->parents.end();parent_ref++)
1520                                                {
1521                                                        (*parent_ref)->positivechildren.remove(*merge_ref);
1522                                                        (*parent_ref)->negativechildren.remove(*merge_ref);
1523                                                        (*parent_ref)->neutralchildren.remove(*merge_ref);
1524                                                        (*parent_ref)->children.remove(*merge_ref);
1525                                                }
1526                                                */
1527
1528                                                for(set<polyhedron*>::iterator grand_ch_ref = (*merge_ref)->totallyneutralgrandchildren.begin();grand_ch_ref!=(*merge_ref)->totallyneutralgrandchildren.end();grand_ch_ref++)
1529                                                {
1530                                                        (*grand_ch_ref)->grandparents.erase(*merge_ref);
1531                                                }
1532
1533                                               
1534                                                for(set<polyhedron*>::iterator grand_p_ref = (*merge_ref)->grandparents.begin();grand_p_ref!=(*merge_ref)->grandparents.end();grand_p_ref++)
1535                                                {
1536                                                        (*grand_p_ref)->totallyneutralgrandchildren.erase(*merge_ref);
1537                                                }
1538                                               
1539                                                for_splitting[k-1].remove(*merge_ref);
1540
1541                                                statistic.delete_polyhedron(k-1,*merge_ref);
1542
1543                                                if(k==1)
1544                                                {
1545                                                        vertices_to_be_reduced.insert((vertex*)(*merge_ref));
1546                                                }
1547                                                else
1548                                                {
1549                                                        delete *merge_ref;
1550                                                }
1551                                        }
1552                                }                       
1553                       
1554                                k++;
1555
1556                        }
1557
1558                        for(set<vertex*>::iterator vert_ref = vertices_to_be_reduced.begin();vert_ref!=vertices_to_be_reduced.end();vert_ref++)
1559                        {
1560                                if((*vert_ref)->get_multiplicity()>1)
1561                                {
1562                                        (*vert_ref)->lower_multiplicity();
1563                                }
1564                                else
1565                                {
1566                                        delete *vert_ref;
1567                                }
1568                        }
1569
1570                        delete condition_to_remove;
1571                }
1572               
1573                /*
1574                vector<int> sizevector;
1575                for(int s = 0;s<statistic.size();s++)
1576                {
1577                        sizevector.push_back(statistic.row_size(s));
1578                        cout << statistic.row_size(s) << ", ";
1579                }*/
1580               
1581
1582                //cout << endl;
1583
1584                // this->step_me(2);
1585
1586                if(should_add)
1587                {
1588                        int k = 1;
1589
1590                        vector<list<polyhedron*>>::iterator beginning_ref = ++for_splitting.begin();
1591
1592                        for(vector<list<polyhedron*>>::iterator vert_ref = beginning_ref;vert_ref<for_splitting.end();vert_ref++)
1593                        {                       
1594
1595                                for(list<polyhedron*>::reverse_iterator split_ref = vert_ref->rbegin();split_ref != vert_ref->rend();split_ref++)
1596                                {
1597                                        polyhedron* new_totally_neutral_child;
1598
1599                                        polyhedron* current_polyhedron = (*split_ref);
1600                                       
1601                                        if(vert_ref == beginning_ref)
1602                                        {
1603                                                vec coordinates1 = ((vertex*)(*(current_polyhedron->children.begin())))->get_coordinates();                                             
1604                                                vec coordinates2 = ((vertex*)(*(++current_polyhedron->children.begin())))->get_coordinates();
1605                                               
1606                                                vec extended_coord2 = coordinates2;
1607                                                extended_coord2.ins(0,-1.0);                                           
1608
1609                                                double t = (-toadd*extended_coord2)/(toadd(1,toadd.size()-1)*(coordinates1-coordinates2));                                             
1610
1611                                                vec new_coordinates = (1-t)*coordinates2+t*coordinates1;                                               
1612
1613                                                // cout << "c1:" << coordinates1 << endl << "c2:" << coordinates2 << endl << "nc:" << new_coordinates << endl;
1614
1615                                                vertex* neutral_vertex = new vertex(new_coordinates);                                           
1616
1617                                                new_totally_neutral_child = neutral_vertex;
1618                                        }
1619                                        else
1620                                        {
1621                                                toprow* neutral_toprow = new toprow();
1622                                               
1623                                                neutral_toprow->condition_sum   = ((toprow*)current_polyhedron)->condition_sum; // tohle tu bylo driv: zeros(number_of_parameters+1);
1624                                                neutral_toprow->condition_order = ((toprow*)current_polyhedron)->condition_order+1;
1625
1626                                                new_totally_neutral_child = neutral_toprow;
1627                                        }
1628
1629                                        new_totally_neutral_child->parentconditions.insert(current_polyhedron->parentconditions.begin(),current_polyhedron->parentconditions.end());
1630                                        new_totally_neutral_child->parentconditions.insert(condition_to_add);
1631
1632                                        new_totally_neutral_child->my_emlig = this;
1633                                       
1634                                        new_totally_neutral_child->children.insert(new_totally_neutral_child->children.end(),
1635                                                                                                                current_polyhedron->totallyneutralgrandchildren.begin(),
1636                                                                                                                                current_polyhedron->totallyneutralgrandchildren.end());
1637
1638                                       
1639
1640                                        // cout << ((toprow*)current_polyhedron)->condition << endl << toadd << endl;
1641
1642                                        toprow* positive_poly = new toprow(((toprow*)current_polyhedron)->condition_sum+toadd, ((toprow*)current_polyhedron)->condition_order+1);
1643                                        toprow* negative_poly = new toprow(((toprow*)current_polyhedron)->condition_sum-toadd, ((toprow*)current_polyhedron)->condition_order+1);
1644
1645                                        positive_poly->my_emlig = this;
1646                                        negative_poly->my_emlig = this;
1647
1648                                        positive_poly->parentconditions.insert(current_polyhedron->parentconditions.begin(),current_polyhedron->parentconditions.end());
1649                                        negative_poly->parentconditions.insert(current_polyhedron->parentconditions.begin(),current_polyhedron->parentconditions.end());
1650
1651                                        for(set<polyhedron*>::iterator grand_ref = current_polyhedron->totallyneutralgrandchildren.begin(); grand_ref != current_polyhedron->totallyneutralgrandchildren.end();grand_ref++)
1652                                        {
1653                                                (*grand_ref)->parents.push_back(new_totally_neutral_child);
1654                                               
1655                                                // tohle tu nebylo. ma to tu byt?
1656                                                //positive_poly->totallyneutralgrandchildren.insert(*grand_ref);
1657                                                //negative_poly->totallyneutralgrandchildren.insert(*grand_ref);
1658
1659                                                //(*grand_ref)->grandparents.insert(positive_poly);
1660                                                //(*grand_ref)->grandparents.insert(negative_poly);
1661
1662                                                new_totally_neutral_child->vertices.insert((*grand_ref)->vertices.begin(),(*grand_ref)->vertices.end());
1663                                        }
1664
1665                                        positive_poly->children.push_back(new_totally_neutral_child);
1666                                        negative_poly->children.push_back(new_totally_neutral_child);
1667                                       
1668
1669                                        for(list<polyhedron*>::iterator parent_ref = current_polyhedron->parents.begin();parent_ref!=current_polyhedron->parents.end();parent_ref++)
1670                                        {
1671                                                (*parent_ref)->totallyneutralgrandchildren.insert(new_totally_neutral_child);
1672                                                // new_totally_neutral_child->grandparents.insert(*parent_ref);
1673
1674                                                (*parent_ref)->neutralchildren.remove(current_polyhedron);
1675                                                (*parent_ref)->children.remove(current_polyhedron);
1676
1677                                                (*parent_ref)->children.push_back(positive_poly);
1678                                                (*parent_ref)->children.push_back(negative_poly);
1679                                                (*parent_ref)->positivechildren.push_back(positive_poly);
1680                                                (*parent_ref)->negativechildren.push_back(negative_poly);
1681                                        }
1682
1683                                        positive_poly->parents.insert(positive_poly->parents.end(),
1684                                                                                                current_polyhedron->parents.begin(),
1685                                                                                                                current_polyhedron->parents.end());
1686
1687                                        negative_poly->parents.insert(negative_poly->parents.end(),
1688                                                                                                current_polyhedron->parents.begin(),
1689                                                                                                                current_polyhedron->parents.end());
1690
1691                                       
1692
1693                                        new_totally_neutral_child->parents.push_back(positive_poly);
1694                                        new_totally_neutral_child->parents.push_back(negative_poly);
1695
1696                                        for(list<polyhedron*>::iterator child_ref = current_polyhedron->positivechildren.begin();child_ref!=current_polyhedron->positivechildren.end();child_ref++)
1697                                        {
1698                                                (*child_ref)->parents.remove(current_polyhedron);
1699                                                (*child_ref)->parents.push_back(positive_poly);                                         
1700                                        }                                       
1701
1702                                        positive_poly->children.insert(positive_poly->children.end(),
1703                                                                                                current_polyhedron->positivechildren.begin(),
1704                                                                                                                        current_polyhedron->positivechildren.end());
1705
1706                                        for(list<polyhedron*>::iterator child_ref = current_polyhedron->negativechildren.begin();child_ref!=current_polyhedron->negativechildren.end();child_ref++)
1707                                        {
1708                                                (*child_ref)->parents.remove(current_polyhedron);
1709                                                (*child_ref)->parents.push_back(negative_poly);
1710                                        }
1711
1712                                        negative_poly->children.insert(negative_poly->children.end(),
1713                                                                                                current_polyhedron->negativechildren.begin(),
1714                                                                                                                        current_polyhedron->negativechildren.end());
1715
1716                                        positive_poly->vertices.insert(current_polyhedron->positiveneutralvertices.begin(),current_polyhedron->positiveneutralvertices.end());
1717                                        positive_poly->vertices.insert(new_totally_neutral_child->vertices.begin(),new_totally_neutral_child->vertices.end());
1718
1719                                        negative_poly->vertices.insert(current_polyhedron->negativeneutralvertices.begin(),current_polyhedron->negativeneutralvertices.end());
1720                                        negative_poly->vertices.insert(new_totally_neutral_child->vertices.begin(),new_totally_neutral_child->vertices.end());
1721                                                               
1722                                        new_totally_neutral_child->triangulate(false);
1723
1724                                        positive_poly->my_emlig->normalization_factor += positive_poly->triangulate(k==for_splitting.size()-1);
1725                                        negative_poly->my_emlig->normalization_factor += negative_poly->triangulate(k==for_splitting.size()-1);
1726                                       
1727                                        statistic.append_polyhedron(k-1, new_totally_neutral_child);                                   
1728                                       
1729                                        statistic.insert_polyhedron(k, positive_poly, current_polyhedron);
1730                                        statistic.insert_polyhedron(k, negative_poly, current_polyhedron);                                     
1731
1732                                        statistic.delete_polyhedron(k, current_polyhedron);
1733
1734                                        delete current_polyhedron;
1735                                }
1736
1737                                k++;
1738                        }
1739                }
1740
1741                vector<int> sizevector;
1742                //sizevector.clear();
1743                for(int s = 0;s<statistic.size();s++)
1744                {
1745                        sizevector.push_back(statistic.row_size(s));
1746                        cout << statistic.row_size(s) << ", ";
1747                }
1748               
1749                cout << endl;
1750               
1751
1752                /*
1753                for(polyhedron* topr_ref = statistic.rows[statistic.size()-1];topr_ref!=statistic.row_ends[statistic.size()-1]->next_poly;topr_ref=topr_ref->next_poly)
1754                {
1755                        cout << ((toprow*)topr_ref)->condition << endl;
1756                }
1757                */
1758
1759                // step_me(0);
1760
1761        }
1762
1763        void set_correction_factors(int order)
1764                {
1765                        for(int remaining_order = correction_factors.size();remaining_order<order;remaining_order++)
1766                        {
1767                                multiset<my_ivec> factor_templates;
1768                                multiset<my_ivec> final_factors;                               
1769
1770                                my_ivec orig_template = my_ivec();                             
1771
1772                                for(int i = 1;i<number_of_parameters-remaining_order+1;i++)
1773                                {                                       
1774                                        bool in_cycle = false;
1775                                        for(int j = 0;j<=remaining_order;j++)                                   {
1776                                               
1777                                                multiset<my_ivec>::iterator fac_ref = factor_templates.begin();
1778
1779                                                do
1780                                                {
1781                                                        my_ivec current_template;
1782                                                        if(!in_cycle)
1783                                                        {
1784                                                                current_template = orig_template;
1785                                                                in_cycle = true;
1786                                                        }
1787                                                        else
1788                                                        {
1789                                                                current_template = (*fac_ref);
1790                                                                fac_ref++;
1791                                                        }                                                       
1792                                                       
1793                                                        current_template.ins(current_template.size(),i);
1794
1795                                                        // cout << "template:" << current_template << endl;
1796                                                       
1797                                                        if(current_template.size()==remaining_order+1)
1798                                                        {
1799                                                                final_factors.insert(current_template);
1800                                                        }
1801                                                        else
1802                                                        {
1803                                                                factor_templates.insert(current_template);
1804                                                        }
1805                                                }
1806                                                while(fac_ref!=factor_templates.end());
1807                                        }
1808                                }       
1809
1810                                correction_factors.push_back(final_factors);                   
1811
1812                        }
1813                }
1814
1815        pair<vec,simplex*> choose_simplex()
1816        {
1817                double rnumber = randu();
1818
1819                // cout << "RND:" << rnumber << endl;
1820
1821                // This could be more efficient (log n), but map::upper_bound() doesn't let me dereference returned iterator
1822                double  prob_sum     = 0;       
1823                toprow* sampled_toprow;                         
1824                for(polyhedron* top_ref = statistic.rows[statistic.size()-1];top_ref!=statistic.row_ends[statistic.size()-1];top_ref=top_ref->next_poly)
1825                {
1826                        // cout << "CDF:"<< (*top_ref).first << endl;
1827
1828                        toprow* current_toprow = ((toprow*)top_ref);
1829
1830                        prob_sum += current_toprow->probability;
1831
1832                        if(prob_sum >= rnumber*normalization_factor)
1833                        {
1834                                sampled_toprow = (toprow*)top_ref;
1835                                break;
1836                        }                                               
1837                }                               
1838
1839                //// cout << "Toprow/Count: " << toprow_count << "/" << ordered_toprows.size() << endl;
1840                // cout << &sampled_toprow << ";";
1841
1842                rnumber = randu();                             
1843
1844                set<simplex*>::iterator s_ref;
1845                prob_sum = 0;           
1846                for(s_ref = sampled_toprow->triangulation.begin();s_ref!=sampled_toprow->triangulation.end();s_ref++)
1847                {               
1848                        prob_sum += (*s_ref)->probability;
1849
1850                        if(prob_sum/sampled_toprow->probability >= rnumber)
1851                                break;
1852                }
1853
1854                return pair<vec,simplex*>(sampled_toprow->condition_sum,*s_ref);       
1855        }
1856
1857        pair<double,double> choose_sigma(simplex* sampled_simplex)
1858        {
1859                double rnumber = randu();
1860                double sigma;
1861                                       
1862                double sum_g = 0;
1863                for(int i = 0;i<sampled_simplex->positive_gamma_parameters.size();i++)
1864                {
1865                        for(multimap<double,double>::iterator g_ref = sampled_simplex->positive_gamma_parameters[i].begin();g_ref != sampled_simplex->positive_gamma_parameters[i].end();g_ref++)
1866                        {
1867                                sum_g += (*g_ref).first/sampled_simplex->positive_gamma_sum;
1868
1869                                                       
1870                                if(sum_g>rnumber)
1871                                {
1872                                        //itpp::Gamma_RNG* gamma = new itpp::Gamma_RNG(conditions.size()-number_of_parameters,1/(*g_ref).second);
1873                                        //sigma = 1/(*gamma)();
1874                                                               
1875                                        GamRNG.setup(conditions.size()-number_of_parameters,(*g_ref).second);
1876                                                                                                                               
1877                                        sigma = 1/GamRNG();
1878
1879                                        // cout << "Sigma mean:   " << (*g_ref).second/(conditions.size()-number_of_parameters-1) << endl;                                                             
1880                                        break;
1881                                }                                                       
1882                        }
1883
1884                        if(sigma!=0)
1885                        {
1886                                break;
1887                        }
1888                }
1889
1890                rnumber = randu();
1891
1892                double pg_sum = 0;
1893                for(vector<multimap<double,double>>::iterator v_ref = sampled_simplex->positive_gamma_parameters.begin();v_ref!=sampled_simplex->positive_gamma_parameters.end();v_ref++)
1894                {
1895                        for(multimap<double,double>::iterator pg_ref = (*v_ref).begin();pg_ref!=(*v_ref).end();pg_ref++)
1896                        {
1897                                pg_sum += exp((sampled_simplex->min_beta-(*pg_ref).second)/sigma)*pow((*pg_ref).second/sigma,(int)conditions.size()-number_of_parameters-1)*(*pg_ref).second/fact(conditions.size()-number_of_parameters-1)*(*pg_ref).first;
1898                        }                                       
1899                }
1900
1901                double ng_sum = 0;
1902                for(vector<multimap<double,double>>::iterator v_ref = sampled_simplex->negative_gamma_parameters.begin();v_ref!=sampled_simplex->negative_gamma_parameters.end();v_ref++)
1903                {
1904                        for(multimap<double,double>::iterator ng_ref = (*v_ref).begin();ng_ref!=(*v_ref).end();ng_ref++)
1905                        {
1906                                ng_sum += exp((sampled_simplex->min_beta-(*ng_ref).second)/sigma)*pow((*ng_ref).second/sigma,(int)conditions.size()-number_of_parameters-1)*(*ng_ref).second/fact(conditions.size()-number_of_parameters-1)*(*ng_ref).first;
1907                        }                                       
1908                }
1909
1910                return pair<double,double>((pg_sum-ng_sum)/pg_sum,sigma);
1911        }
1912
1913        mat sample_mat(int n)
1914        {               
1915
1916                /// \TODO tady je to spatne, tady nesmi byt conditions.size(), viz RARX.bayes()
1917                if(conditions.size()-2-number_of_parameters>=0)
1918                {                       
1919                        mat sample_mat;
1920                        map<double,toprow*> ordered_toprows;                   
1921                        double sum_a = 0;
1922                       
1923                        //cout << "Likelihoods of toprows:" << endl;
1924
1925                        for(polyhedron* top_ref = statistic.rows[number_of_parameters];top_ref!=statistic.end_poly;top_ref=top_ref->next_poly)
1926                        {
1927                                toprow* current_top = (toprow*)top_ref;
1928
1929                                sum_a+=current_top->probability;
1930                                /*
1931                                cout << current_top->probability << "   ";
1932
1933                                for(set<vertex*>::iterator vert_ref = (*top_ref).vertices.begin();vert_ref!=(*top_ref).vertices.end();vert_ref++)
1934                                {
1935                                        cout << round(100*(*vert_ref)->get_coordinates())/100 << " ; ";
1936                                }
1937                                */
1938
1939                                // cout << endl;
1940                                ordered_toprows.insert(pair<double,toprow*>(sum_a,current_top));
1941                        }                       
1942                       
1943                        // cout << "Sum N: " << normalization_factor << endl;
1944
1945                        while(sample_mat.cols()<n)
1946                        {
1947                                //// cout << "*************************************" << endl;
1948
1949                               
1950                               
1951                                double rnumber = randu()*sum_a;
1952
1953                                // cout << "RND:" << rnumber << endl;
1954
1955                                // This could be more efficient (log n), but map::upper_bound() doesn't let me dereference returned iterator
1956                                int toprow_count = 0;
1957                                toprow* sampled_toprow;                         
1958                                for(map<double,toprow*>::iterator top_ref = ordered_toprows.begin();top_ref!=ordered_toprows.end();top_ref++)
1959                                {
1960                                        // cout << "CDF:"<< (*top_ref).first << endl;
1961                                        toprow_count++;
1962
1963                                        if((*top_ref).first >= rnumber)
1964                                        {
1965                                                sampled_toprow = (*top_ref).second;
1966                                                break;
1967                                        }                                               
1968                                }                               
1969
1970                                //// cout << "Toprow/Count: " << toprow_count << "/" << ordered_toprows.size() << endl;
1971                                // cout << &sampled_toprow << ";";
1972
1973                                rnumber = randu();                             
1974
1975                                set<simplex*>::iterator s_ref;
1976                                double sum_b = 0;
1977                                int simplex_count = 0;
1978                                for(s_ref = sampled_toprow->triangulation.begin();s_ref!=sampled_toprow->triangulation.end();s_ref++)
1979                                {
1980                                        simplex_count++;
1981                                       
1982                                        sum_b += (*s_ref)->probability;
1983
1984                                        if(sum_b/sampled_toprow->probability >= rnumber)
1985                                                break;
1986                                }
1987
1988                                //// cout << "Simplex/Count: " << simplex_count << "/" << sampled_toprow->triangulation.size() << endl;
1989                                //// cout << "Simplex factor: " << (*s_ref)->probability << endl;
1990                                //// cout << "Toprow factor:  " << sampled_toprow->probability << endl;
1991                                //// cout << "Emlig factor:   " << normalization_factor << endl;
1992                                // cout << &(*tri_ref) << endl;
1993
1994                                int number_of_runs = 0;
1995                                bool have_sigma = false;
1996                                double sigma = 0;
1997                                do
1998                                {
1999                                        rnumber = randu();
2000                                       
2001                                        double sum_g = 0;
2002                                        for(int i = 0;i<(*s_ref)->positive_gamma_parameters.size();i++)
2003                                        {
2004                                                for(multimap<double,double>::iterator g_ref = (*s_ref)->positive_gamma_parameters[i].begin();g_ref != (*s_ref)->positive_gamma_parameters[i].end();g_ref++)
2005                                                {
2006                                                        sum_g += (*g_ref).first/(*s_ref)->positive_gamma_sum;
2007
2008                                                       
2009                                                        if(sum_g>rnumber)
2010                                                        {
2011                                                                //itpp::Gamma_RNG* gamma = new itpp::Gamma_RNG(conditions.size()-number_of_parameters,1/(*g_ref).second);
2012                                                                //sigma = 1/(*gamma)();
2013                                                               
2014                                                                GamRNG.setup(conditions.size()-number_of_parameters,(*g_ref).second);
2015                                                                                                                               
2016                                                                sigma = 1/GamRNG();
2017
2018                                                                // cout << "Sigma mean:   " << (*g_ref).second/(conditions.size()-number_of_parameters-1) << endl;                                                             
2019                                                                break;
2020                                                        }                                                       
2021                                                }
2022
2023                                                if(sigma!=0)
2024                                                {
2025                                                        break;
2026                                                }
2027                                        }
2028
2029                                        rnumber = randu();
2030
2031                                        double pg_sum = 0;
2032                                        for(vector<multimap<double,double>>::iterator v_ref = (*s_ref)->positive_gamma_parameters.begin();v_ref!=(*s_ref)->positive_gamma_parameters.end();v_ref++)
2033                                        {
2034                                                for(multimap<double,double>::iterator pg_ref = (*v_ref).begin();pg_ref!=(*v_ref).end();pg_ref++)
2035                                                {
2036                                                        pg_sum += exp(((*s_ref)->min_beta-(*pg_ref).second)/sigma)*pow((*pg_ref).second/sigma,(int)conditions.size()-number_of_parameters-1)*(*pg_ref).second/fact(conditions.size()-number_of_parameters-1)*(*pg_ref).first;
2037                                                }                                       
2038                                        }
2039
2040                                        double ng_sum = 0;
2041                                        for(vector<multimap<double,double>>::iterator v_ref = (*s_ref)->negative_gamma_parameters.begin();v_ref!=(*s_ref)->negative_gamma_parameters.end();v_ref++)
2042                                        {
2043                                                for(multimap<double,double>::iterator ng_ref = (*v_ref).begin();ng_ref!=(*v_ref).end();ng_ref++)
2044                                                {
2045                                                        ng_sum += exp(((*s_ref)->min_beta-(*ng_ref).second)/sigma)*pow((*ng_ref).second/sigma,(int)conditions.size()-number_of_parameters-1)*(*ng_ref).second/fact(conditions.size()-number_of_parameters-1)*(*ng_ref).first;
2046                                                }                                       
2047                                        }
2048                                       
2049                                        if((pg_sum-ng_sum)/pg_sum>rnumber)
2050                                        {
2051                                                have_sigma = true;
2052                                        }
2053
2054                                        number_of_runs++;
2055                                }
2056                                while(!have_sigma);
2057
2058                                //// cout << "Sigma: " << sigma << endl;
2059                                //// cout << "Nr. of sigma runs: " << number_of_runs << endl;
2060
2061                                int dimension = (*s_ref)->vertices.size()-1;
2062
2063                                mat jacobian(dimension,dimension);
2064                                vec gradient = sampled_toprow->condition_sum.right(dimension);
2065
2066                                vertex* base_vert = *(*s_ref)->vertices.begin();
2067
2068                                //// cout << "Base vertex coords(should be close to est. param.): " << base_vert->get_coordinates() << endl;
2069                               
2070                                int row_count = 0;
2071
2072                                for(set<vertex*>::iterator vert_ref = ++(*s_ref)->vertices.begin();vert_ref!=(*s_ref)->vertices.end();vert_ref++)
2073                                {
2074                                        vec current_coords = (*vert_ref)->get_coordinates();
2075
2076                                        //// cout << "Coords of vertex[" << row_count << "]: " << current_coords << endl;
2077                                       
2078                                        vec relative_coords = current_coords-base_vert->get_coordinates();                             
2079
2080                                        jacobian.set_row(row_count,relative_coords);
2081
2082                                        row_count++;
2083                                }                               
2084                               
2085                                //// cout << "Jacobian: " << jacobian << endl;
2086
2087                                //// cout << "Gradient before trafo:" << gradient << endl;
2088                                                               
2089                                gradient = jacobian*gradient;   
2090
2091                                //// cout << "Gradient after trafo:" << gradient << endl;
2092
2093                                // vec normal_gradient = gradient/sqrt(gradient*gradient);
2094                                // cout << gradient << endl;
2095                                // cout << normal_gradient << endl;
2096                                // cout << sqrt(gradient*gradient) << endl;
2097
2098                                mat rotation_matrix = eye(dimension);                           
2099
2100                                                               
2101
2102                                for(int i = 1;i<dimension;i++)
2103                                {
2104                                        vec x_axis = zeros(dimension);
2105                                        x_axis.set(0,1);
2106
2107                                        x_axis = rotation_matrix*x_axis;
2108
2109                                        double t = abs(gradient[i]/gradient*x_axis);
2110
2111                                        double sin_theta = sign(gradient[i])*t/sqrt(1+pow(t,2));
2112                                        double cos_theta = sign(gradient*x_axis)/sqrt(1+pow(t,2));
2113
2114                                        mat partial_rotation = eye(dimension);
2115
2116                                        partial_rotation.set(0,0,cos_theta);
2117                                        partial_rotation.set(i,i,cos_theta);
2118                                       
2119                                        partial_rotation.set(0,i,sin_theta);
2120                                        partial_rotation.set(i,0,-sin_theta);
2121                                       
2122                                        rotation_matrix = rotation_matrix*partial_rotation;                             
2123                                       
2124                                }
2125
2126                                // cout << rotation_matrix << endl;
2127                               
2128                                mat extended_rotation = rotation_matrix;
2129                                extended_rotation.ins_col(0,zeros(extended_rotation.rows()));
2130
2131                                //// cout << "Extended rotation: " << extended_rotation << endl;
2132                               
2133                                vec minima = itpp::min(extended_rotation,2);
2134                                vec maxima = itpp::max(extended_rotation,2);
2135
2136                                //// cout << "Minima: " << minima << endl;
2137                                //// cout << "Maxima: " << maxima << endl;
2138
2139                                vec sample_coordinates;         
2140                                bool is_inside = true;
2141                               
2142                                vec new_sample;
2143                                sample_coordinates = new_sample;
2144
2145                                for(int j = 0;j<number_of_parameters;j++)
2146                                {
2147                                        rnumber = randu();
2148                                       
2149                                        double coordinate;
2150
2151                                        if(j==0)
2152                                        {                                               
2153                                                vec new_gradient = rotation_matrix*gradient;
2154                                               
2155                                                //// cout << "New gradient(should have only first component nonzero):" << new_gradient << endl;
2156
2157                                                // cout << "Max: " << maxima[0] << "  Min: " << minima[0] << "  Grad:" << new_gradient[0] << endl;
2158                                               
2159                                                double log_bracket = 1-rnumber*(1-exp(new_gradient[0]/sigma*(minima[0]-maxima[0])));
2160                                               
2161                                                coordinate = minima[0]-sigma/new_gradient[0]*log(log_bracket);
2162                                        }
2163                                        else
2164                                        {
2165                                                coordinate = minima[j]+rnumber*(maxima[j]-minima[j]);
2166                                        }
2167
2168                                        sample_coordinates.ins(j,coordinate);
2169                                }
2170
2171                                //// cout << "Sampled coordinates(gradient direction): " << sample_coordinates << endl;
2172
2173                                sample_coordinates = rotation_matrix.T()*sample_coordinates;
2174
2175                                //// cout << "Sampled coordinates(backrotated direction):" << sample_coordinates << endl;
2176
2177                               
2178                                for(int j = 0;j<sample_coordinates.size();j++)
2179                                {
2180                                        if(sample_coordinates[j]<0)
2181                                        {
2182                                                is_inside = false;
2183                                        }
2184                                }
2185
2186                                double above_criterion = ones(sample_coordinates.size())*sample_coordinates;
2187
2188                                if(above_criterion>1)
2189                                {
2190                                        is_inside = false;
2191                                }
2192
2193                                if(is_inside)
2194                                {                                       
2195                                        sample_coordinates = jacobian.T()*sample_coordinates+(*base_vert).get_coordinates();
2196                                       
2197                                        sample_coordinates.ins(0,sigma);
2198                                       
2199                                        //// cout << "Sampled coordinates(parameter space):" << sample_coordinates << endl;
2200
2201                                        sample_mat.ins_col(0,sample_coordinates);
2202
2203                                        // cout << sample_mat.cols() << ",";
2204                                }
2205
2206                                // cout << sampled_toprow->condition_sum.right(sampled_toprow->condition_sum.size()-1)*min_grad->get_coordinates()-sampled_toprow->condition_sum[0] << endl;
2207                                // cout << sampled_toprow->condition_sum.right(sampled_toprow->condition_sum.size()-1)*max_grad->get_coordinates()-sampled_toprow->condition_sum[0] << endl;
2208
2209                               
2210                        }
2211
2212                        cout << endl;
2213                        return sample_mat;
2214                }
2215                else
2216                {
2217                        throw new exception("You are trying to sample from density that is not determined (parameters can't be integrated out)!");
2218               
2219                        return 0;
2220                }
2221
2222               
2223        }
2224
2225        pair<vec,mat> importance_sample(int n)
2226        {
2227                vec probabilities;
2228                mat samples;
2229               
2230                for(int i = 0;i<n;i++)
2231                {
2232                        pair<vec,simplex*> condition_and_simplex = choose_simplex();
2233
2234                        pair<double,double> probability_and_sigma = choose_sigma(condition_and_simplex.second);
2235
2236                        int dimension = condition_and_simplex.second->vertices.size()-1;
2237
2238                        mat jacobian(dimension,dimension);
2239                        vec gradient = condition_and_simplex.first.right(dimension);
2240
2241                        vertex* base_vert = *condition_and_simplex.second->vertices.begin();
2242
2243                        //// cout << "Base vertex coords(should be close to est. param.): " << base_vert->get_coordinates() << endl;
2244                               
2245                        int row_count = 0;
2246
2247                        for(set<vertex*>::iterator vert_ref = ++condition_and_simplex.second->vertices.begin();vert_ref!=condition_and_simplex.second->vertices.end();vert_ref++)
2248                        {
2249                                vec current_coords = (*vert_ref)->get_coordinates();
2250
2251                                //// cout << "Coords of vertex[" << row_count << "]: " << current_coords << endl;
2252                                       
2253                                vec relative_coords = current_coords-base_vert->get_coordinates();                             
2254
2255                                jacobian.set_row(row_count,relative_coords);
2256
2257                                row_count++;
2258                        }                               
2259                               
2260                        //// cout << "Jacobian: " << jacobian << endl;                 
2261
2262                        /// \todo Is this correct? Are the random coordinates really jointly uniform? I don't know.
2263                        vec sample_coords;
2264                        double sampling_diff = 1;
2265                        for(int j = 0;j<number_of_parameters;j++)
2266                        {
2267                                double rnumber = randu()*sampling_diff;
2268
2269                                sample_coords.ins(0,rnumber);
2270
2271                                sampling_diff -= rnumber;
2272                        }
2273
2274                        sample_coords = jacobian.T()*sample_coords+(*base_vert).get_coordinates();
2275
2276                        vec extended_coords = sample_coords;
2277                        extended_coords.ins(0,-1.0);
2278
2279                        double sample_prob = 1/condition_and_simplex.second->probability/pow(probability_and_sigma.second,(int)conditions.size()-number_of_parameters)*exp(1/probability_and_sigma.second*(extended_coords*condition_and_simplex.first));
2280                        sample_prob *= probability_and_sigma.first;
2281
2282                        sample_coords.ins(0,probability_and_sigma.second);
2283
2284                        samples.ins_col(0,sample_coords);
2285                        probabilities.ins(0,sample_prob);
2286                }
2287       
2288                return pair<vec,mat>(probabilities,samples);
2289        }
2290
2291protected:
2292
2293        /// A method for creating plain default statistic representing only the range of the parameter space.
2294    void create_statistic(int number_of_parameters)
2295        {
2296                /*
2297                for(int i = 0;i<number_of_parameters;i++)
2298                {
2299                        vec condition_vec = zeros(number_of_parameters+1);
2300                        condition_vec[i+1]  = 1;
2301
2302                        condition* new_condition = new condition(condition_vec);
2303                       
2304                        conditions.push_back(new_condition);
2305                }
2306                */
2307
2308                // An empty vector of coordinates.
2309                vec origin_coord;       
2310
2311                // We create an origin - this point will have all the coordinates zero, but now it has an empty vector of coords.
2312                vertex *origin = new vertex(origin_coord);
2313
2314                origin->my_emlig = this;
2315               
2316                /*
2317                // As a statistic, we have to create a vector of vectors of polyhedron pointers. It will then represent the Hasse
2318                // diagram. First we create a vector of polyhedrons..
2319                list<polyhedron*> origin_vec;
2320
2321                // ..we fill it with the origin..
2322                origin_vec.push_back(origin);
2323
2324                // ..and we fill the statistic with the created vector.
2325                statistic.push_back(origin_vec);
2326                */
2327
2328                statistic = *(new c_statistic());               
2329               
2330                statistic.append_polyhedron(0, origin);
2331
2332                // Now we have a statistic for a zero dimensional space. Regarding to how many dimensional space we need to
2333                // describe, we have to widen the descriptional default statistic. We use an iterative procedure as follows:
2334                for(int i=0;i<number_of_parameters;i++)
2335                {
2336                        // We first will create two new vertices. These will be the borders of the parameter space in the dimension
2337                        // of newly added parameter. Therefore they will have all coordinates except the last one zero. We get the
2338                        // right amount of zero cooridnates by reading them from the origin
2339                        vec origin_coord = origin->get_coordinates();                                           
2340
2341                        // And we incorporate the nonzero coordinates into the new cooordinate vectors
2342                        vec origin_coord1 = concat(origin_coord,-max_range); 
2343                        vec origin_coord2 = concat(origin_coord,max_range);                             
2344                                       
2345
2346                        // Now we create the points
2347                        vertex* new_point1 = new vertex(origin_coord1);
2348                        vertex* new_point2 = new vertex(origin_coord2);
2349
2350                        new_point1->my_emlig = this;
2351                        new_point2->my_emlig = this;
2352                       
2353                        //*********************************************************************************************************
2354                        // The algorithm for recursive build of a new Hasse diagram representing the space structure from the old
2355                        // diagram works so that you create two copies of the old Hasse diagram, you shift them up one level (points
2356                        // will be segments, segments will be areas etc.) and you connect each one of the original copied polyhedrons
2357                        // with its offspring by a parent-child relation. Also each of the segments in the first (second) copy is
2358                        // connected to the first (second) newly created vertex by a parent-child relation.
2359                        //*********************************************************************************************************
2360
2361
2362                        /*
2363                        // Create the vectors of vectors of pointers to polyhedrons to hold the copies of the old Hasse diagram
2364                        vector<vector<polyhedron*>> new_statistic1;
2365                        vector<vector<polyhedron*>> new_statistic2;
2366                        */
2367
2368                        c_statistic* new_statistic1 = new c_statistic();
2369                        c_statistic* new_statistic2 = new c_statistic();
2370
2371                       
2372                        // Copy the statistic by rows                   
2373                        for(int j=0;j<statistic.size();j++)
2374                        {
2375                               
2376
2377                                // an element counter
2378                                int element_number = 0;
2379
2380                                /*
2381                                vector<polyhedron*> supportnew_1;
2382                                vector<polyhedron*> supportnew_2;
2383
2384                                new_statistic1.push_back(supportnew_1);
2385                                new_statistic2.push_back(supportnew_2);
2386                                */
2387
2388                                // for each polyhedron in the given row
2389                                for(polyhedron* horiz_ref = statistic.rows[j];horiz_ref!=statistic.get_end();horiz_ref=horiz_ref->next_poly)
2390                                {       
2391                                        // Append an extra zero coordinate to each of the vertices for the new dimension
2392                                        // If vert_ref is at the first index => we loop through vertices
2393                                        if(j == 0)
2394                                        {
2395                                                // cast the polyhedron pointer to a vertex pointer and push a zero to its vector of coordinates
2396                                                ((vertex*) horiz_ref)->push_coordinate(0);
2397                                        }
2398                                        /*
2399                                        else
2400                                        {
2401                                                ((toprow*) (*horiz_ref))->condition.ins(0,0);
2402                                        }*/
2403
2404                                        // if it has parents
2405                                        if(!horiz_ref->parents.empty())
2406                                        {
2407                                                // save the relative address of this child in a vector kids_rel_addresses of all its parents.
2408                                                // This information will later be used for copying the whole Hasse diagram with each of the
2409                                                // relations contained within.
2410                                                for(list<polyhedron*>::iterator parent_ref = horiz_ref->parents.begin();parent_ref != horiz_ref->parents.end();parent_ref++)
2411                                                {
2412                                                        (*parent_ref)->kids_rel_addresses.push_back(element_number);                                                   
2413                                                }                                               
2414                                        }
2415
2416                                        // **************************************************************************************************
2417                                        // Here we begin creating a new polyhedron, which will be a copy of the old one. Each such polyhedron
2418                                        // will be created as a toprow, but this information will be later forgotten and only the polyhedrons
2419                                        // in the top row of the Hasse diagram will be considered toprow for later use.
2420                                        // **************************************************************************************************
2421
2422                                        // First we create vectors specifying a toprow condition. In the case of a preconstructed statistic
2423                                        // this condition will be a vector of zeros. There are two vectors, because we need two copies of
2424                                        // the original Hasse diagram.
2425                                        vec vec1(number_of_parameters+1);
2426                                        vec1.zeros();
2427
2428                                        vec vec2(number_of_parameters+1);
2429                                        vec2.zeros();
2430
2431                                        // We create a new toprow with the previously specified condition.
2432                                        toprow* current_copy1 = new toprow(vec1, 0);
2433                                        toprow* current_copy2 = new toprow(vec2, 0);
2434
2435                                        current_copy1->my_emlig = this;
2436                                        current_copy2->my_emlig = this;
2437
2438                                        // The vertices of the copies will be inherited, because there will be a parent/child relation
2439                                        // between each polyhedron and its offspring (comming from the copy) and a parent has all the
2440                                        // vertices of its child plus more.
2441                                        for(set<vertex*>::iterator vertex_ref = horiz_ref->vertices.begin();vertex_ref!=horiz_ref->vertices.end();vertex_ref++)
2442                                        {
2443                                                current_copy1->vertices.insert(*vertex_ref);
2444                                                current_copy2->vertices.insert(*vertex_ref);                                           
2445                                        }
2446                                       
2447                                        // The only new vertex of the offspring should be the newly created point.
2448                                        current_copy1->vertices.insert(new_point1);
2449                                        current_copy2->vertices.insert(new_point2);                                     
2450                                       
2451                                        // This method guarantees that each polyhedron is already triangulated, therefore its triangulation
2452                                        // is only one set of vertices and it is the set of all its vertices.
2453                                        simplex* t_simplex1 = new simplex(current_copy1->vertices);
2454                                        simplex* t_simplex2 = new simplex(current_copy2->vertices);                                     
2455                                       
2456                                        current_copy1->triangulation.insert(t_simplex1);
2457                                        current_copy2->triangulation.insert(t_simplex2);                                       
2458                                       
2459                                        // Now we have copied the polyhedron and we have to copy all of its relations. Because we are copying
2460                                        // in the Hasse diagram from bottom up, we always have to copy the parent/child relations to all the
2461                                        // kids and when we do that and know the child, in the child we will remember the parent we came from.
2462                                        // This way all the parents/children relations are saved in both the parent and the child.
2463                                        if(!horiz_ref->kids_rel_addresses.empty())
2464                                        {
2465                                                for(list<int>::iterator kid_ref = horiz_ref->kids_rel_addresses.begin();kid_ref!=horiz_ref->kids_rel_addresses.end();kid_ref++)
2466                                                {       
2467                                                        polyhedron* new_kid1 = new_statistic1->rows[j-1];
2468                                                        polyhedron* new_kid2 = new_statistic2->rows[j-1];
2469
2470                                                        // THIS IS NOT EFFECTIVE: It could be improved by having the list indexed for new_statistic, but
2471                                                        // not indexed for statistic. Hopefully this will not cause a big slowdown - happens only offline.
2472                                                        if(*kid_ref)
2473                                                        {
2474                                                                for(int k = 1;k<=(*kid_ref);k++)
2475                                                                {
2476                                                                        new_kid1=new_kid1->next_poly;
2477                                                                        new_kid2=new_kid2->next_poly;
2478                                                                }
2479                                                        }
2480                                                       
2481                                                        // find the child and save the relation to the parent
2482                                                        current_copy1->children.push_back(new_kid1);
2483                                                        current_copy2->children.push_back(new_kid2);
2484
2485                                                        // in the child save the parents' address
2486                                                        new_kid1->parents.push_back(current_copy1);
2487                                                        new_kid2->parents.push_back(current_copy2);
2488                                                }                                               
2489
2490                                                // Here we clear the parents kids_rel_addresses vector for later use (when we need to widen the
2491                                                // Hasse diagram again)
2492                                                horiz_ref->kids_rel_addresses.clear();
2493                                        }
2494                                        // If there were no children previously, we are copying a polyhedron that has been a vertex before.
2495                                        // In this case it is a segment now and it will have a relation to its mother (copywise) and to the
2496                                        // newly created point. Here we create the connection to the new point, again from both sides.
2497                                        else
2498                                        {
2499                                                // Add the address of the new point in the former vertex
2500                                                current_copy1->children.push_back(new_point1);
2501                                                current_copy2->children.push_back(new_point2);
2502
2503                                                // Add the address of the former vertex in the new point
2504                                                new_point1->parents.push_back(current_copy1);
2505                                                new_point2->parents.push_back(current_copy2);
2506                                        }
2507
2508                                        // Save the mother in its offspring
2509                                        current_copy1->children.push_back(horiz_ref);
2510                                        current_copy2->children.push_back(horiz_ref);
2511
2512                                        // Save the offspring in its mother
2513                                        horiz_ref->parents.push_back(current_copy1);
2514                                        horiz_ref->parents.push_back(current_copy2);   
2515                                                               
2516                                       
2517                                        // Add the copies into the relevant statistic. The statistic will later be appended to the previous
2518                                        // Hasse diagram
2519                                        new_statistic1->append_polyhedron(j,current_copy1);
2520                                        new_statistic2->append_polyhedron(j,current_copy2);
2521                                       
2522                                        // Raise the count in the vector of polyhedrons
2523                                        element_number++;                       
2524                                       
2525                                }
2526                               
2527                        }
2528
2529                        /*
2530                        statistic.begin()->push_back(new_point1);
2531                        statistic.begin()->push_back(new_point2);
2532                        */
2533
2534                        statistic.append_polyhedron(0, new_point1);
2535                        statistic.append_polyhedron(0, new_point2);
2536
2537                        // Merge the new statistics into the old one. This will either be the final statistic or we will
2538                        // reenter the widening loop.
2539                        for(int j=0;j<new_statistic1->size();j++)
2540                        {
2541                                /*
2542                                if(j+1==statistic.size())
2543                                {
2544                                        list<polyhedron*> support;
2545                                        statistic.push_back(support);
2546                                }
2547                               
2548                                (statistic.begin()+j+1)->insert((statistic.begin()+j+1)->end(),new_statistic1[j].begin(),new_statistic1[j].end());
2549                                (statistic.begin()+j+1)->insert((statistic.begin()+j+1)->end(),new_statistic2[j].begin(),new_statistic2[j].end());
2550                                */
2551                                statistic.append_polyhedron(j+1,new_statistic1->rows[j],new_statistic1->row_ends[j]);
2552                                statistic.append_polyhedron(j+1,new_statistic2->rows[j],new_statistic2->row_ends[j]);
2553                        }                       
2554                }
2555
2556                /*
2557                vector<list<toprow*>> toprow_statistic;
2558                int line_count = 0;
2559
2560                for(vector<list<polyhedron*>>::iterator polyhedron_ref = ++statistic.begin(); polyhedron_ref!=statistic.end();polyhedron_ref++)
2561                {
2562                        list<toprow*> support_list;
2563                        toprow_statistic.push_back(support_list);                                               
2564
2565                        for(list<polyhedron*>::iterator polyhedron_ref2 = polyhedron_ref->begin(); polyhedron_ref2 != polyhedron_ref->end(); polyhedron_ref2++)
2566                        {
2567                                toprow* support_top = (toprow*)(*polyhedron_ref2);
2568
2569                                toprow_statistic[line_count].push_back(support_top);
2570                        }
2571
2572                        line_count++;
2573                }*/
2574
2575                /*
2576                vector<int> sizevector;
2577                for(int s = 0;s<statistic.size();s++)
2578                {
2579                        sizevector.push_back(statistic.row_size(s));
2580                }
2581                */
2582               
2583        }
2584       
2585};
2586
2587
2588
2589//! Robust Bayesian AR model for Multicriteria-Laplace-Inverse-Gamma density
2590class RARX //: public BM
2591{
2592private:
2593        bool has_constant;
2594
2595        int window_size;       
2596
2597        list<vec> conditions;
2598
2599public:
2600        emlig* posterior;
2601
2602        RARX(int number_of_parameters, const int window_size, bool has_constant)//:BM()
2603        {
2604                this->has_constant = has_constant;
2605               
2606                posterior = new emlig(number_of_parameters);
2607
2608                this->window_size = window_size;               
2609        };
2610
2611        void bayes(itpp::vec yt)
2612        {
2613                if(has_constant)
2614                {
2615                        int c_size = yt.size();
2616                       
2617                        yt.ins(c_size,1.0);
2618                }
2619               
2620                if(yt.size() == posterior->number_of_parameters+1)
2621                {
2622                        conditions.push_back(yt);               
2623                }
2624                else
2625                {
2626                        throw new exception("Wrong condition size for bayesian data update!");
2627                }
2628
2629                //posterior->step_me(0);
2630               
2631                /// \TODO tohle je spatne, tady musi byt jiny vypocet poctu podminek, kdyby nejaka byla multiplicitni, tak tohle bude spatne
2632                if(conditions.size()>window_size && window_size!=0)
2633                {                       
2634                        posterior->add_and_remove_condition(yt,conditions.front());
2635                        conditions.pop_front();
2636
2637                        //posterior->step_me(1);
2638                }
2639                else
2640                {
2641                        posterior->add_condition(yt);
2642                }
2643                               
2644        }
2645
2646};
2647
2648
2649
2650#endif //TRAGE_H
Note: See TracBrowser for help on using the browser.