summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/data/VectorUtil.java
blob: 59200ea9bf65576719628147775480710761eaaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package de.lmu.ifi.dbs.elki.data;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2014
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import gnu.trove.map.hash.TIntDoubleHashMap;

import java.util.BitSet;
import java.util.Comparator;
import java.util.Random;

import de.lmu.ifi.dbs.elki.data.spatial.SpatialComparable;
import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.ids.DBIDRef;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.database.relation.RelationUtil;
import de.lmu.ifi.dbs.elki.math.MathUtil;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.utilities.datastructures.QuickSelect;

/**
 * Utility functions for use with vectors.
 * 
 * Note: obviously, many functions are class methods or database related.
 * 
 * @author Erich Schubert
 * 
 * @apiviz.uses NumberVector
 */
public final class VectorUtil {
  /**
   * Fake constructor. Do not instantiate, use static methods.
   */
  private VectorUtil() {
    // Do not instantiate - utility class.
  }

  /**
   * Produce a new vector based on random numbers in [0:1].
   * 
   * @param factory Vector factory
   * @param dim desired dimensionality
   * @param r Random generator
   * @param <V> vector type
   * @return new instance
   */
  public static <V extends NumberVector> V randomVector(NumberVector.Factory<V> factory, int dim, Random r) {
    return factory.newNumberVector(MathUtil.randomDoubleArray(dim, r));
  }

  /**
   * Produce a new vector based on random numbers in [0:1].
   * 
   * @param factory Vector factory
   * @param dim desired dimensionality
   * @param <V> vector type
   * @return new instance
   */
  public static <V extends NumberVector> V randomVector(NumberVector.Factory<V> factory, int dim) {
    return randomVector(factory, dim, new Random());
  }

  /**
   * Compute the angle for sparse vectors.
   * 
   * @param v1 First vector
   * @param v2 Second vector
   * @return angle
   */
  public static double angleSparse(SparseNumberVector v1, SparseNumberVector v2) {
    // TODO: exploit precomputed length, when available?
    // Length of first vector
    double l1 = 0., l2 = 0., cross = 0.;
    int i1 = v1.iter(), i2 = v2.iter();
    while(v1.iterValid(i1) && v2.iterValid(i2)) {
      final int d1 = v1.iterDim(i1), d2 = v2.iterDim(i2);
      if(d1 < d2) {
        final double val = v1.iterDoubleValue(i1);
        l1 += val * val;
        i1 = v1.iterAdvance(i1);
      }
      else if(d2 < d1) {
        final double val = v2.iterDoubleValue(i2);
        l2 += val * val;
        i2 = v2.iterAdvance(i2);
      }
      else { // d1 == d2
        final double val1 = v1.iterDoubleValue(i1);
        final double val2 = v2.iterDoubleValue(i2);
        l1 += val1 * val1;
        l2 += val2 * val2;
        cross += val1 * val2;
        i1 = v1.iterAdvance(i1);
        i2 = v2.iterAdvance(i2);
      }
    }
    while(v1.iterValid(i1)) {
      final double val = v1.iterDoubleValue(i1);
      l1 += val * val;
      i1 = v1.iterAdvance(i1);
    }
    while(v2.iterValid(i2)) {
      final double val = v2.iterDoubleValue(i2);
      l2 += val * val;
      i2 = v2.iterAdvance(i2);
    }
    if(cross == 0.) {
      return 0.;
    }
    if(l1 == 0. || l2 == 0.) {
      return 1.;
    }
    final double a = Math.sqrt((cross / l1) * (cross / l2));
    return (a < 1.) ? a : 1.;
  }

  /**
   * Compute the angle between two vectors.
   * 
   * @param v1 first vector
   * @param v2 second vector
   * @param o Origin
   * @return Angle
   */
  public static double angle(NumberVector v1, NumberVector v2, Vector o) {
    final int dim1 = v1.getDimensionality(), dim2 = v2.getDimensionality(), dimo = o.getDimensionality();
    final int mindim = (dim1 <= dim2) ? dim1 : dim2;
    // Essentially, we want to compute this:
    // v1' = v1 - o, v2' = v2 - o
    // v1'.transposeTimes(v2') / (v1'.euclideanLength()*v2'.euclideanLength());
    // We can just compute all three in parallel.
    double[] oe = o.getArrayRef();
    double cross = 0., l1 = 0., l2 = 0.;
    for(int k = 0; k < mindim; k++) {
      final double dk = k < dimo ? oe[k] : 0.;
      final double r1 = v1.doubleValue(k) - dk;
      final double r2 = v2.doubleValue(k) - dk;
      cross += r1 * r2;
      l1 += r1 * r1;
      l2 += r2 * r2;
    }
    for(int k = mindim; k < dim1; k++) {
      final double dk = k < dimo ? oe[k] : 0.;
      final double r1 = v1.doubleValue(k) - dk;
      l1 += r1 * r1;
    }
    for(int k = mindim; k < dim2; k++) {
      final double dk = k < dimo ? oe[k] : 0.;
      final double r2 = v2.doubleValue(k) - dk;
      l2 += r2 * r2;
    }
    if(cross == 0.) {
      return 0.;
    }
    if(l1 == 0. || l2 == 0.) {
      return 1.;
    }
    final double a = Math.sqrt((cross / l1) * (cross / l2));
    return (a < 1.) ? a : 1.;
  }

  /**
   * Compute the angle between two vectors.
   * 
   * @param v1 first vector
   * @param v2 second vector
   * @param o Origin
   * @return Angle
   */
  public static double angle(NumberVector v1, NumberVector v2, NumberVector o) {
    final int dim1 = v1.getDimensionality(), dim2 = v2.getDimensionality(), dimo = o.getDimensionality();
    final int mindim = (dim1 <= dim2) ? dim1 : dim2;
    // Essentially, we want to compute this:
    // v1' = v1 - o, v2' = v2 - o
    // v1'.transposeTimes(v2') / (v1'.euclideanLength()*v2'.euclideanLength());
    // We can just compute all three in parallel.
    double cross = 0, l1 = 0, l2 = 0;
    for(int k = 0; k < mindim; k++) {
      final double ok = k < dimo ? o.doubleValue(k) : 0.;
      final double r1 = v1.doubleValue(k) - ok;
      final double r2 = v2.doubleValue(k) - o.doubleValue(k);
      cross += r1 * r2;
      l1 += r1 * r1;
      l2 += r2 * r2;
    }
    for(int k = mindim; k < dim1; k++) {
      final double ok = k < dimo ? o.doubleValue(k) : 0.;
      final double r1 = v1.doubleValue(k) - ok;
      l1 += r1 * r1;
    }
    for(int k = mindim; k < dim2; k++) {
      final double ok = k < dimo ? o.doubleValue(k) : 0.;
      final double r2 = v2.doubleValue(k) - ok;
      l2 += r2 * r2;
    }
    if(cross == 0.) {
      return 0.;
    }
    if(l1 == 0. || l2 == 0.) {
      return 1.;
    }
    final double a = Math.sqrt((cross / l1) * (cross / l2));
    return (a < 1.) ? a : 1.;
  }

  /**
   * Compute the absolute cosine of the angle between two vectors.
   * 
   * To convert it to radians, use <code>Math.acos(angle)</code>!
   * 
   * @param v1 first vector
   * @param v2 second vector
   * @return Angle
   */
  public static double cosAngle(NumberVector v1, NumberVector v2) {
    if(v1 instanceof SparseNumberVector && v2 instanceof SparseNumberVector) {
      return angleSparse((SparseNumberVector) v1, (SparseNumberVector) v2);
    }
    final int dim1 = v1.getDimensionality(), dim2 = v2.getDimensionality();
    final int mindim = (dim1 <= dim2) ? dim1 : dim2;
    // Essentially, we want to compute this:
    // v1.transposeTimes(v2) / (v1.euclideanLength() * v2.euclideanLength());
    // We can just compute all three in parallel.
    double cross = 0, l1 = 0, l2 = 0;
    for(int k = 0; k < mindim; k++) {
      final double r1 = v1.doubleValue(k);
      final double r2 = v2.doubleValue(k);
      cross += r1 * r2;
      l1 += r1 * r1;
      l2 += r2 * r2;
    }
    for(int k = mindim; k < dim1; k++) {
      final double r1 = v1.doubleValue(k);
      l1 += r1 * r1;
    }
    for(int k = mindim; k < dim2; k++) {
      final double r2 = v2.doubleValue(k);
      l2 += r2 * r2;
    }
    if(cross == 0.) {
      return 0.;
    }
    if(l1 == 0. || l2 == 0.) {
      return 1.;
    }
    final double a = Math.sqrt((cross / l1) * (cross / l2));
    return (a < 1.) ? a : 1.;
  }

  // TODO: add more precise but slower O(n^2) angle computation according to:
  // Computing the Angle between Vectors, P. Schatte
  // Journal of Computing, Volume 63, Number 1 (1999)

  /**
   * Compute the minimum angle between two rectangles.
   * 
   * @param v1 first rectangle
   * @param v2 second rectangle
   * @return Angle
   */
  public static double minCosAngle(SpatialComparable v1, SpatialComparable v2) {
    if(v1 instanceof NumberVector && v2 instanceof NumberVector) {
      return cosAngle((NumberVector) v1, (NumberVector) v2);
    }
    final int dim1 = v1.getDimensionality(), dim2 = v2.getDimensionality();
    final int mindim = (dim1 <= dim2) ? dim1 : dim2;
    // Essentially, we want to compute this:
    // absmax(v1.transposeTimes(v2))/(min(v1.euclideanLength())*min(v2.euclideanLength()));
    // We can just compute all three in parallel.
    double s1 = 0, s2 = 0, l1 = 0, l2 = 0;
    for(int k = 0; k < mindim; k++) {
      final double min1 = v1.getMin(k), max1 = v1.getMax(k);
      final double min2 = v2.getMin(k), max2 = v2.getMax(k);
      final double p1 = min1 * min2, p2 = min1 * max2;
      final double p3 = max1 * min2, p4 = max1 * max2;
      s1 += Math.max(p1 > p2 ? p1 : p2, p3 > p4 ? p3 : p4);
      s2 += Math.min(p1 < p2 ? p1 : p2, p3 < p4 ? p3 : p4);
      if(max1 < 0) {
        l1 += max1 * max1;
      }
      else if(min1 > 0) {
        l1 += min1 * min1;
      } // else: 0
      if(max2 < 0) {
        l2 += max2 * max2;
      }
      else if(min2 > 0) {
        l2 += min2 * min2;
      } // else: 0
    }
    for(int k = mindim; k < dim1; k++) {
      final double min1 = v1.getMin(k), max1 = v1.getMax(k);
      if(max1 < 0.) {
        l1 += max1 * max1;
      }
      else if(min1 > 0.) {
        l1 += min1 * min1;
      } // else: 0
    }
    for(int k = mindim; k < dim2; k++) {
      final double min2 = v2.getMin(k), max2 = v2.getMax(k);
      if(max2 < 0.) {
        l2 += max2 * max2;
      }
      else if(min2 > 0.) {
        l2 += min2 * min2;
      } // else: 0
    }
    final double cross = Math.max(s1, Math.abs(s2));
    if(cross == 0.) {
      return 0.;
    }
    if(l1 == 0. || l2 == 0.) {
      return 1.;
    }
    final double a = Math.sqrt((cross / l1) * (cross / l2));
    return (a < 1.) ? a : 1.;
  }

  /**
   * Compute the scalar product (inner product) of this and the given
   * DoubleVector.
   * 
   * @param d1 the first vector to compute the scalar product for
   * @param d2 the second vector to compute the scalar product for
   * @return the scalar product (inner product) of this and the given
   *         DoubleVector
   */
  public static double scalarProduct(NumberVector d1, NumberVector d2) {
    final int dim = d1.getDimensionality();
    double result = 0.;
    for(int i = 0; i < dim; i++) {
      result += d1.doubleValue(i) * d2.doubleValue(i);
    }
    return result;
  }

  /**
   * Compute medoid for a given subset.
   * 
   * @param relation Relation to process
   * @param sample Sample set
   * @return Medoid vector
   */
  public static Vector computeMedoid(Relation<? extends NumberVector> relation, DBIDs sample) {
    final int dim = RelationUtil.dimensionality(relation);
    ArrayModifiableDBIDs mids = DBIDUtil.newArray(sample);
    SortDBIDsBySingleDimension s = new SortDBIDsBySingleDimension(relation);
    Vector medoid = new Vector(dim);
    for(int d = 0; d < dim; d++) {
      s.setDimension(d);
      medoid.set(d, relation.get(QuickSelect.median(mids, s)).doubleValue(d));
    }
    return medoid;
  }

  /**
   * This is an ugly hack, but we don't want to have the {@link Matrix} class
   * depend on {@link NumberVector}. Maybe a future version will no longer need
   * this.
   * 
   * @param mat Matrix
   * @param v Vector
   * @return {@code mat * v}, as double array.
   */
  public static double[] fastTimes(Matrix mat, NumberVector v) {
    final double[][] elements = mat.getArrayRef();
    final int cdim = mat.getColumnDimensionality();
    final double[] X = new double[elements.length];
    // multiply it with each row from A
    for(int i = 0; i < elements.length; i++) {
      final double[] Arowi = elements[i];
      double s = 0;
      for(int k = 0; k < cdim; k++) {
        s += Arowi[k] * v.doubleValue(k);
      }
      X[i] = s;
    }
    return X;
  }

  /**
   * Compare number vectors by a single dimension.
   * 
   * @author Erich Schubert
   * 
   * @apiviz.exclude
   */
  public static class SortDBIDsBySingleDimension implements Comparator<DBIDRef> {
    /**
     * Dimension to sort with.
     */
    private int d;

    /**
     * The relation to sort.
     */
    private Relation<? extends NumberVector> data;

    /**
     * Constructor.
     * 
     * @param data Vector data source
     * @param dim Dimension to sort by
     */
    public SortDBIDsBySingleDimension(Relation<? extends NumberVector> data, int dim) {
      super();
      this.data = data;
      this.d = dim;
    };

    /**
     * Constructor.
     * 
     * @param data Vector data source
     */
    public SortDBIDsBySingleDimension(Relation<? extends NumberVector> data) {
      super();
      this.data = data;
    };

    /**
     * Get the dimension to sort by.
     * 
     * @return Dimension to sort with
     */
    public int getDimension() {
      return this.d;
    }

    /**
     * Set the dimension to sort by.
     * 
     * @param d2 Dimension to sort with
     */
    public void setDimension(int d2) {
      this.d = d2;
    }

    @Override
    public int compare(DBIDRef id1, DBIDRef id2) {
      return Double.compare(data.get(id1).doubleValue(d), data.get(id2).doubleValue(d));
    }
  }

  /**
   * Compare number vectors by a single dimension.
   * 
   * @author Erich Schubert
   * 
   * @apiviz.exclude
   */
  public static class SortVectorsBySingleDimension implements Comparator<NumberVector> {
    /**
     * Dimension to sort with.
     */
    private int d;

    /**
     * Constructor.
     * 
     * @param dim Dimension to sort by.
     */
    public SortVectorsBySingleDimension(int dim) {
      super();
      this.d = dim;
    };

    /**
     * Constructor.
     */
    public SortVectorsBySingleDimension() {
      super();
    };

    /**
     * Get the dimension to sort by.
     * 
     * @return Dimension to sort with
     */
    public int getDimension() {
      return this.d;
    }

    /**
     * Set the dimension to sort by.
     * 
     * @param d2 Dimension to sort with
     */
    public void setDimension(int d2) {
      this.d = d2;
    }

    @Override
    public int compare(NumberVector o1, NumberVector o2) {
      return Double.compare(o1.doubleValue(d), o2.doubleValue(d));
    }
  }

  /**
   * Project a number vector to the specified attributes.
   * 
   * @param v a NumberVector to project
   * @param selectedAttributes the attributes selected for projection
   * @param factory Vector factory
   * @param <V> Vector type
   * @return a new NumberVector as a projection on the specified attributes
   */
  public static <V extends NumberVector> V project(V v, BitSet selectedAttributes, NumberVector.Factory<V> factory) {
    if(factory instanceof SparseNumberVector.Factory) {
      final SparseNumberVector.Factory<?> sfactory = (SparseNumberVector.Factory<?>) factory;
      TIntDoubleHashMap values = new TIntDoubleHashMap(selectedAttributes.cardinality(), 1);
      for(int d = selectedAttributes.nextSetBit(0); d >= 0; d = selectedAttributes.nextSetBit(d + 1)) {
        if(v.doubleValue(d) != 0.0) {
          values.put(d, v.doubleValue(d));
        }
      }
      // We can't avoid this cast, because Java doesn't know that V is a
      // SparseNumberVector:
      @SuppressWarnings("unchecked")
      V projectedVector = (V) sfactory.newNumberVector(values, selectedAttributes.cardinality());
      return projectedVector;
    }
    else {
      double[] newAttributes = new double[selectedAttributes.cardinality()];
      int i = 0;
      for(int d = selectedAttributes.nextSetBit(0); d >= 0; d = selectedAttributes.nextSetBit(d + 1)) {
        newAttributes[i] = v.doubleValue(d);
        i++;
      }
      return factory.newNumberVector(newAttributes);
    }
  }
}