root/applications/robust/robustlib.h @ 1413

Revision 1413, 100.8 kB (checked in by sindj, 12 years ago)

Update hlavnich casti z Thinkeru. JS

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