root/applications/robust/robustlib.h @ 1393

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