forked from laurentnoe/iedera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.hh
1791 lines (1550 loc) · 63.9 KB
/
matrix.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef __MATRIX_HH__
#define __MATRIX_HH__
/** @page matrix Matrix
* @brief Matrix description and functions
* @tableofcontents
*
* @section matrix-description Description
*
* This part describes a matrix\<T\> : each @ref matrix<T> is mainly represented by a set of row\<T\>, each @ref row<T> can be represented as a @b sparse or @b non-sparse set of \<T\> cells.
* @li each @ref row<T> has an additional integer attribute @ref row<T>::_final, to match its equivalent @ref transition<T> attributes (see @ref automaton<T>).
* @li each @ref row<T> can be stored in a @e sparse or @e non-sparse form ( @ref row<T>::_sparse) with a way to revert the storage selection (@ref row<T>::setsparse(const bool sparse)).
* @li each @ref matrix<T> may bring probabilities (T = double, T = polynomial\<long long int\>), costs (T = cost\<int\>), counts (T = unsigned long long).
*
* @ref matrix<T> are (just) a more compact way to store @ref automata<T> attributes, once letters are not needed anymore.
* Default @ref matrix<T> constructor is almost empty, but several methods from @ref automaton<T> are proposed to produce matrices. They must be used first!
*
* The set of rows is stored in the @ref matrix::_rows vector. The set of cells per row is stored either in the @ref row::_cells_dense or @ref row::_cells_sparse vector.
* Several methods are also proposed to manipulate theses matrices (@ref local-matrix-manipulation or @ref global-matrices-manipulation), compute properties (@ref matrix-computed-properties),
* and an additional class is given (@ref matrices-slicer) for specific computations.
*
* @section local-matrix-manipulation Local matrix manipulation
*
* Two methods are proposed to manipulate matrices locally :
* @li @ref matrix::addNewRow(const int final, const bool sparse) to append a new row at the end of the @ref matrix<T>
* @li @ref matrix::addNewCell(const int i, const int j, const T v) to a add a cell on row @e i , @b provided @b that the coordinate @e i for the row\<T\> @b is @b correct.
*
* @section global-matrices-manipulation Global matrices manipulation
*
* Two methods are proposed to manipulate matrices globally :
*
* @li @ref matrix::Transpose() to reverse lines/columns,
* @li @ref matrix::Compose() for the product of two, compatible in size, matrices.
*
* @section matrix-computed-properties Matrices computed properties
*
* @li @ref matrix::Pr() is the most classical computation to reach @e final or @e non-final states after @e nbSteps transitions
* @li @ref matrix::Pr_transitive_final() is more complex, it computes "the transitive sum" of the @e final states values (@e final could be 1, but also more) that are crossed during the walk
* @li @ref matrix::Pr_one_step_from_one() is doing one single computation step, but use the @e final values from a second matrix @m_final that is passed as a parameter
*
* @section matrices-slicer Set of matrices computations
*
* The class @ref matrices_slicer is provided when several differents matrices have to be multiplied with a sliding windows moving along them.
* This class gives the ability to compute a "breadth first" product as an ordered set of matrices @f$M_1,M_2,M_3\ldots,M_l@f$,
* thus enabling an easy computation of @f$M_i,M_{i+1}\ldots,M_{j}@f$ and this @f$\forall 0 \leq i < j \leq l@f$ with @f$i@f$ and @f$j@f$ defined as one-step increasing functions
*
* You can find more details for Sliding windows computation :
*
* Spaced seed design on profile HMMs for precise HTS read-mapping
* efficient sliding window product on the matrix semi-group
*
* Additional files are also provided at @ref https://bioinfo.lifl.fr/yass/iedera_stepproduct/index.html
*
* You can also find three "stepwise equivalent" methods in the @ref automaton<T> class :
* @see automaton::matrices_step_pr_product, @see automaton::matrices_step_cost_product, and @see automaton::matrices_step_count_product
*
*
* @todo FIXME : to be continued
*
*/
/** @defgroup matrix matrix and row class templates
* @brief sparse / dense matrix template, with "automaton like" attributes ("final" integer attribute per row), and with semi-ring templates for each cell
*/
// @{
/// A try with classical TYPE_TRAITS
#if !defined(USE_TYPE_TRAITS) && !defined(USE_TR1_TYPE_TRAITS)
#define USE_TYPE_TRAITS
#endif
/// A try with classical STD
#if !defined(HAS_STD_TYPE_TRAITS) && !defined(HAS_STD_TR1_TYPE_TRAITS)
#define HAS_STD_TYPE_TRAITS
#endif
//STL
#include <functional>
#include <algorithm>
#include <vector>
//STD
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
//STR1
#ifdef USE_TYPE_TRAITS
#include <type_traits>
#else
#ifdef USE_TR1_TYPE_TRAITS
#include <tr1/type_traits>
#else
#error <type_traits> or <tr1/type_traits> not selected in "matrix.hh" : try g++ ... -DUSE_TR1_TYPE_TRAITS or -DUSE_TYPE_TRAITS, and use g++ version >= 4.3 with "-std=c++0x" or "-std=gnu++0x"
#endif
#endif
#ifdef HAS_STD_TYPE_TRAITS
using namespace std;
#else
#ifdef HAS_STD_TR1_TYPE_TRAITS
using namespace std::tr1;
#else
#error std or std::tr1 not selected in "matrix.hh" : try g++ ... -DHAS_STD_TYPE_TRAITS or -DHAS_STD_TR1_TYPE_TRAITS, and use g++ version >= 4.3 with "-std=c++0x" or "-std=gnu++0x"
#endif
#endif
//STR
#include "macro.h"
#include "infint.hh"
#include "cost.hh"
#include "polynomial.hh"
/**@name Enable/Disable if
* @brief only for definition and selection of good functions
*/
// @{
/** @brief struct template is enabled for bool = true
*/
template <bool B, typename T = void> struct enable_if_ca { /** type enabled */ typedef T type; };
/** @brief struct template is disabled for bool = false
*/
template <typename T> struct enable_if_ca <false, T> {};
/** @brief struct template is enabled for bool = false
*/
template <bool B, typename T = void> struct disable_if_ca { /** type enabled */ typedef T type; };
/** @brief struct template is disabled for bool = true
*/
template <typename T> struct disable_if_ca <true, T> {};
// @}
/** Zero and One are defined as "copies" for "arithmetic" types (but not for "Cost" types that are <min,plus> defined ... ),
* Transition gives the correct weight for a transition for "arithmetic types" (but for "Cost" type, gives the cost of the letter and not the letter)
*/
// @{
#ifdef HAS_STD_TYPE_TRAITS
/// arithmetic templates (for double probabilities or for integer count)
/** @brief Zero constant in the (+,x) semi-ring
* @return 0
*/
/** @addtogroup polynomial
* @addtogroup infint
*/
template<typename T> typename enable_if_ca < std::is_arithmetic<T>::value || std::is_same<T, infint<long long> >::value || std::is_same<T, polynomial<long long> >::value || std::is_same<T, polynomial<infint<long long> > >::value, T >::type Zero() {return T(0);}
/** @brief One constant in the (+,x) semi-ring
* @return 1
*/
template<typename T> typename enable_if_ca < std::is_arithmetic<T>::value || std::is_same<T, infint<long long> >::value || std::is_same<T, polynomial<long long> >::value || std::is_same<T, polynomial<infint<long long> > >::value, T >::type One() {return T(1);}
/// cost template (cost is not defined "arithmetic")
/** @addtogroup cost
*/
// @{
/** @brief Zero constant in the (min,+) semi-ring
* @return +infinity
*/
template<typename T> typename disable_if_ca < std::is_arithmetic<T>::value || std::is_same<T, infint<long long> >::value || std::is_same<T, polynomial<long long> >::value || std::is_same<T, polynomial<infint<long long> > >::value, T>::type Zero() {return T(0x7fffffff);}
/** @brief One constant in the (min,+) semi-ring
* @return 0
*/
template<typename T> typename disable_if_ca < std::is_arithmetic<T>::value || std::is_same<T, infint<long long> >::value || std::is_same<T, polynomial<long long> >::value || std::is_same<T, polynomial<infint<long long> > >::value, T>::type One() {return T(0x00000000);}
// @}
/** @brief IsProb() check if \<T\> can be interpreted as a probability
* @return true if \<T\> is a probability, false otherwise
*/
/// floating point and polynomials
template<typename T> typename enable_if_ca< (std::is_arithmetic<T>::value && std::is_floating_point<T>::value) || std::is_same<T, polynomial<long long int> >::value || std::is_same<T, polynomial<infint<long long int> > >::value, bool>::type IsProb() {return true;}
/// integer count and costs
template<typename T> typename disable_if_ca< (std::is_arithmetic<T>::value && std::is_floating_point<T>::value) || std::is_same<T, polynomial<long long int> >::value || std::is_same<T, polynomial<infint<long long int> > >::value, bool>::type IsProb() {return false;}
/** @brief IsVoid() check if \<T\> is a void type
* @return true if \<T\> is a void, false otherwise
*/
/// floating point and polynomial
template<typename T> typename enable_if_ca< std::is_void<T>::value && true, bool>::type IsVoid() {return true;}
/// integer count and costs
template<typename T> typename disable_if_ca< std::is_void<T>::value && true, bool>::type IsVoid() {return false;}
#else
/// arithmetic templates (for double)
/** @brief Zero constant in the (+,x) semi-ring
* @return 0
*/
/** @addtogroup polynomial
* @addtogroup infint
*/
template<typename T> typename enable_if_ca < std::tr1::is_arithmetic<T>::value || std::tr1::is_same<T, infint<long long> >::value || std::tr1::is_same<T, polynomial<long long> >::value || std::tr1::is_same<T, polynomial<infint<long long> > >::value, T >::type Zero() {return T(0);}
/** @brief One constant in the (+,x) semi-ring
* @return 1
*/
template<typename T> typename enable_if_ca < std::tr1::is_arithmetic<T>::value || std::tr1::is_same<T, infint<long long> >::value || std::tr1::is_same<T, polynomial<long long> >::value || std::tr1::is_same<T, polynomial<infint<long long> > >::value, T >::type One() {return T(1);}
/// cost template (cost is not defined "arithmetic")
/** @addtogroup cost
*/
// @{
/** @brief Zero constant in the (min,+) semi-ring
* @return +infinity
*/
template<typename T> typename disable_if_ca < std::tr1::is_arithmetic<T>::value || std::tr1::is_same<T, infint<long long> >::value || std::tr1::is_same<T, polynomial<long long> >::value || std::tr1::is_same<T, polynomial<infint<long long> > >::value, T>::type Zero() {return T(0x7fffffff);}
/** @brief One constant in the (min,+) semi-ring
* @return 0
*/
template<typename T> typename disable_if_ca < std::tr1::is_arithmetic<T>::value || std::tr1::is_same<T, infint<long long> >::value || std::tr1::is_same<T, polynomial<long long> >::value || std::tr1::is_same<T, polynomial<infint<long long> > >::value, T>::type One() {return T(0x00000000);}
// @}
/** @brief IsProb() check if \<T\> can be interpreted as a probability
* @return true if \<T\> is a probability, false otherwise
*/
/// floating point and polynomials
template<typename T> typename enable_if_ca< (std::tr1::is_arithmetic<T>::value && std::tr1::is_floating_point<T>::value) || std::tr1::is_same<T, polynomial<long long int> >::value || std::tr1::is_same<T, polynomial<infint<long long int> > >::value, bool>::type IsProb() {return true;}
/// integer count and costs
template<typename T> typename disable_if_ca< (std::tr1::is_arithmetic<T>::value && std::tr1::is_floating_point<T>::value) || std::tr1::is_same<T, polynomial<long long int> >::value || std::tr1::is_same<T, polynomial<infint<long long int> > >::value, bool>::type IsProb() {return false;}
/** @brief IsVoid() check if \<T\> is a void type
* @return true if \<T\> is a void, false otherwise
*/
/// floating point and polynomials
template<typename T> typename enable_if_ca< std::tr1::is_void<T>::value && true, bool>::type IsVoid() {return true;}
/// integer count and costs
template<typename T> typename disable_if_ca< std::tr1::is_void<T>::value && true, bool>::type IsVoid() {return false;}
#endif
// @}
/**
* @class row
* @tparam T
* @brief sparse / dense vector, represented by an ordered vector of cells, each cell containing either a couple @f$ ( integer \times T ) @f$ or a single element @f$ T @f$
* T may represents here
* - a probability
* - a cost
* each row has a also a flag to together with a "final" state for this row.
*/
template<typename T> class row {
public:
/** @brief Constructor for an empty row (empty cell lists)
* @param final is the row state (final or not)
* @param sparse is the implementation choosen for the row being created
*/
inline row(const int final = 0, const bool sparse = true): _final(final), _sparse(sparse), _cells_sparse(), _cells_dense() {};
/** @brief Copy constructor
* @param r is the row to be cloned (vector reallocation)
*/
inline row(const row<T> & r): _final(r._final), _sparse(r._sparse), _cells_sparse(r._cells_sparse), _cells_dense(r._cells_dense) {};
/** @brief Erase a row (clear cell lists first)
*/
inline ~row() { _cells_sparse.clear(); _cells_dense.clear(); _final = 0; _sparse = true;};
/** @brief Clear a row (clear the vector _cells and set _final to 0)
*/
inline void clear() { _cells_sparse.clear(); _cells_dense.clear(); _final = 0; _sparse = true;};
/** @brief add a new cell (j) if does not exists, otherwise "add" (according to T) the "v" value to the current cell (j)
* @param j is the column number
* @param v is the element to be inserted (or added if it already exists)
*/
void insert(const int j, const T v);
/** @brief final state
* @return final state of the current row
*/
inline int final() const { return _final; }
/** @brief set final state
* @param final is the value that will be set to the current row
*/
inline void setfinal(const int final) { _final = final; }
/** @brief get the implementation of the current row
* @return true if the row is sparse (dense otherwise)
*/
inline bool sparse() const { return _sparse; }
/** @brief change the implementation of the current row (sparse to dense and dense to sparse)
* @param sparse is the implementation choosen for the row being modified
*/
inline void setsparse(const bool sparse) {
if (!_sparse && sparse) {
for (unsigned i = 0; i < _cells_dense.size(); i++) {
if (_cells_dense[i] != Zero<T>()) {
std::pair<int,T> p = make_pair(i,_cells_dense[i]);
_cells_sparse.push_back(p);
}
}
_cells_dense.clear();
_sparse = true;
} else if (_sparse && !sparse) {
for (typename std::vector< std::pair<int,T> >::const_iterator i = _cells_sparse.begin(); i != _cells_sparse.end(); i++) {
int j = i->first;
T v = i->second;
if (_cells_dense.size() <= (unsigned)j)
_cells_dense.resize(j+1, Zero<T>());
_cells_dense[j] = _cells_dense[j] + v;
}
_cells_sparse.clear();
_sparse = false;
}
}
/** @brief return the size as the number of cells
* @return the number of cells
*/
inline int size() const { if (_sparse) return _cells_sparse.size(); else return _cells_dense.size(); }
/** @brief return the size as the number of cells
* @return the number of cells
*/
inline int max_index() const {
if (_sparse) {
int max_column = 0;
for (typename std::vector< std::pair<int,T> >::const_iterator i = _cells_sparse.begin(); i != _cells_sparse.end(); i++) {
max_column = MAX(max_column,i->first);
}
return max_column;
} else {
return _cells_dense.size() - 1;
}
}
/** @brief return the density as the number of cells over the max index (virtual size)
* @return the density
*/
double density() const {
if (_sparse) {
return (double) _cells_sparse.size() / (max_index()+1);
} else {
int n = 0;
for (unsigned i = 0; i < _cells_dense.size(); i++)
if (_cells_dense[i] != Zero<T>()) n++;
return (double) n / _cells_dense.size(); //FIXME if (_cell_dense.size() == 0)
}
}
/** @brief return the reference to the vector of sparse cells
* @return a reference to the vector
*/
const std::vector< std::pair<int,T> > & cells_sparse() const { return _cells_sparse; }
/** @brief return the reference to the vector of dense cells
* @return a reference to the vector
*/
const std::vector< T > & cells_dense() const { return _cells_dense; }
// @{
/// print row information
template<typename U> friend ostream& operator<< (ostream& os, const row<U>& m);
/** @brief print a row in "maple" format
* @param os is the outputstream
* @param max_size is used to pad with Zeros<T>() on a sparse row
* @param ignore_indices_sorted is a sorted list of elements indices that must not be in the output (because not needed for example)
* @param v_end_cell is a cumulative cell that keep the values of elements not present in the output between two outputed elements
*/
void maple(ostream& os, int max_size, std::vector<int> & ignore_indices_sorted, T & v_end_cell) const;
/** @brief print a row in "maple" recursive format
* @param os is the outputstream
*/
void maple_recursive(ostream& os) const;
/// load row information
template<typename U> friend istream& operator>> (istream& is, row<U>& m);
// @}
protected :
/// final state
int _final;
/// is the row sparse or dense represented ?
bool _sparse;
/// cells list in sparse mode
std::vector< std::pair<int,T> > _cells_sparse;
/// cells vector in dense mode
std::vector< T > _cells_dense;
/// matrix is a friend class to ease access
template<typename U> friend class matrix;
/// matrices_slicer is a friend class to ease access
template<typename U> friend class matrices_slicer;
};
/**
* @class matrix
* @tparam T
* @brief sparse matrix, represented by a (dense) vector of (sparse / dense) rows.
* This class has strong link with automaton as it usualy represents such objects (final/non-final states) after
* being processed with a HMM model.
* @see row
* @see automaton
*/
template<typename T> class matrix {
public:
/** @brief Constructor for an empty matrix
*/
matrix() : _rows() {};
/** @brief Copy constructor
* @param m is the matrix to be cloned (vector reallocation)
*/
matrix(const matrix<T> & m) {
_rows = std::vector<row<T> >(m._rows.size());
for (unsigned i = 0; i < m._rows.size(); i++)
_rows[i] = row<T>(m._rows[i]);
};
/** @brief Erase a matrix (clear _cells_sparse and _cells_dense for each row first)
*/
~matrix() {
for (unsigned i = 0; i < _rows.size(); i++)
_rows[i].clear();
_rows.clear();
};
/** @brief Clear a matrix (clear _cells_sparse and _cells_dense for each row first)
*/
void clear() {
for (unsigned i = 0; i < _rows.size(); i++)
_rows[i].clear();
_rows.clear();
};
/** @brief Resize the number of line of the matrix (clear the rows)
* @param s is the new number of rows.
*/
void resize(int s) {
_rows.resize(s);
};
/** @brief add a new cell (i,j) if does not exists, otherwise "add" (according to T) the "v" value to the current cell (i,j)
* @param i is the row number
* @param j is the column number
* @param v is the element to be inserted (or added if it already exists)
*/
inline void insert(const int i, const int j, const T v) { _rows[i].insert(j,v);}
/** @brief add a new row at the end of the matrix
* @param final is the row state (final or not)
* @param sparse is the implementation choosen for the row being added
* @return the "new" index of the row being added
*/
inline int addNewRow(const int final = 0, const bool sparse = true) { _rows.push_back(row<T>(final,sparse)); return _rows.size() - 1;}
/** @brief add a new cell (i,j) if does not exists, otherwise "add" (according to T) the "v" value to the current cell (i,j)
* @param i is the row number
* @param j is the column number
* @param v is the element to be inserted (or added if it already exists)
*/
inline void addNewCell(const int i, const int j, const T v) { _rows[i].insert(j,v); }
/** @brief return the size as the number of rows
* @return the number of rows
*/
inline int size() const { return _rows.size(); }
/** @brief return the fullsize as the full number of cells
* @return the numrber of cells
*/
inline int fullsize() const {
int fsize = 0;
for (unsigned i = 0; i < _rows.size(); i++)
fsize += _rows[i].size();
return fsize;
}
/** @brief selfLoop on row i
* @param i the row and also the column number (since this is a selfloop)
* @param p is the value to be inserted (by default it is a One\<T\>(), i.e. the neutral element of the *\<T\>)
*/
inline void selfLoop(const int i, const T p = One<T>()) { insert(i,i,p); }
/** @brief Compute the transposed matrix
* @return the transposed matrix
* @todo{FIXME : final states/rows are not set}
*/
matrix<T> * Transpose() const;
/** @brief Compute the composition of two matrices
* @param other is the matrix that will be composed with the current matrix this
* @return the composed matrix of the current matrix with the other matrix
*/
matrix<T> * Compose(const matrix<T> &other) const;
/** @brief Compute the probability/(min cost/count) to be at a final/(non final) row during the "nbSteps"th step
* @param nbSteps is the number of iterated products done on the matrix
* @param final is set when the computation is done on final states, otherwise, it is done on non final states (default, true, is on final states)
* @return the probability/(min cost) to be at a final/(non final) row during the "nbSteps"-th step
* @warning only work with "non window" matrices (must be "square" and "self-injecting") : otherwise final states are not set correctly
* @see Pr_transitive_final,Pr_one_step_from_one
*/
const T Pr(const int nbSteps = gv_alignment_length, const bool final = true) const;
/** @brief Compute the probability/(min cost/count) to be at a "transitive-sum of final values" during the "nbSteps"th step
* @param nbSteps is the number of iterated products done on the matrix
* @param max_final_value is the value that must not be reached by a "transitive-sum of finals states" (set to maximal \<int\> value by default)
* @param sub_final_value is the replacement value when the previous max_final_value is reached (set to 1 by default)
* @return the probability/(min cost) to be at a "transitive-sum of final values" during the "nbSteps"th step, represented as a vector indexed by the "transitive-sum"
* @warning only work "non window" matrices (must be "square" and "self-injecting") : otherwise final states are not set correctly
* @warning previous automata products must use the UNION_ADD operator only to keep "final values" greater than one
* @see Pr
*/
std::vector<T> * Pr_transitive_final(const int nbSteps, const unsigned max_final_value = INT_INFINITY, const int sub_final_value = 1) const;
/** @brief Compute a one-step single walk from the initial to the final states marked by the matrix "m_final"
* @param m_final is the matrix used at the end to mark final states
* (matrices are otherwise represented as one final/row + a set of links, but nothing is known on the reaching states, so "m_final" is usefull here ...)
* @param final is set when the computation is done on final states, otherwise, it is done on non final states (default, true, is on final states)
* @return the probability/min cost/count to be at a final/(non final) row during the "nbSteps"-th step
* @warning only work with "full-window" computed matrices (not "self-injecting")
* @see Pr
*/
const T Pr_one_step_from_one(const matrix<T> &m_final, const bool final = true) const;
/**@name IO methods
* @brief IO streams to print/store/load matrix
*/
// @{
/// print matrix information
template<typename U> friend ostream& operator<< (ostream& os, const matrix<U>& m);
/** @brief print a matrix in "maple" format
* @param os is the outputstream
* @param separate_final indicates if final states ùmust be included in the matrix
*/
void maple(ostream& os, bool separate_final = false) const;
/** @brief print a row in "maple" recursive format
* @param os is the outputstream
*/
void maple_recursive(ostream& os) const;
/// load matrix information
template<typename U> friend istream& operator>> (istream& is, matrix<U>& m);
// @}
protected :
/// vector of rows
std::vector< row<T> > _rows;
/// matrices_slicer is a friend class to ease access
template<typename U> friend class matrices_slicer;
};
/// compare pairs of elements in a row only on their first index number (and not the second T element)
template<typename T> inline bool pairless(const std::pair<int, T> l, const std::pair<int, T> r) {
return l.first < r.first;
}
/// output method for a row
template<typename T> inline ostream& operator<<(ostream& os, const row<T>& r) {
os << "\t" << (r.size()) << "\t" << (r.final()) << endl;
// for each row, display each cell
if (r.sparse()) {
for (typename std::vector< std::pair<int,T> >::const_iterator i = r._cells_sparse.begin(); i != r._cells_sparse.end(); i++) {
os << "\t\t\t" << (i->first) << "\t" << (i->second) << endl;
}
} else {
for (typename std::vector< T >::const_iterator i = r._cells_dense.begin(); i != r._cells_dense.end(); i++) {
if ((*i) != Zero<T>()) {
os << "\t\t\t" << (i - r._cells_dense.begin()) << "\t" << (*i) << endl;
}
}
}
return os;
}
/// output method as a "maple" row
template<typename T> inline void row<T>::maple(ostream& os, int max_size, std::vector<int> & ignore_indices_sorted, T & v_end_cell) const {
os << "[";
unsigned ignore_i = 0;
// for each row, display each cell
if (sparse()) {
/* sparse implementation */
int u_old = 0;
bool first_element = false;
for (typename std::vector< std::pair<int,T> >::const_iterator i = _cells_sparse.begin(); i != _cells_sparse.end(); i++) {
while (u_old < (i->first)) {
if (ignore_i < ignore_indices_sorted.size() && ignore_indices_sorted[ignore_i] == u_old) {
ignore_i++;
} else {
if (first_element)
os << ",";
os << Zero<T>();
first_element = true;
}
u_old++;
}
if (ignore_i < ignore_indices_sorted.size() && ignore_indices_sorted[ignore_i] == u_old) {
v_end_cell = v_end_cell + i->second;
ignore_i++;
} else {
if (first_element)
os << ",";
os << (i->second);
first_element = true;
}
u_old++;
}
while (u_old < (max_size)) {
if (ignore_i < ignore_indices_sorted.size() && ignore_indices_sorted[ignore_i] == u_old) {
ignore_i++;
} else {
if (first_element)
os << ",";
os << Zero<T>();
first_element = true;
}
u_old++;
}
} else {
/* dense implementation */
bool first_element = false;
for (typename std::vector< T >::const_iterator i = _cells_dense.begin(); i != _cells_dense.end(); i++) {
if (ignore_i < ignore_indices_sorted.size() && ignore_indices_sorted[ignore_i] == (i-_cells_dense.begin())) {
v_end_cell = v_end_cell + (*i);
ignore_i++;
} else {
if (first_element)
os << ",";
os << (*i);
first_element = true;
}
os << (*i);
first_element = true;
}
}
os << "] # final : " << final() << endl;
}
/// output method as a "maple" recursive definition
template<typename T> inline void row<T>::maple_recursive(ostream& os) const {
// for each row, display each cell
if (sparse()) {
/* sparse implementation */
bool first_element = false;
for (typename std::vector< std::pair<int,T> >::const_iterator i = _cells_sparse.begin(); i != _cells_sparse.end(); i++) {
if ((i->second) != Zero<T>()) {
if (first_element)
os << " + ";
os << "q" << (i->first) << "(n-1) * " << (i->second);
first_element = true;
}
}
} else {
/* dense implementation */
bool first_element = false;
for (typename std::vector< T >::const_iterator i = _cells_dense.begin(); i != _cells_dense.end(); i++) {
if ((*i) != Zero<T>()) {
if (first_element)
os << " + ";
os << "q" << (i - _cells_dense.begin()) << "(n-1) * " << (*i);
first_element = true;
}
}
}
}
/// input method for a row
template<typename T> inline istream& operator>>(istream& is, row<T>& r) {
// previous data removed if any
r._cells_dense.clear();
r._cells_sparse.clear();
r._sparse = true;
// a) read row length
int nbcells = 0;
is >> nbcells;
#ifdef DEBUGREADING
cerr << nbcells << endl;
#endif
if (nbcells <= 0) {
cerr << "> when reading nbcells" << endl;
_ERROR("row operator>>","incorrect size "<< nbcells);
}
// b) read row final
int final;
is >> final;
r._final = final;
// c) read row data
for (int j = 0; j<nbcells; j++){
int to = 0;
T pr = T();
is >> to >> pr;
#ifdef DEBUGREADING
cerr << "\t\t" << to << "\t" << pr << endl;
#endif
if (to < 0) {
cerr << "> when reading cell" << endl;
_ERROR("row operator>>","incorrect column value "<< to);
}
r.insert(to,pr);
}
return is;
}
/// output method for the current matrix
template<typename T> inline ostream& operator<<(ostream& os, const matrix<T>& m) {
os << m._rows.size() << endl;
// display each row
for (typename std::vector< row<T> >::const_iterator i = m._rows.begin(); i != m._rows.end(); i++) {
const row<T> & r = *i;
os << "\t" << r;
}
return os;
}
/// output method as a maple "matrix" (must be square here)
template<typename T> inline void matrix<T>::maple(ostream& os, bool separate_final) const {
os << "[" << endl;
std::vector<int> ignore_indices_sorted(0);
if (separate_final) {
for (typename std::vector< row<T> >::const_iterator i = _rows.begin(); i != _rows.end(); i++) {
const row<T> & r = *i;
if (r.final())
ignore_indices_sorted.push_back(i-_rows.begin());
}
}
std::vector<T> v_end(_rows.size()-ignore_indices_sorted.size(),Zero<T>());
// display each row
bool first_element = false;
unsigned ignore_i = 0;
for (typename std::vector< row<T> >::const_iterator i = _rows.begin(); i != _rows.end(); i++) {
const row<T> & r = *i;
if (separate_final && ignore_i < ignore_indices_sorted.size() && (ignore_indices_sorted[ignore_i] == i - _rows.begin())) {
ignore_i++;
} else {
if (first_element)
os << "," << endl;
r.maple(os,_rows.size(),ignore_indices_sorted,v_end[(i - _rows.begin()) - ignore_i]);
first_element = true;
}
}
os << "];" << endl;
// display the v_end vector
if (separate_final) {
os << "[";
for (unsigned u = 0; u < v_end.size(); u++) {
if (u)
os << ",";
os << (v_end[u]);
}
os << "];" << endl;
}
}
/// output method as a "maple" recursive definition
template<typename T> inline void matrix<T>::maple_recursive(ostream& os) const {
matrix<T> * m_t = Transpose();
os << "{" << endl;
// display each row
bool first_element = false;
for (typename std::vector< row<T> >::const_iterator i = m_t->_rows.begin(); i != m_t->_rows.end(); i++) {
const row<T> & r = *i;
if (first_element)
os << "," << endl;
os << "q" << (i-m_t->_rows.begin()) << "(n) = ";
r.maple_recursive(os);
first_element = true;
}
// display initial conditions
for (typename std::vector< row<T> >::const_iterator i = m_t->_rows.begin(); i != m_t->_rows.end(); i++) {
os << "," << endl;
os << "q" << (i-m_t->_rows.begin()) << "(0) = " << (((i-m_t->_rows.begin()) == 1) ? 1 : 0);
}
os << endl << "}," << endl;
// display variables
os << "{" << endl;
for (typename std::vector< row<T> >::const_iterator i = m_t->_rows.begin(); i != m_t->_rows.end(); i++) {
if (i != m_t->_rows.begin())
os << "," << endl;
os << "q" << (i-m_t->_rows.begin());
}
os << "}" << endl;
delete m_t;
}
/// input method for the current matrix
template<typename T> inline istream& operator>>(istream& is, matrix<T>& m) {
// clear previous matrix
m._rows.clear();
// read matrix size
int nbrows = 0;
is >> nbrows;
#ifdef DEBUGREADING
cerr << nbrows << endl;
#endif
if (nbrows <= 0) {
cerr << "> when reading matrix size" << endl;
_ERROR("matrix operator>>","incorrect size "<< nbrows);
}
// add rows first
for (int i = 0;i<nbrows;i++){
m.addNewRow();
}
// get each row content
int introw;
for (int from = 0; from<nbrows; from++){
is >> introw >> (m._rows[from]);
#ifdef DEBUGREADING
cerr << "\t" << introw << "\t" << (m._rows[from]);
#endif
if (introw < 0 || introw >= nbrows) {
cerr << "> when reading matrix cell line " << introw << " (line nb " << from << ")" << endl;
_ERROR("matrix operator>>","incorrect row number " << introw << " (not in [0.."<<(nbrows-1)<<"])");
}
}
return is;
}
/// insert an element to a row (or "add" it using the T "+" operator)
template<typename T> inline void row<T>::insert(const int j, const T v) {
if (_sparse) {
/* sparse implementation */
std::pair<int,T> p(j,v);
typename std::vector< std::pair<int,T> >::iterator it = lower_bound(_cells_sparse.begin(),_cells_sparse.end(),p,pairless<T>);
if (it != _cells_sparse.end())
if (it->first == j)
it->second = it->second + v;
else
_cells_sparse.insert(it,p);
else
_cells_sparse.push_back(p);
} else {
/* dense implementation */
if (_cells_dense.size() <= (unsigned)j)
_cells_dense.resize(j+1, Zero<T>());
_cells_dense[j] = _cells_dense[j] + v;
}
}
/// transpose a matrix
template<typename T> inline matrix<T> * matrix<T>::Transpose() const {
matrix * result = new matrix();
// find the max column on the original matrix
int max_column = 0;
for (unsigned i = 0; i < _rows.size(); i++) {
max_column = MAX(max_column,_rows[i].max_index());
}
// build the transpose matrix in dense format first
for (int i = 0; i <= max_column; i++) {
result->addNewRow(false/* final does not mean anything here so set to false */, false /* dense */);
result->_rows[i]._cells_dense.resize(_rows.size(), Zero<T>());
}
// fill the transpose matrix in dense format first then put the sparse row when needed ...
for (unsigned i = 0; i < _rows.size(); i++) {
if (_rows[i]._sparse) {
for (typename std::vector< std::pair<int,T> >::const_iterator j=_rows[i]._cells_sparse.begin(); j != _rows[i]._cells_sparse.end(); j++) {
result->_rows[j->first]._cells_dense[i] = j->second;
}
} else {
for (unsigned j = 0 ; j < _rows[i]._cells_dense.size(); j++) {
result->_rows[j]._cells_dense[i] = _rows[i]._cells_dense[j];
}
}
}
for (unsigned i = 0; i < result->_rows.size(); i++) {
if (result->_rows[i].density() < MATRIX_SPARSE_ROW_DENSITY) {
result->_rows[i].setsparse(true);
}
}
return result;
}
/// matrix composition (or product)
template<typename T> inline matrix<T> * matrix<T>::Compose(const matrix<T> &other) const {
matrix * result = new matrix();
matrix * other_transpose = other.Transpose();
for (unsigned i = 0; i < _rows.size(); i++) {
result->addNewRow(_rows[i].final(),false);
result->_rows[i]._cells_dense.resize(other_transpose->_rows.size(), Zero<T>()); // FIXME dense mode first
for (unsigned j = 0; j < other_transpose->_rows.size(); j++) {
if (_rows[i]._sparse) {
if (other_transpose->_rows[j]._sparse) {
/* 1/4 */
typename std::vector< std::pair<int,T> >::const_iterator k_this = _rows[i]._cells_sparse.begin();
typename std::vector< std::pair<int,T> >::const_iterator k_other = other_transpose->_rows[j]._cells_sparse.begin();
while (k_this != _rows[i]._cells_sparse.end() && k_other != other_transpose->_rows[j]._cells_sparse.end()) {
if (k_this->first == k_other->first) {
result->_rows[i]._cells_dense[j] = result->_rows[i]._cells_dense[j] + (k_this->second * k_other->second);
k_this++;
k_other++;
} else if (k_this->first < k_other->first) {
k_this++;
} else {
k_other++;
}
}
} else {
/* 2/4 */
for (typename std::vector< std::pair<int,T> >::const_iterator k_this = _rows[i]._cells_sparse.begin(); k_this < _rows[i]._cells_sparse.end(); k_this++) {
if (other_transpose->_rows[j]._cells_dense[k_this->first] != Zero<T>()) {
result->_rows[i]._cells_dense[j] = result->_rows[i]._cells_dense[j] + (k_this->second * other_transpose->_rows[j]._cells_dense[k_this->first]);
}
}
}
} else {
if (other_transpose->_rows[j]._sparse) {
/* 3/4 */
for (typename std::vector< std::pair<int,T> >::const_iterator k_other = other_transpose->_rows[j]._cells_sparse.begin(); k_other < other_transpose->_rows[j]._cells_sparse.end(); k_other++) {
if (_rows[i]._cells_dense[k_other->first] != Zero<T>()) {
result->_rows[i]._cells_dense[j] = result->_rows[i]._cells_dense[j] + (_rows[i]._cells_dense[k_other->first] * k_other->second);
}
}
} else {
/* 4/4 */
for (unsigned k=0; k < _rows[i]._cells_dense.size(); k++) {
result->_rows[i]._cells_dense[j] = result->_rows[i]._cells_dense[j] + (_rows[i]._cells_dense[k] * other_transpose->_rows[j]._cells_dense[k]);
}
}
}
}
if (result->_rows[i].density() < MATRIX_SPARSE_ROW_DENSITY) {
result->_rows[i].setsparse(true);
}
}
delete other_transpose;
return result;
}
/// matrix "Pr" classical algorithm : compute the "T"-lity to be at a final or non final state after nbSteps on the same matrix
template<typename T> inline const T matrix<T>::Pr(const int nbSteps, const bool final) const {
int i_min = 1;
int i_max = 1;
// set all the other probabilities or counts to 0 (PLUS neutral element) or cost to infinity (MIN neutral element)
std::vector<T> v0(size(),Zero<T>());
std::vector<T> v1(size(),Zero<T>());
// set initial state probability or count to 1 (PRODUCT neutral element) or initial cost to 0 (PLUS neutral element)
v1[1] = One<T>();
// compute probability/cost/count at step i provided probabilities/costs/counts at step i-1
for (int k = 0 ; k < nbSteps ; k++) {
int j_min = size()-1;
int j_max = 0;
if (k&1) {
for (int i = i_min; i <= i_max; i++) {