root/applications/robust/robustlib.h @ 1337

Revision 1337, 73.6 kB (checked in by sindj, 13 years ago)

Zacatky experimentovani s knihovnou robustlib. 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                        if(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                        if(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                                        switch(sender->get_state(SPLIT))
892                                        {
893                                        case 1:
894                                                current_parent->positivechildren.push_back(sender);
895                                                current_parent->positiveneutralvertices.insert(sender->vertices.begin(),sender->vertices.end());
896                                        break;
897                                        case 0:
898                                                current_parent->neutralchildren.push_back(sender);
899                                                current_parent->positiveneutralvertices.insert(sender->positiveneutralvertices.begin(),sender->positiveneutralvertices.end());
900                                                current_parent->negativeneutralvertices.insert(sender->negativeneutralvertices.begin(),sender->negativeneutralvertices.end());
901
902                                                if(current_parent->totally_neutral == NULL)
903                                                {
904                                                        current_parent->totally_neutral = sender->totally_neutral;
905                                                }
906                                                else
907                                                {
908                                                        current_parent->totally_neutral = current_parent->totally_neutral && sender->totally_neutral;
909                                                }
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                                                /// \TODO Nechapu druhou podminku, zda se mi ze je to spatne.. Nemela by byt jen prvni? Nebo se jedna o nastaveni totalni neutrality?
927                                                if((current_parent->negativechildren.size()>0&&current_parent->positivechildren.size()>0)||
928                                                                                                        (current_parent->neutralchildren.size()>0&&current_parent->totally_neutral==false))
929                                                {
930                                                        for_splitting[level+1].push_back(current_parent);                                               
931                                                               
932                                                        current_parent->set_state(0, SPLIT);
933                                                }
934                                                else
935                                                {
936                                                        if(current_parent->negativechildren.size()>0)
937                                                        {
938                                                                current_parent->set_state(-1, SPLIT);
939
940                                                                ((toprow*)current_parent)->condition_sum-=toadd->value;
941                                                                       
942                                                        }
943                                                        else if(current_parent->positivechildren.size()>0)
944                                                        {
945                                                                current_parent->set_state(1, SPLIT);
946
947                                                                ((toprow*)current_parent)->condition_sum+=toadd->value;                                                                 
948                                                        }
949                                                        else
950                                                        {
951                                                                current_parent->raise_multiplicity();                                                           
952                                                        }
953
954                                                        ((toprow*)current_parent)->condition_order++;
955
956                                                        if(level == number_of_parameters - 1)
957                                                        {
958                                                                toprow* cur_par_toprow = ((toprow*)current_parent);
959                                                                cur_par_toprow->probability = 0.0;
960                                                                       
961                                                                //map<double,set<vertex*>> new_triangulation;
962                                                               
963                                                                for(set<simplex*>::iterator s_ref = current_parent->triangulation.begin();s_ref!=current_parent->triangulation.end();s_ref++)
964                                                                {
965                                                                        double cur_prob = cur_par_toprow->integrate_simplex((*s_ref),'C');
966                                                                       
967                                                                        cur_par_toprow->probability += cur_prob;
968
969                                                                        //new_triangulation.insert(pair<double,set<vertex*>>(cur_prob,(*t_ref).second));
970                                                                }
971
972                                                                cur_par_toprow->my_emlig->normalization_factor += cur_par_toprow->probability;
973
974                                                                //current_parent->triangulation.clear();
975                                                                //current_parent->triangulation.insert(new_triangulation.begin(),new_triangulation.end());
976                                                        }
977
978                                                        if(current_parent->mergechild == NULL)
979                                                        {
980                                                                current_parent->positivechildren.clear();
981                                                                current_parent->negativechildren.clear();
982                                                                current_parent->neutralchildren.clear();
983                                                                current_parent->totallyneutralchildren.clear();
984                                                                current_parent->totallyneutralgrandchildren.clear();
985                                                                // current_parent->grandparents.clear();
986                                                                current_parent->positiveneutralvertices.clear();
987                                                                current_parent->negativeneutralvertices.clear();
988                                                                current_parent->totally_neutral = NULL;
989                                                                current_parent->kids_rel_addresses.clear();
990                                                        }                                                       
991                                                }
992                                        }
993                                }
994
995                                if(is_last)
996                                {
997                                        current_parent->mergechild = NULL;
998                                        current_parent->message_counter = 0;
999
1000                                        send_state_message(current_parent,toadd,toremove,level+1);
1001                                }
1002                       
1003                        }
1004                       
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                                if(i==0)
1060                                {
1061                                        cout << ((vertex*)horiz_ref)->get_coordinates() << endl;
1062                                }
1063                                */
1064
1065                                /*
1066                                char* string = "Checkpoint";
1067
1068
1069                                if((*horiz_ref).parentconditions.size()==0)
1070                                {
1071                                        zero++;
1072                                }
1073                                else if((*horiz_ref).parentconditions.size()==1)
1074                                {
1075                                        one++;                                 
1076                                }
1077                                else
1078                                {
1079                                        two++;
1080                                }
1081                                */
1082                               
1083                        }
1084                }
1085               
1086
1087                /*
1088                list<vec> table_entries;
1089                for(polyhedron* horiz_ref = statistic.rows[statistic.size()-1];horiz_ref!=statistic.row_ends[statistic.size()-1];horiz_ref=horiz_ref->next_poly)
1090                {
1091                        toprow *current_toprow = (toprow*)(horiz_ref);
1092                        for(list<set<vertex*>>::iterator tri_ref = current_toprow->triangulation.begin();tri_ref!=current_toprow->triangulation.end();tri_ref++)
1093                        {
1094                                for(set<vertex*>::iterator vert_ref = (*tri_ref).begin();vert_ref!=(*tri_ref).end();vert_ref++)
1095                                {
1096                                        vec table_entry = vec();
1097                                       
1098                                        table_entry.ins(0,(*vert_ref)->get_coordinates()*current_toprow->condition.get(1,current_toprow->condition.size()-1)-current_toprow->condition.get(0,0));
1099                                       
1100                                        table_entry.ins(0,(*vert_ref)->get_coordinates());
1101
1102                                        table_entries.push_back(table_entry);
1103                                }
1104                        }                       
1105                }
1106
1107                unique(table_entries.begin(),table_entries.end());
1108
1109                               
1110               
1111                for(list<vec>::iterator entry_ref = table_entries.begin();entry_ref!=table_entries.end();entry_ref++)
1112                {
1113                        ofstream myfile;
1114                        myfile.open("robust_data.txt", ios::out | ios::app);
1115                        if (myfile.is_open())
1116                        {
1117                                for(int i = 0;i<(*entry_ref).size();i++)
1118                                {
1119                                        myfile << (*entry_ref)[i] << ";";
1120                                }
1121                                myfile << endl;
1122                       
1123                                myfile.close();
1124                        }
1125                        else
1126                        {
1127                                cout << "File problem." << endl;
1128                        }
1129                }
1130                */
1131               
1132
1133                return;
1134        }
1135
1136        int statistic_rowsize(int row)
1137        {
1138                return statistic.row_size(row);
1139        }
1140
1141        void add_condition(vec toadd)
1142        {
1143                vec null_vector = "";
1144
1145                add_and_remove_condition(toadd, null_vector);
1146        }
1147
1148
1149        void remove_condition(vec toremove)
1150        {               
1151                vec null_vector = "";
1152
1153                add_and_remove_condition(null_vector, toremove);
1154       
1155        }
1156
1157        void add_and_remove_condition(vec toadd, vec toremove)
1158        {
1159                //step_me(0);
1160                normalization_factor = 0;
1161                min_ll = numeric_limits<double>::max();
1162
1163                bool should_remove = (toremove.size() != 0);
1164                bool should_add    = (toadd.size() != 0);
1165
1166                for_splitting.clear();
1167                for_merging.clear();
1168
1169                for(int i = 0;i<statistic.size();i++)
1170                {
1171                        list<polyhedron*> empty_split;
1172                        list<polyhedron*> empty_merge;
1173
1174                        for_splitting.push_back(empty_split);
1175                        for_merging.push_back(empty_merge);
1176                }
1177
1178                list<condition*>::iterator toremove_ref = conditions.end();
1179                bool condition_should_be_added = should_add;
1180
1181                for(list<condition*>::iterator ref = conditions.begin();ref!=conditions.end();ref++)
1182                {
1183                        if(should_remove)
1184                        {
1185                                if((*ref)->value == toremove)
1186                                {
1187                                        if((*ref)->multiplicity>1)
1188                                        {
1189                                                (*ref)->multiplicity--;
1190
1191                                                alter_toprow_conditions(*ref,false);
1192
1193                                                should_remove = false;
1194                                        }
1195                                        else
1196                                        {
1197                                                toremove_ref = ref;                                                     
1198                                        }
1199                                }
1200                        }
1201
1202                        if(should_add)
1203                        {
1204                                if((*ref)->value == toadd)
1205                                {
1206                                        (*ref)->multiplicity++;
1207
1208                                        alter_toprow_conditions(*ref,true);
1209
1210                                        should_add = false;
1211
1212                                        condition_should_be_added = false;
1213                                }                               
1214                        }
1215                }       
1216
1217                condition* condition_to_remove = NULL;
1218
1219                if(toremove_ref!=conditions.end())
1220                {
1221                        condition_to_remove = *toremove_ref;
1222                        conditions.erase(toremove_ref);                 
1223                }
1224
1225                condition* condition_to_add = NULL;
1226
1227                if(condition_should_be_added)
1228                {
1229                        condition* new_condition = new condition(toadd);
1230                       
1231                        conditions.push_back(new_condition);
1232                        condition_to_add = new_condition;
1233                }               
1234               
1235                for(polyhedron* horizontal_position = statistic.rows[0];horizontal_position!=statistic.get_end();horizontal_position=horizontal_position->next_poly)
1236                {               
1237                        vertex* current_vertex = (vertex*)horizontal_position;
1238                       
1239                        if(should_add||should_remove)
1240                        {
1241                                vec appended_coords = current_vertex->get_coordinates();
1242                                appended_coords.ins(0,-1.0);                           
1243
1244                                if(should_add)
1245                                {
1246                                        double local_condition = 0;// = toadd*(appended_coords.first/=appended_coords.second);
1247
1248                                        local_condition = appended_coords*toadd;
1249
1250                                        current_vertex->set_state(local_condition,SPLIT);
1251
1252                                        /// \TODO There should be a rounding error tolerance used here to insure we are not having too many points because of rounding error.
1253                                        if(local_condition == 0)
1254                                        {
1255                                                current_vertex->totally_neutral = true;
1256
1257                                                current_vertex->raise_multiplicity();
1258
1259                                                current_vertex->negativeneutralvertices.insert(current_vertex);
1260                                                current_vertex->positiveneutralvertices.insert(current_vertex);
1261                                        }                                       
1262                                }
1263                       
1264                                if(should_remove)
1265                                {                                       
1266                                        set<condition*>::iterator cond_ref;
1267                                       
1268                                        for(cond_ref = current_vertex->parentconditions.begin();cond_ref!=current_vertex->parentconditions.end();cond_ref++)
1269                                        {
1270                                                if(*cond_ref == condition_to_remove)
1271                                                {
1272                                                        break;
1273                                                }
1274                                        }
1275
1276                                        if(cond_ref!=current_vertex->parentconditions.end())
1277                                        {
1278                                                current_vertex->parentconditions.erase(cond_ref);
1279                                                current_vertex->set_state(0,MERGE);
1280                                                for_merging[0].push_back(current_vertex);
1281                                        }
1282                                        else
1283                                        {
1284                                                double local_condition = toremove*appended_coords;
1285                                                current_vertex->set_state(local_condition,MERGE);
1286                                        }
1287                                }                               
1288                        }
1289
1290                        send_state_message(current_vertex, condition_to_add, condition_to_remove, 0);           
1291                       
1292                }
1293
1294               
1295               
1296                if(should_remove)
1297                {
1298                        for(int i = 0;i<for_merging.size();i++)
1299                        {
1300                                for(list<polyhedron*>::iterator merge_ref = for_merging[i].begin();merge_ref!=for_merging[i].end();merge_ref++)
1301                                {
1302                                        cout << (*merge_ref)->get_state(MERGE) << ",";
1303                                }
1304
1305                                cout << endl;
1306                        }
1307
1308                        set<vertex*> vertices_to_be_reduced;                   
1309                       
1310                        int k = 1;
1311
1312                        for(vector<list<polyhedron*>>::iterator vert_ref = for_merging.begin();vert_ref<for_merging.end();vert_ref++)
1313                        {
1314                                for(list<polyhedron*>::reverse_iterator merge_ref = vert_ref->rbegin();merge_ref!=vert_ref->rend();merge_ref++)
1315                                {
1316                                        if((*merge_ref)->get_multiplicity()>1)
1317                                        {
1318                                                if(k==1)
1319                                                {
1320                                                        vertices_to_be_reduced.insert((vertex*)(*merge_ref));
1321                                                }
1322                                                else
1323                                                {
1324                                                        (*merge_ref)->lower_multiplicity();
1325                                                }
1326                                        }
1327                                        else
1328                                        {
1329                                                toprow* current_positive = (toprow*)(*merge_ref)->positiveparent;
1330                                                toprow* current_negative = (toprow*)(*merge_ref)->negativeparent;
1331
1332                                                //current_positive->condition_sum -= toremove;
1333                                                //current_positive->condition_order--;
1334
1335                                                current_positive->parentconditions.erase(condition_to_remove);
1336                                               
1337                                                current_positive->children.insert(current_positive->children.end(),current_negative->children.begin(),current_negative->children.end());
1338                                                current_positive->children.remove(*merge_ref);
1339
1340                                                for(list<polyhedron*>::iterator child_ref = current_negative->children.begin();child_ref!=current_negative->children.end();child_ref++)
1341                                                {
1342                                                        (*child_ref)->parents.remove(current_negative);
1343                                                        (*child_ref)->parents.push_back(current_positive);                                                                                                     
1344                                                }
1345
1346                                                // current_positive->parents.insert(current_positive->parents.begin(),current_negative->parents.begin(),current_negative->parents.end());
1347                                                // unique(current_positive->parents.begin(),current_positive->parents.end());
1348
1349                                                for(list<polyhedron*>::iterator parent_ref = current_negative->parents.begin();parent_ref!=current_negative->parents.end();parent_ref++)
1350                                                {
1351                                                        (*parent_ref)->children.remove(current_negative);
1352
1353                                                        switch(current_negative->get_state(SPLIT))
1354                                                        {
1355                                                        case -1:
1356                                                                (*parent_ref)->negativechildren.remove(current_negative);
1357                                                                break;
1358                                                        case 0:
1359                                                                (*parent_ref)->neutralchildren.remove(current_negative);                                                               
1360                                                                break;
1361                                                        case 1:
1362                                                                (*parent_ref)->positivechildren.remove(current_negative);
1363                                                                break;
1364                                                        }
1365                                                        //(*parent_ref)->children.push_back(current_positive);
1366                                                }
1367
1368                                                if(current_positive->get_state(SPLIT)!=0&&current_negative->get_state(SPLIT)==0)
1369                                                {
1370                                                        for(list<polyhedron*>::iterator parent_ref = current_positive->parents.begin();parent_ref!=current_positive->parents.end();parent_ref++)
1371                                                        {
1372                                                                if(current_positive->get_state(SPLIT)==1)
1373                                                                {
1374                                                                        (*parent_ref)->positivechildren.remove(current_positive);
1375                                                                }
1376                                                                else
1377                                                                {
1378                                                                        (*parent_ref)->negativechildren.remove(current_positive);
1379                                                                }
1380
1381                                                                (*parent_ref)->neutralchildren.push_back(current_positive);
1382                                                        }
1383
1384                                                        current_positive->set_state(0,SPLIT);
1385                                                        for_splitting[k].push_back(current_positive);
1386                                                }
1387                                               
1388                                                if((current_positive->get_state(SPLIT)==0&&!current_positive->totally_neutral)||(current_negative->get_state(SPLIT)==0&&!current_negative->totally_neutral))
1389                                                {
1390                                                        current_positive->negativechildren.insert(current_positive->negativechildren.end(),current_negative->negativechildren.begin(),current_negative->negativechildren.end());                                               
1391                                                       
1392                                                        current_positive->positivechildren.insert(current_positive->positivechildren.end(),current_negative->positivechildren.begin(),current_negative->positivechildren.end());
1393                                                                                                       
1394                                                        current_positive->neutralchildren.insert(current_positive->neutralchildren.end(),current_negative->neutralchildren.begin(),current_negative->neutralchildren.end());
1395                                               
1396                                                        switch((*merge_ref)->get_state(SPLIT))
1397                                                        {
1398                                                        case -1:
1399                                                                current_positive->negativechildren.remove(*merge_ref);
1400                                                                break;
1401                                                        case 0:
1402                                                                current_positive->neutralchildren.remove(*merge_ref);
1403                                                                break;
1404                                                        case 1:
1405                                                                current_positive->positivechildren.remove(*merge_ref);
1406                                                                break;
1407                                                        }
1408
1409                                                        current_positive->totallyneutralchildren.insert(current_negative->totallyneutralchildren.begin(),current_negative->totallyneutralchildren.end());
1410                                                       
1411                                                        current_positive->totallyneutralchildren.erase(*merge_ref);
1412
1413                                                        current_positive->totallyneutralgrandchildren.insert(current_negative->totallyneutralgrandchildren.begin(),current_negative->totallyneutralgrandchildren.end());
1414
1415                                                        current_positive->negativeneutralvertices.insert(current_negative->negativeneutralvertices.begin(),current_negative->negativeneutralvertices.end());
1416                                                        current_positive->positiveneutralvertices.insert(current_negative->positiveneutralvertices.begin(),current_negative->positiveneutralvertices.end());
1417                                                }
1418                                                else
1419                                                {
1420                                                        if(!current_positive->totally_neutral)
1421                                                        {
1422                                                                current_positive->positivechildren.clear();
1423                                                                current_positive->negativechildren.clear();
1424                                                                current_positive->neutralchildren.clear();
1425                                                                current_positive->totallyneutralchildren.clear();
1426                                                                current_positive->totallyneutralgrandchildren.clear();                                                         
1427                                                                current_positive->positiveneutralvertices.clear();
1428                                                                current_positive->negativeneutralvertices.clear();
1429                                                                current_positive->totally_neutral = NULL;
1430                                                                current_positive->kids_rel_addresses.clear();                                                           
1431                                                        }
1432                                               
1433                                                }
1434
1435                                                                                               
1436                                               
1437                                                current_positive->vertices.insert(current_negative->vertices.begin(),current_negative->vertices.end());
1438                                               
1439                                               
1440                                                for(set<vertex*>::iterator vert_ref = (*merge_ref)->vertices.begin();vert_ref!=(*merge_ref)->vertices.end();vert_ref++)
1441                                                {
1442                                                        if((*vert_ref)->get_multiplicity()==1)
1443                                                        {
1444                                                                current_positive->vertices.erase(*vert_ref);
1445                                                               
1446                                                                if((current_positive->get_state(SPLIT)==0&&!current_positive->totally_neutral)||(current_negative->get_state(SPLIT)==0&&!current_negative->totally_neutral))
1447                                                                {
1448                                                                        current_positive->negativeneutralvertices.erase(*vert_ref);
1449                                                                        current_positive->positiveneutralvertices.erase(*vert_ref);
1450                                                                }
1451                                                        }
1452                                                }
1453                                               
1454                                                if(current_negative->get_state(SPLIT)==0&&!current_negative->totally_neutral)
1455                                                {
1456                                                        for_splitting[k].remove(current_negative);     
1457                                                }
1458
1459                                                if(current_positive->totally_neutral)
1460                                                {
1461                                                        if(!current_negative->totally_neutral)
1462                                                        {
1463                                                                for(set<polyhedron*>::iterator grand_ref = current_positive->grandparents.begin();grand_ref!=current_positive->grandparents.end();grand_ref++)
1464                                                                {
1465                                                                        (*grand_ref)->totallyneutralgrandchildren.erase(current_positive);
1466                                                                }                                                               
1467                                                        }
1468                                                        else
1469                                                        {
1470                                                                for(set<polyhedron*>::iterator grand_ref = current_negative->grandparents.begin();grand_ref!=current_negative->grandparents.end();grand_ref++)
1471                                                                {
1472                                                                        (*grand_ref)->totallyneutralgrandchildren.erase(current_negative);
1473                                                                        (*grand_ref)->totallyneutralgrandchildren.insert(current_positive);
1474                                                                }                                                               
1475                                                        }
1476                                                }
1477                                                else
1478                                                {
1479                                                        if(current_negative->totally_neutral)
1480                                                        {
1481                                                                for(set<polyhedron*>::iterator grand_ref = current_negative->grandparents.begin();grand_ref!=current_negative->grandparents.end();grand_ref++)
1482                                                                {
1483                                                                        (*grand_ref)->totallyneutralgrandchildren.erase(current_negative);                                                                     
1484                                                                }
1485                                                        }                                                       
1486                                                }
1487
1488                                                current_positive->grandparents.clear();
1489
1490                                               
1491                                               
1492                                                current_positive->totally_neutral = (current_positive->totally_neutral && current_negative->totally_neutral);
1493
1494                                                current_positive->my_emlig->normalization_factor += current_positive->triangulate(k==for_splitting.size()-1);
1495                                               
1496                                                statistic.delete_polyhedron(k,current_negative);
1497
1498                                                delete current_negative;
1499
1500                                                for(list<polyhedron*>::iterator child_ref = (*merge_ref)->children.begin();child_ref!=(*merge_ref)->children.end();child_ref++)
1501                                                {
1502                                                        (*child_ref)->parents.remove(*merge_ref);
1503                                                }
1504
1505                                                /*
1506                                                for(list<polyhedron*>::iterator parent_ref = (*merge_ref)->parents.begin();parent_ref!=(*merge_ref)->parents.end();parent_ref++)
1507                                                {
1508                                                        (*parent_ref)->positivechildren.remove(*merge_ref);
1509                                                        (*parent_ref)->negativechildren.remove(*merge_ref);
1510                                                        (*parent_ref)->neutralchildren.remove(*merge_ref);
1511                                                        (*parent_ref)->children.remove(*merge_ref);
1512                                                }
1513                                                */
1514
1515                                                for(set<polyhedron*>::iterator grand_ch_ref = (*merge_ref)->totallyneutralgrandchildren.begin();grand_ch_ref!=(*merge_ref)->totallyneutralgrandchildren.end();grand_ch_ref++)
1516                                                {
1517                                                        (*grand_ch_ref)->grandparents.erase(*merge_ref);
1518                                                }
1519
1520                                               
1521                                                for(set<polyhedron*>::iterator grand_p_ref = (*merge_ref)->grandparents.begin();grand_p_ref!=(*merge_ref)->grandparents.end();grand_p_ref++)
1522                                                {
1523                                                        (*grand_p_ref)->totallyneutralgrandchildren.erase(*merge_ref);
1524                                                }
1525                                               
1526                                                for_splitting[k-1].remove(*merge_ref);
1527
1528                                                statistic.delete_polyhedron(k-1,*merge_ref);
1529
1530                                                if(k==1)
1531                                                {
1532                                                        vertices_to_be_reduced.insert((vertex*)(*merge_ref));
1533                                                }
1534                                                else
1535                                                {
1536                                                        delete *merge_ref;
1537                                                }
1538                                        }
1539                                }                       
1540                       
1541                                k++;
1542
1543                        }
1544
1545                        for(set<vertex*>::iterator vert_ref = vertices_to_be_reduced.begin();vert_ref!=vertices_to_be_reduced.end();vert_ref++)
1546                        {
1547                                if((*vert_ref)->get_multiplicity()>1)
1548                                {
1549                                        (*vert_ref)->lower_multiplicity();
1550                                }
1551                                else
1552                                {
1553                                        delete *vert_ref;
1554                                }
1555                        }
1556
1557                        delete condition_to_remove;
1558                }
1559               
1560                vector<int> sizevector;
1561                for(int s = 0;s<statistic.size();s++)
1562                {
1563                        sizevector.push_back(statistic.row_size(s));
1564                        cout << statistic.row_size(s) << ", ";
1565                }
1566
1567                cout << endl;
1568
1569                if(should_add)
1570                {
1571                        int k = 1;
1572
1573                        vector<list<polyhedron*>>::iterator beginning_ref = ++for_splitting.begin();
1574
1575                        for(vector<list<polyhedron*>>::iterator vert_ref = beginning_ref;vert_ref<for_splitting.end();vert_ref++)
1576                        {                       
1577
1578                                for(list<polyhedron*>::reverse_iterator split_ref = vert_ref->rbegin();split_ref != vert_ref->rend();split_ref++)
1579                                {
1580                                        polyhedron* new_totally_neutral_child;
1581
1582                                        polyhedron* current_polyhedron = (*split_ref);
1583                                       
1584                                        if(vert_ref == beginning_ref)
1585                                        {
1586                                                vec coordinates1 = ((vertex*)(*(current_polyhedron->children.begin())))->get_coordinates();                                             
1587                                                vec coordinates2 = ((vertex*)(*(++current_polyhedron->children.begin())))->get_coordinates();
1588                                               
1589                                                vec extended_coord2 = coordinates2;
1590                                                extended_coord2.ins(0,-1.0);                                           
1591
1592                                                double t = (-toadd*extended_coord2)/(toadd(1,toadd.size()-1)*(coordinates1-coordinates2));                                             
1593
1594                                                vec new_coordinates = (1-t)*coordinates2+t*coordinates1;                                               
1595
1596                                                // cout << "c1:" << coordinates1 << endl << "c2:" << coordinates2 << endl << "nc:" << new_coordinates << endl;
1597
1598                                                vertex* neutral_vertex = new vertex(new_coordinates);                                           
1599
1600                                                new_totally_neutral_child = neutral_vertex;
1601                                        }
1602                                        else
1603                                        {
1604                                                toprow* neutral_toprow = new toprow();
1605                                               
1606                                                neutral_toprow->condition_sum   = ((toprow*)current_polyhedron)->condition_sum; // tohle tu bylo driv: zeros(number_of_parameters+1);
1607                                                neutral_toprow->condition_order = ((toprow*)current_polyhedron)->condition_order+1;
1608
1609                                                new_totally_neutral_child = neutral_toprow;
1610                                        }
1611
1612                                        new_totally_neutral_child->parentconditions.insert(current_polyhedron->parentconditions.begin(),current_polyhedron->parentconditions.end());
1613                                        new_totally_neutral_child->parentconditions.insert(condition_to_add);
1614
1615                                        new_totally_neutral_child->my_emlig = this;
1616                                       
1617                                        new_totally_neutral_child->children.insert(new_totally_neutral_child->children.end(),
1618                                                                                                                current_polyhedron->totallyneutralgrandchildren.begin(),
1619                                                                                                                                current_polyhedron->totallyneutralgrandchildren.end());
1620
1621                                       
1622
1623                                        // cout << ((toprow*)current_polyhedron)->condition << endl << toadd << endl;
1624
1625                                        toprow* positive_poly = new toprow(((toprow*)current_polyhedron)->condition_sum+toadd, ((toprow*)current_polyhedron)->condition_order+1);
1626                                        toprow* negative_poly = new toprow(((toprow*)current_polyhedron)->condition_sum-toadd, ((toprow*)current_polyhedron)->condition_order+1);
1627
1628                                        positive_poly->my_emlig = this;
1629                                        negative_poly->my_emlig = this;
1630
1631                                        positive_poly->parentconditions.insert(current_polyhedron->parentconditions.begin(),current_polyhedron->parentconditions.end());
1632                                        negative_poly->parentconditions.insert(current_polyhedron->parentconditions.begin(),current_polyhedron->parentconditions.end());
1633
1634                                        for(set<polyhedron*>::iterator grand_ref = current_polyhedron->totallyneutralgrandchildren.begin(); grand_ref != current_polyhedron->totallyneutralgrandchildren.end();grand_ref++)
1635                                        {
1636                                                (*grand_ref)->parents.push_back(new_totally_neutral_child);
1637                                               
1638                                                // tohle tu nebylo. ma to tu byt?
1639                                                //positive_poly->totallyneutralgrandchildren.insert(*grand_ref);
1640                                                //negative_poly->totallyneutralgrandchildren.insert(*grand_ref);
1641
1642                                                //(*grand_ref)->grandparents.insert(positive_poly);
1643                                                //(*grand_ref)->grandparents.insert(negative_poly);
1644
1645                                                new_totally_neutral_child->vertices.insert((*grand_ref)->vertices.begin(),(*grand_ref)->vertices.end());
1646                                        }
1647
1648                                        positive_poly->children.push_back(new_totally_neutral_child);
1649                                        negative_poly->children.push_back(new_totally_neutral_child);
1650                                       
1651
1652                                        for(list<polyhedron*>::iterator parent_ref = current_polyhedron->parents.begin();parent_ref!=current_polyhedron->parents.end();parent_ref++)
1653                                        {
1654                                                (*parent_ref)->totallyneutralgrandchildren.insert(new_totally_neutral_child);
1655                                                // new_totally_neutral_child->grandparents.insert(*parent_ref);
1656
1657                                                (*parent_ref)->neutralchildren.remove(current_polyhedron);
1658                                                (*parent_ref)->children.remove(current_polyhedron);
1659
1660                                                (*parent_ref)->children.push_back(positive_poly);
1661                                                (*parent_ref)->children.push_back(negative_poly);
1662                                                (*parent_ref)->positivechildren.push_back(positive_poly);
1663                                                (*parent_ref)->negativechildren.push_back(negative_poly);
1664                                        }
1665
1666                                        positive_poly->parents.insert(positive_poly->parents.end(),
1667                                                                                                current_polyhedron->parents.begin(),
1668                                                                                                                current_polyhedron->parents.end());
1669
1670                                        negative_poly->parents.insert(negative_poly->parents.end(),
1671                                                                                                current_polyhedron->parents.begin(),
1672                                                                                                                current_polyhedron->parents.end());
1673
1674                                       
1675
1676                                        new_totally_neutral_child->parents.push_back(positive_poly);
1677                                        new_totally_neutral_child->parents.push_back(negative_poly);
1678
1679                                        for(list<polyhedron*>::iterator child_ref = current_polyhedron->positivechildren.begin();child_ref!=current_polyhedron->positivechildren.end();child_ref++)
1680                                        {
1681                                                (*child_ref)->parents.remove(current_polyhedron);
1682                                                (*child_ref)->parents.push_back(positive_poly);                                         
1683                                        }                                       
1684
1685                                        positive_poly->children.insert(positive_poly->children.end(),
1686                                                                                                current_polyhedron->positivechildren.begin(),
1687                                                                                                                        current_polyhedron->positivechildren.end());
1688
1689                                        for(list<polyhedron*>::iterator child_ref = current_polyhedron->negativechildren.begin();child_ref!=current_polyhedron->negativechildren.end();child_ref++)
1690                                        {
1691                                                (*child_ref)->parents.remove(current_polyhedron);
1692                                                (*child_ref)->parents.push_back(negative_poly);
1693                                        }
1694
1695                                        negative_poly->children.insert(negative_poly->children.end(),
1696                                                                                                current_polyhedron->negativechildren.begin(),
1697                                                                                                                        current_polyhedron->negativechildren.end());
1698
1699                                        positive_poly->vertices.insert(current_polyhedron->positiveneutralvertices.begin(),current_polyhedron->positiveneutralvertices.end());
1700                                        positive_poly->vertices.insert(new_totally_neutral_child->vertices.begin(),new_totally_neutral_child->vertices.end());
1701
1702                                        negative_poly->vertices.insert(current_polyhedron->negativeneutralvertices.begin(),current_polyhedron->negativeneutralvertices.end());
1703                                        negative_poly->vertices.insert(new_totally_neutral_child->vertices.begin(),new_totally_neutral_child->vertices.end());
1704                                                               
1705                                        new_totally_neutral_child->triangulate(false);
1706
1707                                        positive_poly->my_emlig->normalization_factor += positive_poly->triangulate(k==for_splitting.size()-1);
1708                                        negative_poly->my_emlig->normalization_factor += negative_poly->triangulate(k==for_splitting.size()-1);
1709                                       
1710                                        statistic.append_polyhedron(k-1, new_totally_neutral_child);                                   
1711                                       
1712                                        statistic.insert_polyhedron(k, positive_poly, current_polyhedron);
1713                                        statistic.insert_polyhedron(k, negative_poly, current_polyhedron);                                     
1714
1715                                        statistic.delete_polyhedron(k, current_polyhedron);
1716
1717                                        delete current_polyhedron;
1718                                }
1719
1720                                k++;
1721                        }
1722                }
1723
1724               
1725                sizevector.clear();
1726                for(int s = 0;s<statistic.size();s++)
1727                {
1728                        sizevector.push_back(statistic.row_size(s));
1729                        cout << statistic.row_size(s) << ", ";
1730                }
1731               
1732                cout << endl;
1733
1734                /*
1735                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)
1736                {
1737                        cout << ((toprow*)topr_ref)->condition << endl;
1738                }
1739                */
1740
1741                // step_me(0);
1742
1743        }
1744
1745        void set_correction_factors(int order)
1746                {
1747                        for(int remaining_order = correction_factors.size();remaining_order<order;remaining_order++)
1748                        {
1749                                multiset<my_ivec> factor_templates;
1750                                multiset<my_ivec> final_factors;                               
1751
1752                                my_ivec orig_template = my_ivec();                             
1753
1754                                for(int i = 1;i<number_of_parameters-remaining_order+1;i++)
1755                                {                                       
1756                                        bool in_cycle = false;
1757                                        for(int j = 0;j<=remaining_order;j++)                                   {
1758                                               
1759                                                multiset<my_ivec>::iterator fac_ref = factor_templates.begin();
1760
1761                                                do
1762                                                {
1763                                                        my_ivec current_template;
1764                                                        if(!in_cycle)
1765                                                        {
1766                                                                current_template = orig_template;
1767                                                                in_cycle = true;
1768                                                        }
1769                                                        else
1770                                                        {
1771                                                                current_template = (*fac_ref);
1772                                                                fac_ref++;
1773                                                        }                                                       
1774                                                       
1775                                                        current_template.ins(current_template.size(),i);
1776
1777                                                        // cout << "template:" << current_template << endl;
1778                                                       
1779                                                        if(current_template.size()==remaining_order+1)
1780                                                        {
1781                                                                final_factors.insert(current_template);
1782                                                        }
1783                                                        else
1784                                                        {
1785                                                                factor_templates.insert(current_template);
1786                                                        }
1787                                                }
1788                                                while(fac_ref!=factor_templates.end());
1789                                        }
1790                                }       
1791
1792                                correction_factors.push_back(final_factors);                   
1793
1794                        }
1795                }
1796
1797
1798
1799        mat sample_mat(int n)
1800        {               
1801
1802                /// \TODO tady je to spatne, tady nesmi byt conditions.size(), viz RARX.bayes()
1803                if(conditions.size()-2-number_of_parameters>=0)
1804                {                       
1805                        mat sample_mat;
1806                        map<double,toprow*> ordered_toprows;                   
1807                        double sum_a = 0;
1808                       
1809                        //cout << "Likelihoods of toprows:" << endl;
1810
1811                        for(polyhedron* top_ref = statistic.rows[number_of_parameters];top_ref!=statistic.end_poly;top_ref=top_ref->next_poly)
1812                        {
1813                                toprow* current_top = (toprow*)top_ref;
1814
1815                                sum_a+=current_top->probability;
1816                                /*
1817                                cout << current_top->probability << "   ";
1818
1819                                for(set<vertex*>::iterator vert_ref = (*top_ref).vertices.begin();vert_ref!=(*top_ref).vertices.end();vert_ref++)
1820                                {
1821                                        cout << round(100*(*vert_ref)->get_coordinates())/100 << " ; ";
1822                                }
1823                                */
1824
1825                                // cout << endl;
1826                                ordered_toprows.insert(pair<double,toprow*>(sum_a,current_top));
1827                        }                       
1828                       
1829                        // cout << "Sum N: " << normalization_factor << endl;
1830
1831                        while(sample_mat.cols()<n)
1832                        {
1833                                //// cout << "*************************************" << endl;
1834
1835                               
1836                               
1837                                double rnumber = randu()*sum_a;
1838
1839                                // cout << "RND:" << rnumber << endl;
1840
1841                                // This could be more efficient (log n), but map::upper_bound() doesn't let me dereference returned iterator
1842                                int toprow_count = 0;
1843                                toprow* sampled_toprow;                         
1844                                for(map<double,toprow*>::iterator top_ref = ordered_toprows.begin();top_ref!=ordered_toprows.end();top_ref++)
1845                                {
1846                                        // cout << "CDF:"<< (*top_ref).first << endl;
1847                                        toprow_count++;
1848
1849                                        if((*top_ref).first >= rnumber)
1850                                        {
1851                                                sampled_toprow = (*top_ref).second;
1852                                                break;
1853                                        }                                               
1854                                }                               
1855
1856                                //// cout << "Toprow/Count: " << toprow_count << "/" << ordered_toprows.size() << endl;
1857                                // cout << &sampled_toprow << ";";
1858
1859                                rnumber = randu();                             
1860
1861                                set<simplex*>::iterator s_ref;
1862                                double sum_b = 0;
1863                                int simplex_count = 0;
1864                                for(s_ref = sampled_toprow->triangulation.begin();s_ref!=sampled_toprow->triangulation.end();s_ref++)
1865                                {
1866                                        simplex_count++;
1867                                       
1868                                        sum_b += (*s_ref)->probability;
1869
1870                                        if(sum_b/sampled_toprow->probability >= rnumber)
1871                                                break;
1872                                }
1873
1874                                //// cout << "Simplex/Count: " << simplex_count << "/" << sampled_toprow->triangulation.size() << endl;
1875                                //// cout << "Simplex factor: " << (*s_ref)->probability << endl;
1876                                //// cout << "Toprow factor:  " << sampled_toprow->probability << endl;
1877                                //// cout << "Emlig factor:   " << normalization_factor << endl;
1878                                // cout << &(*tri_ref) << endl;
1879
1880                                int number_of_runs = 0;
1881                                bool have_sigma = false;
1882                                double sigma = 0;
1883                                do
1884                                {
1885                                        rnumber = randu();
1886                                       
1887                                        double sum_g = 0;
1888                                        for(int i = 0;i<(*s_ref)->positive_gamma_parameters.size();i++)
1889                                        {
1890                                                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++)
1891                                                {
1892                                                        sum_g += (*g_ref).first/(*s_ref)->positive_gamma_sum;
1893
1894                                                       
1895                                                        if(sum_g>rnumber)
1896                                                        {
1897                                                                //itpp::Gamma_RNG* gamma = new itpp::Gamma_RNG(conditions.size()-number_of_parameters,1/(*g_ref).second);
1898                                                                //sigma = 1/(*gamma)();
1899                                                               
1900                                                                GamRNG.setup(conditions.size()-number_of_parameters,(*g_ref).second);
1901                                                                                                                               
1902                                                                sigma = 1/GamRNG();
1903
1904                                                                // cout << "Sigma mean:   " << (*g_ref).second/(conditions.size()-number_of_parameters-1) << endl;                                                             
1905                                                                break;
1906                                                        }                                                       
1907                                                }
1908
1909                                                if(sigma!=0)
1910                                                {
1911                                                        break;
1912                                                }
1913                                        }
1914
1915                                        rnumber = randu();
1916
1917                                        double pg_sum = 0;
1918                                        for(vector<multimap<double,double>>::iterator v_ref = (*s_ref)->positive_gamma_parameters.begin();v_ref!=(*s_ref)->positive_gamma_parameters.end();v_ref++)
1919                                        {
1920                                                for(multimap<double,double>::iterator pg_ref = (*v_ref).begin();pg_ref!=(*v_ref).end();pg_ref++)
1921                                                {
1922                                                        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;
1923                                                }                                       
1924                                        }
1925
1926                                        double ng_sum = 0;
1927                                        for(vector<multimap<double,double>>::iterator v_ref = (*s_ref)->negative_gamma_parameters.begin();v_ref!=(*s_ref)->negative_gamma_parameters.end();v_ref++)
1928                                        {
1929                                                for(multimap<double,double>::iterator ng_ref = (*v_ref).begin();ng_ref!=(*v_ref).end();ng_ref++)
1930                                                {
1931                                                        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;
1932                                                }                                       
1933                                        }
1934                                       
1935                                        if((pg_sum-ng_sum)/pg_sum>rnumber)
1936                                        {
1937                                                have_sigma = true;
1938                                        }
1939
1940                                        number_of_runs++;
1941                                }
1942                                while(!have_sigma);
1943
1944                                //// cout << "Sigma: " << sigma << endl;
1945                                //// cout << "Nr. of runs: " << number_of_runs << endl;
1946
1947                                int dimension = (*s_ref)->vertices.size()-1;
1948
1949                                mat jacobian(dimension,dimension);
1950                                vec gradient = sampled_toprow->condition_sum.right(dimension);
1951
1952                                vertex* base_vert = *(*s_ref)->vertices.begin();
1953
1954                                //// cout << "Base vertex coords(should be close to est. param.): " << base_vert->get_coordinates() << endl;
1955                               
1956                                int row_count = 0;
1957
1958                                for(set<vertex*>::iterator vert_ref = ++(*s_ref)->vertices.begin();vert_ref!=(*s_ref)->vertices.end();vert_ref++)
1959                                {
1960                                        vec current_coords = (*vert_ref)->get_coordinates();
1961
1962                                        //// cout << "Coords of vertex[" << row_count << "]: " << current_coords << endl;
1963                                       
1964                                        vec relative_coords = current_coords-base_vert->get_coordinates();                             
1965
1966                                        jacobian.set_row(row_count,relative_coords);
1967
1968                                        row_count++;
1969                                }                               
1970                               
1971                                //// cout << "Jacobian: " << jacobian << endl;
1972
1973                                //// cout << "Gradient before trafo:" << gradient << endl;
1974                                                               
1975                                gradient = jacobian*gradient;   
1976
1977                                //// cout << "Gradient after trafo:" << gradient << endl;
1978
1979                                // vec normal_gradient = gradient/sqrt(gradient*gradient);
1980                                // cout << gradient << endl;
1981                                // cout << normal_gradient << endl;
1982                                // cout << sqrt(gradient*gradient) << endl;
1983
1984                                mat rotation_matrix = eye(dimension);                           
1985
1986                                                               
1987
1988                                for(int i = 1;i<dimension;i++)
1989                                {
1990                                        vec x_axis = zeros(dimension);
1991                                        x_axis.set(0,1);
1992
1993                                        x_axis = rotation_matrix*x_axis;
1994
1995                                        double t = abs(gradient[i]/gradient*x_axis);
1996
1997                                        double sin_theta = sign(gradient[i])*t/sqrt(1+pow(t,2));
1998                                        double cos_theta = sign(gradient*x_axis)/sqrt(1+pow(t,2));
1999
2000                                        mat partial_rotation = eye(dimension);
2001
2002                                        partial_rotation.set(0,0,cos_theta);
2003                                        partial_rotation.set(i,i,cos_theta);
2004                                       
2005                                        partial_rotation.set(0,i,sin_theta);
2006                                        partial_rotation.set(i,0,-sin_theta);
2007                                       
2008                                        rotation_matrix = rotation_matrix*partial_rotation;                             
2009                                       
2010                                }
2011
2012                                // cout << rotation_matrix << endl;
2013                               
2014                                mat extended_rotation = rotation_matrix;
2015                                extended_rotation.ins_col(0,zeros(extended_rotation.rows()));
2016
2017                                //// cout << "Extended rotation: " << extended_rotation << endl;
2018                               
2019                                vec minima = itpp::min(extended_rotation,2);
2020                                vec maxima = itpp::max(extended_rotation,2);
2021
2022                                //// cout << "Minima: " << minima << endl;
2023                                //// cout << "Maxima: " << maxima << endl;
2024
2025                                vec sample_coordinates;         
2026                                bool is_inside = true;
2027                               
2028                                vec new_sample;
2029                                sample_coordinates = new_sample;
2030
2031                                for(int j = 0;j<number_of_parameters;j++)
2032                                {
2033                                        rnumber = randu();
2034                                       
2035                                        double coordinate;
2036
2037                                        if(j==0)
2038                                        {                                               
2039                                                vec new_gradient = rotation_matrix*gradient;
2040                                               
2041                                                //// cout << "New gradient(should have only first component nonzero):" << new_gradient << endl;
2042
2043                                                // cout << "Max: " << maxima[0] << "  Min: " << minima[0] << "  Grad:" << new_gradient[0] << endl;
2044                                               
2045                                                double log_bracket = 1-rnumber*(1-exp(new_gradient[0]/sigma*(minima[0]-maxima[0])));
2046                                               
2047                                                coordinate = minima[0]-sigma/new_gradient[0]*log(log_bracket);
2048                                        }
2049                                        else
2050                                        {
2051                                                coordinate = minima[j]+rnumber*(maxima[j]-minima[j]);
2052                                        }
2053
2054                                        sample_coordinates.ins(j,coordinate);
2055                                }
2056
2057                                //// cout << "Sampled coordinates(gradient direction): " << sample_coordinates << endl;
2058
2059                                sample_coordinates = rotation_matrix.T()*sample_coordinates;
2060
2061                                //// cout << "Sampled coordinates(backrotated direction):" << sample_coordinates << endl;
2062
2063                               
2064                                for(int j = 0;j<sample_coordinates.size();j++)
2065                                {
2066                                        if(sample_coordinates[j]<0)
2067                                        {
2068                                                is_inside = false;
2069                                        }
2070                                }
2071
2072                                double above_criterion = ones(sample_coordinates.size())*sample_coordinates;
2073
2074                                if(above_criterion>1)
2075                                {
2076                                        is_inside = false;
2077                                }
2078
2079                                if(is_inside)
2080                                {                                       
2081                                        sample_coordinates = jacobian.T()*sample_coordinates+(*base_vert).get_coordinates();
2082                                       
2083                                        sample_coordinates.ins(0,sigma);
2084                                       
2085                                        //// cout << "Sampled coordinates(parameter space):" << sample_coordinates << endl;
2086
2087                                        sample_mat.ins_col(0,sample_coordinates);
2088
2089                                        cout << sample_mat.cols() << ",";
2090                                }
2091
2092                                // cout << sampled_toprow->condition_sum.right(sampled_toprow->condition_sum.size()-1)*min_grad->get_coordinates()-sampled_toprow->condition_sum[0] << endl;
2093                                // cout << sampled_toprow->condition_sum.right(sampled_toprow->condition_sum.size()-1)*max_grad->get_coordinates()-sampled_toprow->condition_sum[0] << endl;
2094
2095                               
2096                        }
2097
2098                        cout << endl;
2099                        return sample_mat;
2100                }
2101                else
2102                {
2103                        throw new exception("You are trying to sample from density that is not determined (parameters can't be integrated out)!");
2104               
2105                        return 0;
2106                }
2107
2108               
2109        }
2110
2111protected:
2112
2113        /// A method for creating plain default statistic representing only the range of the parameter space.
2114    void create_statistic(int number_of_parameters)
2115        {
2116                /*
2117                for(int i = 0;i<number_of_parameters;i++)
2118                {
2119                        vec condition_vec = zeros(number_of_parameters+1);
2120                        condition_vec[i+1]  = 1;
2121
2122                        condition* new_condition = new condition(condition_vec);
2123                       
2124                        conditions.push_back(new_condition);
2125                }
2126                */
2127
2128                // An empty vector of coordinates.
2129                vec origin_coord;       
2130
2131                // We create an origin - this point will have all the coordinates zero, but now it has an empty vector of coords.
2132                vertex *origin = new vertex(origin_coord);
2133
2134                origin->my_emlig = this;
2135               
2136                /*
2137                // As a statistic, we have to create a vector of vectors of polyhedron pointers. It will then represent the Hasse
2138                // diagram. First we create a vector of polyhedrons..
2139                list<polyhedron*> origin_vec;
2140
2141                // ..we fill it with the origin..
2142                origin_vec.push_back(origin);
2143
2144                // ..and we fill the statistic with the created vector.
2145                statistic.push_back(origin_vec);
2146                */
2147
2148                statistic = *(new c_statistic());               
2149               
2150                statistic.append_polyhedron(0, origin);
2151
2152                // Now we have a statistic for a zero dimensional space. Regarding to how many dimensional space we need to
2153                // describe, we have to widen the descriptional default statistic. We use an iterative procedure as follows:
2154                for(int i=0;i<number_of_parameters;i++)
2155                {
2156                        // We first will create two new vertices. These will be the borders of the parameter space in the dimension
2157                        // of newly added parameter. Therefore they will have all coordinates except the last one zero. We get the
2158                        // right amount of zero cooridnates by reading them from the origin
2159                        vec origin_coord = origin->get_coordinates();                                           
2160
2161                        // And we incorporate the nonzero coordinates into the new cooordinate vectors
2162                        vec origin_coord1 = concat(origin_coord,-max_range); 
2163                        vec origin_coord2 = concat(origin_coord,max_range);                             
2164                                       
2165
2166                        // Now we create the points
2167                        vertex* new_point1 = new vertex(origin_coord1);
2168                        vertex* new_point2 = new vertex(origin_coord2);
2169
2170                        new_point1->my_emlig = this;
2171                        new_point2->my_emlig = this;
2172                       
2173                        //*********************************************************************************************************
2174                        // The algorithm for recursive build of a new Hasse diagram representing the space structure from the old
2175                        // diagram works so that you create two copies of the old Hasse diagram, you shift them up one level (points
2176                        // will be segments, segments will be areas etc.) and you connect each one of the original copied polyhedrons
2177                        // with its offspring by a parent-child relation. Also each of the segments in the first (second) copy is
2178                        // connected to the first (second) newly created vertex by a parent-child relation.
2179                        //*********************************************************************************************************
2180
2181
2182                        /*
2183                        // Create the vectors of vectors of pointers to polyhedrons to hold the copies of the old Hasse diagram
2184                        vector<vector<polyhedron*>> new_statistic1;
2185                        vector<vector<polyhedron*>> new_statistic2;
2186                        */
2187
2188                        c_statistic* new_statistic1 = new c_statistic();
2189                        c_statistic* new_statistic2 = new c_statistic();
2190
2191                       
2192                        // Copy the statistic by rows                   
2193                        for(int j=0;j<statistic.size();j++)
2194                        {
2195                               
2196
2197                                // an element counter
2198                                int element_number = 0;
2199
2200                                /*
2201                                vector<polyhedron*> supportnew_1;
2202                                vector<polyhedron*> supportnew_2;
2203
2204                                new_statistic1.push_back(supportnew_1);
2205                                new_statistic2.push_back(supportnew_2);
2206                                */
2207
2208                                // for each polyhedron in the given row
2209                                for(polyhedron* horiz_ref = statistic.rows[j];horiz_ref!=statistic.get_end();horiz_ref=horiz_ref->next_poly)
2210                                {       
2211                                        // Append an extra zero coordinate to each of the vertices for the new dimension
2212                                        // If vert_ref is at the first index => we loop through vertices
2213                                        if(j == 0)
2214                                        {
2215                                                // cast the polyhedron pointer to a vertex pointer and push a zero to its vector of coordinates
2216                                                ((vertex*) horiz_ref)->push_coordinate(0);
2217                                        }
2218                                        /*
2219                                        else
2220                                        {
2221                                                ((toprow*) (*horiz_ref))->condition.ins(0,0);
2222                                        }*/
2223
2224                                        // if it has parents
2225                                        if(!horiz_ref->parents.empty())
2226                                        {
2227                                                // save the relative address of this child in a vector kids_rel_addresses of all its parents.
2228                                                // This information will later be used for copying the whole Hasse diagram with each of the
2229                                                // relations contained within.
2230                                                for(list<polyhedron*>::iterator parent_ref = horiz_ref->parents.begin();parent_ref != horiz_ref->parents.end();parent_ref++)
2231                                                {
2232                                                        (*parent_ref)->kids_rel_addresses.push_back(element_number);                                                   
2233                                                }                                               
2234                                        }
2235
2236                                        // **************************************************************************************************
2237                                        // Here we begin creating a new polyhedron, which will be a copy of the old one. Each such polyhedron
2238                                        // will be created as a toprow, but this information will be later forgotten and only the polyhedrons
2239                                        // in the top row of the Hasse diagram will be considered toprow for later use.
2240                                        // **************************************************************************************************
2241
2242                                        // First we create vectors specifying a toprow condition. In the case of a preconstructed statistic
2243                                        // this condition will be a vector of zeros. There are two vectors, because we need two copies of
2244                                        // the original Hasse diagram.
2245                                        vec vec1(number_of_parameters+1);
2246                                        vec1.zeros();
2247
2248                                        vec vec2(number_of_parameters+1);
2249                                        vec2.zeros();
2250
2251                                        // We create a new toprow with the previously specified condition.
2252                                        toprow* current_copy1 = new toprow(vec1, 0);
2253                                        toprow* current_copy2 = new toprow(vec2, 0);
2254
2255                                        current_copy1->my_emlig = this;
2256                                        current_copy2->my_emlig = this;
2257
2258                                        // The vertices of the copies will be inherited, because there will be a parent/child relation
2259                                        // between each polyhedron and its offspring (comming from the copy) and a parent has all the
2260                                        // vertices of its child plus more.
2261                                        for(set<vertex*>::iterator vertex_ref = horiz_ref->vertices.begin();vertex_ref!=horiz_ref->vertices.end();vertex_ref++)
2262                                        {
2263                                                current_copy1->vertices.insert(*vertex_ref);
2264                                                current_copy2->vertices.insert(*vertex_ref);                                           
2265                                        }
2266                                       
2267                                        // The only new vertex of the offspring should be the newly created point.
2268                                        current_copy1->vertices.insert(new_point1);
2269                                        current_copy2->vertices.insert(new_point2);                                     
2270                                       
2271                                        // This method guarantees that each polyhedron is already triangulated, therefore its triangulation
2272                                        // is only one set of vertices and it is the set of all its vertices.
2273                                        simplex* t_simplex1 = new simplex(current_copy1->vertices);
2274                                        simplex* t_simplex2 = new simplex(current_copy2->vertices);                                     
2275                                       
2276                                        current_copy1->triangulation.insert(t_simplex1);
2277                                        current_copy2->triangulation.insert(t_simplex2);                                       
2278                                       
2279                                        // Now we have copied the polyhedron and we have to copy all of its relations. Because we are copying
2280                                        // in the Hasse diagram from bottom up, we always have to copy the parent/child relations to all the
2281                                        // kids and when we do that and know the child, in the child we will remember the parent we came from.
2282                                        // This way all the parents/children relations are saved in both the parent and the child.
2283                                        if(!horiz_ref->kids_rel_addresses.empty())
2284                                        {
2285                                                for(list<int>::iterator kid_ref = horiz_ref->kids_rel_addresses.begin();kid_ref!=horiz_ref->kids_rel_addresses.end();kid_ref++)
2286                                                {       
2287                                                        polyhedron* new_kid1 = new_statistic1->rows[j-1];
2288                                                        polyhedron* new_kid2 = new_statistic2->rows[j-1];
2289
2290                                                        // THIS IS NOT EFFECTIVE: It could be improved by having the list indexed for new_statistic, but
2291                                                        // not indexed for statistic. Hopefully this will not cause a big slowdown - happens only offline.
2292                                                        if(*kid_ref)
2293                                                        {
2294                                                                for(int k = 1;k<=(*kid_ref);k++)
2295                                                                {
2296                                                                        new_kid1=new_kid1->next_poly;
2297                                                                        new_kid2=new_kid2->next_poly;
2298                                                                }
2299                                                        }
2300                                                       
2301                                                        // find the child and save the relation to the parent
2302                                                        current_copy1->children.push_back(new_kid1);
2303                                                        current_copy2->children.push_back(new_kid2);
2304
2305                                                        // in the child save the parents' address
2306                                                        new_kid1->parents.push_back(current_copy1);
2307                                                        new_kid2->parents.push_back(current_copy2);
2308                                                }                                               
2309
2310                                                // Here we clear the parents kids_rel_addresses vector for later use (when we need to widen the
2311                                                // Hasse diagram again)
2312                                                horiz_ref->kids_rel_addresses.clear();
2313                                        }
2314                                        // If there were no children previously, we are copying a polyhedron that has been a vertex before.
2315                                        // In this case it is a segment now and it will have a relation to its mother (copywise) and to the
2316                                        // newly created point. Here we create the connection to the new point, again from both sides.
2317                                        else
2318                                        {
2319                                                // Add the address of the new point in the former vertex
2320                                                current_copy1->children.push_back(new_point1);
2321                                                current_copy2->children.push_back(new_point2);
2322
2323                                                // Add the address of the former vertex in the new point
2324                                                new_point1->parents.push_back(current_copy1);
2325                                                new_point2->parents.push_back(current_copy2);
2326                                        }
2327
2328                                        // Save the mother in its offspring
2329                                        current_copy1->children.push_back(horiz_ref);
2330                                        current_copy2->children.push_back(horiz_ref);
2331
2332                                        // Save the offspring in its mother
2333                                        horiz_ref->parents.push_back(current_copy1);
2334                                        horiz_ref->parents.push_back(current_copy2);   
2335                                                               
2336                                       
2337                                        // Add the copies into the relevant statistic. The statistic will later be appended to the previous
2338                                        // Hasse diagram
2339                                        new_statistic1->append_polyhedron(j,current_copy1);
2340                                        new_statistic2->append_polyhedron(j,current_copy2);
2341                                       
2342                                        // Raise the count in the vector of polyhedrons
2343                                        element_number++;                       
2344                                       
2345                                }
2346                               
2347                        }
2348
2349                        /*
2350                        statistic.begin()->push_back(new_point1);
2351                        statistic.begin()->push_back(new_point2);
2352                        */
2353
2354                        statistic.append_polyhedron(0, new_point1);
2355                        statistic.append_polyhedron(0, new_point2);
2356
2357                        // Merge the new statistics into the old one. This will either be the final statistic or we will
2358                        // reenter the widening loop.
2359                        for(int j=0;j<new_statistic1->size();j++)
2360                        {
2361                                /*
2362                                if(j+1==statistic.size())
2363                                {
2364                                        list<polyhedron*> support;
2365                                        statistic.push_back(support);
2366                                }
2367                               
2368                                (statistic.begin()+j+1)->insert((statistic.begin()+j+1)->end(),new_statistic1[j].begin(),new_statistic1[j].end());
2369                                (statistic.begin()+j+1)->insert((statistic.begin()+j+1)->end(),new_statistic2[j].begin(),new_statistic2[j].end());
2370                                */
2371                                statistic.append_polyhedron(j+1,new_statistic1->rows[j],new_statistic1->row_ends[j]);
2372                                statistic.append_polyhedron(j+1,new_statistic2->rows[j],new_statistic2->row_ends[j]);
2373                        }                       
2374                }
2375
2376                /*
2377                vector<list<toprow*>> toprow_statistic;
2378                int line_count = 0;
2379
2380                for(vector<list<polyhedron*>>::iterator polyhedron_ref = ++statistic.begin(); polyhedron_ref!=statistic.end();polyhedron_ref++)
2381                {
2382                        list<toprow*> support_list;
2383                        toprow_statistic.push_back(support_list);                                               
2384
2385                        for(list<polyhedron*>::iterator polyhedron_ref2 = polyhedron_ref->begin(); polyhedron_ref2 != polyhedron_ref->end(); polyhedron_ref2++)
2386                        {
2387                                toprow* support_top = (toprow*)(*polyhedron_ref2);
2388
2389                                toprow_statistic[line_count].push_back(support_top);
2390                        }
2391
2392                        line_count++;
2393                }*/
2394
2395                /*
2396                vector<int> sizevector;
2397                for(int s = 0;s<statistic.size();s++)
2398                {
2399                        sizevector.push_back(statistic.row_size(s));
2400                }
2401                */
2402               
2403        }
2404       
2405};
2406
2407
2408
2409//! Robust Bayesian AR model for Multicriteria-Laplace-Inverse-Gamma density
2410class RARX //: public BM
2411{
2412private:
2413        bool has_constant;
2414
2415        int window_size;       
2416
2417        list<vec> conditions;
2418
2419public:
2420        emlig* posterior;
2421
2422        RARX(int number_of_parameters, const int window_size, bool has_constant)//:BM()
2423        {
2424                this->has_constant = has_constant;
2425               
2426                posterior = new emlig(number_of_parameters);
2427
2428                this->window_size = window_size;               
2429        };
2430
2431        void bayes(itpp::vec yt)
2432        {
2433                if(has_constant)
2434                {
2435                        int c_size = yt.size();
2436                       
2437                        yt.ins(c_size,1.0);
2438                }
2439               
2440                if(yt.size() == posterior->number_of_parameters+1)
2441                {
2442                        conditions.push_back(yt);               
2443                }
2444                else
2445                {
2446                        throw new exception("Wrong condition size for bayesian data update!");
2447                }
2448
2449                //posterior->step_me(0);
2450               
2451                /// \TODO tohle je spatne, tady musi byt jiny vypocet poctu podminek, kdyby nejaka byla multiplicitni, tak tohle bude spatne
2452                if(conditions.size()>window_size && window_size!=0)
2453                {                       
2454                        posterior->add_and_remove_condition(yt,conditions.front());
2455                        conditions.pop_front();
2456
2457                        //posterior->step_me(1);
2458                }
2459                else
2460                {
2461                        posterior->add_condition(yt);
2462                }
2463                               
2464        }
2465
2466};
2467
2468
2469
2470#endif //TRAGE_H
Note: See TracBrowser for help on using the browser.