sparse_vector.h 19.9 KB
Newer Older
1
// Copyright (C) 2009  Davis E. King (davis@dlib.net)
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
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SVm_SPARSE_VECTOR
#define DLIB_SVm_SPARSE_VECTOR

#include "sparse_vector_abstract.h"
#include <cmath>
#include <limits>
#include "../algs.h"


namespace dlib
{

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

    namespace sparse_vector
    {

        template <typename T, typename U>
        typename T::value_type::second_type distance_squared (
            const T& a,
            const U& b
        )
        {
            typedef typename T::value_type::second_type scalar_type;
            typedef typename U::value_type::second_type scalar_typeU;
            // Both T and U must contain the same kinds of elements
            COMPILE_TIME_ASSERT((is_same_type<scalar_type, scalar_typeU>::value));

            typename T::const_iterator ai = a.begin();
            typename U::const_iterator bi = b.begin();

            scalar_type sum = 0, temp = 0;
            while (ai != a.end() && bi != b.end())
            {
                if (ai->first == bi->first)
                {
                    temp = ai->second - bi->second;
                    ++ai;
                    ++bi;
                }
                else if (ai->first < bi->first)
                {
                    temp = ai->second;
                    ++ai;
                }
                else 
                {
                    temp = bi->second;
                    ++bi;
                }

                sum += temp*temp;
            }

            while (ai != a.end())
            {
                sum += ai->second*ai->second;
60
                ++ai;
61
62
63
64
            }
            while (bi != b.end())
            {
                sum += bi->second*bi->second;
65
                ++bi;
66
67
68
69
70
            }

            return sum;
        }

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

        template <typename T, typename U, typename V, typename W>
        typename T::value_type::second_type distance_squared (
            const V& a_scale,
            const T& a,
            const W& b_scale,
            const U& b
        )
        {
            typedef typename T::value_type::second_type scalar_type;
            typedef typename U::value_type::second_type scalar_typeU;
            // Both T and U must contain the same kinds of elements
            COMPILE_TIME_ASSERT((is_same_type<scalar_type, scalar_typeU>::value));

            typename T::const_iterator ai = a.begin();
            typename U::const_iterator bi = b.begin();

            scalar_type sum = 0, temp = 0;
            while (ai != a.end() && bi != b.end())
            {
                if (ai->first == bi->first)
                {
                    temp = a_scale*ai->second - b_scale*bi->second;
                    ++ai;
                    ++bi;
                }
                else if (ai->first < bi->first)
                {
                    temp = a_scale*ai->second;
                    ++ai;
                }
                else 
                {
                    temp = b_scale*bi->second;
                    ++bi;
                }

                sum += temp*temp;
            }

            while (ai != a.end())
            {
                sum += a_scale*a_scale*ai->second*ai->second;
                ++ai;
            }
            while (bi != b.end())
            {
                sum += b_scale*b_scale*bi->second*bi->second;
                ++bi;
            }

            return sum;
        }

126
127
128
129
130
131
132
133
134
135
136
    // ------------------------------------------------------------------------------------

        template <typename T, typename U>
        typename T::value_type::second_type distance (
            const T& a,
            const U& b
        )
        {
            return std::sqrt(distance_squared(a,b));
        }

137
138
139
140
141
142
143
144
145
146
147
148
149
    // ------------------------------------------------------------------------------------

        template <typename T, typename U, typename V, typename W>
        typename T::value_type::second_type distance (
            const V& a_scale,
            const T& a,
            const W& b_scale,
            const U& b
        )
        {
            return std::sqrt(distance_squared(a_scale,a,b_scale,b));
        }

150
    // ------------------------------------------------------------------------------------
151
152
153
    // ------------------------------------------------------------------------------------

        template <typename T, typename EXP>
154
        typename enable_if<is_matrix<T> >::type assign (
155
156
157
158
159
160
            T& dest,
            const matrix_exp<EXP>& src
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(src),
161
                "\t void assign(dest,src)"
162
163
164
165
166
167
168
                << "\n\t the src matrix must be a row or column vector"
                );

            dest = src;
        }

        template <typename T, typename EXP>
169
        typename disable_if<is_matrix<T> >::type assign (
170
171
172
173
174
175
            T& dest,
            const matrix_exp<EXP>& src
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(src),
176
                "\t void assign(dest,src)"
177
178
179
180
181
182
183
184
185
186
187
188
                << "\n\t the src matrix must be a row or column vector"
                );

            dest.clear();
            typedef typename T::value_type item_type;
            for (long i = 0; i < src.size(); ++i)
            {
                if (src(i) != 0)
                    dest.insert(dest.end(),item_type(i, src(i)));
            }
        }

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        template <typename T, typename U>
        typename disable_if_c<is_matrix<T>::value || is_matrix<U>::value>::type assign (
            T& dest,        // sparse
            const U& src    // sparse
        )
        {
            dest.assign(src.begin(), src.end());
        }

        template <typename T, typename U, typename Comp, typename Alloc, typename S>
        typename disable_if<is_matrix<S> >::type assign (
            std::map<T,U,Comp,Alloc>& dest, // sparse
            const S& src                    // sparse
        )
        {
            dest.clear();
            dest.insert(src.begin(), src.end());
        }

    // ------------------------------------------------------------------------------------
209
210
211
212
213
214
215
216
    // ------------------------------------------------------------------------------------

        template <typename T>
        struct has_unsigned_keys
        {
            static const bool value = is_unsigned_type<typename T::value_type::first_type>::value;
        };

217
218
    // ------------------------------------------------------------------------------------

219
        template <typename T>
220
        typename T::value_type::second_type dot (
221
            const T& a,
222
            const T& b
223
224
225
226
227
        )
        {
            typedef typename T::value_type::second_type scalar_type;

            typename T::const_iterator ai = a.begin();
228
            typename T::const_iterator bi = b.begin();
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

            scalar_type sum = 0;
            while (ai != a.end() && bi != b.end())
            {
                if (ai->first == bi->first)
                {
                    sum += ai->second * bi->second;
                    ++ai;
                    ++bi;
                }
                else if (ai->first < bi->first)
                {
                    ++ai;
                }
                else 
                {
                    ++bi;
                }
            }

            return sum;
        }

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

        template <typename T, typename EXP>
        typename T::value_type::second_type dot (
            const T& a,
            const matrix_exp<EXP>& b
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(b) && max_index_plus_one(a) <= (unsigned long)b.size(),
                "\t scalar_type dot(sparse_vector a, dense_vector b)"
                << "\n\t 'b' must be a vector to be used in a dot product and the sparse vector 'a'"
                << "\n\t can't be bigger that the dense vector 'b'."
                );

            typedef typename T::value_type::second_type scalar_type;

            scalar_type sum = 0;
            for (typename T::const_iterator ai = a.begin(); ai != a.end(); ++ai)
            {
                sum += ai->second * b(ai->first);
            }

            return sum;
        }

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

        template <typename T, typename EXP>
        typename T::value_type::second_type dot (
            const matrix_exp<EXP>& b,
            const T& a
        )
        {
            return dot(a,b);
        }

289
290
291
292
293
294
295
296
297
    // ------------------------------------------------------------------------------------

        template <typename T>
        typename T::value_type::second_type length_squared (
            const T& a
        )
        {
            typedef typename T::value_type::second_type scalar_type;

298
            typename T::const_iterator i;
299
300

            scalar_type sum = 0;
301
302

            for (i = a.begin(); i != a.end(); ++i)
303
304
305
306
307
308
309
            {
                sum += i->second * i->second;
            }

            return sum;
        }

310
311
312
313
314
315
316
317
318
319
    // ------------------------------------------------------------------------------------

        template <typename T>
        typename T::value_type::second_type length (
            const T& a
        )
        {
            return std::sqrt(length_squared(a));
        }

320
321
322
    // ------------------------------------------------------------------------------------

        template <typename T, typename U>
Davis King's avatar
Davis King committed
323
        void scale_by (
324
325
326
327
328
329
330
331
332
333
            T& a,
            const U& value
        )
        {
            for (typename T::iterator i = a.begin(); i != a.end(); ++i)
            {
                i->second *= value;
            }
        }

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

        namespace impl
        {
            template <typename T>
            typename enable_if<is_matrix<typename T::type>,unsigned long>::type max_index_plus_one (
                const T& samples
            ) 
            {
                if (samples.size() > 0)
                    return samples(0).size();
                else
                    return 0;
            }

            template <typename T>
            typename enable_if<is_built_in_scalar_type<typename T::type>,unsigned long>::type max_index_plus_one (
                const T& sample
            ) 
            {
                return sample.size();
            }

            template <typename T>
            typename enable_if<is_pair<typename T::type::value_type> ,unsigned long>::type max_index_plus_one (
                const T& samples
            ) 
            {
                typedef typename T::type sample_type;
                // You are getting this error because you are attempting to use sparse sample vectors 
                // but you aren't using an unsigned integer as your key type in the sparse vectors.
                COMPILE_TIME_ASSERT(sparse_vector::has_unsigned_keys<sample_type>::value);


                // these should be sparse samples so look over all them to find the max index.
                unsigned long max_dim = 0;
                for (long i = 0; i < samples.size(); ++i)
                {
                    if (samples(i).size() > 0)
                        max_dim = std::max<unsigned long>(max_dim, (--samples(i).end())->first + 1);
                }

                return max_dim;
            }
        }

        template <typename T>
        typename enable_if<is_pair<typename T::value_type>,unsigned long>::type max_index_plus_one (
            const T& sample
        ) 
        {
            if (sample.size() > 0)
                return (--sample.end())->first + 1;
            return 0;
        }

        template <typename T>
        typename disable_if<is_pair<typename T::value_type>,unsigned long>::type max_index_plus_one (
            const T& samples
        ) 
        {
            return impl::max_index_plus_one(vector_to_matrix(samples));
        }

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

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP>
        inline void add_to (
            matrix<T,NR,NC,MM,L>& dest,
            const matrix_exp<EXP>& src 
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void add_to(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (long r = 0; r < src.size(); ++r)
                dest(r) += src(r);
        }

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP>
        inline typename disable_if<is_matrix<EXP> >::type add_to (
            matrix<T,NR,NC,MM,L>& dest,
            const EXP& src
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void add_to(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (typename EXP::const_iterator i = src.begin(); i != src.end(); ++i)
                dest(i->first) += i->second;
        }

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

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP, typename U>
        inline void add_to (
            matrix<T,NR,NC,MM,L>& dest,
            const matrix_exp<EXP>& src,
            const U& C
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void add_to(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (long r = 0; r < src.size(); ++r)
                dest(r) += C*src(r);
        }

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP, typename U>
        inline typename disable_if<is_matrix<EXP> >::type add_to (
            matrix<T,NR,NC,MM,L>& dest,
            const EXP& src,
            const U& C
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void add_to(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (typename EXP::const_iterator i = src.begin(); i != src.end(); ++i)
                dest(i->first) += C*i->second;
        }

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

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP>
        inline void subtract_from (
            matrix<T,NR,NC,MM,L>& dest,
            const matrix_exp<EXP>& src 
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void subtract_from(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (long r = 0; r < src.size(); ++r)
                dest(r) -= src(r);
        }

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP>
        inline typename disable_if<is_matrix<EXP> >::type subtract_from (
            matrix<T,NR,NC,MM,L>& dest,
            const EXP& src
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void subtract_from(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (typename EXP::const_iterator i = src.begin(); i != src.end(); ++i)
                dest(i->first) -= i->second;
        }

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

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP, typename U>
        inline void subtract_from (
            matrix<T,NR,NC,MM,L>& dest,
            const matrix_exp<EXP>& src,
            const U& C
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void subtract_from(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (long r = 0; r < src.size(); ++r)
                dest(r) -= C*src(r);
        }

        template <typename T, long NR, long NC, typename MM, typename L, typename EXP, typename U>
        inline typename disable_if<is_matrix<EXP> >::type subtract_from (
            matrix<T,NR,NC,MM,L>& dest,
            const EXP& src,
            const U& C
        ) 
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_vector(dest) && max_index_plus_one(src) <= static_cast<unsigned long>(dest.size()),
                "\t void subtract_from(dest,src)"
                << "\n\t dest must be a vector large enough to hold the src vector."
                << "\n\t is_vector(dest):         " << is_vector(dest)
                << "\n\t max_index_plus_one(src): " << max_index_plus_one(src)
                << "\n\t dest.size():             " << dest.size() 
                );

            for (typename EXP::const_iterator i = src.begin(); i != src.end(); ++i)
                dest(i->first) -= C*i->second;
        }

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

565
566
567
568
569
570
571
572
573
574
575
    }

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

}

#endif // DLIB_SVm_SPARSE_VECTOR