-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMatrix.java
739 lines (637 loc) · 22.6 KB
/
Matrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*
* MIT License
*
* Copyright (c) 2019 Sebastian Gössl
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package matrix;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleConsumer;
import java.util.function.DoubleFunction;
import java.util.function.DoubleSupplier;
import java.util.function.DoubleUnaryOperator;
import java.util.function.ToDoubleBiFunction;
import java.util.stream.IntStream;
/**
* Matrix class used to store and operate on matricies.
* The indices of the elements are zero indexed like if it would be a two
* dimensional array (what it actually is internally).
* The first index is always the row index counted from top to bottom and the
* second index is always the column index counted from left to right.
* e.g. a 2x3 matrix
* [[0,0 0,1 0,2],
* [1,0 1,1 1,2]]
*
* All operations are applied, if possible, in parallel, otherwise
* column-row vise.
*
*
* @author Sebastian Gössl
* @version 1.4 3.9.2019
*/
public class Matrix implements Iterable<Double> {
/**
* Dimensions of the matrix.
* Height: Number of rows
* Width: Number of columns
*/
private final int height, width;
/**
* Elements of the matrix.
*/
private final double[][] data;
/**
* Constructs a copy of the given matrix.
*
* @param other matrix to copy
*/
public Matrix(Matrix other) {
this(other.getHeight(), other.getWidth());
set(other);
}
/**
* Constructs a new matrix with the content of the given array.
*
* @param array data to be stored into the matrix
*/
public Matrix(double[][] array) {
this(array.length, array[0].length, (j, i) -> array[j][i]);
}
/**
* Constructs a new matrix with <code>height</code> rows and
* <code>width</code> columns and fills it with the given value.
*
* @param height number of rows
* @param width number of columns
* @param value value to fill the matrix with
*/
public Matrix(int height, int width, double value) {
this(height, width);
set(value);
}
/**
* Constructs a new matrix with <code>height</code> rows and
* <code>width</code> columns and fills it with the elements returned from
* the given supplier.
*
* @param height number of rows
* @param width number of columns
* @param supplier supplier to fill the matrix with values
*/
public Matrix(int height, int width, DoubleSupplier supplier) {
this(height, width);
set(supplier);
}
/**
* Constructs a new matrix with <code>height</code> rows and
* <code>width</code> columns and fills the elements with the given
* function.
* The function receives the row and column indices of the current element
* to calculate.
*
* @param height number of rows
* @param width number of columns
* @param function function that recieves the indices of the element it
* shall calculate
*/
public Matrix(int height, int width,
ToDoubleBiFunction<Integer, Integer> function) {
this(height, width);
set(function);
}
/**
* Constructs a new matrix with <code>height</code> rows and
* <code>width</code> columns.
* All elements are initialized to zero.
*
* @param height number of rows
* @param width number of columns
*/
public Matrix(int height, int width) {
this.height = height;
this.width = width;
data = new double[height][width];
}
/**
* Returns the number of rows.
*
* @return number of rows
*/
public int getHeight() {
return height;
}
/**
* Returns the number of columns.
*
* @return number of columns
*/
public int getWidth() {
return width;
}
/**
* Returns the element at the specified position.
*
* @param row row of the element to return
* @param column column of the element to return
* @return the element at the specified position
*/
public double get(int row, int column) {
return data[row][column];
}
/**
* Replaces the element at the specified position with the specified
* element.
*
* @param row row of the element to set
* @param column column of the element to set
* @param value element to be stored at the specified position
* @return element previously at the specified position
*/
public double set(int row, int column, double value) {
final double oldElement = data[row][column];
data[row][column] = value;
return oldElement;
}
/**
* Replaces all elements of the matrix with the specified elements.
*
* @param value element to replace all elements
*/
public void set(double value) {
forEachIndicesParallel((j, i) -> set(j, i, value));
}
/**
* Replaces all elements with the values returned from the given supplier.
* The elements of the matrix are filled into the matrix column-row vise.
*
* @param supplier supplier to supply new values for all elements
*/
public void set(DoubleSupplier supplier) {
forEachIndices((j, i) -> set(j, i, supplier.getAsDouble()));
}
/**
* Replaces all elements with the values returned from the given function.
* It recieves the position (row and column indices) of the element to
* replace as arguments.
*
* @param function function to calculate new values for all elements
*/
public void set(ToDoubleBiFunction<Integer, Integer> function) {
forEachIndices(
(j, i) -> set(j, i, function.applyAsDouble(j, i)));
}
/**
* Replaces all elements with the values of the given matrix.
*
* @param other other matrix to get values from
*/
public void set(Matrix other) {
setParallel((j, i) -> other.get(j, i));
}
/**
* Replaces all elements with the values returned from the given function
* in parallel.
* It recieves the position (row and column indices) of the element to
* replace as arguments.
*
* @param function function to calculate new values for all elements
*/
public void setParallel(ToDoubleBiFunction<Integer, Integer> function) {
forEachIndicesParallel(
(j, i) -> set(j, i, function.applyAsDouble(j, i)));
}
/**
* Adds the given matrix to this matrix elementwise and returns the result.
*
* @param operand other summand
* @return sum
*/
public Matrix add(Matrix operand) {
return applyNewParallel(operand, (x, y) -> x + y);
}
/**
* Subtracts the given matrix from this matrix elementwise and returns the
* result.
*
* @param operand subtrahend
* @return difference
*/
public Matrix subtract(Matrix operand) {
return applyNewParallel(operand, (x, y) -> x - y);
}
/**
* Multiplies every element of this matrix with the given value and returns
* the result.
* Scalar multiplication.
*
* @param factor scalar factor
* @return product
*/
public Matrix multiply(double factor) {
return applyNewParallel((x) -> factor * x);
}
/**
* Matrix multiplies this matrix with the given matrix and returns the
* result.
*
* @param operand second factor
* @return product
*/
public Matrix multiply(Matrix operand) {
final Matrix result = new Matrix(getHeight(), operand.getWidth());
result.setParallel((j, i) -> {
double sum = 0;
for(int k=0; k<getWidth() && k<operand.getHeight(); k++) {
sum += get(j, k) * operand.get(k, i);
}
return sum;
});
return result;
}
/**
* Multiplies this matrix with the given matrix elementwise and returns the
* result.
*
* @param operand factor
* @return product
*/
public Matrix multiplyElementwise(Matrix operand) {
return applyNewParallel(operand, (x, y) -> x * y);
}
/**
* Divides this matrix by the given matrix elementwise and returns the
* result.
*
* @param operand divisor
* @return quotient
*/
public Matrix divideElementwise(Matrix operand) {
return applyNewParallel(operand, (x, y) -> x / y);
}
/**
* Returns the transpose of this matrix.
*
* @return transpose of this matrix.
*/
public Matrix transpose() {
final Matrix result = new Matrix(getWidth(), getHeight());
result.setParallel((j, i) -> get(i, j));
return result;
}
/**
* Returns the determinant of this matrix.
* The determinant is calculated recursively with the Laplace expansion
* along the first row.
*
* @return determinant of this matrix
*/
public double determinant() {
if(getHeight() != getWidth()) {
throw new ArithmeticException(
"determinant only defined for square matricies");
}
if(getHeight() == 0) {
return 1;
}
if(getHeight() == 1) {
return get(0, 0);
}
if(getHeight() == 2) {
return get(0, 0)*get(1, 1) - get(0, 1)*get(1, 0);
}
if(getHeight() == 3) {
return get(0, 0) * get(1, 1) * get(2, 2)
+ get(0, 1) * get(1, 2) * get(2, 0)
+ get(0, 2) * get(1, 0) * get(2, 1)
- get(0, 2) * get(1, 1) * get(2, 0)
- get(0, 1) * get(1, 0) * get(2, 2)
- get(0, 0) * get(1, 2) * get(2, 1);
}
double sum = 0;
for(int j=0; j<getWidth(); j++) {
final double sgn = (j % 2 == 0) ? (1) : (-1);
final Matrix under = rowColRem(0, j);
sum += sgn * get(0, j) * under.determinant();
}
return sum;
}
/**
* Helper method for Laplace expansion in determinant().
* Returns a copy of this matrix with the specified row & column removed.
*
* @param row row to be removed
* @param column column to be removed
* @return copy of this matrix with the specified row & column removed
*/
private Matrix rowColRem(int row, int column) {
return new Matrix(getHeight()-1, getWidth()-1, (j, i) -> {
if(j >= row) {
j++;
}
if(i >= column) {
i++;
}
return get(j, i);
});
}
/**
* Applies the given operator on every element of this matrix.
*
* @param operator operator to apply on every element of this matrix
*/
public void apply(DoubleUnaryOperator operator) {
set((j, i) -> operator.applyAsDouble(get(j, i)));
}
/**
* Applies the given operator elementwise on every element of this matrix
* and the given one.
*
* @param operand second operand
* @param operator operator to apply on every element of this matrix
*/
public void apply(Matrix operand, DoubleBinaryOperator operator) {
set((j, i) -> operator.applyAsDouble(get(j, i), operand.get(j, i)));
}
/**
* Applies the given operator on every element of this matrix and the given
* matrix elementwise wrapping around.
*
* @param operand second operand
* @param operator operator to apply on every element of the matrix
*/
public void applyDifSize(Matrix operand, DoubleBinaryOperator operator) {
set((j, i) -> operator.applyAsDouble(
get(j, i),
operand.get(j % getHeight(), i % getWidth())));
}
/**
* Applies the given operator on every element of this matrix and returns
* the result.
*
* @param operator operator to apply on every element of this matrix
* @return result of the operation
*/
public Matrix applyNew(DoubleUnaryOperator operator) {
return new Matrix(getHeight(), getWidth(),
(j, i) -> operator.applyAsDouble(get(j, i)));
}
/**
* Applies the given operator elementwise on every element of this matrix
* and the given one and returns the result.
*
* @param operand second operand
* @param operator operator to apply on every element of the matricies
* @return result of the operation
*/
public Matrix applyNew(Matrix operand, DoubleBinaryOperator operator) {
return new Matrix(getHeight(), getWidth(), (j, i) ->
operator.applyAsDouble(get(j, i), operand.get(j, i)));
}
/**
* Applies the given operator on every element of this matrix and the given
* matrix elementwise wrapping around and returns the result.
* The result has as many rows and the matrix with more rows and as many
* columns as the matrix with more columns.
*
* @param operand second operand
* @param operator operator to apply on every element of the matricies
* @return result of the operation
*/
public Matrix applyNewDifSize(Matrix operand,
DoubleBinaryOperator operator) {
return new Matrix(
Math.max(getHeight(), operand.getHeight()),
Math.max(getWidth(), operand.getWidth()),
(j, i) -> {
final double value1 = get(j % getHeight(), i % getWidth());
final double value2 = operand.get(
j % operand.getHeight(), i % operand.getWidth());
return operator.applyAsDouble(value1, value2);
});
}
/**
* Applies the given operator on every element of this matrix in parallel.
*
* @param operator operator to apply on every element of this matrix
*/
public void applyParallel(DoubleUnaryOperator operator) {
setParallel((j, i) -> operator.applyAsDouble(get(j, i)));
}
/**
* Applies the given operator elementwise on every element of this matrix
* and the given one in parallel.
*
* @param operand second operand
* @param operator operator to apply on every element of this matrix
*/
public void applyParallel(Matrix operand, DoubleBinaryOperator operator) {
setParallel((j, i) ->
operator.applyAsDouble(get(j, i), operand.get(j, i)));
}
/**
* Applies the given operator on every element of this matrix and the given
* matrix in parallel elementwise wrapping around.
*
* @param operand second operand
* @param operator operator to apply on every element of the matrix
*/
public void applyDifSizeParallel(Matrix operand,
DoubleBinaryOperator operator) {
setParallel((j, i) -> operator.applyAsDouble(
get(j, i),
operand.get(j % getHeight(), i % getWidth())));
}
/**
* Applies the given operator on every element of this matrix in parallel
* and returns the result.
*
* @param operator operator to apply on every element of this matrix
* @return result of the operation
*/
public Matrix applyNewParallel(DoubleUnaryOperator operator) {
final Matrix newMatrix = new Matrix(getHeight(), getWidth());
newMatrix.setParallel((j, i) -> operator.applyAsDouble(get(j, i)));
return newMatrix;
}
/**
* Applies the given operator elementwise on every element of this matrix
* and the given one in parallel and returns the result.
*
* @param operand second operand
* @param operator operator to apply on every element of the matricies
* @return result of the operation
*/
public Matrix applyNewParallel(Matrix operand,
DoubleBinaryOperator operator) {
final Matrix newMatrix = new Matrix(getHeight(), getWidth());
newMatrix.setParallel((j, i) ->
operator.applyAsDouble(get(j, i), operand.get(j, i)));
return newMatrix;
}
/**
* Applies the given operator on every element of this matrix and the given
* matrix in parallel elementwise wrapping around and returns the result.
* The result has as many rows and the matrix with more rows and as many
* columns as the matrix with more columns.
*
* @param operand second operand
* @param operator operator to apply on every element of the matricies
* @return result of the operation
*/
public Matrix applyNewDifSizeParallel(Matrix operand,
DoubleBinaryOperator operator) {
final Matrix newMatrix = new Matrix(
Math.max(getHeight(), operand.getHeight()),
Math.max(getWidth(), operand.getWidth()));
newMatrix.setParallel((j, i) -> {
final double value1 = get(j % getHeight(), i % getWidth());
final double value2 = operand.get(
j % operand.getHeight(), i % operand.getWidth());
return operator.applyAsDouble(value1, value2);
});
return newMatrix;
}
/**
* Iterator which iterates over all elements column-row wise.
*/
private class MatrixIterator implements PrimitiveIterator.OfDouble {
/**
* Indices of the next element.
*/
private int row = 0, column = 0;
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
return row < getHeight() && column < getWidth();
}
/**
* {@inheritDoc}
*/
@Override
public double nextDouble() {
if(!hasNext()) {
throw new NoSuchElementException();
}
final double element = get(row, column);
if(++column >= getWidth()) {
column = 0;
row++;
}
return element;
}
}
/**
* Returns and iterator which iterates over all elements column-row wise.
*
* @return iterator which iterates over all elements column-row wise
*/
@Override
public PrimitiveIterator.OfDouble iterator() {
return new MatrixIterator();
}
/**
* {@inheritDoc}
*/
@Override
public void forEach(Consumer<? super Double> action) {
forEachIndices((j, i) -> action.accept(get(j, i)));
}
/**
* Same as forEach but the elements are processed in parallel.
*
* @param action action to be performed for each element
*/
public void forEachParallel(DoubleConsumer action) {
forEachIndicesParallel((j, i) -> action.accept(get(j, i)));
}
/**
* Applies the given consumer to all available indices in this matrix in
* the same order as the iterator traverses them.
*
* @param consumer consumer to be applied on all available indices
*/
public void forEachIndices(BiConsumer<Integer, Integer> consumer) {
for(int j=0; j<getHeight(); j++) {
for(int i=0; i<getWidth(); i++) {
consumer.accept(j, i);
}
}
}
/**
* Applies the given consumer to all available indices in this matrix in
* parallel.
*
* @param consumer consumer to be applied on all available indices
*/
public void forEachIndicesParallel(BiConsumer<Integer, Integer> consumer) {
IntStream.range(0, getHeight()).parallel().forEach((j) ->
IntStream.range(0, getWidth()).parallel().forEach((i) ->
consumer.accept(j, i)));
}
/**
* Generates a BufferedImage by mapping the content of this matrix to the
* pixels of the image with the given colormap.
*
* @param colorMap function that maps values of the matrix to colours
* @return image mapped with the content of this matrix
*/
public BufferedImage toImage(DoubleFunction<Color> colorMap) {
final BufferedImage image = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_RGB);
forEachIndices((j, i) -> {
final double value = get(j, i);
final Color color = colorMap.apply(value);
image.setRGB(i, j, color.getRGB());
});
return image;
}
/**
* Returns a copy of this matrix in 2 dimensional array form
*
* @return copy of this matrix in 2 dimensional array form
*/
public double[][] toArray() {
final double[][] array = new double[getHeight()][getWidth()];
forEachIndices((j, i) -> array[j][i] = get(j, i));
return array;
}
/**
* Returns a string representation of the contents of this matrix.
*
* @return string representation of the contents of this matrix
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
for(double[] array : toArray()) {
builder.append(Arrays.toString(array)).append('\n');
}
return builder.toString();
}
}