summaryrefslogtreecommitdiff
path: root/boost/units/detail/linear_algebra.hpp
blob: 17ed34bd1b7ea62df6672c1f569ad23c6b6c03d2 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
// Boost.Units - A C++ library for zero-overhead dimensional analysis and 
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UNITS_DETAIL_LINEAR_ALGEBRA_HPP
#define BOOST_UNITS_DETAIL_LINEAR_ALGEBRA_HPP

#include <boost/units/static_rational.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/arithmetic.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/assert.hpp>

#include <boost/units/dim.hpp>
#include <boost/units/dimensionless_type.hpp>
#include <boost/units/static_rational.hpp>
#include <boost/units/detail/dimension_list.hpp>
#include <boost/units/detail/sort.hpp>

namespace boost {

namespace units {

namespace detail {

// typedef list<rational> equation;

template<int N>
struct eliminate_from_pair_of_equations_impl;

template<class E1, class E2>
struct eliminate_from_pair_of_equations;

template<int N>
struct elimination_impl;

template<bool is_zero, bool element_is_last>
struct elimination_skip_leading_zeros_impl;

template<class Equation, class Vars>
struct substitute;

template<int N>
struct substitute_impl;

template<bool is_end>
struct solve_impl;

template<class T>
struct solve;

template<int N>
struct check_extra_equations_impl;

template<int N>
struct normalize_units_impl;

struct inconsistent {};

// generally useful utilies.

template<int N>
struct divide_equation {
    template<class Begin, class Divisor>
    struct apply {
        typedef list<typename mpl::divides<typename Begin::item, Divisor>::type, typename divide_equation<N - 1>::template apply<typename Begin::next, Divisor>::type> type;
    };
};

template<>
struct divide_equation<0> {
    template<class Begin, class Divisor>
    struct apply {
        typedef dimensionless_type type;
    };
};

// eliminate_from_pair_of_equations takes a pair of
// equations and eliminates the first variable.
//
// equation eliminate_from_pair_of_equations(equation l1, equation l2) {
//     rational x1 = l1.front();
//     rational x2 = l2.front();
//     return(transform(pop_front(l1), pop_front(l2), _1 * x2 - _2 * x1));
// }

template<int N>
struct eliminate_from_pair_of_equations_impl {
    template<class Begin1, class Begin2, class X1, class X2>
    struct apply {
        typedef list<
            typename mpl::minus<
                typename mpl::times<typename Begin1::item, X2>::type,
                typename mpl::times<typename Begin2::item, X1>::type
            >::type,
            typename eliminate_from_pair_of_equations_impl<N - 1>::template apply<
                typename Begin1::next,
                typename Begin2::next,
                X1,
                X2
            >::type
        > type;
    };
};

template<>
struct eliminate_from_pair_of_equations_impl<0> {
    template<class Begin1, class Begin2, class X1, class X2>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<class E1, class E2>
struct eliminate_from_pair_of_equations {
    typedef E1 begin1;
    typedef E2 begin2;
    typedef typename eliminate_from_pair_of_equations_impl<(E1::size::value - 1)>::template apply<
        typename begin1::next,
        typename begin2::next,
        typename begin1::item,
        typename begin2::item
    >::type type;
};



// Stage 1.  Determine which dimensions should
// have dummy base units.  For this purpose
// row reduce the matrix.

template<int N>
struct make_zero_vector {
    typedef list<static_rational<0>, typename make_zero_vector<N - 1>::type> type;
};
template<>
struct make_zero_vector<0> {
    typedef dimensionless_type type;
};

template<int Column, int TotalColumns>
struct create_row_of_identity {
    typedef list<static_rational<0>, typename create_row_of_identity<Column - 1, TotalColumns - 1>::type> type;
};
template<int TotalColumns>
struct create_row_of_identity<0, TotalColumns> {
    typedef list<static_rational<1>, typename make_zero_vector<TotalColumns - 1>::type> type;
};
template<int Column>
struct create_row_of_identity<Column, 0> {
    // error
};

template<int RemainingRows>
struct determine_extra_equations_impl;

template<bool first_is_zero, bool is_last>
struct determine_extra_equations_skip_zeros_impl;

// not the last row and not zero.
template<>
struct determine_extra_equations_skip_zeros_impl<false, false> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        // remove the equation being eliminated against from the set of equations.
        typedef typename determine_extra_equations_impl<RemainingRows - 1>::template apply<typename RowsBegin::next, typename RowsBegin::item>::type next_equations;
        // since this column was present, strip it out.
        typedef Result type;
    };
};

// the last row but not zero.
template<>
struct determine_extra_equations_skip_zeros_impl<false, true> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        // remove this equation.
        typedef dimensionless_type next_equations;
        // since this column was present, strip it out.
        typedef Result type;
    };
};


// the first columns is zero but it is not the last column.
// continue with the same loop.
template<>
struct determine_extra_equations_skip_zeros_impl<true, false> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        typedef typename RowsBegin::next::item next_row;
        typedef typename determine_extra_equations_skip_zeros_impl<
            next_row::item::Numerator == 0,
            RemainingRows == 2  // the next one will be the last.
        >::template apply<
            typename RowsBegin::next,
            RemainingRows - 1,
            CurrentColumn,
            TotalColumns,
            Result
        > next;
        typedef list<typename RowsBegin::item::next, typename next::next_equations> next_equations;
        typedef typename next::type type;
    };
};

// all the elements in this column are zero.
template<>
struct determine_extra_equations_skip_zeros_impl<true, true> {
    template<class RowsBegin, int RemainingRows, int CurrentColumn, int TotalColumns, class Result>
    struct apply {
        typedef list<typename RowsBegin::item::next, dimensionless_type> next_equations;
        typedef list<typename create_row_of_identity<CurrentColumn, TotalColumns>::type, Result> type;
    };
};

template<int RemainingRows>
struct determine_extra_equations_impl {
    template<class RowsBegin, class EliminateAgainst>
    struct apply {
        typedef list<
            typename eliminate_from_pair_of_equations<typename RowsBegin::item, EliminateAgainst>::type,
            typename determine_extra_equations_impl<RemainingRows-1>::template apply<typename RowsBegin::next, EliminateAgainst>::type
        > type;
    };
};

template<>
struct determine_extra_equations_impl<0> {
    template<class RowsBegin, class EliminateAgainst>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<int RemainingColumns, bool is_done>
struct determine_extra_equations {
    template<class RowsBegin, int TotalColumns, class Result>
    struct apply {
        typedef typename RowsBegin::item top_row;
        typedef typename determine_extra_equations_skip_zeros_impl<
            top_row::item::Numerator == 0,
            RowsBegin::size::value == 1
        >::template apply<
            RowsBegin,
            RowsBegin::size::value,
            TotalColumns - RemainingColumns,
            TotalColumns,
            Result
        > column_info;
        typedef typename determine_extra_equations<
            RemainingColumns - 1,
            column_info::next_equations::size::value == 0
        >::template apply<
            typename column_info::next_equations,
            TotalColumns,
            typename column_info::type
        >::type type;
    };
};

template<int RemainingColumns>
struct determine_extra_equations<RemainingColumns, true> {
    template<class RowsBegin, int TotalColumns, class Result>
    struct apply {
        typedef typename determine_extra_equations<RemainingColumns - 1, true>::template apply<
            RowsBegin,
            TotalColumns,
            list<typename create_row_of_identity<TotalColumns - RemainingColumns, TotalColumns>::type, Result>
        >::type type;
    };
};

template<>
struct determine_extra_equations<0, true> {
    template<class RowsBegin, int TotalColumns, class Result>
    struct apply {
        typedef Result type;
    };
};

// Stage 2
// invert the matrix using Gauss-Jordan elimination


template<bool is_zero, bool is_last>
struct invert_strip_leading_zeroes;

template<int N>
struct invert_handle_after_pivot_row;

// When processing column N, none of the first N rows 
// can be the pivot column.
template<int N>
struct invert_handle_inital_rows {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename invert_handle_inital_rows<N - 1>::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next
        > next;
        typedef typename RowsBegin::item current_row;
        typedef typename IdentityBegin::item current_identity_row;
        typedef typename next::pivot_row pivot_row;
        typedef typename next::identity_pivot_row identity_pivot_row;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_row::size::value) - 1>::template apply<
                typename current_row::next,
                pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::new_matrix
        > new_matrix;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_identity_row::size::value)>::template apply<
                current_identity_row,
                identity_pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::identity_result
        > identity_result;
    };
};

// This handles the switch to searching for a pivot column.
// The pivot row will be propagated up in the typedefs
// pivot_row and identity_pivot_row.  It is inserted here.
template<>
struct invert_handle_inital_rows<0> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename invert_strip_leading_zeroes<
            (current_row::item::Numerator == 0),
            (RowsBegin::size::value == 1)
        >::template apply<
            RowsBegin,
            IdentityBegin
        > next;
        // results
        typedef list<typename next::pivot_row, typename next::new_matrix> new_matrix;
        typedef list<typename next::identity_pivot_row, typename next::identity_result> identity_result;
        typedef typename next::pivot_row pivot_row;
        typedef typename next::identity_pivot_row identity_pivot_row;
    };
};

// The first internal element which is not zero.
template<>
struct invert_strip_leading_zeroes<false, false> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename current_row::item current_value;
        typedef typename divide_equation<(current_row::size::value - 1)>::template apply<typename current_row::next, current_value>::type new_equation;
        typedef typename divide_equation<(IdentityBegin::item::size::value)>::template apply<typename IdentityBegin::item, current_value>::type transformed_identity_equation;
        typedef typename invert_handle_after_pivot_row<(RowsBegin::size::value - 1)>::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next,
            new_equation,
            transformed_identity_equation
        > next;

        // results
        // Note that we don't add the pivot row to the
        // results here, because it needs to propagated up
        // to the diagonal.
        typedef typename next::new_matrix new_matrix;
        typedef typename next::identity_result identity_result;
        typedef new_equation pivot_row;
        typedef transformed_identity_equation identity_pivot_row;
    };
};

// The one and only non-zero element--at the end
template<>
struct invert_strip_leading_zeroes<false, true> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename current_row::item current_value;
        typedef typename divide_equation<(current_row::size::value - 1)>::template apply<typename current_row::next, current_value>::type new_equation;
        typedef typename divide_equation<(IdentityBegin::item::size::value)>::template apply<typename IdentityBegin::item, current_value>::type transformed_identity_equation;

        // results
        // Note that we don't add the pivot row to the
        // results here, because it needs to propagated up
        // to the diagonal.
        typedef dimensionless_type identity_result;
        typedef dimensionless_type new_matrix;
        typedef new_equation pivot_row;
        typedef transformed_identity_equation identity_pivot_row;
    };
};

// One of the initial zeroes
template<>
struct invert_strip_leading_zeroes<true, false> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename RowsBegin::item current_row;
        typedef typename RowsBegin::next::item next_row;
        typedef typename invert_strip_leading_zeroes<
            next_row::item::Numerator == 0,
            RowsBegin::size::value == 2
        >::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next
        > next;
        typedef typename IdentityBegin::item current_identity_row;
        // these are propagated up.
        typedef typename next::pivot_row pivot_row;
        typedef typename next::identity_pivot_row identity_pivot_row;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_row::size::value - 1)>::template apply<
                typename current_row::next,
                pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::new_matrix
        > new_matrix;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_identity_row::size::value)>::template apply<
                current_identity_row,
                identity_pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::identity_result
        > identity_result;
    };
};

// the last element, and is zero.
// Should never happen.
template<>
struct invert_strip_leading_zeroes<true, true> {
};

template<int N>
struct invert_handle_after_pivot_row {
    template<class RowsBegin, class IdentityBegin, class MatrixPivot, class IdentityPivot>
    struct apply {
        typedef typename invert_handle_after_pivot_row<N - 1>::template apply<
            typename RowsBegin::next,
            typename IdentityBegin::next,
            MatrixPivot,
            IdentityPivot
        > next;
        typedef typename RowsBegin::item current_row;
        typedef typename IdentityBegin::item current_identity_row;
        typedef MatrixPivot pivot_row;
        typedef IdentityPivot identity_pivot_row;

        // results
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_row::size::value - 1)>::template apply<
                typename current_row::next,
                pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::new_matrix
        > new_matrix;
        typedef list<
            typename eliminate_from_pair_of_equations_impl<(current_identity_row::size::value)>::template apply<
                current_identity_row,
                identity_pivot_row,
                typename current_row::item,
                static_rational<1>
            >::type,
            typename next::identity_result
        > identity_result;
    };
};

template<>
struct invert_handle_after_pivot_row<0> {
    template<class RowsBegin, class IdentityBegin, class MatrixPivot, class IdentityPivot>
    struct apply {
        typedef dimensionless_type new_matrix;
        typedef dimensionless_type identity_result;
    };
};

template<int N>
struct invert_impl {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef typename invert_handle_inital_rows<RowsBegin::size::value - N>::template apply<RowsBegin, IdentityBegin> process_column;
        typedef typename invert_impl<N - 1>::template apply<
            typename process_column::new_matrix,
            typename process_column::identity_result
        >::type type;
    };
};

template<>
struct invert_impl<0> {
    template<class RowsBegin, class IdentityBegin>
    struct apply {
        typedef IdentityBegin type;
    };
};

template<int N>
struct make_identity {
    template<int Size>
    struct apply {
        typedef list<typename create_row_of_identity<Size - N, Size>::type, typename make_identity<N - 1>::template apply<Size>::type> type;
    };
};

template<>
struct make_identity<0> {
    template<int Size>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<class Matrix>
struct make_square_and_invert {
    typedef typename Matrix::item top_row;
    typedef typename determine_extra_equations<(top_row::size::value), false>::template apply<
        Matrix,                 // RowsBegin
        top_row::size::value,   // TotalColumns
        Matrix                  // Result
    >::type invertible;
    typedef typename invert_impl<invertible::size::value>::template apply<
        invertible,
        typename make_identity<invertible::size::value>::template apply<invertible::size::value>::type
    >::type type;
};


// find_base_dimensions takes a list of
// base_units and returns a sorted list
// of all the base_dimensions they use.
//
// list<base_dimension> find_base_dimensions(list<base_unit> l) {
//     set<base_dimension> dimensions;
//     for_each(base_unit unit : l) {
//         for_each(dim d : unit.dimension_type) {
//             dimensions = insert(dimensions, d.tag_type);
//         }
//     }
//     return(sort(dimensions, _1 > _2, front_inserter(list<base_dimension>())));
// }

typedef char set_no;
struct set_yes { set_no dummy[2]; };

template<class T>
struct wrap {};

struct set_end {
    static set_no lookup(...);
    typedef mpl::long_<0> size;
};

template<class T, class Next>
struct set : Next {
    using Next::lookup;
    static set_yes lookup(wrap<T>*);
    typedef T item;
    typedef Next next;
    typedef typename mpl::next<typename Next::size>::type size;
};

template<bool has_key>
struct set_insert;

template<>
struct set_insert<true> {
    template<class Set, class T>
    struct apply {
        typedef Set type;
    };
};

template<>
struct set_insert<false> {
    template<class Set, class T>
    struct apply {
        typedef set<T, Set> type;
    };
};

template<class Set, class T>
struct has_key {
    BOOST_STATIC_CONSTEXPR long size = sizeof(Set::lookup((wrap<T>*)0));
    BOOST_STATIC_CONSTEXPR bool value = (size == sizeof(set_yes));
};

template<int N>
struct find_base_dimensions_impl_impl {
    template<class Begin, class S>
    struct apply {
        typedef typename find_base_dimensions_impl_impl<N-1>::template apply<
            typename Begin::next,
            S
        >::type next;

        typedef typename set_insert<
            (has_key<next, typename Begin::item::tag_type>::value)
        >::template apply<
            next,
            typename Begin::item::tag_type
        >::type type;
    };
};

template<>
struct find_base_dimensions_impl_impl<0> {
    template<class Begin, class S>
    struct apply {
        typedef S type;
    };
};

template<int N>
struct find_base_dimensions_impl {
    template<class Begin>
    struct apply {
        typedef typename find_base_dimensions_impl_impl<(Begin::item::dimension_type::size::value)>::template apply<
            typename Begin::item::dimension_type,
            typename find_base_dimensions_impl<N-1>::template apply<typename Begin::next>::type
        >::type type;
    };
};

template<>
struct find_base_dimensions_impl<0> {
    template<class Begin>
    struct apply {
        typedef set_end type;
    };
};

template<class T>
struct find_base_dimensions {
    typedef typename insertion_sort<
        typename find_base_dimensions_impl<
            (T::size::value)
        >::template apply<T>::type
    >::type type;
};

// calculate_base_dimension_coefficients finds
// the coefficients corresponding to the first
// base_dimension in each of the dimension_lists.
// It returns two values.  The first result
// is a list of the coefficients.  The second
// is a list with all the incremented iterators.
// When we encounter a base_dimension that is
// missing from a dimension_list, we do not
// increment the iterator and we set the
// coefficient to zero.

template<bool has_dimension>
struct calculate_base_dimension_coefficients_func;

template<>
struct calculate_base_dimension_coefficients_func<true> {
    template<class T>
    struct apply {
        typedef typename T::item::value_type type;
        typedef typename T::next next;
    };
};

template<>
struct calculate_base_dimension_coefficients_func<false> {
    template<class T>
    struct apply {
        typedef static_rational<0> type;
        typedef T next;
    };
};

// begins_with_dimension returns true iff its first
// parameter is a valid iterator which yields its
// second parameter when dereferenced.

template<class Iterator>
struct begins_with_dimension {
    template<class Dim>
    struct apply : 
        boost::is_same<
            Dim,
            typename Iterator::item::tag_type
        > {};
};

template<>
struct begins_with_dimension<dimensionless_type> {
    template<class Dim>
    struct apply : mpl::false_ {};
};

template<int N>
struct calculate_base_dimension_coefficients_impl {
    template<class BaseUnitDimensions,class Dim,class T>
    struct apply {
        typedef typename calculate_base_dimension_coefficients_func<
            begins_with_dimension<typename BaseUnitDimensions::item>::template apply<
                Dim
            >::value
        >::template apply<
            typename BaseUnitDimensions::item
        > result;
        typedef typename calculate_base_dimension_coefficients_impl<N-1>::template apply<
            typename BaseUnitDimensions::next,
            Dim,
            list<typename result::type, T>
        > next_;
        typedef typename next_::type type;
        typedef list<typename result::next, typename next_::next> next;
    };
};

template<>
struct calculate_base_dimension_coefficients_impl<0> {
    template<class Begin, class BaseUnitDimensions, class T>
    struct apply {
        typedef T type;
        typedef dimensionless_type next;
    };
};

// add_zeroes pushs N zeroes onto the
// front of a list.
//
// list<rational> add_zeroes(list<rational> l, int N) {
//     if(N == 0) {
//         return(l);
//     } else {
//         return(push_front(add_zeroes(l, N-1), 0));
//     }
// }

template<int N>
struct add_zeroes_impl {
    // If you get an error here and your base units are
    // in fact linearly independent, please report it.
    BOOST_MPL_ASSERT_MSG((N > 0), base_units_are_probably_not_linearly_independent, (void));
    template<class T>
    struct apply {
        typedef list<
            static_rational<0>,
            typename add_zeroes_impl<N-1>::template apply<T>::type
        > type;
    };
};

template<>
struct add_zeroes_impl<0> {
    template<class T>
    struct apply {
        typedef T type;
    };
};

// expand_dimensions finds the exponents of
// a set of dimensions in a dimension_list.
// the second parameter is assumed to be
// a superset of the base_dimensions of
// the first parameter.
//
// list<rational> expand_dimensions(dimension_list, list<base_dimension>);

template<int N>
struct expand_dimensions {
    template<class Begin, class DimensionIterator>
    struct apply {
        typedef typename calculate_base_dimension_coefficients_func<
            begins_with_dimension<DimensionIterator>::template apply<typename Begin::item>::value
        >::template apply<DimensionIterator> result;
        typedef list<
            typename result::type,
            typename expand_dimensions<N-1>::template apply<typename Begin::next, typename result::next>::type
        > type;
    };
};

template<>
struct expand_dimensions<0> {
    template<class Begin, class DimensionIterator>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<int N>
struct create_unit_matrix {
    template<class Begin, class Dimensions>
    struct apply {
        typedef typename create_unit_matrix<N - 1>::template apply<typename Begin::next, Dimensions>::type next;
        typedef list<typename expand_dimensions<Dimensions::size::value>::template apply<Dimensions, typename Begin::item::dimension_type>::type, next> type;
    };
};

template<>
struct create_unit_matrix<0> {
    template<class Begin, class Dimensions>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<class T>
struct normalize_units {
    typedef typename find_base_dimensions<T>::type dimensions;
    typedef typename create_unit_matrix<(T::size::value)>::template apply<
        T,
        dimensions
    >::type matrix;
    typedef typename make_square_and_invert<matrix>::type type;
    BOOST_STATIC_CONSTEXPR long extra = (type::size::value) - (T::size::value);
};

// multiply_add_units computes M x V
// where M is a matrix and V is a horizontal
// vector
//
// list<rational> multiply_add_units(list<list<rational> >, list<rational>);

template<int N>
struct multiply_add_units_impl {
    template<class Begin1, class Begin2 ,class X>
    struct apply {
        typedef list<
            typename mpl::plus<
                typename mpl::times<
                    typename Begin2::item,
                    X
                >::type,
                typename Begin1::item
            >::type,
            typename multiply_add_units_impl<N-1>::template apply<
                typename Begin1::next,
                typename Begin2::next,
                X
            >::type
        > type;
    };
};

template<>
struct multiply_add_units_impl<0> {
    template<class Begin1, class Begin2 ,class X>
    struct apply {
        typedef dimensionless_type type;
    };
};

template<int N>
struct multiply_add_units {
    template<class Begin1, class Begin2>
    struct apply {
        typedef typename multiply_add_units_impl<
            (Begin2::item::size::value)
        >::template apply<
            typename multiply_add_units<N-1>::template apply<
                typename Begin1::next,
                typename Begin2::next
            >::type,
            typename Begin2::item,
            typename Begin1::item
        >::type type;
    };
};

template<>
struct multiply_add_units<1> {
    template<class Begin1, class Begin2>
    struct apply {
        typedef typename add_zeroes_impl<
            (Begin2::item::size::value)
        >::template apply<dimensionless_type>::type type1;
        typedef typename multiply_add_units_impl<
            (Begin2::item::size::value)
        >::template apply<
            type1,
            typename Begin2::item,
            typename Begin1::item
        >::type type;
    };
};


// strip_zeroes erases the first N elements of a list if
// they are all zero, otherwise returns inconsistent
//
// list strip_zeroes(list l, int N) {
//     if(N == 0) {
//         return(l);
//     } else if(l.front == 0) {
//         return(strip_zeroes(pop_front(l), N-1));
//     } else {
//         return(inconsistent);
//     }
// }

template<int N>
struct strip_zeroes_impl;

template<class T>
struct strip_zeroes_func {
    template<class L, int N>
    struct apply {
        typedef inconsistent type;
    };
};

template<>
struct strip_zeroes_func<static_rational<0> > {
    template<class L, int N>
    struct apply {
        typedef typename strip_zeroes_impl<N-1>::template apply<typename L::next>::type type;
    };
};

template<int N>
struct strip_zeroes_impl {
    template<class T>
    struct apply {
        typedef typename strip_zeroes_func<typename T::item>::template apply<T, N>::type type;
    };
};

template<>
struct strip_zeroes_impl<0> {
    template<class T>
    struct apply {
        typedef T type;
    };
};

// Given a list of base_units, computes the
// exponents of each base unit for a given
// dimension.
//
// list<rational> calculate_base_unit_exponents(list<base_unit> units, dimension_list dimensions);

template<class T>
struct is_base_dimension_unit {
    typedef mpl::false_ type;
    typedef void base_dimension_type;
};
template<class T>
struct is_base_dimension_unit<list<dim<T, static_rational<1> >, dimensionless_type> > {
    typedef mpl::true_ type;
    typedef T base_dimension_type;
};

template<int N>
struct is_simple_system_impl {
    template<class Begin, class Prev>
    struct apply {
        typedef is_base_dimension_unit<typename Begin::item::dimension_type> test;
        typedef mpl::and_<
            typename test::type,
            mpl::less<Prev, typename test::base_dimension_type>,
            typename is_simple_system_impl<N-1>::template apply<
                typename Begin::next,
                typename test::base_dimension_type
            >
        > type;
        BOOST_STATIC_CONSTEXPR bool value = (type::value);
    };
};

template<>
struct is_simple_system_impl<0> {
    template<class Begin, class Prev>
    struct apply : mpl::true_ {
    };
};

template<class T>
struct is_simple_system {
    typedef T Begin;
    typedef is_base_dimension_unit<typename Begin::item::dimension_type> test;
    typedef typename mpl::and_<
        typename test::type,
        typename is_simple_system_impl<
            T::size::value - 1
        >::template apply<
            typename Begin::next::type,
            typename test::base_dimension_type
        >
    >::type type;
    BOOST_STATIC_CONSTEXPR bool value = type::value;
};

template<bool>
struct calculate_base_unit_exponents_impl;

template<>
struct calculate_base_unit_exponents_impl<true> {
    template<class T, class Dimensions>
    struct apply {
        typedef typename expand_dimensions<(T::size::value)>::template apply<
            typename find_base_dimensions<T>::type,
            Dimensions
        >::type type;
    };
};

template<>
struct calculate_base_unit_exponents_impl<false> {
    template<class T, class Dimensions>
    struct apply {
        // find the units that correspond to each base dimension
        typedef normalize_units<T> base_solutions;
        // pad the dimension with zeroes so it can just be a
        // list of numbers, making the multiplication easy
        // e.g. if the arguments are list<pound, foot> and
        // list<mass,time^-2> then this step will
        // yield list<0,1,-2>
        typedef typename expand_dimensions<(base_solutions::dimensions::size::value)>::template apply<
            typename base_solutions::dimensions,
            Dimensions
        >::type dimensions;
        // take the unit corresponding to each base unit
        // multiply each of its exponents by the exponent
        // of the base_dimension in the result and sum.
        typedef typename multiply_add_units<dimensions::size::value>::template apply<
            dimensions,
            typename base_solutions::type
        >::type units;
        // Now, verify that the dummy units really
        // cancel out and remove them.
        typedef typename strip_zeroes_impl<base_solutions::extra>::template apply<units>::type type;
    };
};

template<class T, class Dimensions>
struct calculate_base_unit_exponents {
    typedef typename calculate_base_unit_exponents_impl<is_simple_system<T>::value>::template apply<T, Dimensions>::type type;
};

} // namespace detail

} // namespace units

} // namespace boost

#endif