-
Notifications
You must be signed in to change notification settings - Fork 457
/
FrameBlock.java
1709 lines (1520 loc) · 55.3 KB
/
FrameBlock.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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysds.runtime.frame.data;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sysds.api.DMLException;
import org.apache.sysds.common.Types.ValueType;
import org.apache.sysds.conf.ConfigurationManager;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.codegen.CodegenUtils;
import org.apache.sysds.runtime.controlprogram.caching.CacheBlock;
import org.apache.sysds.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer;
import org.apache.sysds.runtime.controlprogram.parfor.util.IDSequence;
import org.apache.sysds.runtime.frame.data.columns.Array;
import org.apache.sysds.runtime.frame.data.columns.ArrayFactory;
import org.apache.sysds.runtime.frame.data.columns.ColumnMetadata;
import org.apache.sysds.runtime.frame.data.iterators.IteratorFactory;
import org.apache.sysds.runtime.frame.data.lib.FrameFromMatrixBlock;
import org.apache.sysds.runtime.frame.data.lib.FrameLibAppend;
import org.apache.sysds.runtime.frame.data.lib.FrameLibDetectSchema;
import org.apache.sysds.runtime.frame.data.lib.FrameLibRemoveEmpty;
import org.apache.sysds.runtime.frame.data.lib.FrameUtil;
import org.apache.sysds.runtime.functionobjects.ValueComparisonFunction;
import org.apache.sysds.runtime.instructions.cp.BooleanObject;
import org.apache.sysds.runtime.instructions.cp.DoubleObject;
import org.apache.sysds.runtime.instructions.cp.IntObject;
import org.apache.sysds.runtime.instructions.cp.ScalarObject;
import org.apache.sysds.runtime.io.IOUtilFunctions;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.runtime.matrix.data.Pair;
import org.apache.sysds.runtime.matrix.operators.BinaryOperator;
import org.apache.sysds.runtime.meta.DataCharacteristics;
import org.apache.sysds.runtime.meta.MatrixCharacteristics;
import org.apache.sysds.runtime.util.CommonThreadPool;
import org.apache.sysds.runtime.util.DMVUtils;
import org.apache.sysds.runtime.util.EMAUtils;
import org.apache.sysds.runtime.util.IndexRange;
import org.apache.sysds.runtime.util.UtilFunctions;
import org.apache.sysds.utils.MemoryEstimates;
@SuppressWarnings({"rawtypes", "unchecked"}) // allow generic native arrays
public class FrameBlock implements CacheBlock<FrameBlock>, Externalizable {
private static final Log LOG = LogFactory.getLog(FrameBlock.class.getName());
private static final long serialVersionUID = -3993450030207130665L;
private static final IDSequence CLASS_ID = new IDSequence();
/** Buffer size variable: 1M elements, size of default matrix block */
public static final int BUFFER_SIZE = 1 * 1000 * 1000;
/** If debugging is enabled for the FrameBlocks in stable state */
public static boolean debug = false;
/** The schema of the data frame as an ordered list of value types */
private ValueType[] _schema = null;
/** The column names of the data frame as an ordered list of strings, allocated on-demand */
private String[] _colnames = null;
/** The column metadata */
private ColumnMetadata[] _colmeta = null;
/** The data frame data as an ordered list of columns */
private Array[] _coldata = null;
/** Locks on the columns not tied to the columns objects. */
private SoftReference<Object[]> _columnLocks = null;
private int _nRow = 0;
/** Cached size in memory to avoid repeated scans of string columns */
private long _msize = -1;
public FrameBlock() {
}
/**
* Copy constructor for frame blocks, which uses a shallow copy for the schema (column types and names) but a deep
* copy for meta data and actual column data.
*
* @param that frame block
*/
public FrameBlock(FrameBlock that) {
this(that.getSchema(), that.getColumnNames(false));
copy(that);
setColumnMetadata(that.getColumnMetadata());
}
public FrameBlock(int ncols, ValueType vt) {
this(UtilFunctions.nCopies(ncols, vt), null, null);
}
public FrameBlock(ValueType[] schema) {
this(schema, null, null);
}
public FrameBlock(ValueType[] schema, int rlen) {
this(schema, null, null);
_nRow = rlen;
}
public FrameBlock(ValueType[] schema, String[] names) {
this(schema, names, null);
}
public FrameBlock(ValueType[] schema, String[] names, int rlen) {
this(schema, names, null);
_nRow = rlen;
}
public FrameBlock(ValueType[] schema, String[][] data) {
// default column names not materialized
this(schema, null, data);
}
/**
* FrameBlock constructor with constant
*
* @param schema The schema to allocate (also specifying number of columns)
* @param constant The constant to allocate in all cells
* @param nRow the number of rows
*/
public FrameBlock(ValueType[] schema, String constant, int nRow) {
this();
// allocate the values.
_nRow = nRow;
for(int i = 0; i < schema.length; i++)
appendColumn(ArrayFactory.allocate(schema[i], nRow, constant));
}
/**
* allocate a FrameBlock with the given data arrays.
*
* The data is in row major, making the first dimension number of rows. second number of columns.
*
* @param schema the schema to allocate
* @param names The names of the column
* @param data The data.
*/
public FrameBlock(ValueType[] schema, String[] names, String[][] data) {
_schema = schema;
if(names != null) {
_colnames = names;
if(schema.length != names.length)
throw new DMLRuntimeException("Invalid FrameBlock construction, invalid schema and names combination");
}
ensureAllocateMeta();
if(data != null) {
for(int i = 0; i < data.length; i++)
appendRow(data[i]);
}
}
public FrameBlock(ValueType[] schema, String[] colNames, ColumnMetadata[] meta, Array<?>[] data) {
_schema = schema;
_colnames = colNames;
_colmeta = meta;
_coldata = data;
_nRow = data[0].size();
}
/**
* Create a FrameBlock containing columns of the specified arrays
*
* @param data The column data contained
*/
public FrameBlock(Array<?>[] data) {
_schema = new ValueType[data.length];
for(int i = 0; i < data.length; i++)
_schema[i] = data[i].getValueType();
_colnames = null;
ensureAllocateMeta();
_coldata = data;
_nRow = data[0].size();
if(debug) {
for(int i = 0; i < data.length; i++) {
if(data[i].size() != getNumRows())
throw new DMLRuntimeException(
"Invalid Frame allocation with different size arrays " + data[i].size() + " vs " + getNumRows());
}
}
}
/**
* Create a FrameBlock containing columns of the specified arrays and names
*
* @param data The column data contained
* @param colnames The column names of the contained columns
*/
public FrameBlock(Array<?>[] data, String[] colnames) {
_schema = new ValueType[data.length];
for(int i = 0; i < data.length; i++)
_schema[i] = data[i].getValueType();
_colnames = colnames;
ensureAllocateMeta();
_coldata = data;
_nRow = data[0].size();
if(debug) {
for(int i = 0; i < data.length; i++) {
if(data[i].size() != getNumRows())
throw new DMLRuntimeException(
"Invalid Frame allocation with different size arrays " + data[i].size() + " vs " + getNumRows());
}
}
}
/**
* Get the number of rows of the frame block.
*
* @return number of rows
*/
@Override
public int getNumRows() {
return _nRow;
}
@Override
public double getDouble(int r, int c) {
return _coldata[c].getAsDouble(r);
}
@Override
public double getDoubleNaN(int r, int c) {
return _coldata[c].getAsNaNDouble(r);
}
@Override
public String getString(int r, int c) {
Object o = get(r, c);
String s = (o == null) ? null : o.toString();
if(s != null && s.isEmpty())
return null;
return s;
}
/**
* Get the number of columns of the frame block, that is the number of columns defined in the schema.
*
* @return number of columns
*/
@Override
public int getNumColumns() {
return (_schema != null) ? _schema.length : 0;
}
@Override
public DataCharacteristics getDataCharacteristics() {
return new MatrixCharacteristics(getNumRows(), getNumColumns(), -1);
}
/**
* Returns the schema of the frame block.
*
* @return schema as array of ValueTypes
*/
public ValueType[] getSchema() {
return _schema;
}
/**
* Sets the schema of the frame block.
*
* @param schema schema as array of ValueTypes
*/
public void setSchema(ValueType[] schema) {
_schema = schema;
}
/**
* Returns the column names of the frame block. This method allocates default column names if required.
*
* @return column names
*/
public String[] getColumnNames() {
return getColumnNames(true);
}
public FrameBlock getColumnNamesAsFrame() {
FrameBlock fb = new FrameBlock(getNumColumns(), ValueType.STRING);
fb.appendRow(getColumnNames());
return fb;
}
/**
* Returns the column names of the frame block. This method allocates default column names if required.
*
* @param alloc if true, create column names
* @return array of column names
*/
public String[] getColumnNames(boolean alloc) {
if(_colnames == null && alloc)
_colnames = createColNames(getNumColumns());
return _colnames;
}
/**
* Returns the column name for the requested column. This method allocates default column names if required.
*
* @param c column index
* @return column name
*/
public String getColumnName(int c) {
if(_colnames == null)
_colnames = createColNames(getNumColumns());
return _colnames[c];
}
public void setColumnNames(String[] colnames) {
_colnames = colnames;
}
public void setColumnName(int index, String name) {
if(_colnames == null)
_colnames = createColNames(getNumColumns());
_colnames[index] = name;
}
public ColumnMetadata[] getColumnMetadata() {
return _colmeta;
}
public ColumnMetadata getColumnMetadata(int c) {
return _colmeta[c];
}
public Array<?>[] getColumns() {
return _coldata;
}
public boolean isColumnMetadataDefault() {
boolean ret = true;
for(int j = 0; j < getNumColumns() && ret; j++)
ret &= isColumnMetadataDefault(j);
return ret;
}
public boolean isColumnMetadataDefault(int c) {
return _colmeta[c].isDefault();
}
public void setColumnMetadata(ColumnMetadata[] colmeta) {
System.arraycopy(colmeta, 0, _colmeta, 0, _colmeta.length);
}
public void setColumnMetadata(int c, ColumnMetadata colmeta) {
_colmeta[c] = colmeta;
}
/**
* Creates a mapping from column names to column IDs, i.e., 1-based column indexes
*
* @return map of column name keys and id values
*/
public Map<String, Integer> getColumnNameIDMap() {
Map<String, Integer> ret = new HashMap<>();
for(int j = 0; j < getNumColumns(); j++)
ret.put(getColumnName(j), j + 1);
return ret;
}
/**
* Allocate column data structures if necessary, i.e., if schema specified but not all column data structures created
* yet.
*
* @param numRows number of rows
*/
public void ensureAllocatedColumns(int numRows) {
_msize = -1;
final int nRow = getNumRows();
// allocate column meta data if necessary
ensureAllocateMeta();
// early abort if already allocated
if(_coldata != null && _schema.length == _coldata.length) {
// handle special case that to few rows allocated
if(nRow < numRows) {
String[] tmp = new String[getNumColumns()];
int len = numRows - nRow;
// TODO: Add append N function.
for(int i = 0; i < len; i++)
appendRow(tmp);
}
return;
}
else {
// allocate columns if necessary
_coldata = new Array[_schema.length];
if(numRows > 0)
for(int j = 0; j < _schema.length; j++)
_coldata[j] = ArrayFactory.allocate(_schema[j], numRows);
_nRow = numRows;
}
}
private void ensureAllocateMeta() {
if(_colmeta == null || _schema.length != _colmeta.length) {
_colmeta = new ColumnMetadata[_schema.length];
for(int j = 0; j < _schema.length; j++)
_colmeta[j] = new ColumnMetadata();
}
}
/**
* Checks for matching column sizes in case of existing columns.
*
* If the check parses the number of rows is reassigned to the given newLen
*
* @param newLen number of rows to compare with existing number of rows
*/
public void ensureColumnCompatibility(int newLen) {
final int nRow = getNumRows();
if(_coldata != null && _coldata.length > 0 && ((nRow == 0) || nRow != newLen)) {
throw new RuntimeException("Mismatch in number of rows: " + newLen + " (expected: " + nRow + ")");
}
_nRow = newLen;
}
public static String[] createColNames(int size) {
return createColNames(0, size);
}
public static String[] createColNames(int off, int size) {
String[] ret = new String[size];
for(int i = off + 1; i <= off + size; i++)
ret[i - off - 1] = createColName(i);
return ret;
}
public static String createColName(int i) {
return "C" + i;
}
public boolean isColNamesDefault() {
boolean ret = (_colnames != null);
for(int j = 0; j < getNumColumns() && ret; j++)
ret &= isColNameDefault(j);
return ret;
}
public boolean isColNameDefault(int i) {
return _colnames == null || _colnames[i].equals("C" + (i + 1));
}
public void recomputeColumnCardinality() {
for(int j = 0; j < getNumColumns(); j++) {
int card = 0;
for(int i = 0; i < getNumRows(); i++)
card += (get(i, j) != null) ? 1 : 0;
_colmeta[j].setNumDistinct(card);
}
}
///////
// basic get and set functionality
/**
* Gets a boxed object of the value in position (r,c).
*
* @param r row index, 0-based
* @param c column index, 0-based
* @return object of the value at specified position
*/
public Object get(int r, int c) {
return _coldata[c].get(r);
}
/**
* Sets the value in position (r,c), where the input is assumed to be a boxed object consistent with the schema
* definition.
*
* @param r row index
* @param c column index
* @param val value to set at specified position
*/
public void set(int r, int c, Object val) {
_coldata[c].set(r, UtilFunctions.objectToObject(_schema[c], val));
}
/**
* Sets the value in position (r,c), to the input string value, and at the individual arrays, convert to correct
* type.
*
* @param r row index
* @param c column index
* @param val value to set at specified position
*/
public void set(int r, int c, String val) {
_coldata[c].set(r, val);
}
public void reset(int nrow, boolean clearMeta) {
if(clearMeta) {
_schema = null;
_colnames = null;
if(_colmeta != null) {
for(int i = 0; i < _colmeta.length; i++)
if(!isColumnMetadataDefault(i))
_colmeta[i] = new ColumnMetadata();
}
}
if(_coldata != null) {
for(int i = 0; i < _coldata.length; i++)
_coldata[i].reset(nrow);
}
_nRow = nrow;
_msize = -1;
}
public void reset() {
reset(0, true);
}
/**
* Append a row to the end of the data frame, where all row fields are boxed objects according to the schema.
*
* Append row should be avoided if possible.
*
* @param row array of objects
*/
public void appendRow(Object[] row) {
if(row.length != _schema.length)
throw new DMLRuntimeException("Invalid number of values in rowAppend");
if(_nRow == 0) {
ensureAllocateMeta();
_coldata = new Array[_schema.length];
for(int j = 0; j < _schema.length; j++) {
_coldata[j] = ArrayFactory.allocate(_schema[j], 1);
_coldata[j].set(0, row[j]);
}
}
else {
for(int j = 0; j < row.length; j++)
_coldata[j].append(row[j]);
}
_nRow++;
_msize = -1;
}
/**
* Append a row to the end of the data frame, where all row fields are string encoded.
*
* Append row should be avoided if possible
*
* @param row array of strings
*/
public void appendRow(String[] row) {
if(row.length != _schema.length)
throw new DMLRuntimeException("Invalid number of values in rowAppend");
else if(_nRow == 0) {
ensureAllocateMeta();
_coldata = new Array[_schema.length];
for(int j = 0; j < _schema.length; j++) {
_coldata[j] = ArrayFactory.allocate(_schema[j], 1);
_coldata[j].set(0, row[j]);
}
}
else {
for(int j = 0; j < row.length; j++)
_coldata[j].append(row[j]);
}
_nRow++;
_msize = -1;
}
/**
* Append a column of value type STRING as the last column of the data frame. The given array is wrapped but not
* copied and hence might be updated in the future.
*
* @param col array of strings
*/
public void appendColumn(String[] col) {
ensureColumnCompatibility(col.length);
appendColumnMetaData(ValueType.STRING);
_coldata = FrameUtil.add(_coldata, ArrayFactory.create(col));
}
/**
* Append a column of value type BOOLEAN as the last column of the data frame. The given array is wrapped but not
* copied and hence might be updated in the future.
*
* @param col array of booleans
*/
public void appendColumn(boolean[] col) {
ensureColumnCompatibility(col.length);
appendColumnMetaData(ValueType.BOOLEAN);
_coldata = FrameUtil.add(_coldata, ArrayFactory.create(col));
}
/**
* Append a column of value type INT as the last column of the data frame. The given array is wrapped but not copied
* and hence might be updated in the future.
*
* @param col array of longs
*/
public void appendColumn(int[] col) {
ensureColumnCompatibility(col.length);
appendColumnMetaData(ValueType.INT32);
_coldata = FrameUtil.add(_coldata, ArrayFactory.create(col));
}
/**
* Append a column of value type LONG as the last column of the data frame. The given array is wrapped but not copied
* and hence might be updated in the future.
*
* @param col array of longs
*/
public void appendColumn(long[] col) {
ensureColumnCompatibility(col.length);
appendColumnMetaData(ValueType.INT64);
_coldata = FrameUtil.add(_coldata, ArrayFactory.create(col));
}
/**
* Append a column of value type float as the last column of the data frame. The given array is wrapped but not
* copied and hence might be updated in the future.
*
* @param col array of doubles
*/
public void appendColumn(float[] col) {
ensureColumnCompatibility(col.length);
appendColumnMetaData(ValueType.FP32);
_coldata = FrameUtil.add(_coldata, ArrayFactory.create(col));
}
/**
* Append a column of value type DOUBLE as the last column of the data frame. The given array is wrapped but not
* copied and hence might be updated in the future.
*
* @param col array of doubles
*/
public void appendColumn(double[] col) {
ensureColumnCompatibility(col.length);
appendColumnMetaData(ValueType.FP64);
_coldata = FrameUtil.add(_coldata, ArrayFactory.create(col));
}
/**
* Append the metadata associated with adding a column.
*
* @param vt The Value type
*/
private void appendColumnMetaData(ValueType vt) {
if(_colnames != null)
_colnames = (String[]) ArrayUtils.add(getColumnNames(), createColName(_colnames.length + 1));
_schema = (ValueType[]) ArrayUtils.add(_schema, vt);
_colmeta = (ColumnMetadata[]) ArrayUtils.add(getColumnMetadata(), new ColumnMetadata());
_msize = -1;
}
/**
* Append a set of column of value type DOUBLE at the end of the frame in order to avoid repeated allocation with
* appendColumns. The given array is wrapped but not copied and hence might be updated in the future.
*
* @param cols 2d array of doubles
*/
public void appendColumns(double[][] cols) {
int ncol = cols.length;
boolean empty = (_schema == null);
ValueType[] tmpSchema = UtilFunctions.nCopies(ncol, ValueType.FP64);
Array[] tmpData = new Array[ncol];
for(int j = 0; j < ncol; j++)
tmpData[j] = ArrayFactory.create(cols[j]);
_colnames = empty ? null : (String[]) ArrayUtils.addAll(getColumnNames(), createColNames(getNumColumns(), ncol)); // before
// schema
// modification
_schema = empty ? tmpSchema : (ValueType[]) ArrayUtils.addAll(_schema, tmpSchema);
_coldata = empty ? tmpData : (Array[]) ArrayUtils.addAll(_coldata, tmpData);
_nRow = cols[0].length;
_msize = -1;
}
public static FrameBlock convertToFrameBlock(MatrixBlock mb, ValueType[] schema, int k) {
return FrameFromMatrixBlock.convertToFrameBlock(mb, schema, k);
}
/**
* Add a column of already allocated Array type.
*
* @param col column to add.
*/
public void appendColumn(Array col) {
ensureColumnCompatibility(col.size());
appendColumnMetaData(col.getValueType());
_coldata = FrameUtil.add(_coldata, col);
}
public Object getColumnData(int c) {
return _coldata[c].get();
}
public ValueType getColumnType(int c) {
return _schema[c];
}
public Array<?> getColumn(int c) {
return _coldata[c];
}
public void setColumn(int c, Array<?> column) {
if(_coldata == null) {
_coldata = new Array[getNumColumns()];
_nRow = column.size();
}
if(column.size() != _nRow)
throw new DMLRuntimeException("Invalid number of rows in set column");
_coldata[c] = column;
_msize = -1;
}
@Override
public void write(DataOutput out) throws IOException {
final boolean isDefaultMeta = isColNamesDefault() && isColumnMetadataDefault();
// write header (rows, cols, default)
out.writeInt(getNumRows());
out.writeInt(getNumColumns());
out.writeBoolean(isDefaultMeta);
// write columns (value type, data)
for(int j = 0; j < getNumColumns(); j++) {
final byte type = getTypeForIO(j);
out.writeByte(type);
if(!isDefaultMeta) {
out.writeUTF(getColumnName(j));
_colmeta[j].write(out);
}
if(type >= 0) // if allocated write column data
_coldata[j].write(out);
}
}
private byte getTypeForIO(int col) {
// ! +1 to allow reflecting around zero if not allocated
byte type = (byte) (_schema[col].ordinal() + 1);
if(_coldata == null || _coldata[col] == null)
type *= -1; // negative to indicate not allocated
return type;
}
private ValueType interpretByteAsType(byte type) {
return ValueType.values()[Math.abs(type) - 1];
}
@Override
public void readFields(DataInput in) throws IOException {
// read head (rows, cols)
_nRow = in.readInt();
final int numCols = in.readInt();
final boolean isDefaultMeta = in.readBoolean();
// allocate schema/meta data arrays
_schema = (_schema != null && _schema.length == numCols) ? _schema : new ValueType[numCols];
_colnames = (_colnames != null && _colnames.length == numCols) ? _colnames : // if already allocated reuse
isDefaultMeta ? null : new String[numCols]; // if meta is default allocate on demand
_colmeta = (_colmeta != null && _colmeta.length == numCols) ? _colmeta : new ColumnMetadata[numCols];
_coldata = (_coldata != null && _coldata.length == numCols) ? _coldata : new Array[numCols];
// read columns (value type, meta, data)
for(int j = 0; j < numCols; j++) {
byte type = in.readByte();
_schema[j] = interpretByteAsType(type);
if(!isDefaultMeta) { // If not default meta read in meta
_colnames[j] = in.readUTF();
_colmeta[j] = ColumnMetadata.read(in);
}
else
_colmeta[j] = new ColumnMetadata(); // must be allocated.
if(type >= 0) // if in allocated column data then read it
_coldata[j] = ArrayFactory.read(in, _nRow);
}
_msize = -1;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// redirect serialization to writable impl
write(out);
}
@Override
public void readExternal(ObjectInput in) throws IOException {
// redirect deserialization to writable impl
readFields(in);
}
@Override
public long getInMemorySize() {
// reuse previously computed size
if(_msize > 0)
return _msize;
// frame block header
double size = 16 + 4; // object, msize
final int clen = getNumColumns();
// schema array (overhead and int entries)
size += MemoryEstimates.byteArrayCost(clen);
// col name array (overhead and string entries)
size += _colnames == null ? 8 : MemoryEstimates.stringArrayCost(_colnames);
// meta data array (overhead and entries)
size += MemoryEstimates.objectArrayCost(clen);
for(ColumnMetadata mtd : _colmeta)
size += mtd == null ? 8 : mtd.getInMemorySize();
// data array
size += MemoryEstimates.objectArrayCost(clen);
size += arraysSizeInMemory();
return _msize = (long) size;
}
private double arraysSizeInMemory() {
final int clen = getNumColumns();
final int rlen = getNumRows();
double size = 0;
if(_coldata == null) // not allocated estimate if allocated
for(int j = 0; j < clen; j++)
size += ArrayFactory.getInMemorySize(_schema[j], rlen);
else {// allocated
if(rlen > 1000 && clen > 10 && ConfigurationManager.isParallelIOEnabled()) {
final ExecutorService pool = CommonThreadPool.get(InfrastructureAnalyzer.getLocalParallelism());
try {
size += pool.submit(() -> {
return Arrays.stream(_coldata).parallel() // parallel columns
.map(x -> x.getInMemorySize()).reduce(0L, Long::sum);
}).get();
pool.shutdown();
}
catch(InterruptedException | ExecutionException e) {
pool.shutdown();
LOG.error(e);
for(Array<?> aa : _coldata)
size += aa.getInMemorySize();
}
}
else {
for(Array<?> aa : _coldata)
size += aa.getInMemorySize();
}
}
return size;
}
@Override
public long getExactSerializedSize() {
// header: 2 x int, boolean
long size = 4 + 4 + 1;
size += 1 * getNumColumns(); // column schema
// column sizes
final boolean isDefaultMeta = isColNamesDefault() && isColumnMetadataDefault();
for(int j = 0; j < getNumColumns(); j++) {
final byte type = getTypeForIO(j);
if(!isDefaultMeta) {
size += IOUtilFunctions.getUTFSize(getColumnName(j));
size += _colmeta[j].getExactSerializedSize();
}
if(type >= 0)
size += _coldata[j].getExactSerializedSize();
}
return size;
}
@Override
public boolean isShallowSerialize() {
return isShallowSerialize(false);
}
@Override
public boolean isShallowSerialize(boolean inclConvert) {
// shallow serialize if non-string schema because a frame block
// is always dense but strings have large array overhead per cell
boolean ret = true;
for(int j = 0; j < _schema.length && ret; j++)
ret &= _coldata[j].isShallowSerialize();
return ret;
}
@Override
public void toShallowSerializeBlock() {
// do nothing (not applicable).
}
@Override
public void compactEmptyBlock() {
// do nothing
}
/**
* This method performs the value comparison on two frames if the values in both frames are equal, not equal, less
* than, greater than, less than/greater than and equal to the output frame will store boolean value for each each
* comparison
*
* @param bop binary operator
* @param that frame block of rhs of m * n dimensions
* @param out output frame block
* @return a boolean frameBlock
*/
public FrameBlock binaryOperations(BinaryOperator bop, FrameBlock that, FrameBlock out) {
if(getNumColumns() != that.getNumColumns() && getNumRows() != that.getNumColumns())
throw new DMLRuntimeException("Frame dimension mismatch " + getNumRows() + " * " + getNumColumns() + " != "
+ that.getNumRows() + " * " + that.getNumColumns());
String[][] outputData = new String[getNumRows()][getNumColumns()];
// compare output value, incl implicit type promotion if necessary
if(bop.fn instanceof ValueComparisonFunction) {
ValueComparisonFunction vcomp = (ValueComparisonFunction) bop.fn;
out = executeValueComparisons(this, that, vcomp, outputData);
}
else
throw new DMLRuntimeException("Unsupported binary operation on frames (only comparisons supported)");
return out;
}
private FrameBlock executeValueComparisons(FrameBlock frameBlock, FrameBlock that, ValueComparisonFunction vcomp,
String[][] outputData) {
for(int i = 0; i < getNumColumns(); i++) {
if(getSchema()[i] == ValueType.STRING || that.getSchema()[i] == ValueType.STRING) {
for(int j = 0; j < getNumRows(); j++) {
if(checkAndSetEmpty(frameBlock, that, outputData, j, i))
continue;
String v1 = UtilFunctions.objectToString(get(j, i));
String v2 = UtilFunctions.objectToString(that.get(j, i));
outputData[j][i] = String.valueOf(vcomp.compare(v1, v2));
}
}
else if(getSchema()[i] == ValueType.FP64 || that.getSchema()[i] == ValueType.FP64 ||
getSchema()[i] == ValueType.FP32 || that.getSchema()[i] == ValueType.FP32) {
for(int j = 0; j < getNumRows(); j++) {
if(checkAndSetEmpty(frameBlock, that, outputData, j, i))
continue;
ScalarObject so1 = new DoubleObject(Double.parseDouble(get(j, i).toString()));
ScalarObject so2 = new DoubleObject(Double.parseDouble(that.get(j, i).toString()));
outputData[j][i] = String.valueOf(vcomp.compare(so1.getDoubleValue(), so2.getDoubleValue()));
}
}
else if(getSchema()[i] == ValueType.INT64 || that.getSchema()[i] == ValueType.INT64 ||
getSchema()[i] == ValueType.INT32 || that.getSchema()[i] == ValueType.INT32) {
for(int j = 0; j < this.getNumRows(); j++) {
if(checkAndSetEmpty(frameBlock, that, outputData, j, i))
continue;
ScalarObject so1 = new IntObject(Integer.parseInt(get(j, i).toString()));
ScalarObject so2 = new IntObject(Integer.parseInt(that.get(j, i).toString()));
outputData[j][i] = String.valueOf(vcomp.compare(so1.getLongValue(), so2.getLongValue()));
}
}
else {
for(int j = 0; j < getNumRows(); j++) {
if(checkAndSetEmpty(frameBlock, that, outputData, j, i))
continue;
ScalarObject so1 = new BooleanObject(Boolean.parseBoolean(get(j, i).toString()));
ScalarObject so2 = new BooleanObject(Boolean.parseBoolean(that.get(j, i).toString()));
outputData[j][i] = String.valueOf(vcomp.compare(so1.getBooleanValue(), so2.getBooleanValue()));
}
}
}