-
Notifications
You must be signed in to change notification settings - Fork 461
/
FrameBlock.java
1879 lines (1665 loc) · 61 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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.IntStream;
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.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.codegen.CodegenUtils;
import org.apache.sysds.runtime.controlprogram.caching.CacheBlock;
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.columns.StringArray;
import org.apache.sysds.runtime.frame.data.iterators.IteratorFactory;
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.transform.encode.ColumnEncoderRecode;
import org.apache.sysds.runtime.util.CommonThreadPool;
import org.apache.sysds.runtime.util.DMVUtils;
import org.apache.sysds.runtime.util.DataConverter;
import org.apache.sysds.runtime.util.EMAUtils;
import org.apache.sysds.runtime.util.IndexRange;
import org.apache.sysds.runtime.util.UtilFunctions;
@SuppressWarnings({"rawtypes","unchecked"}) //allow generic native arrays
public class FrameBlock implements CacheBlock, Externalizable {
private static final long serialVersionUID = -3993450030207130665L;
private static final Log LOG = LogFactory.getLog(FrameBlock.class.getName());
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;
/** internal configuration */
private static final boolean REUSE_RECODE_MAPS = true;
/** The number of rows of the FrameBlock */
private int _numRows = -1;
/** 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;
private ColumnMetadata[] _colmeta = null;
/** The data frame data as an ordered list of columns */
private Array[] _coldata = null;
/** Cached size in memory to avoid repeated scans of string columns */
long _msize = -1;
public FrameBlock() {
_numRows = 0;
}
/**
* 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, String[] names) {
this(schema, names, null);
}
public FrameBlock(ValueType[] schema, String[][] data) {
//default column names not materialized
this(schema, null, data);
}
public FrameBlock(ValueType[] schema, String[] names, String[][] data) {
_numRows = 0; //maintained on append
_schema = schema;
_colnames = names;
ensureAllocateMeta();
if(data != null)
for( int i=0; i<data.length; i++ )
appendRow(data[i]);
}
/**
* Get the number of rows of the frame block.
*
* @return number of rows
*/
@Override
public int getNumRows() {
return _numRows;
}
@Override
public double getDouble(int r, int c) {
Object o = get(r, c);
if(o == null || (getSchema()[c] == ValueType.STRING && o.toString().isEmpty()))
return 0;
return UtilFunctions.objectToDouble(getSchema()[c], o);
}
@Override
public double getDoubleNaN(int r, int c) {
Object o = get(r, c);
if(o == null || (getSchema()[c] == ValueType.STRING && o.toString().isEmpty()))
return Double.NaN;
return UtilFunctions.objectToDouble(getSchema()[c], o);
}
@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;
}
public void setNumRows(int numRows) {
_numRows = numRows;
}
/**
* 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 ColumnMetadata[] getColumnMetadata() {
return _colmeta;
}
public ColumnMetadata getColumnMetadata(int c) {
return _colmeta[c];
}
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;
// 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( _numRows < numRows ) {
String[] tmp = new String[getNumColumns()];
int len = numRows - _numRows;
// TODO: Add append N function.
for(int i=0; i<len; i++)
appendRow(tmp);
}
return;
}
//allocate columns if necessary
_coldata = new Array[_schema.length];
for( int j=0; j<_schema.length; j++ )
_coldata[j] = ArrayFactory.allocate(_schema[j], numRows);
_numRows = 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) {
if( _coldata!=null && _coldata.length > 0 && _numRows != newLen )
throw new RuntimeException("Mismatch in number of rows: "+newLen+" (expected: "+_numRows+")");
_numRows = 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));
_msize = -1;
}
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);
}
_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.
*
* @param row array of objects
*/
public void appendRow(Object[] row) {
ensureAllocatedColumns(0);
for( int j=0; j<row.length; j++ )
_coldata[j].append(row[j]);
_numRows++;
}
/**
* Append a row to the end of the data frame, where all row fields
* are string encoded.
*
* @param row array of strings
*/
public void appendRow(String[] row) {
ensureAllocatedColumns(0);
for( int j=0; j<row.length; j++ )
_coldata[j].append(row[j]);
_numRows++;
}
/**
* 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);
_numRows = cols[0].length;
_msize = -1;
}
/**
* 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 String getColumnType(int c){
switch(_schema[c]) {
case STRING: return "String";
case BOOLEAN: return "Boolean";
case INT64: return "Long";
case INT32: return "Int";
case FP64: return "Double";
case FP32: return "Float";
default: return null;
}
}
/**
* Get a specific index as bytes, this method is used to parse the strings into Python.
* It should only be used in columns where the datatype is String.
* Since in other cases it might be faster to return other types.
*
* @param c The column index.
* @param r The row index.
* @return The returned byte array.
*/
public byte[] getIndexAsBytes(int c, int r){
switch(_schema[c]){
case STRING:
String[] col = ((StringArray)_coldata[c]).get();
if(col[r] != null)
return col[r].getBytes();
else
return null;
default:
throw new NotImplementedException();
}
}
/**
* Serialize the columns data as byte.
*
* This serialization is used for transferring the frame to python.
*
* @param c The column index
* @return The columns data as byte array.
*/
public byte[] getColumnAsBytes(int c) {
return _coldata[c].getAsByteArray(getNumRows());
}
public Array getColumn(int c) {
return _coldata[c];
}
public void setColumn(int c, Array column) {
if( _coldata == null )
_coldata = new Array[getNumColumns()];
_coldata[c] = column;
_msize = -1;
}
///////
// serialization / deserialization (implementation of writable and externalizable)
// FIXME for FrameBlock fix write and readFields, it does not work if the Arrays are not yet
// allocated (after fixing remove hack in FederatedWorkerHandler.createFrameEncodeMeta(FederatedRequest) call to
// FrameBlock.ensureAllocatedColumns())
@Override
public void write(DataOutput out) throws IOException {
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++ ) {
byte type = (byte)_schema[j].ordinal();
if( _coldata == null || _coldata[j] == null )
type *= -1; //negative to indicate non-existence
out.writeByte(type);
if( !isDefaultMeta ) {
out.writeUTF(getColumnName(j));
out.writeLong(_colmeta[j].getNumDistinct());
out.writeUTF( (_colmeta[j].getMvValue()!=null) ?
_colmeta[j].getMvValue() : "" );
}
if( type >= 0 )
_coldata[j].write(out);
}
}
@Override
public void readFields(DataInput in) throws IOException {
//read head (rows, cols)
_numRows = in.readInt();
int numCols = in.readInt();
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 : new String[numCols];
_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();
ValueType vt = ValueType.values()[Math.abs(type)];
String name = isDefaultMeta ? createColName(j) : in.readUTF();
long ndistinct = isDefaultMeta ? 0 : in.readLong();
String mvvalue = isDefaultMeta ? null : in.readUTF();
Array arr = type > 0? ArrayFactory.read(in, vt, _numRows): null;
_schema[j] = vt;
_colnames[j] = name;
_colmeta[j] = new ColumnMetadata(ndistinct,
(mvvalue==null || mvvalue.isEmpty()) ? null : mvvalue);
_coldata[j] = arr;
}
_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);
}
////////
// CacheBlock implementation
@Override
public long getInMemorySize() {
//reuse previously computed size
if( _msize > 0 )
return _msize;
//frame block header
long size = 16 + 4; //object, num rows
//schema array (overhead and int entries)
int clen = getNumColumns();
size += 8 + 32 + clen * 4;
//colname array (overhead and string entries)
size += 8 + ((_colnames!=null) ? 32 : 0);
for( int j=0; j<clen && _colnames!=null; j++ )
size += getInMemoryStringSize(getColumnName(j));
//meta data array (overhead and entries)
size += 8 + 32;
for( int j=0; j<clen; j++ ) {
size += 16 + 8 + 8 //object, long num distinct, ref mv
+ getInMemoryStringSize(_colmeta[j].getMvValue());
}
//data array (overhead and entries)
size += 8 + 32 + clen * (16+4+8+32);
for( int j=0; j<clen; j++ ) {
switch( _schema[j] ) {
case BOOLEAN: size += _numRows; break;
case INT64:
case FP64: size += 8*_numRows; break;
case INT32:
case FP32: size += 4*_numRows; break;
case STRING:
StringArray arr = (StringArray)_coldata[j];
for( int i=0; i<_numRows; i++ )
size += getInMemoryStringSize(arr.get(i));
break;
default: //not applicable
}
}
return _msize = size;
}
@Override
public long getExactSerializedSize() {
//header: 2xint, boolean
long size = 9;
//column sizes
boolean isDefaultMeta = isColNamesDefault()
&& isColumnMetadataDefault();
for( int j=0; j<getNumColumns(); j++ ) {
size += 1; //column schema
if( !isDefaultMeta ) {
size += IOUtilFunctions.getUTFSize(getColumnName(j));
size += 8;
size += IOUtilFunctions.getUTFSize(_colmeta[j].getMvValue());
}
switch( _schema[j] ) {
case BOOLEAN: size += _numRows; break;
case INT64:
case FP64: size += 8*_numRows; break;
case INT32:
case FP32: size += 4 * _numRows; break;
case STRING:
StringArray arr = (StringArray)_coldata[j];
for( int i=0; i<_numRows; i++ )
size += IOUtilFunctions.getUTFSize(arr.get(i));
break;
default: //not applicable
}
}
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 &= (_schema[j] != ValueType.STRING);
return ret;
}
@Override
public void toShallowSerializeBlock() {
//do nothing (not applicable).
}
@Override
public void compactEmptyBlock() {
//do nothing
}
/**
* Returns the in-memory size in bytes of the given string value.
*
* @param value string value
* @return in-memory size of string value
*/
private static long getInMemoryStringSize(String value) {
if( value == null )
return 0;
return 16 + 4 + 8 //object, hash, array ref
+ 32 + value.length(); //char array
}
/**
* 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()));
}
}
}
return new FrameBlock(UtilFunctions.nCopies(frameBlock.getNumColumns(), ValueType.BOOLEAN), outputData);
}
private static boolean checkAndSetEmpty(FrameBlock fb1, FrameBlock fb2, String[][] out, int r, int c) {
if(fb1.get(r, c) == null || fb2.get(r, c) == null) {
out[r][c] = (fb1.get(r, c) == null && fb2.get(r, c) == null) ? "true" : "false";
return true;
}
return false;
}
///////
// indexing and append operations
public FrameBlock leftIndexingOperations(FrameBlock rhsFrame, IndexRange ixrange, FrameBlock ret) {
return leftIndexingOperations(rhsFrame,
(int)ixrange.rowStart, (int)ixrange.rowEnd,
(int)ixrange.colStart, (int)ixrange.colEnd, ret);
}
public FrameBlock leftIndexingOperations(FrameBlock rhsFrame, int rl, int ru, int cl, int cu, FrameBlock ret) {
// check the validity of bounds
if ( rl < 0 || rl >= getNumRows() || ru < rl || ru >= getNumRows()
|| cl < 0 || cu >= getNumColumns() || cu < cl || cu >= getNumColumns() ) {
throw new DMLRuntimeException("Invalid values for frame indexing: ["+(rl+1)+":"+(ru+1)+"," + (cl+1)+":"+(cu+1)+"] " +
"must be within frame dimensions ["+getNumRows()+","+getNumColumns()+"].");
}
if ( (ru-rl+1) < rhsFrame.getNumRows() || (cu-cl+1) < rhsFrame.getNumColumns()) {
throw new DMLRuntimeException("Invalid values for frame indexing: " +
"dimensions of the source frame ["+rhsFrame.getNumRows()+"x" + rhsFrame.getNumColumns() + "] " +
"do not match the shape of the frame specified by indices [" +
(rl+1) +":" + (ru+1) + ", " + (cl+1) + ":" + (cu+1) + "].");
}
//allocate output frame (incl deep copy schema)
if( ret == null )
ret = new FrameBlock();
ret._numRows = _numRows;
ret._schema = _schema.clone();
ret._colnames = (_colnames != null) ? _colnames.clone() : null;
ret._colmeta = _colmeta.clone();
ret._coldata = new Array[getNumColumns()];
//copy data to output and partial overwrite w/ rhs
for( int j=0; j<getNumColumns(); j++ ) {
Array tmp = _coldata[j].clone();
if( j>=cl && j<=cu ) {
//fast-path for homogeneous column schemas
if( _schema[j]==rhsFrame._schema[j-cl] )
tmp.set(rl, ru, rhsFrame._coldata[j-cl]);
//general-path for heterogeneous column schemas
else {
for( int i=rl; i<=ru; i++ )
tmp.set(i, UtilFunctions.objectToObject(
_schema[j], rhsFrame._coldata[j-cl].get(i-rl)));
}
}
ret._coldata[j] = tmp;
}
return ret;
}
public FrameBlock slice(IndexRange ixrange, FrameBlock ret) {
return slice(
(int)ixrange.rowStart, (int)ixrange.rowEnd,
(int)ixrange.colStart, (int)ixrange.colEnd, ret);