matrix.h 59.9 KB
Newer Older
1
2
3
4
5
// Copyright (C) 2006  Davis E. King (davisking@users.sourceforge.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_MATRIx_
#define DLIB_MATRIx_

6
#include "matrix_fwd.h"
7
8
9
10
11
12
13
#include "matrix_abstract.h"
#include "../algs.h"
#include "../serialize.h"
#include "../enable_if.h"
#include <sstream>
#include <algorithm>
#include "../memory_manager.h"
14
#include "../is_kind.h"
15
#include "matrix_data_layout.h"
16
#include "matrix_assign_fwd.h"
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#ifdef _MSC_VER
// Disable the following warnings for Visual Studio

// This warning is:
//    "warning C4355: 'this' : used in base member initializer list"
// Which we get from this code but it is not an error so I'm turning this
// warning off and then turning it back on at the end of the file.
#pragma warning(disable : 4355)

#endif

namespace dlib
{

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    // We want to return the compile time constant if our NR and NC dimensions
    // aren't zero but if they are then we want to call ref_.nx() and return
    // the correct values. 
39
    template < typename exp_type, long NR >
40
41
    struct get_nr_helper
    {
42
        static inline long get(const exp_type&) { return NR; }
43
44
    };

45
46
    template < typename exp_type >
    struct get_nr_helper<exp_type,0>
47
    {
48
        static inline long get(const exp_type& m) { return m.nr(); }
49
50
    };

51
    template < typename exp_type, long NC >
52
53
    struct get_nc_helper
    {
54
        static inline long get(const exp_type&) { return NC; }
55
56
    };

57
58
    template < typename exp_type >
    struct get_nc_helper<exp_type,0>
59
    {
60
        static inline long get(const exp_type& m) { return m.nc(); }
61
62
    };

63
64
65
66
67
    template <typename EXP>
    struct matrix_traits
    {
        typedef typename EXP::type type;
        typedef typename EXP::mem_manager_type mem_manager_type;
68
        typedef typename EXP::layout_type layout_type;
69
70
71
72
        const static long NR = EXP::NR;
        const static long NC = EXP::NC;
        const static long cost = EXP::cost;
    };
73
74
75
76

    template <
        typename EXP
        >
77
    class matrix_exp 
78
    {
79
80
81
82
83
84
        /*!
            REQUIREMENTS ON EXP
                EXP should be something convertible to a matrix_exp.  That is,
                it should inherit from matrix_exp
        !*/

85
    public:
86
87
        typedef typename matrix_traits<EXP>::type type;
        typedef typename matrix_traits<EXP>::mem_manager_type mem_manager_type;
88
        typedef typename matrix_traits<EXP>::layout_type layout_type;
89
90
91
        const static long NR = matrix_traits<EXP>::NR;
        const static long NC = matrix_traits<EXP>::NC;
        const static long cost = matrix_traits<EXP>::cost;
92

93
        typedef matrix<type,NR,NC,mem_manager_type,layout_type> matrix_type;
94
        typedef EXP exp_type;
95
96
97
98
99
100

        inline const type operator() (
            long r,
            long c
        ) const 
        { 
101
            DLIB_ASSERT(r < nr() && c < nc() && r >= 0 && c >= 0, 
102
103
104
105
106
107
108
109
                "\tconst type matrix_exp::operator(r,c)"
                << "\n\tYou must give a valid row and column"
                << "\n\tr:    " << r 
                << "\n\tc:    " << c
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc() 
                << "\n\tthis: " << this
                );
110
            return ref()(r,c); 
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
        }

        const type operator() (
            long i
        ) const 
        {
            COMPILE_TIME_ASSERT(NC == 1 || NC == 0 || NR == 1 || NR == 0);
            DLIB_ASSERT(nc() == 1 || nr() == 1, 
                "\tconst type matrix_exp::operator(i)"
                << "\n\tYou can only use this operator on column or row vectors"
                << "\n\ti:    " << i
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc()
                << "\n\tthis: " << this
                );
            DLIB_ASSERT( ((nc() == 1 && i < nr()) || (nr() == 1 && i < nc())) && i >= 0, 
                "\tconst type matrix_exp::operator(i)"
                << "\n\tYou must give a valid row/column number"
                << "\n\ti:    " << i
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc()
                << "\n\tthis: " << this
                );
            if (nc() == 1)
135
                return ref()(i,0);
136
            else
137
                return ref()(0,i);
138
139
140
141
142
143
        }

        long size (
        ) const { return nr()*nc(); }

        long nr (
144
        ) const { return get_nr_helper<exp_type,NR>::get(ref()); }
145
146

        long nc (
147
        ) const { return get_nc_helper<exp_type,NC>::get(ref()); }
148

149
        template <typename U, long iNR, long iNC, typename mm, typename l >
150
        bool aliases (
151
            const matrix<U,iNR,iNC,mm,l>& item
152
        ) const { return ref().aliases(item); }
153

154
        template <typename U, long iNR, long iNC , typename mm, typename l>
155
        bool destructively_aliases (
156
            const matrix<U,iNR,iNC,mm,l>& item
157
        ) const { return ref().destructively_aliases(item); }
158

159
160
        inline const exp_type& ref (
        ) const { return *static_cast<const exp_type*>(this); }
161
162
163
164
165
166
167
168
169
170
171
172
173

        inline operator const type (
        ) const 
        {
            COMPILE_TIME_ASSERT(NC == 1 || NC == 0);
            COMPILE_TIME_ASSERT(NR == 1 || NR == 0);
            DLIB_ASSERT(nr() == 1 && nc() == 1, 
                "\tmatrix_exp::operator const type&() const"
                << "\n\tYou can only use this operator on a 1x1 matrix"
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc()
                << "\n\tthis: " << this
                );
174
175
176
177
178

            // Put the expression contained in this matrix_exp into
            // a temporary 1x1 matrix so that the expression will encounter
            // all the overloads of matrix_assign() and have the chance to
            // go through any applicable optimizations.
179
            matrix<type,1,1> temp(ref());
180
            return temp(0);
181
182
        }

183
    protected:
184
185
        matrix_exp() {}
        matrix_exp(const matrix_exp& ) {}
186
187
188

    private:

189
        matrix_exp& operator= (const matrix_exp&);
190
191
    };

192
193
// ----------------------------------------------------------------------------------------

194
// something is a matrix if it is convertible to a matrix_exp object
195
    template <typename T>
196
197
    struct is_matrix<T, typename enable_if<is_convertible<T, const matrix_exp<typename T::exp_type>& > >::type > 
    { static const bool value = true; }; 
198
199
200
201
    /*
        is_matrix<T>::value == 1 if T is a matrix type else 0
    */

202
// ----------------------------------------------------------------------------------------
203
204
205
206
207
208
209
210
211
212
213
214

    // This template will perform the needed loop for element multiplication using whichever
    // dimension is provided as a compile time constant (if one is at all).
    template <
        typename LHS,
        typename RHS,
        long lhs_nc = LHS::NC,
        long rhs_nr = RHS::NR
        >
    struct matrix_multiply_helper 
    {
        typedef typename LHS::type type;
215
        template <typename RHS_, typename LHS_>
216
        inline const static type  eval (
217
218
            const RHS_& rhs,
            const LHS_& lhs,
219
220
            const long r, 
            const long c
221
222
        )  
        { 
223
224
            type temp = lhs(r,0)*rhs(0,c);
            for (long i = 1; i < rhs.nr(); ++i)
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
            {
                temp += lhs(r,i)*rhs(i,c);
            }
            return temp;
        }
    };

    template <
        typename LHS,
        typename RHS,
        long lhs_nc 
        >
    struct matrix_multiply_helper <LHS,RHS,lhs_nc,0>
    {
        typedef typename LHS::type type;
240
        template <typename RHS_, typename LHS_>
241
        inline const static type  eval (
242
243
            const RHS_& rhs,
            const LHS_& lhs,
244
245
            const long r, 
            const long c
246
247
        )  
        { 
248
249
            type temp = lhs(r,0)*rhs(0,c);
            for (long i = 1; i < lhs.nc(); ++i)
250
251
252
253
254
255
256
            {
                temp += lhs(r,i)*rhs(i,c);
            }
            return temp;
        }
    };

257
258
259
260
261
262
263
264
    template <typename LHS, typename RHS>
    class matrix_multiply_exp;

    template <typename LHS, typename RHS>
    struct matrix_traits<matrix_multiply_exp<LHS,RHS> >
    {
        typedef typename LHS::type type;
        typedef typename LHS::mem_manager_type mem_manager_type;
265
        typedef typename LHS::layout_type layout_type;
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        const static long NR = LHS::NR;
        const static long NC = RHS::NC;

        const static bool lhs_is_costly = (LHS::cost > 4)&&(RHS::NC != 1);
        const static bool rhs_is_costly = (RHS::cost > 4)&&(LHS::NR != 1);

        // Note that if we decide that one of the matrices is too costly we will evaluate it
        // into a temporary.  Doing this resets its cost back to 1.
        const static long lhs_cost = ((lhs_is_costly==true)? 1 : (LHS::cost));
        const static long rhs_cost = ((rhs_is_costly==true)? 1 : (RHS::cost));

        // The cost of evaluating an element of a matrix multiply is the cost of evaluating elements from
        // RHS and LHS times the number of rows/columns in the RHS/LHS matrix.  If we don't know the matrix
        // dimensions then just assume it is really large.
        const static long cost = (lhs_cost+rhs_cost)*
                                 ((tmax<LHS::NC,RHS::NR>::value!=0)? (tmax<LHS::NC,RHS::NR>::value):(10000));
    };

    template <typename T, bool is_ref> struct conditional_matrix_temp { typedef typename T::matrix_type type; };
    template <typename T> struct conditional_matrix_temp<T,true>      { typedef T& type; };

287
288
    template <
        typename LHS,
289
        typename RHS
290
        >
291
    class matrix_multiply_exp : public matrix_exp<matrix_multiply_exp<LHS,RHS> >
292
293
294
    {
        /*!
            REQUIREMENTS ON LHS AND RHS
295
                - must be matrix_exp objects.
296
297
298
        !*/
    public:

299
300
301
302
303
        typedef typename matrix_traits<matrix_multiply_exp>::type type;
        typedef typename matrix_traits<matrix_multiply_exp>::mem_manager_type mem_manager_type;
        const static long NR = matrix_traits<matrix_multiply_exp>::NR;
        const static long NC = matrix_traits<matrix_multiply_exp>::NC;
        const static long cost = matrix_traits<matrix_multiply_exp>::cost;
304
        typedef typename matrix_traits<matrix_multiply_exp>::layout_type layout_type;
305
306
307
308


        const static bool lhs_is_costly = matrix_traits<matrix_multiply_exp>::lhs_is_costly;
        const static bool rhs_is_costly = matrix_traits<matrix_multiply_exp>::rhs_is_costly;
309
310
        const static bool either_is_costly = lhs_is_costly || rhs_is_costly;
        const static bool both_are_costly = lhs_is_costly && rhs_is_costly;
311
312
313
314

        typedef typename conditional_matrix_temp<const LHS,lhs_is_costly == false>::type LHS_ref_type;
        typedef typename conditional_matrix_temp<const RHS,rhs_is_costly == false>::type RHS_ref_type;

315
316
317
318
        // This constructor exists simply for the purpose of causing a compile time error if
        // someone tries to create an instance of this object with the wrong kind of objects.
        template <typename T1, typename T2>
        matrix_multiply_exp (T1,T2); 
319
320
321
322
323
324
325
326
327
328
329

        inline matrix_multiply_exp (
            const LHS& lhs_,
            const RHS& rhs_
        ) :
            lhs(lhs_),
            rhs(rhs_)
        {
            // You are trying to multiply two incompatible matrices together.  The number of columns 
            // in the matrix on the left must match the number of rows in the matrix on the right.
            COMPILE_TIME_ASSERT(LHS::NC == RHS::NR || LHS::NC*RHS::NR == 0);
330
            DLIB_ASSERT(lhs.nc() == rhs.nr() && lhs.size() > 0 && rhs.size() > 0, 
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
                "\tconst matrix_exp operator*(const matrix_exp& lhs, const matrix_exp& rhs)"
                << "\n\tYou are trying to multiply two incompatible matrices together"
                << "\n\tlhs.nr(): " << lhs.nr()
                << "\n\tlhs.nc(): " << lhs.nc()
                << "\n\trhs.nr(): " << rhs.nr()
                << "\n\trhs.nc(): " << rhs.nc()
                << "\n\t&lhs: " << &lhs 
                << "\n\t&rhs: " << &rhs 
                );

            // You can't multiply matrices together if they don't both contain the same type of elements.
            COMPILE_TIME_ASSERT((is_same_type<typename LHS::type, typename RHS::type>::value == true));
        }

        inline const type operator() (
346
347
            const long r, 
            const long c
348
349
350
351
352
        ) const 
        { 
            return matrix_multiply_helper<LHS,RHS>::eval(rhs,lhs,r,c);
        }

353
354
355
        inline const type operator() ( long i ) const 
        { return matrix_exp<matrix_multiply_exp>::operator()(i); }

356
357
358
359
360
361
        long nr (
        ) const { return lhs.nr(); }

        long nc (
        ) const { return rhs.nc(); }

362
        template <typename U, long iNR, long iNC, typename mm, typename l >
363
        bool aliases (
364
            const matrix<U,iNR,iNC,mm,l>& item
365
366
        ) const { return lhs.aliases(item) || rhs.aliases(item); }

367
        template <typename U, long iNR, long iNC , typename mm, typename l>
368
        bool destructively_aliases (
369
            const matrix<U,iNR,iNC,mm,l>& item
370
371
        ) const { return aliases(item); }

372
373
        LHS_ref_type lhs;
        RHS_ref_type rhs;
374
375
    };

376
377
    template < typename EXP1, typename EXP2 >
    inline const matrix_multiply_exp<EXP1, EXP2> operator* (
378
379
380
381
        const matrix_exp<EXP1>& m1,
        const matrix_exp<EXP2>& m2
    )
    {
382
        return matrix_multiply_exp<EXP1, EXP2>(m1.ref(), m2.ref());
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
    template <typename M, bool use_reference = true>
    class matrix_mul_scal_exp;

    // -------------------------

    // Now we declare some overloads that cause any scalar multiplications to percolate 
    // up and outside of any matrix multiplies.  Note that we are using the non-reference containing
    // mode of the matrix_mul_scal_exp object since we are passing in locally constructed matrix_multiply_exp 
    // objects.  So the matrix_mul_scal_exp object will contain copies of matrix_multiply_exp objects
    // rather than references to them.  This could result in extra matrix copies if the matrix_multiply_exp
    // decided it should evaluate any of its arguments.  So we also try to not apply this percolating operation 
    // if the matrix_multiply_exp would contain a fully evaluated copy of the original matrix_mul_scal_exp 
    // expression.
    // 
    // Also, the reason we want to apply this transformation in the first place is because it (1) makes
    // the expressions going into matrix multiply expressions simpler and (2) it makes it a lot more
    // straight forward to bind BLAS calls to matrix expressions involving scalar multiplies.
    template < typename EXP1, typename EXP2 >
    inline const typename disable_if_c< matrix_multiply_exp<matrix_mul_scal_exp<EXP1>, matrix_mul_scal_exp<EXP2> >::both_are_costly ,      
                                        matrix_mul_scal_exp<matrix_multiply_exp<EXP1, EXP2>,false> >::type operator* (
        const matrix_mul_scal_exp<EXP1>& m1,
        const matrix_mul_scal_exp<EXP2>& m2
    )
    {
        typedef matrix_multiply_exp<EXP1, EXP2> exp1;
        typedef matrix_mul_scal_exp<exp1,false> exp2;
        return exp2(exp1(m1.m, m2.m), m1.s*m2.s);
    }

    template < typename EXP1, typename EXP2 >
    inline const typename disable_if_c< matrix_multiply_exp<matrix_mul_scal_exp<EXP1>, EXP2 >::lhs_is_costly ,      
                                      matrix_mul_scal_exp<matrix_multiply_exp<EXP1, EXP2>,false> >::type operator* (
        const matrix_mul_scal_exp<EXP1>& m1,
        const matrix_exp<EXP2>& m2
    )
    {
        typedef matrix_multiply_exp<EXP1, EXP2> exp1;
        typedef matrix_mul_scal_exp<exp1,false> exp2;
        return exp2(exp1(m1.m, m2.ref()), m1.s);
    }

    template < typename EXP1, typename EXP2 >
    inline const typename disable_if_c< matrix_multiply_exp<EXP1, matrix_mul_scal_exp<EXP2> >::rhs_is_costly ,      
                                      matrix_mul_scal_exp<matrix_multiply_exp<EXP1, EXP2>,false> >::type operator* (
        const matrix_exp<EXP1>& m1,
        const matrix_mul_scal_exp<EXP2>& m2
    )
    {
        typedef matrix_multiply_exp<EXP1, EXP2> exp1;
        typedef matrix_mul_scal_exp<exp1,false> exp2;
        return exp2(exp1(m1.ref(), m2.m), m2.s);
    }

438
// ----------------------------------------------------------------------------------------
439

440
441
    template <typename LHS, typename RHS>
    class matrix_add_exp;
442

443
444
    template <typename LHS, typename RHS>
    struct matrix_traits<matrix_add_exp<LHS,RHS> >
445
    {
446
447
        typedef typename LHS::type type;
        typedef typename LHS::mem_manager_type mem_manager_type;
448
        typedef typename LHS::layout_type layout_type;
449
450
451
452
        const static long NR = (RHS::NR > LHS::NR) ? RHS::NR : LHS::NR;
        const static long NC = (RHS::NC > LHS::NC) ? RHS::NC : LHS::NC;
        const static long cost = LHS::cost+RHS::cost;
    };
453
454
455
456
457

    template <
        typename LHS,
        typename RHS
        >
458
    class matrix_add_exp : public matrix_exp<matrix_add_exp<LHS,RHS> >
459
460
461
    {
        /*!
            REQUIREMENTS ON LHS AND RHS
462
                - must be matrix_exp objects. 
463
464
        !*/
    public:
465
466
467
468
469
        typedef typename matrix_traits<matrix_add_exp>::type type;
        typedef typename matrix_traits<matrix_add_exp>::mem_manager_type mem_manager_type;
        const static long NR = matrix_traits<matrix_add_exp>::NR;
        const static long NC = matrix_traits<matrix_add_exp>::NC;
        const static long cost = matrix_traits<matrix_add_exp>::cost;
470
        typedef typename matrix_traits<matrix_add_exp>::layout_type layout_type;
471

472
473
474
475
        // This constructor exists simply for the purpose of causing a compile time error if
        // someone tries to create an instance of this object with the wrong kind of objects.
        template <typename T1, typename T2>
        matrix_add_exp (T1,T2); 
476
477

        matrix_add_exp (
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
            const LHS& lhs_,
            const RHS& rhs_
        ) :
            lhs(lhs_),
            rhs(rhs_)
        {
            // You can only add matrices together if they both have the same number of rows and columns.
            COMPILE_TIME_ASSERT(LHS::NR == RHS::NR || LHS::NR == 0 || RHS::NR == 0);
            COMPILE_TIME_ASSERT(LHS::NC == RHS::NC || LHS::NC == 0 || RHS::NC == 0);
            DLIB_ASSERT(lhs.nc() == rhs.nc() &&
                   lhs.nr() == rhs.nr(), 
                "\tconst matrix_exp operator+(const matrix_exp& lhs, const matrix_exp& rhs)"
                << "\n\tYou are trying to add two incompatible matrices together"
                << "\n\tlhs.nr(): " << lhs.nr()
                << "\n\tlhs.nc(): " << lhs.nc()
                << "\n\trhs.nr(): " << rhs.nr()
                << "\n\trhs.nc(): " << rhs.nc()
                << "\n\t&lhs: " << &lhs 
                << "\n\t&rhs: " << &rhs 
                );

            // You can only add matrices together if they both contain the same types of elements.
            COMPILE_TIME_ASSERT((is_same_type<typename LHS::type, typename RHS::type>::value == true));
        }

        const type operator() (
            long r, 
            long c
        ) const { return lhs(r,c) + rhs(r,c); }

508
509
510
        inline const type operator() ( long i ) const 
        { return matrix_exp<matrix_add_exp>::operator()(i); }

511
        template <typename U, long iNR, long iNC , typename mm, typename l>
512
        bool aliases (
513
            const matrix<U,iNR,iNC,mm,l>& item
514
515
        ) const { return lhs.aliases(item) || rhs.aliases(item); }

516
        template <typename U, long iNR, long iNC, typename mm, typename l >
517
        bool destructively_aliases (
518
            const matrix<U,iNR,iNC,mm,l>& item
519
520
521
522
523
524
525
526
        ) const { return lhs.destructively_aliases(item) || rhs.destructively_aliases(item); }

        long nr (
        ) const { return lhs.nr(); }

        long nc (
        ) const { return lhs.nc(); }

527
528
        const LHS& lhs;
        const RHS& rhs;
529
530
531
532
533
534
    };

    template <
        typename EXP1,
        typename EXP2
        >
535
    inline const matrix_add_exp<EXP1, EXP2> operator+ (
536
537
538
539
        const matrix_exp<EXP1>& m1,
        const matrix_exp<EXP2>& m2
    )
    {
540
        return matrix_add_exp<EXP1, EXP2>(m1.ref(),m2.ref());
541
542
543
544
    }

// ----------------------------------------------------------------------------------------

545
546
547
548
549
550
551
552
    template <typename LHS, typename RHS>
    class matrix_subtract_exp;

    template <typename LHS, typename RHS>
    struct matrix_traits<matrix_subtract_exp<LHS,RHS> >
    {
        typedef typename LHS::type type;
        typedef typename LHS::mem_manager_type mem_manager_type;
553
        typedef typename LHS::layout_type layout_type;
554
555
556
557
558
        const static long NR = (RHS::NR > LHS::NR) ? RHS::NR : LHS::NR;
        const static long NC = (RHS::NC > LHS::NC) ? RHS::NC : LHS::NC;
        const static long cost = LHS::cost+RHS::cost;
    };

559
560
561
562
    template <
        typename LHS,
        typename RHS
        >
563
    class matrix_subtract_exp : public matrix_exp<matrix_subtract_exp<LHS,RHS> >
564
565
566
    {
        /*!
            REQUIREMENTS ON LHS AND RHS
567
                - must be matrix_exp objects. 
568
569
        !*/
    public:
570
571
572
573
574
        typedef typename matrix_traits<matrix_subtract_exp>::type type;
        typedef typename matrix_traits<matrix_subtract_exp>::mem_manager_type mem_manager_type;
        const static long NR = matrix_traits<matrix_subtract_exp>::NR;
        const static long NC = matrix_traits<matrix_subtract_exp>::NC;
        const static long cost = matrix_traits<matrix_subtract_exp>::cost;
575
        typedef typename matrix_traits<matrix_subtract_exp>::layout_type layout_type;
576

577
578
579
580
581

        // This constructor exists simply for the purpose of causing a compile time error if
        // someone tries to create an instance of this object with the wrong kind of objects.
        template <typename T1, typename T2>
        matrix_subtract_exp (T1,T2); 
582
583
584
585

        matrix_subtract_exp (
            const LHS& lhs_,
            const RHS& rhs_
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
            lhs(lhs_),
            rhs(rhs_)
        {
            // You can only subtract one matrix from another if they both have the same number of rows and columns.
            COMPILE_TIME_ASSERT(LHS::NR == RHS::NR || LHS::NR == 0 || RHS::NR == 0);
            COMPILE_TIME_ASSERT(LHS::NC == RHS::NC || LHS::NC == 0 || RHS::NC == 0);
            DLIB_ASSERT(lhs.nc() == rhs.nc() &&
                   lhs.nr() == rhs.nr(), 
                "\tconst matrix_exp operator-(const matrix_exp& lhs, const matrix_exp& rhs)"
                << "\n\tYou are trying to add two incompatible matrices together"
                << "\n\tlhs.nr(): " << lhs.nr()
                << "\n\tlhs.nc(): " << lhs.nc()
                << "\n\trhs.nr(): " << rhs.nr()
                << "\n\trhs.nc(): " << rhs.nc()
                << "\n\t&lhs: " << &lhs 
                << "\n\t&rhs: " << &rhs 
                );

            // You can only subtract one matrix from another if they both contain elements of the same type.
            COMPILE_TIME_ASSERT((is_same_type<typename LHS::type, typename RHS::type>::value == true));
        }

        const type operator() (
            long r, 
            long c
        ) const { return lhs(r,c) - rhs(r,c); }

614
615
616
        inline const type operator() ( long i ) const 
        { return matrix_exp<matrix_subtract_exp>::operator()(i); }

617
        template <typename U, long iNR, long iNC, typename mm, typename l >
618
        bool aliases (
619
            const matrix<U,iNR,iNC, mm,l>& item
620
621
        ) const { return lhs.aliases(item) || rhs.aliases(item); }

622
        template <typename U, long iNR, long iNC , typename mm, typename l>
623
        bool destructively_aliases (
624
            const matrix<U,iNR,iNC,mm,l>& item
625
626
627
628
629
630
631
632
        ) const { return lhs.destructively_aliases(item) || rhs.destructively_aliases(item); }

        long nr (
        ) const { return lhs.nr(); }

        long nc (
        ) const { return lhs.nc(); }

633
634
        const LHS& lhs;
        const RHS& rhs;
635
636
637
638
639
640
    };

    template <
        typename EXP1,
        typename EXP2
        >
641
    inline const matrix_subtract_exp<EXP1, EXP2> operator- (
642
643
644
645
        const matrix_exp<EXP1>& m1,
        const matrix_exp<EXP2>& m2
    )
    {
646
        return matrix_subtract_exp<EXP1, EXP2>(m1.ref(),m2.ref());
647
648
649
650
    }

// ----------------------------------------------------------------------------------------

Davis King's avatar
Davis King committed
651
    template <typename M>
652
653
    class matrix_div_scal_exp;

Davis King's avatar
Davis King committed
654
655
    template <typename M>
    struct matrix_traits<matrix_div_scal_exp<M> >
656
657
658
    {
        typedef typename M::type type;
        typedef typename M::mem_manager_type mem_manager_type;
659
        typedef typename M::layout_type layout_type;
660
661
662
663
664
        const static long NR = M::NR;
        const static long NC = M::NC;
        const static long cost = M::cost+1;
    };

665
    template <
Davis King's avatar
Davis King committed
666
        typename M
667
        >
Davis King's avatar
Davis King committed
668
    class matrix_div_scal_exp : public matrix_exp<matrix_div_scal_exp<M> >
669
670
671
    {
        /*!
            REQUIREMENTS ON M 
672
                - must be a matrix_exp object.
673
674
        !*/
    public:
675
676
677
678
679
        typedef typename matrix_traits<matrix_div_scal_exp>::type type;
        typedef typename matrix_traits<matrix_div_scal_exp>::mem_manager_type mem_manager_type;
        const static long NR = matrix_traits<matrix_div_scal_exp>::NR;
        const static long NC = matrix_traits<matrix_div_scal_exp>::NC;
        const static long cost = matrix_traits<matrix_div_scal_exp>::cost;
680
        typedef typename matrix_traits<matrix_div_scal_exp>::layout_type layout_type;
681

682
683
684
685

        // This constructor exists simply for the purpose of causing a compile time error if
        // someone tries to create an instance of this object with the wrong kind of objects.
        template <typename T1>
Davis King's avatar
Davis King committed
686
        matrix_div_scal_exp (T1, const type&); 
687

688
        matrix_div_scal_exp (
689
            const M& m_,
Davis King's avatar
Davis King committed
690
            const type& s_
691
692
693
694
695
696
697
698
699
700
        ) :
            m(m_),
            s(s_)
        {}

        const type operator() (
            long r, 
            long c
        ) const { return m(r,c)/s; }

701
702
703
        inline const type operator() ( long i ) const 
        { return matrix_exp<matrix_div_scal_exp>::operator()(i); }

704
        template <typename U, long iNR, long iNC, typename mm , typename l>
705
        bool aliases (
706
            const matrix<U,iNR,iNC,mm,l>& item
707
708
        ) const { return m.aliases(item); }

709
        template <typename U, long iNR, long iNC, typename mm, typename l >
710
        bool destructively_aliases (
711
            const matrix<U,iNR,iNC,mm,l>& item
712
713
714
715
716
717
718
719
        ) const { return m.destructively_aliases(item); }

        long nr (
        ) const { return m.nr(); }

        long nc (
        ) const { return m.nc(); }

720
        const M& m;
Davis King's avatar
Davis King committed
721
        const type s;
722
723
724
725
    };

    template <
        typename EXP,
726
        typename S
727
        >
728
    inline const typename enable_if_c<std::numeric_limits<typename EXP::type>::is_integer, matrix_div_scal_exp<EXP> >::type operator/ (
729
730
731
732
        const matrix_exp<EXP>& m,
        const S& s
    )
    {
733
        return matrix_div_scal_exp<EXP>(m.ref(),static_cast<typename EXP::type>(s));
734
735
736
737
    }

// ----------------------------------------------------------------------------------------

738
739
    template <typename M, bool use_reference >
    struct matrix_traits<matrix_mul_scal_exp<M,use_reference> >
740
741
742
    {
        typedef typename M::type type;
        typedef typename M::mem_manager_type mem_manager_type;
743
        typedef typename M::layout_type layout_type;
744
745
746
747
748
        const static long NR = M::NR;
        const static long NC = M::NC;
        const static long cost = M::cost+1;
    };

749
750
751
752
    template <typename T, bool is_ref> struct conditional_reference { typedef T type; };
    template <typename T> struct conditional_reference<T,true>      { typedef T& type; };


753
    template <
754
755
        typename M,
        bool use_reference
756
        >
757
    class matrix_mul_scal_exp : public matrix_exp<matrix_mul_scal_exp<M,use_reference> >
758
759
760
    {
        /*!
            REQUIREMENTS ON M 
761
                - must be a matrix_exp object.
762
763
764

        !*/
    public:
765
766
767
768
769
        typedef typename matrix_traits<matrix_mul_scal_exp>::type type;
        typedef typename matrix_traits<matrix_mul_scal_exp>::mem_manager_type mem_manager_type;
        const static long NR = matrix_traits<matrix_mul_scal_exp>::NR;
        const static long NC = matrix_traits<matrix_mul_scal_exp>::NC;
        const static long cost = matrix_traits<matrix_mul_scal_exp>::cost;
770
        typedef typename matrix_traits<matrix_mul_scal_exp>::layout_type layout_type;
771

772
773
774
775

        // This constructor exists simply for the purpose of causing a compile time error if
        // someone tries to create an instance of this object with the wrong kind of objects.
        template <typename T1>
Davis King's avatar
Davis King committed
776
        matrix_mul_scal_exp (T1, const type&); 
777
778

        matrix_mul_scal_exp (
779
            const M& m_,
Davis King's avatar
Davis King committed
780
            const type& s_
781
782
783
784
785
786
787
788
789
790
        ) :
            m(m_),
            s(s_)
        {}

        const type operator() (
            long r, 
            long c
        ) const { return m(r,c)*s; }

791
792
793
        inline const type operator() ( long i ) const 
        { return matrix_exp<matrix_mul_scal_exp>::operator()(i); }

794
        template <typename U, long iNR, long iNC , typename mm, typename l>
795
        bool aliases (
796
            const matrix<U,iNR,iNC,mm,l>& item
797
798
        ) const { return m.aliases(item); }

799
        template <typename U, long iNR, long iNC, typename mm, typename l >
800
        bool destructively_aliases (
801
            const matrix<U,iNR,iNC,mm,l>& item
802
803
804
805
806
807
808
809
        ) const { return m.destructively_aliases(item); }

        long nr (
        ) const { return m.nr(); }

        long nc (
        ) const { return m.nc(); }

810
811
812
        typedef typename conditional_reference<const M,use_reference>::type M_ref_type;

        M_ref_type m;
Davis King's avatar
Davis King committed
813
        const type s;
814
815
816
817
818
819
    };

    template <
        typename EXP,
        typename S 
        >
Davis King's avatar
Davis King committed
820
    inline typename disable_if<is_matrix<S>, const matrix_mul_scal_exp<EXP> >::type operator* (
821
822
823
824
        const matrix_exp<EXP>& m,
        const S& s
    )
    {
825
826
        typedef typename EXP::type type;
        return matrix_mul_scal_exp<EXP>(m.ref(),static_cast<type>(s));
827
828
    }

829
830
831
832
833
834
835
836
837
838
    template <
        typename EXP,
        typename S,
        bool B
        >
    inline typename disable_if<is_matrix<S>, const matrix_mul_scal_exp<EXP> >::type operator* (
        const matrix_mul_scal_exp<EXP,B>& m,
        const S& s
    )
    {
839
840
        typedef typename EXP::type type;
        return matrix_mul_scal_exp<EXP>(m.m,static_cast<type>(s)*m.s);
841
842
    }

843
844
845
846
    template <
        typename EXP,
        typename S 
        >
Davis King's avatar
Davis King committed
847
    inline typename disable_if<is_matrix<S>, const matrix_mul_scal_exp<EXP> >::type operator* (
848
849
850
851
        const S& s,
        const matrix_exp<EXP>& m
    )
    {
852
853
        typedef typename EXP::type type;
        return matrix_mul_scal_exp<EXP>(m.ref(),static_cast<type>(s));
854
855
856
    }

    template <
857
858
859
        typename EXP,
        typename S,
        bool B
860
        >
861
862
863
    inline typename disable_if<is_matrix<S>, const matrix_mul_scal_exp<EXP> >::type operator* (
        const S& s,
        const matrix_mul_scal_exp<EXP,B>& m
864
865
    )
    {
866
867
        typedef typename EXP::type type;
        return matrix_mul_scal_exp<EXP>(m.m,static_cast<type>(s)*m.s);
868
869
870
    }

    template <
871
872
        typename EXP ,
        typename S
873
        >
874
    inline const typename disable_if_c<std::numeric_limits<typename EXP::type>::is_integer, matrix_mul_scal_exp<EXP> >::type operator/ (
875
        const matrix_exp<EXP>& m,
876
        const S& s
877
878
    )
    {
879
880
881
        typedef typename EXP::type type;
        const type one = 1;
        return matrix_mul_scal_exp<EXP>(m.ref(),one/static_cast<type>(s));
882
883
884
    }

    template <
885
886
887
        typename EXP,
        bool B,
        typename S
888
        >
889
890
891
    inline const typename disable_if_c<std::numeric_limits<typename EXP::type>::is_integer, matrix_mul_scal_exp<EXP> >::type operator/ (
        const matrix_mul_scal_exp<EXP,B>& m,
        const S& s
892
893
    )
    {
894
895
        typedef typename EXP::type type;
        return matrix_mul_scal_exp<EXP>(m.m,m.s/static_cast<type>(s));
896
897
898
899
900
    }

    template <
        typename EXP
        >
Davis King's avatar
Davis King committed
901
    inline const matrix_mul_scal_exp<EXP> operator- (
902
903
904
        const matrix_exp<EXP>& m
    )
    {
Davis King's avatar
Davis King committed
905
        return matrix_mul_scal_exp<EXP>(m.ref(),-1);
906
907
    }

908
909
910
911
912
913
914
915
916
917
918
    template <
        typename EXP,
        bool B
        >
    inline const matrix_mul_scal_exp<EXP> operator- (
        const matrix_mul_scal_exp<EXP,B>& m
    )
    {
        return matrix_mul_scal_exp<EXP>(m.m,-1*m.s);
    }

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
// ----------------------------------------------------------------------------------------

    template <
        typename EXP1,
        typename EXP2
        >
    bool operator== (
        const matrix_exp<EXP1>& m1,
        const matrix_exp<EXP2>& m2
    )
    {
        if (m1.nr() == m2.nr() && m1.nc() == m2.nc())
        {
            for (long r = 0; r < m1.nr(); ++r)
            {
                for (long c = 0; c < m1.nc(); ++c)
                {
                    if (m1(r,c) != m2(r,c))
                        return false;
                }
            }
            return true;
        }
        return false;
    }

    template <
        typename EXP1,
        typename EXP2
        >
    inline bool operator!= (
        const matrix_exp<EXP1>& m1,
        const matrix_exp<EXP2>& m2
    ) { return !(m1 == m2); }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename T,
        long num_rows,
        long num_cols,
962
963
        typename mem_manager,
        typename layout
964
        >
965
    struct matrix_traits<matrix<T,num_rows, num_cols, mem_manager, layout> >
966
967
968
    {
        typedef T type;
        typedef mem_manager mem_manager_type;
969
        typedef layout layout_type;
970
971
        const static long NR = num_rows;
        const static long NC = num_cols;
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
        const static long cost = 1;

    };

    template <
        typename T,
        long num_rows,
        long num_cols,
        typename mem_manager,
        typename layout
        >
    class matrix : public matrix_exp<matrix<T,num_rows,num_cols, mem_manager,layout> > 
    {

        COMPILE_TIME_ASSERT(num_rows >= 0 && num_cols >= 0); 
987

988
989
990
991
992
993
994
995
    public:
        typedef typename matrix_traits<matrix>::type type;
        typedef typename matrix_traits<matrix>::mem_manager_type mem_manager_type;
        typedef typename matrix_traits<matrix>::layout_type layout_type;
        const static long NR = matrix_traits<matrix>::NR;
        const static long NC = matrix_traits<matrix>::NC;
        const static long cost = matrix_traits<matrix>::cost;

996
        matrix () 
997
998
999
1000
1001
        {
        }

        explicit matrix (
            long length 
1002
        ) 
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        {
            // This object you are trying to call matrix(length) on is not a column or 
            // row vector.
            COMPILE_TIME_ASSERT(NR == 1 || NC == 1);
            DLIB_ASSERT( length >= 0, 
                "\tmatrix::matrix(length)"
                << "\n\tlength must be at least 0"
                << "\n\tlength: " << length 
                << "\n\tNR:     " << NR 
                << "\n\tNC:     " << NC 
                << "\n\tthis:   " << this
                );

            if (NR == 1)
            {
                DLIB_ASSERT(NC == 0 || NC == length,
                    "\tmatrix::matrix(length)"
Davis King's avatar
Davis King committed
1020
                    << "\n\tSince this is a statically sized matrix length must equal NC"
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
                    << "\n\tlength: " << length 
                    << "\n\tNR:     " << NR 
                    << "\n\tNC:     " << NC 
                    << "\n\tthis:   " << this
                    );

                data.set_size(1,length);
            }
            else
            {
                DLIB_ASSERT(NR == 0 || NR == length,
                    "\tvoid matrix::set_size(length)"
Davis King's avatar
Davis King committed
1033
                    << "\n\tSince this is a statically sized matrix length must equal NR"
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
                    << "\n\tlength: " << length 
                    << "\n\tNR:     " << NR 
                    << "\n\tNC:     " << NC 
                    << "\n\tthis:   " << this
                    );

                data.set_size(length,1);
            }
        }

        matrix (
            long rows,
            long cols 
1047
        )  
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
        {
            DLIB_ASSERT( (NR == 0 || NR == rows) && ( NC == 0 || NC == cols) && 
                    rows >= 0 && cols >= 0, 
                "\tvoid matrix::matrix(rows, cols)"
                << "\n\tYou have supplied conflicting matrix dimensions"
                << "\n\trows: " << rows
                << "\n\tcols: " << cols
                << "\n\tNR:   " << NR 
                << "\n\tNC:   " << NC 
                );
            data.set_size(rows,cols);
        }

        template <typename EXP>
        matrix (
            const matrix_exp<EXP>& m
1064
        )
1065
        {
1066
1067
1068
1069
1070
            // You get an error on this line if the matrix m contains a type that isn't
            // the same as the type contained in the target matrix.
            COMPILE_TIME_ASSERT((is_same_type<typename EXP::type,type>::value == true) ||
                                (is_matrix<typename EXP::type>::value == true));

1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
            // The matrix you are trying to assign m to is a statically sized matrix and 
            // m's dimensions don't match that of *this. 
            COMPILE_TIME_ASSERT(EXP::NR == NR || NR == 0 || EXP::NR == 0);
            COMPILE_TIME_ASSERT(EXP::NC == NC || NC == 0 || EXP::NC == 0);
            DLIB_ASSERT((NR == 0 || NR == m.nr()) && (NC == 0 || NC == m.nc()), 
                "\tmatrix& matrix::matrix(const matrix_exp& m)"
                << "\n\tYou are trying to assign a dynamically sized matrix to a statically sized matrix with the wrong size"
                << "\n\tNR:     " << NR
                << "\n\tNC:     " << NC
                << "\n\tm.nr(): " << m.nr()
                << "\n\tm.nc(): " << m.nc()
                << "\n\tthis:   " << this
                );

            data.set_size(m.nr(),m.nc());

1087
            matrix_assign(*this, m);
1088
1089
1090
1091
        }

        matrix (
            const matrix& m
1092
        ) 
1093
1094
        {
            data.set_size(m.nr(),m.nc());
1095
            matrix_assign(*this, m);
1096
1097
1098
1099
1100
        }

        template <typename U, size_t len>
        matrix (
            U (&array)[len]
1101
        ) 
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
        {
            COMPILE_TIME_ASSERT(NR*NC == len && len > 0);
            size_t idx = 0;
            for (long r = 0; r < NR; ++r)
            {
                for (long c = 0; c < NC; ++c)
                {
                    data(r,c) = static_cast<T>(array[idx]);
                    ++idx;
                }
            }
        }

        T& operator() (
            long r, 
            long c
        ) 
        { 
            DLIB_ASSERT(r < nr() && c < nc() &&
                   r >= 0 && c >= 0, 
                "\tT& matrix::operator(r,c)"
                << "\n\tYou must give a valid row and column"
                << "\n\tr:    " << r 
                << "\n\tc:    " << c
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc() 
                << "\n\tthis: " << this
                );
            return data(r,c); 
        }

        const T& operator() (
            long r, 
            long c
        ) const 
        { 
            DLIB_ASSERT(r < nr() && c < nc() &&
                   r >= 0 && c >= 0, 
                "\tconst T& matrix::operator(r,c)"
                << "\n\tYou must give a valid row and column"
                << "\n\tr:    " << r 
                << "\n\tc:    " << c
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc() 
                << "\n\tthis: " << this
                );
            return data(r,c);
        }

        T& operator() (
            long i
        ) 
        {
            // You can only use this operator on column vectors.
            COMPILE_TIME_ASSERT(NC == 1 || NC == 0 || NR == 1 || NR == 0);
            DLIB_ASSERT(nc() == 1 || nr() == 1, 
                "\tconst type matrix::operator(i)"
                << "\n\tYou can only use this operator on column or row vectors"
                << "\n\ti:    " << i
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc()
                << "\n\tthis: " << this
                );
1165
            DLIB_ASSERT( 0 <= i && i < size(), 
1166
1167
                "\tconst type matrix::operator(i)"
                << "\n\tYou must give a valid row/column number"
1168
1169
1170
                << "\n\ti:      " << i
                << "\n\tsize(): " << size()
                << "\n\tthis:   " << this
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
                );
            return data(i);
        }

        const T& operator() (
            long i
        ) const
        {
            // You can only use this operator on column vectors.
            COMPILE_TIME_ASSERT(NC == 1 || NC == 0 || NR == 1 || NR == 0);
            DLIB_ASSERT(nc() == 1 || nr() == 1, 
                "\tconst type matrix::operator(i)"
                << "\n\tYou can only use this operator on column or row vectors"
                << "\n\ti:    " << i
                << "\n\tnr(): " << nr()
                << "\n\tnc(): " << nc()
                << "\n\tthis: " << this
                );
1189
            DLIB_ASSERT( 0 <= i && i < size(), 
1190
1191
                "\tconst type matrix::operator(i)"
                << "\n\tYou must give a valid row/column number"
1192
1193
1194
                << "\n\ti:      " << i
                << "\n\tsize(): " << size()
                << "\n\tthis:   " << this
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
                );
            return data(i);
        }

        inline operator const type (
        ) const 
        {
            COMPILE_TIME_ASSERT(NC == 1 || NC == 0);
            COMPILE_TIME_ASSERT(NR == 1 || NR == 0);
            DLIB_ASSERT( nr() == 1 && nc() == 1 , 
                "\tmatrix::operator const type"
Davis King's avatar
Davis King committed
1206
                << "\n\tYou can only attempt to implicit convert a matrix to a scalar if"
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
                << "\n\tthe matrix is a 1x1 matrix"
                << "\n\tnr(): " << nr() 
                << "\n\tnc(): " << nc() 
                << "\n\tthis: " << this
                );
            return data(0);
        }

        void set_size (
            long rows,
            long cols
        )
        {
            DLIB_ASSERT( (NR == 0 || NR == rows) && ( NC == 0 || NC == cols) &&
                    rows >= 0 && cols >= 0, 
                "\tvoid matrix::set_size(rows, cols)"
                << "\n\tYou have supplied conflicting matrix dimensions"
                << "\n\trows: " << rows
                << "\n\tcols: " << cols
                << "\n\tNR:   " << NR 
                << "\n\tNC:   " << NC 
                << "\n\tthis: " << this
                );
            if (nr() != rows || nc() != cols)
                data.set_size(rows,cols);
        }

        void set_size (
            long length
        )
        {
            // This object you are trying to call set_size(length) on is not a column or 
            // row vector.
            COMPILE_TIME_ASSERT(NR == 1 || NC == 1);
            DLIB_ASSERT( length >= 0, 
                "\tvoid matrix::set_size(length)"
                << "\n\tlength must be at least 0"
                << "\n\tlength: " << length 
                << "\n\tNR:     " << NR 
                << "\n\tNC:     " << NC 
                << "\n\tthis:   " << this
                );

            if (NR == 1)
            {
                DLIB_ASSERT(NC == 0 || NC == length,
                    "\tvoid matrix::set_size(length)"
Davis King's avatar
Davis King committed
1254
                    << "\n\tSince this is a statically sized matrix length must equal NC"
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
                    << "\n\tlength: " << length 
                    << "\n\tNR:     " << NR 
                    << "\n\tNC:     " << NC 
                    << "\n\tthis:   " << this
                    );

                if (nc() != length)
                    data.set_size(1,length);
            }
            else
            {
                DLIB_ASSERT(NR == 0 || NR == length,
                    "\tvoid matrix::set_size(length)"
Davis King's avatar
Davis King committed
1268
                    << "\n\tSince this is a statically sized matrix length must equal NR"
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
                    << "\n\tlength: " << length 
                    << "\n\tNR:     " << NR 
                    << "\n\tNC:     " << NC 
                    << "\n\tthis:   " << this
                    );

                if (nr() != length)
                    data.set_size(length,1);
            }
        }

        long nr (
        ) const { return data.nr(); }

        long nc (
        ) const { return data.nc(); }

        long size (
        ) const { return data.nr()*data.nc(); }

        template <typename U, size_t len>
        matrix& operator= (
            U (&array)[len]
        )
        {
            COMPILE_TIME_ASSERT(NR*NC == len && len > 0);
            size_t idx = 0;
            for (long r = 0; r < NR; ++r)
            {
                for (long c = 0; c < NC; ++c)
                {
                    data(r,c) = static_cast<T>(array[idx]);
                    ++idx;
                }
            }
            return *this;
        }

        template <typename EXP>
        matrix& operator= (
            const matrix_exp<EXP>& m
        )
        {
1312
1313
1314
            // You get an error on this line if the matrix you are trying to 
            // assign m to is a statically sized matrix and  m's dimensions don't 
            // match that of *this. 
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
            COMPILE_TIME_ASSERT(EXP::NR == NR || NR == 0 || EXP::NR == 0);
            COMPILE_TIME_ASSERT(EXP::NC == NC || NC == 0 || EXP::NC == 0);
            DLIB_ASSERT((NR == 0 || nr() == m.nr()) && 
                   (NC == 0 || nc() == m.nc()), 
                "\tmatrix& matrix::operator=(const matrix_exp& m)"
                << "\n\tYou are trying to assign a dynamically sized matrix to a statically sized matrix with the wrong size"
                << "\n\tnr():   " << nr()
                << "\n\tnc():   " << nc()
                << "\n\tm.nr(): " << m.nr()
                << "\n\tm.nc(): " << m.nc()
                << "\n\tthis:   " << this
                );
1327
1328
1329
1330
1331

            // You get an error on this line if the matrix m contains a type that isn't
            // the same as the type contained in the target matrix.
            COMPILE_TIME_ASSERT((is_same_type<typename EXP::type,type>::value == true) ||
                                (is_matrix<typename EXP::type>::value == true));
1332
1333
            if (m.destructively_aliases(*this) == false)
            {
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
                // This if statement is seemingly unnecessary since set_size() contains this
                // exact same if statement.  However, structuring the code this way causes
                // gcc to handle the way it inlines this function in a much more favorable way.
                if (data.nr() == m.nr() && data.nc() == m.nc())
                {
                    matrix_assign(*this, m);
                }
                else
                {
                    set_size(m.nr(),m.nc());
                    matrix_assign(*this, m);
                }
1346
1347
1348
            }
            else
            {
1349
1350
1351
                // we have to use a temporary matrix object here because
                // *this is aliased inside the matrix_exp m somewhere.
                matrix temp;
1352
                temp.set_size(m.nr(),m.nc());
1353
                matrix_assign(temp, m);
1354
                temp.swap(*this);
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
            }
            return *this;
        }

        template <typename EXP>
        matrix& operator += (
            const matrix_exp<EXP>& m
        )
        {
            // The matrix you are trying to assign m to is a statically sized matrix and 
            // m's dimensions don't match that of *this. 
            COMPILE_TIME_ASSERT(EXP::NR == NR || NR == 0 || EXP::NR == 0);
            COMPILE_TIME_ASSERT(EXP::NC == NC || NC == 0 || EXP::NC == 0);
            DLIB_ASSERT(this->nr() == m.nr() && this->nc() == m.nc(), 
                "\tmatrix& matrix::operator+=(const matrix_exp& m)"
                << "\n\tYou are trying to add a dynamically sized matrix to a statically sized matrix with the wrong size"
                << "\n\tthis->nr(): " << nr()
                << "\n\tthis->nc(): " << nc()
                << "\n\tm.nr():     " << m.nr()
                << "\n\tm.nc():     " << m.nc()
                << "\n\tthis:       " << this
                );
            COMPILE_TIME_ASSERT((is_same_type<typename EXP::type,type>::value == true));
            if (m.destructively_aliases(*this) == false)
            {
1380
                matrix_assign(*this, *this + m);
1381
1382
1383
            }
            else
            {
1384
                // we have to use a temporary matrix object here because
1385
                // this->data is aliased inside the matrix_exp m somewhere.
1386
                matrix temp;
1387
                temp.set_size(m.nr(),m.nc());
1388
                matrix_assign(temp, *this + m);
1389
                temp.swap(*this);
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
            }
            return *this;
        }


        template <typename EXP>
        matrix& operator -= (
            const matrix_exp<EXP>& m
        )
        {
            // The matrix you are trying to assign m to is a statically sized matrix and 
            // m's dimensions don't match that of *this. 
            COMPILE_TIME_ASSERT(EXP::NR == NR || NR == 0 || EXP::NR == 0);
            COMPILE_TIME_ASSERT(EXP::NC == NC || NC == 0 || EXP::NC == 0);
            DLIB_ASSERT(this->nr() == m.nr() && this->nc() == m.nc(), 
                "\tmatrix& matrix::operator-=(const matrix_exp& m)"
                << "\n\tYou are trying to subtract a dynamically sized matrix from a statically sized matrix with the wrong size"
                << "\n\tthis->nr(): " << nr()
                << "\n\tthis->nc(): " << nc()
                << "\n\tm.nr():     " << m.nr()
                << "\n\tm.nc():     " << m.nc()
                << "\n\tthis:       " << this
                );
            COMPILE_TIME_ASSERT((is_same_type<typename EXP::type,type>::value == true));
            if (m.destructively_aliases(*this) == false)
            {
1416
                matrix_assign(*this, *this - m);
1417
1418
1419
            }
            else
            {
1420
                // we have to use a temporary matrix object here because
1421
                // this->data is aliased inside the matrix_exp m somewhere.
1422
                matrix temp;
1423
                temp.set_size(m.nr(),m.nc());
1424
                matrix_assign(temp, *this - m);
1425
                temp.swap(*this);
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
            }
            return *this;
        }

        matrix& operator += (
            const matrix& m
        )
        {
            const long size = m.nr()*m.nc();
            for (long i = 0; i < size; ++i)
                data(i) += m.data(i);
            return *this;
        }

        matrix& operator -= (
            const matrix& m
        )
        {
            const long size = m.nr()*m.nc();
            for (long i = 0; i < size; ++i)
                data(i) -= m.data(i);
            return *this;
        }

        matrix& operator *= (
            const T& a
        )
        {
            const long size = data.nr()*data.nc();
            for (long i = 0; i < size; ++i)
                data(i) *= a;
            return *this;
        }

        matrix& operator /= (
            const T& a
        )
        {
            const long size = data.nr()*data.nc();
            for (long i = 0; i < size; ++i)
                data(i) /= a;
            return *this;
        }

        matrix& operator= (
            const matrix& m
        )
        {
            if (this != &m)
            {
                set_size(m.nr(),m.nc());
                const long size = m.nr()*m.nc();
                for (long i = 0; i < size; ++i)
                    data(i) = m.data(i);
            }
            return *this;
        }

        void swap (
            matrix& item
        )
        {
            data.swap(item.data);
        }

1491
1492
        template <typename U, long iNR, long iNC, typename mm, typename l >
        bool aliases (
1493
            const matrix<U,iNR,iNC,mm,l>& 
1494
1495
1496
1497
        ) const  { return false; }

        template <typename U, long iNR, long iNC, typename mm, typename l>
        bool destructively_aliases (
1498
            const matrix<U,iNR,iNC,mm,l>& 
1499
1500
1501
1502
1503
1504
        ) const { return false; }

        bool aliases (
            const matrix& item
        ) const { return (this == &item); }

1505
    private:
1506
1507
1508
1509
1510
1511
1512
1513
        struct literal_assign_helper
        {
            /*
                This struct is a helper struct returned by the operator<<() function below.  It is
                used primarily to enable us to put DLIB_CASSERT statements on the usage of the
                operator<< form of matrix assignment.
            */

1514
1515
            literal_assign_helper(const literal_assign_helper& item) : m(item.m), r(item.r), c(item.c), has_been_used(false) {}
            literal_assign_helper(matrix* m_): m(m_), r(0), c(0),has_been_used(false) {next();}
1516
1517
            ~literal_assign_helper()
            {
1518
1519
                DLIB_CASSERT(!has_been_used || r == m->nr(),
                             "You have used the matrix comma based assignment incorrectly by failing to\n"
1520
1521
1522
1523
                             "supply a full set of values for every element of a matrix object.\n");
            }

            const literal_assign_helper& operator, (
1524
                const T& val
1525
1526
1527
            ) const
            {
                DLIB_CASSERT(r < m->nr() && c < m->nc(),
1528
                             "You have used the matrix comma based assignment incorrectly by attempting to\n" <<
1529
1530
                             "supply more values than there are elements in the matrix object being assigned to.\n\n" <<
                             "Did you forget to call set_size()?\n");
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
                (*m)(r,c) = val;
                next();
                has_been_used = true;
                return *this;
            }

        private:

            void next (
            ) const
            {
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
                ++c;
                if (c == m->nc())
                {
                    c = 0;
                    ++r;
                }
            }

            matrix* m;
            mutable long r;
            mutable long c;
1553
            mutable bool has_been_used;
1554
1555
1556
1557
        };

    public:

1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
        const literal_assign_helper operator = (
            const T& val
        ) 
        {  
            // assign the given value to every spot in this matrix
            for (long r = 0; r < nr(); ++r)
            {
                for (long c = 0; c < nc(); ++c)
                {
                    data(r,c) = val;
                }
            }

            // Now return the literal_assign_helper so that the user
            // can use the overloaded comma notation to initialize 
            // the matrix if they want to.
            return literal_assign_helper(this); 
        }
1576
1577
1578
1579

    private:


1580
        typename layout::template layout<T,NR,NC,mem_manager> data;
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
    };

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename T,
        long NR,
        long NC,
1591
1592
        typename mm,
        typename l
1593
1594
        >
    void swap(
1595
1596
        matrix<T,NR,NC,mm,l>& a,
        matrix<T,NR,NC,mm,l>& b
1597
1598
1599
1600
1601
1602
    ) { a.swap(b); }

    template <
        typename T,
        long NR,
        long NC,
1603
1604
        typename mm,
        typename l
1605
1606
        >
    void serialize (
1607
        const matrix<T,NR,NC,mm,l>& item, 
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
        std::ostream& out
    )
    {
        try
        {
            serialize(item.nr(),out);
            serialize(item.nc(),out);
            for (long r = 0; r < item.nr(); ++r)
            {
                for (long c = 0; c < item.nc(); ++c)
                {
                    serialize(item(r,c),out);
                }
            }
        }
        catch (serialization_error& e)
        {
            throw serialization_error(e.info + "\n   while serializing dlib::matrix");
        }
    }

    template <
        typename T,
        long NR,
        long NC,
1633
1634
        typename mm,
        typename l
1635
1636
        >
    void deserialize (
1637
        matrix<T,NR,NC,mm,l>& item, 
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
        std::istream& in
    )
    {
        try
        {
            long nr, nc;
            deserialize(nr,in); 
            deserialize(nc,in); 

            if (NR != 0 && nr != NR)
                throw serialization_error("Error while deserializing a dlib::matrix.  Invalid rows");
            if (NC != 0 && nc != NC)
                throw serialization_error("Error while deserializing a dlib::matrix.  Invalid columns");

            item.set_size(nr,nc);
            for (long r = 0; r < nr; ++r)
            {
                for (long c = 0; c < nc; ++c)
                {
                    deserialize(item(r,c),in);
                }
            }
        }
        catch (serialization_error& e)
        {
            throw serialization_error(e.info + "\n   while deserializing a dlib::matrix");
        }
    }

    template <
        typename EXP
        >
    std::ostream& operator<< (
        std::ostream& out,
        const matrix_exp<EXP>& m
    )
    {
        using namespace std;
        const streamsize old = out.width();

        // first figure out how wide we should make each field
        string::size_type w = 0;
        ostringstream sout;
        for (long r = 0; r < m.nr(); ++r)
        {
            for (long c = 0; c < m.nc(); ++c)
            {
                sout << m(r,c); 
                w = std::max(sout.str().size(),w);
                sout.str("");
            }
        }

        // now actually print it
        for (long r = 0; r < m.nr(); ++r)
        {
            for (long c = 0; c < m.nc(); ++c)
            {
                out.width(static_cast<streamsize>(w));
                out << m(r,c) << " ";
            }
            out << "\n";
        }
        out.width(old);
        return out;
    }

1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <typename EXP>
    class const_temp_matrix;

    template <
        typename EXP
        >
    struct matrix_traits<const_temp_matrix<EXP> >
    {
        typedef typename EXP::type type;
        typedef typename EXP::mem_manager_type mem_manager_type;
        typedef typename EXP::layout_type layout_type;
        const static long NR = EXP::NR;
        const static long NC = EXP::NC;
        const static long cost = 1;
    };

    template <typename EXP>
    class const_temp_matrix : public matrix_exp<const_temp_matrix<EXP> >, noncopyable 
    {
    public:
        typedef typename matrix_traits<const_temp_matrix>::type type;
        typedef typename matrix_traits<const_temp_matrix>::mem_manager_type mem_manager_type;
        typedef typename matrix_traits<const_temp_matrix>::layout_type layout_type;
        const static long NR = matrix_traits<const_temp_matrix>::NR;
        const static long NC = matrix_traits<const_temp_matrix>::NC;
        const static long cost = matrix_traits<const_temp_matrix>::cost;

        const_temp_matrix (
            const matrix_exp<EXP>& item
        ) :
            ref_(item.ref())
        {}
        const_temp_matrix (
            const EXP& item
        ) :
            ref_(item)
        {}

        const type operator() (
            long r, 
            long c
        ) const { return ref_(r,c); }

        const type operator() ( long i ) const 
        { return ref_(i); }

        template <typename U, long iNR, long iNC, typename MM, typename L >
        bool aliases (
            const matrix<U,iNR,iNC,MM,L>& item
        ) const { return ref_.aliases(item); }

        template <typename U, long iNR, long iNC, typename MM, typename L >
        bool destructively_aliases (
            const matrix<U,iNR,iNC,MM,L>& item
        ) const { return ref_.destructively_aliases(item); }

        long nr (
        ) const { return ref_.nr(); }

        long nc (
        ) const { return ref_.nc(); }

    private:

        typename conditional_matrix_temp<const EXP, (EXP::cost <= 1)>::type ref_;
    };

1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
// ----------------------------------------------------------------------------------------

}

#ifdef _MSC_VER
// put that warning back to its default setting
#pragma warning(default : 4355)
#endif

#endif // DLIB_MATRIx_