-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Transposer.cs
1757 lines (1558 loc) · 80.5 KB
/
Transposer.cs
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 .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.ML.Runtime.CommandLine;
using Microsoft.ML.Runtime.Data.IO;
using Microsoft.ML.Runtime.Internal.Utilities;
namespace Microsoft.ML.Runtime.Data
{
/// <summary>
/// This provides a scalable method of getting a "transposed" view of a subset of columns from an
/// <see cref="IDataView"/>. Instances of <see cref="Transposer"/> act like a wrapped version of
/// the input dataview, except that an indicated set of columns will be transposable, even if they
/// were not transposable before. Note that transposition is a somewhat slow and resource intensive
/// operation.
/// </summary>
public sealed class Transposer : ITransposeDataView, IDisposable
{
private readonly IHost _host;
// The input view.
private readonly IDataView _view;
// Note that the transposer will still present things as transposed, if the input was a transpose
// dataview and that thing was listed as transposed.
private readonly ITransposeDataView _tview;
private readonly Dictionary<string, int> _nameToICol;
// The following may be null, if no columns needed to be split.
private readonly BinaryLoader _splitView;
public readonly int RowCount;
// -1 for input columns that were not transposed, a non-negative index into _cols for those that were.
private readonly int[] _inputToTransposed;
private readonly ColumnInfo[] _cols;
private readonly int[] _splitLim;
private readonly SchemaImpl _tschema;
private bool _disposed;
public ITransposeSchema TransposeSchema { get { return _tschema; } }
/// <summary>
/// Creates an instance given a list of column names.
/// </summary>
/// <param name="env">The host environment</param>
/// <param name="view">The view whose columns we want to transpose</param>
/// <param name="forceSave">Whether the internal transposer should always unconditionally
/// save the column we are transposing. Can be useful if the original dataview is possibly
/// slow to iterate over that column.</param>
/// <param name="columns">The non-empty list of columns to transpose</param>
public static Transposer Create(IHostEnvironment env, IDataView view, bool forceSave,
params string[] columns)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register("Transposer");
h.CheckValue(view, nameof(view));
var indices = CheckNamesAndGetIndices(h, view, columns);
return new Transposer(h, view, forceSave, indices);
}
/// <summary>
/// Creates an instance given a list of column indices.
/// </summary>
/// <param name="env">The host environment</param>
/// <param name="view">The view whose columns we want to transpose</param>
/// <param name="forceSave">Whether the internal transposer should always unconditionally
/// save the column we are transposing. Can be useful if the original dataview is possibly
/// slow to iterate over that column.</param>
/// <param name="columns">The non-empty list of columns to transpose</param>
public static Transposer Create(IHostEnvironment env, IDataView view, bool forceSave,
params int[] columns)
{
Contracts.CheckValue(env, nameof(env));
var host = env.Register("Transposer");
host.CheckValue(view, nameof(view));
var indices = CheckIndices(host, view, columns);
return new Transposer(host, view, forceSave, indices);
}
private Transposer(IHost host, IDataView view, bool forceSave, int[] columns)
{
Contracts.AssertValue(host);
_host = host;
_host.AssertValue(view);
_host.CheckParam(Utils.Size(columns) > 0, nameof(columns), "Cannot be empty");
// REVIEW: Might be a good idea to not have the view as is, but to
// instead apply choose columns to it first. This could simplify some of
// the operations.
_view = view;
_tview = _view as ITransposeDataView;
// Remove duplicates and ensure it is sorted.
IEnumerable<int> columnSet = columns.Distinct().OrderBy(c => c);
if (_tview != null)
{
var ttschema = _tview.TransposeSchema;
// Keep only those columns for which we do not have a slot view already.
columnSet = columnSet.Where(c => ttschema.GetSlotType(c) == null);
}
columns = columnSet.ToArray();
_cols = new ColumnInfo[columns.Length];
var schema = _view.Schema;
_nameToICol = new Dictionary<string, int>();
_inputToTransposed = Utils.CreateArray(schema.ColumnCount, -1);
for (int c = 0; c < columns.Length; ++c)
{
_nameToICol[(_cols[c] = ColumnInfo.CreateFromIndex(schema, columns[c])).Name] = c;
_inputToTransposed[columns[c]] = c;
}
using (var ch = _host.Start("Init"))
{
var args = new BinarySaver.Arguments();
// Run deflate at a slightly degraded level, since we anticipate that this is
// a read-once situation, as opposed to general IDVs which we expect to be run
// multiple times.
args.Compression = CompressionKind.Default;
// Our access into the file will be more or less
// unstructured and random consistently so keep
// the block size pretty safe.
args.MaxBytesPerBlock = 1 << 28;
args.Silent = true;
var saver = new BinarySaver(_host, args);
for (int c = 0; c < _cols.Length; ++c)
{
// REVIEW: Despite not *necessarily* relying on the serialization
// for the transposition, I'm still going to insist on serialization,
// since it would be strange if the same type failed or not in the
// transposer depending on the size. At least as a user, that would
// surprise me. Also I expect this to never happen...
var type = schema.GetColumnType(_cols[c].Index);
if (!saver.IsColumnSavable(type))
throw ch.ExceptParam(nameof(view), "Column named '{0}' is not serializable by the transposer", _cols[c].Name);
if (type.IsVector && !type.IsKnownSizeVector)
throw ch.ExceptParam(nameof(view), "Column named '{0}' is vector, but not of known size, and so cannot be transposed", _cols[c].Name);
}
var slicer = new DataViewSlicer(_host, view, columns);
var slicerSchema = slicer.Schema;
ch.Assert(Enumerable.Range(0, slicerSchema.ColumnCount).All(c => saver.IsColumnSavable(slicerSchema.GetColumnType(c))));
_splitLim = new int[_cols.Length];
List<int> toSave = new List<int>();
int offset = 0;
int slicedCount = 0;
for (int c = 0; c < _cols.Length; ++c)
{
int min;
int lim;
slicer.InColToOutRange(c, out min, out lim);
// It must be a passthrough. We're not going to write it, and will just rely
// on the original view to provide the column.
ch.Assert(min < lim);
int count = lim - min;
if (forceSave || count > 1)
{
toSave.AddRange(Enumerable.Range(min, count));
slicedCount++;
offset += count;
}
_splitLim[c] = offset;
}
long rowCount;
ch.Trace("{0} of {1} input columns sliced into {2} columns", slicedCount, _cols.Length, toSave.Count);
if (toSave.Count > 0)
{
// Only bother to create _splitView if we have to.
var stream = new HybridMemoryStream();
saver.SaveData(stream, slicer, toSave.ToArray());
stream.Seek(0, SeekOrigin.Begin);
ch.Trace("Sliced data saved to {0} bytes", stream.Length);
var loaderArgs = new BinaryLoader.Arguments();
_splitView = new BinaryLoader(_host, loaderArgs, stream, leaveOpen: false);
rowCount = DataViewUtils.ComputeRowCount(_splitView);
}
else
rowCount = DataViewUtils.ComputeRowCount(_view);
ch.Assert(rowCount >= 0);
if (rowCount > Utils.ArrayMaxSize)
throw _host.ExceptParam(nameof(view), "View has {0} rows, we cannot transpose with more than {1}", rowCount, Utils.ArrayMaxSize);
RowCount = (int)rowCount;
_tschema = new SchemaImpl(this);
ch.Done();
}
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
if (_splitView != null)
_splitView.Dispose();
}
}
private static int[] CheckNamesAndGetIndices(IHost host, IDataView view, string[] columns)
{
Contracts.AssertValue(host, "host");
host.AssertValue(view, "view");
host.CheckParam(Utils.Size(columns) > 0, nameof(columns), "Cannot be empty");
var schema = view.Schema;
int[] indices = new int[columns.Length];
for (int c = 0; c < columns.Length; ++c)
{
if (!schema.TryGetColumnIndex(columns[c], out indices[c]))
throw host.ExceptParam(nameof(columns), "Column named '{0}' not found", columns[c]);
}
return indices;
}
private static int[] CheckIndices(IHost host, IDataView view, int[] columns)
{
Contracts.AssertValue(host);
host.AssertValue(view);
var schema = view.Schema;
for (int c = 0; c < columns.Length; ++c)
{
if (!(0 <= columns[c] && columns[c] < schema.ColumnCount))
throw host.ExceptParam(nameof(columns), "Column index {0} illegal for data with {1} column", columns[c], schema.ColumnCount);
}
return columns;
}
public ISlotCursor GetSlotCursor(int col)
{
_host.CheckParam(0 <= col && col < _tschema.ColumnCount, nameof(col));
if (_inputToTransposed[col] == -1)
{
// Check if the parent view has this slot transposed. If it doesn't, fail.
if (_tview != null && _tview.TransposeSchema.GetSlotType(col) != null)
return _tview.GetSlotCursor(col);
throw _host.ExceptParam(nameof(col), "Bad call to GetSlotCursor on untransposable column '{0}'",
_tschema.GetColumnName(col));
}
var type = _tschema.GetSlotType(col).ItemType.RawType;
var tcol = _inputToTransposed[col];
_host.Assert(0 <= tcol && tcol < _cols.Length);
_host.Assert(_cols[tcol].Index == col);
return Utils.MarshalInvoke(GetSlotCursorCore<int>, type, col);
}
private ISlotCursor GetSlotCursorCore<T>(int col)
{
if (_tschema.GetColumnType(col).IsVector)
return new SlotCursorVec<T>(this, col);
return new SlotCursorOne<T>(this, col);
}
#region IDataView implementation stuff, passthrough on to view.
// It is helpful to have transposed data views actually implement dataview, since
// we are still and will likely forever remain in a state where only a few specialized
// operations make use of the transpose dataview, with many operations instead being
// handled in the standard row-wise fashion.
public ISchema Schema { get { return _view.Schema; } }
public bool CanShuffle { get { return _view.CanShuffle; } }
public IRowCursor GetRowCursor(Func<int, bool> predicate, IRandom rand = null)
{
return _view.GetRowCursor(predicate, rand);
}
public IRowCursor[] GetRowCursorSet(out IRowCursorConsolidator consolidator, Func<int, bool> predicate, int n, IRandom rand = null)
{
return _view.GetRowCursorSet(out consolidator, predicate, n, rand);
}
public long? GetRowCount(bool lazy = true)
{
// Not a passthrough.
return RowCount;
}
#endregion
private sealed class SchemaImpl : ITransposeSchema
{
private readonly Transposer _parent;
private readonly IExceptionContext _ectx;
private readonly VectorType[] _slotTypes;
private ISchema InputSchema { get { return _parent._view.Schema; } }
public int ColumnCount { get { return InputSchema.ColumnCount; } }
public SchemaImpl(Transposer parent)
{
Contracts.AssertValue(parent, "parent");
Contracts.AssertValue(parent._host, "parent");
_parent = parent;
_ectx = _parent._host;
_slotTypes = new VectorType[_parent._cols.Length];
for (int c = 0; c < _slotTypes.Length; ++c)
{
ColumnInfo srcInfo = _parent._cols[c];
var ctype = srcInfo.Type.ItemType;
_ectx.Assert(ctype.IsPrimitive);
_slotTypes[c] = new VectorType(ctype.AsPrimitive, _parent.RowCount);
}
}
public bool TryGetColumnIndex(string name, out int col)
{
_ectx.CheckValueOrNull(name);
return InputSchema.TryGetColumnIndex(name, out col);
}
public string GetColumnName(int col)
{
return InputSchema.GetColumnName(col);
}
public ColumnType GetColumnType(int col)
{
return InputSchema.GetColumnType(col);
}
public IEnumerable<KeyValuePair<string, ColumnType>> GetMetadataTypes(int col)
{
return InputSchema.GetMetadataTypes(col);
}
public ColumnType GetMetadataTypeOrNull(string kind, int col)
{
return InputSchema.GetMetadataTypeOrNull(kind, col);
}
public void GetMetadata<TValue>(string kind, int col, ref TValue value)
{
InputSchema.GetMetadata(kind, col, ref value);
}
public VectorType GetSlotType(int col)
{
_ectx.Check(0 <= col && col < ColumnCount, "col");
if (_parent._inputToTransposed[col] == -1)
{
if (_parent._tview != null)
return _parent._tview.TransposeSchema.GetSlotType(col);
return null;
}
return _slotTypes[_parent._inputToTransposed[col]];
}
}
private abstract class SlotCursor<T> : RootCursorBase, ISlotCursor
{
private readonly Transposer _parent;
private readonly int _col;
private ValueGetter<VBuffer<T>> _getter;
public override long Batch { get { return 0; } }
protected SlotCursor(Transposer parent, int col)
: base(parent._host)
{
Ch.Assert(0 <= col && col < parent.Schema.ColumnCount);
_parent = parent;
_col = col;
}
public override ValueGetter<UInt128> GetIdGetter()
{
return
(ref UInt128 val) =>
{
Ch.Check(IsGood, "Cannot call ID getter in current state");
val = new UInt128((ulong)Position, 0);
};
}
public ValueGetter<VBuffer<TValue>> GetGetter<TValue>()
{
if (_getter == null)
_getter = GetGetterCore();
ValueGetter<VBuffer<TValue>> getter = _getter as ValueGetter<VBuffer<TValue>>;
if (getter == null)
throw Ch.Except("Invalid TValue: '{0}'", typeof(TValue));
return getter;
}
public VectorType GetSlotType()
{
return _parent.TransposeSchema.GetSlotType(_col);
}
protected abstract ValueGetter<VBuffer<T>> GetGetterCore();
}
private sealed class SlotCursorOne<T> : SlotCursor<T>
{
private readonly IDataView _view;
private readonly int _col;
private readonly int _len;
public SlotCursorOne(Transposer parent, int col)
: base(parent, col)
{
Ch.Assert(0 <= col && col < parent.Schema.ColumnCount);
int iinfo = parent._inputToTransposed[col];
Ch.Assert(iinfo >= 0);
int smin = iinfo == 0 ? 0 : parent._splitLim[iinfo - 1];
if (parent._splitLim[iinfo] == smin)
{
// This is a passthrough column.
_view = parent._view;
_col = parent._cols[iinfo].Index;
}
else
{
_view = parent._splitView;
_col = smin;
Ch.Assert(parent._splitLim[iinfo] - _col == 1);
}
Ch.AssertValue(_view);
Ch.Assert(_view.Schema.GetColumnType(_col).IsPrimitive);
Ch.Assert(_view.Schema.GetColumnType(_col).RawType == typeof(T));
_len = parent.RowCount;
}
protected override bool MoveNextCore()
{
// We only can move next on one slot, since this is a scalar column.
return State == CursorState.NotStarted;
}
protected override ValueGetter<VBuffer<T>> GetGetterCore()
{
var isDefault = Conversion.Conversions.Instance.GetIsDefaultPredicate<T>(_view.Schema.GetColumnType(_col));
bool valid = false;
VBuffer<T> cached = default(VBuffer<T>);
return
(ref VBuffer<T> dst) =>
{
Ch.Check(IsGood, "Cannot get values in the cursor's current state");
if (!valid)
{
using (var cursor = _view.GetRowCursor(c => c == _col))
{
int[] indices = null;
T[] values = null;
int len = -1;
int count = 0;
T value = default(T);
ValueGetter<T> getter = cursor.GetGetter<T>(_col);
while (cursor.MoveNext())
{
len++;
Ch.Assert(len <= _len);
getter(ref value);
if (isDefault(ref value))
continue;
Utils.EnsureSize(ref indices, ++count);
indices[count - 1] = len;
Utils.EnsureSize(ref values, count);
values[count - 1] = value;
}
len++;
Ch.Assert(len == _len);
if (count < len / 2 || count == len)
cached = new VBuffer<T>(len, count, values, count == len ? null : indices);
else
(new VBuffer<T>(len, count, values, indices)).CopyToDense(ref cached);
}
valid = true;
}
cached.CopyTo(ref dst);
};
}
}
private sealed class SlotCursorVec<T> : SlotCursor<T>
{
// The source data view. Note that this might be either the original input dataview
// if the column was not sufficiently large to justify "slicing," or the slicer dataview
// if it was large enough to justify splitting. (So this source data view will not
// necessarily be the same as the Transposer _view, but it might be.)
private readonly IDataView _view;
// In the case when we've sliced a dataview, the slot cursor will need to iterative over
// multiple cursors to get all slots from the original dataview that transposer is transposing.
// These fields define this range.
private readonly int _colMin;
private readonly int _colLim;
// The length of the resulting vectors. This is the same as the row count from the original dataview.
private readonly int _len;
// Temporary working/storage buffers.
private readonly VBuffer<T>[] _rbuff; // Working intermediate row-wise buffer.
private readonly int[] _rbuffIndices; // Working intermediate row-wise indices.
private int[][] _indices; // Working intermediate index buffers.
private T[][] _values; // Working intermediate value buffers.
private int[] _counts; // Working intermediate count buffers.
// The transposed contents of _colStored.
private VBuffer<T>[] _cbuff; // Working intermediate column-wise buffer.
// Variables to track current cursor position.
private int _colStored; // The current column of the source data view actually stored in the intermediate buffers.
private int _colCurr; // The current column of the split view that our cursor has on its position.
private int _slotCurr; // The current slot that our cursor has on its position.
private int _slotLim; // The limit of the slot index for the current column, so we know when to move to next columns.
/// <summary>
/// Constructs a slot cursor.
/// </summary>
/// <param name="parent">The transposer.</param>
/// <param name="col">The index of the transposed column.</param>
public SlotCursorVec(Transposer parent, int col)
: base(parent, col)
{
int iinfo = parent._inputToTransposed[col];
Ch.Assert(iinfo >= 0);
int smin = iinfo == 0 ? 0 : parent._splitLim[iinfo - 1];
if (parent._splitLim[iinfo] == smin)
{
// This is a passthrough column.
_view = parent._view;
_colMin = parent._cols[iinfo].Index;
_colLim = _colMin + 1;
}
else
{
_view = parent._splitView;
_colMin = smin;
_colLim = parent._splitLim[iinfo];
}
Ch.AssertValue(_view);
// Make the current state just "before" the first column so
// we can move cleanly onto the first slot of the first column.
_colStored = _colCurr = _colMin - 1;
_slotLim = 0;
_slotCurr = -1;
// The transposer will store this many rows from the source data view (either the
// slicer, or the original dataview if the column was not sufficiently large) column
// before copying into the _indices/_values/_counts working buffers, during a phase
// of EnsureValid.
_rbuff = new VBuffer<T>[16];
_rbuffIndices = new int[_rbuff.Length];
_len = parent.RowCount;
}
/// <summary>
/// Ensures that the column from the source data view stored in our intermediate buffers is the
/// current column requested.
/// </summary>
private void EnsureValid()
{
Ch.Check(State == CursorState.Good, "Cursor is not in good state, cannot get values");
Ch.Assert(_slotCurr >= 0);
if (_colStored == _colCurr)
return;
var type = _view.Schema.GetColumnType(_colCurr);
Ch.Assert(type.ItemType.RawType == typeof(T));
Ch.Assert(type.ValueCount > 0);
RefPredicate<T> isDefault = Conversion.Conversions.Instance.GetIsDefaultPredicate<T>(type.ItemType);
int vecLen = type.ValueCount;
int maxPossibleSize = _rbuff.Length * vecLen;
const int sparseThresholdRatio = 5;
int sparseThreshold = (maxPossibleSize + sparseThresholdRatio - 1) / sparseThresholdRatio;
Array.Clear(_rbuffIndices, 0, _rbuffIndices.Length);
int offset = 0;
// REVIEW: An obvious enhancement to make to this system is to take everything in the
// below "using" and make it part of some sort of external task, which this method waits on
// instead of actually doing the computation itself. The benefit there is that the next column
// is having its values loaded into _indices/_values/_counts while the current column is being
// served up to the consumer through _cbuff.
using (var cursor = _view.GetRowCursor(c => c == _colCurr))
{
// Make sure that the buffers (and subbuffers) are all of appropriate size.
Utils.EnsureSize(ref _indices, vecLen);
for (int i = 0; i < type.ValueCount; ++i)
_indices[i] = _indices[i] ?? new int[_len];
Utils.EnsureSize(ref _values, vecLen);
for (int i = 0; i < type.ValueCount; ++i)
_values[i] = _values[i] ?? new T[_len];
Utils.EnsureSize(ref _counts, vecLen, keepOld: false);
if (vecLen > 0)
Array.Clear(_counts, 0, vecLen);
var getter = cursor.GetGetter<VBuffer<T>>(_colCurr);
int irbuff = 0; // Next index into _rbuff. During the copy phase this doubles as the lim.
int countSum = 0;
// In the key value pair, the first is the slot index, then second is the row index in _rbuff.
var heap = new Heap<KeyValuePair<int, int>>((p1, p2) => p1.Key > p2.Key || (p1.Key == p2.Key && p1.Value > p2.Value), _rbuff.Length);
Action copyPhase =
() =>
{
if (countSum >= sparseThreshold)
{
// Slot by slot insertion, involving an exhaustive check over the tile.
for (int s = 0; s < vecLen; ++s)
{
int[] indices = _indices[s];
T[] values = _values[s];
for (int r = 0; r < irbuff; ++r)
{
int rowNum = offset + r;
var rbuff = _rbuff[r];
if (rbuff.IsDense)
{
// Store it as sparse. We will densify later, if we must.
if (!isDefault(ref rbuff.Values[s]))
{
indices[_counts[s]] = rowNum;
values[_counts[s]++] = rbuff.Values[s];
}
}
else
{
int ii = _rbuffIndices[r];
if (ii < rbuff.Count && rbuff.Indices[ii] == s)
{
if (!isDefault(ref rbuff.Values[ii]))
{
indices[_counts[s]] = rowNum;
values[_counts[s]++] = rbuff.Values[ii];
}
_rbuffIndices[r]++;
}
}
}
}
}
else
{
// Slot by slot insertion, involving a structure to determine the row to insert next.
Ch.Assert(heap.Count == 0);
int s = -1;
int[] indices = null;
T[] values = null;
// Construct the initial heap.
for (int r = 0; r < irbuff; ++r)
{
var rbuff = _rbuff[r];
if (rbuff.Count > 0)
heap.Add(new KeyValuePair<int, int>(rbuff.IsDense ? 0 : rbuff.Indices[0], r));
}
while (heap.Count > 0)
{
var pair = heap.Pop(); // Key is the slot, pair is the row index.
if (pair.Key != s)
{
Ch.Assert(pair.Key > s);
s = pair.Key;
indices = _indices[s];
values = _values[s];
}
var rbuff = _rbuff[pair.Value];
int ii = rbuff.IsDense ? s : _rbuffIndices[pair.Value]++;
Ch.Assert(rbuff.IsDense || rbuff.Indices[ii] == s);
indices[_counts[s]] = pair.Value + offset;
values[_counts[s]++] = rbuff.Values[ii];
if (++ii < rbuff.Count) // Still more stuff. Add another followup item to the heap.
heap.Add(new KeyValuePair<int, int>(rbuff.IsDense ? s + 1 : rbuff.Indices[ii], pair.Value));
}
}
Array.Clear(_rbuffIndices, 0, irbuff);
offset += irbuff;
countSum = irbuff = 0;
};
while (cursor.MoveNext())
{
int idx = checked((int)cursor.Position);
Ch.Assert(0 <= idx && idx < _len);
getter(ref _rbuff[irbuff]);
countSum += _rbuff[irbuff].Count;
if (++irbuff == _rbuff.Length)
copyPhase();
}
if (irbuff > 0)
copyPhase();
Ch.Assert(offset == _len);
}
// REVIEW: Everything *above* could be factored into async code, but the below absolutely must
// occur as an exclusive section.
// Finalize the contents of _cbuff based on _counts/_values/_indices.
Utils.EnsureSize(ref _cbuff, vecLen);
for (int s = 0; s < vecLen; ++s)
{
var temp = new VBuffer<T>(_len, _counts[s], _values[s], _indices[s]);
if (temp.Count < _len / 2)
{
// Already sparse enough, I guess. Swap out the arrays.
Utils.Swap(ref temp, ref _cbuff[s]);
_indices[s] = temp.Indices ?? new int[_len];
_values[s] = temp.Values ?? new T[_len];
Ch.Assert(_indices[s].Length == _len);
Ch.Assert(_values[s].Length == _len);
}
else
{
// Not dense enough. Densify temp into _cbuff[s]. Don't swap the arrays.
temp.CopyToDense(ref _cbuff[s]);
}
}
_colStored = _colCurr;
}
protected override bool MoveNextCore()
{
if (++_slotCurr < _slotLim)
return true;
Ch.Assert(_slotCurr == _slotLim);
_slotCurr = 0;
if (++_colCurr == _colLim)
return false;
_slotLim = _view.Schema.GetColumnType(_colCurr).ValueCount;
Ch.Assert(_slotLim > 0);
return true;
}
private void Getter(ref VBuffer<T> dst)
{
Ch.Check(IsGood, "Cannot get values in the cursor's current state");
EnsureValid();
Ch.Assert(0 <= _slotCurr && _slotCurr < Utils.Size(_cbuff) && _cbuff[_slotCurr].Length == _len);
_cbuff[_slotCurr].CopyTo(ref dst);
}
protected override ValueGetter<VBuffer<T>> GetGetterCore()
{
return Getter;
}
}
/// <summary>
/// This takes an input data view, and presents a dataset with "sliced" up columns
/// that are partitionings of the original columns. Scalar columns and sufficiently
/// small vector columns are just served up as themselves. The idea is that each of
/// those slices should be small enough that storing an entire column in memory.
/// </summary>
private sealed class DataViewSlicer : IDataView
{
// REVIEW: Could this be useful in its own right as a transform? We will
// have to have something that selects out a subset of columns, somehow, someday.
private readonly IDataView _input;
// For each input column, the structure handling the mapping of that column
// into multiple split output columns.
private readonly Splitter[] _splitters;
// For each input column, indicate what the limit of the output columns is.
private readonly int[] _incolToLim;
// Each of our output columns maps to a splitter. Multiple columns can
// map to the same splitter, that being kind of the point of a splitter.
private readonly int[] _colToSplitIndex;
// For each output column, indicates what output column it's surfacing
// from the splitter.
private readonly int[] _colToSplitCol;
private readonly SchemaImpl _schema;
private readonly IHost _host;
public ISchema Schema { get { return _schema; } }
public bool CanShuffle { get { return _input.CanShuffle; } }
public DataViewSlicer(IHost host, IDataView input, int[] toSlice)
{
Contracts.AssertValue(host, "host");
_host = host;
_host.AssertValue(input);
_host.AssertValue(toSlice);
_input = input;
_splitters = new Splitter[toSlice.Length];
_incolToLim = new int[toSlice.Length];
int outputColumnCount = 0;
// Also build our schema's name to index here. The slicers just surface the original
// input name as the name to all of our input columns.
var nameToCol = new Dictionary<string, int>();
for (int c = 0; c < toSlice.Length; ++c)
{
var splitter = _splitters[c] = Splitter.Create(_input, toSlice[c]);
_host.Assert(splitter.ColumnCount >= 1);
_incolToLim[c] = outputColumnCount += splitter.ColumnCount;
nameToCol[_input.Schema.GetColumnName(toSlice[c])] = outputColumnCount - 1;
}
_colToSplitIndex = new int[outputColumnCount];
_colToSplitCol = new int[outputColumnCount];
outputColumnCount = 0;
for (int c = 0; c < _splitters.Length; ++c)
{
int outCount = _splitters[c].ColumnCount;
for (int i = 0; i < outCount; ++i)
{
_colToSplitIndex[outputColumnCount] = c;
_colToSplitCol[outputColumnCount++] = i;
}
}
_host.Assert(outputColumnCount == _colToSplitIndex.Length);
_schema = new SchemaImpl(this, nameToCol);
}
public long? GetRowCount(bool lazy = true)
{
return _input.GetRowCount(lazy);
}
/// <summary>
/// Given the index of a column we were told to split, get the corresponding range out output
/// ranges.
/// </summary>
/// <param name="incol">The index into the array of column indices.</param>
/// <param name="outMin">The minimum output column index corresponding to that split column</param>
/// <param name="outLim">The exclusive limit of the output column index corresponding to that
/// split column</param>
public void InColToOutRange(int incol, out int outMin, out int outLim)
{
_host.Assert(0 <= incol && incol < _incolToLim.Length);
outMin = incol == 0 ? 0 : _incolToLim[incol - 1];
outLim = _incolToLim[incol];
}
private void OutputColumnToSplitterIndices(int col, out int splitInd, out int splitCol)
{
_host.Assert(0 <= col && col < _colToSplitIndex.Length);
splitInd = _colToSplitIndex[col];
splitCol = _colToSplitCol[col];
}
public IRowCursor GetRowCursor(Func<int, bool> predicate, IRandom rand = null)
{
_host.CheckValue(predicate, nameof(predicate));
bool[] activeSplitters;
var srcPred = CreateInputPredicate(predicate, out activeSplitters);
return new Cursor(_host, this, _input.GetRowCursor(srcPred, rand), predicate, activeSplitters);
}
public IRowCursor[] GetRowCursorSet(out IRowCursorConsolidator consolidator, Func<int, bool> predicate, int n, IRandom rand = null)
{
_host.CheckValue(predicate, nameof(predicate));
_host.CheckValueOrNull(rand);
bool[] activeSplitters;
var srcPred = CreateInputPredicate(predicate, out activeSplitters);
var result = _input.GetRowCursorSet(out consolidator, srcPred, n, rand);
for (int i = 0; i < result.Length; ++i)
result[i] = new Cursor(_host, this, result[i], predicate, activeSplitters);
return result;
}
/// <summary>
/// Given a possibly null predicate for this data view, produce the dependency predicate for the sources,
/// as well as a list of all the splitters for which we should produce rowsets.
/// </summary>
/// <param name="pred">The predicate input into the <see cref="GetRowCursor(Func{int, bool}, IRandom)"/> method.</param>
/// <param name="activeSplitters">A boolean indicator array of length equal to the number of splitters,
/// indicating whether that splitter has any active columns in its outputs or not</param>
/// <returns>The predicate to use when constructing the row cursor from the source</returns>
private Func<int, bool> CreateInputPredicate(Func<int, bool> pred, out bool[] activeSplitters)
{
_host.AssertValueOrNull(pred);
activeSplitters = new bool[_splitters.Length];
var activeSrcSet = new HashSet<int>();
int offset = 0;
for (int i = 0; i < activeSplitters.Length; ++i)
{
var splitter = _splitters[i];
// Don't activate input source columns if none of the resulting columns were selected.
bool isActive = pred == null || Enumerable.Range(offset, splitter.ColumnCount).Any(c => pred(c));
if (isActive)
{
activeSplitters[i] = isActive;
activeSrcSet.Add(splitter.SrcCol);
}
offset += splitter.ColumnCount;
}
return activeSrcSet.Contains;
}
/// <summary>
/// This collates the schemas of all the columns from the <see cref="Splitter"/> instances.
/// </summary>
private sealed class SchemaImpl : NoMetadataSchema
{
private readonly DataViewSlicer _slicer;
private readonly Dictionary<string, int> _nameToCol;
public override int ColumnCount { get { return _slicer._colToSplitIndex.Length; } }
public SchemaImpl(DataViewSlicer slicer, Dictionary<string, int> nameToCol)
{
Contracts.AssertValue(slicer);
Contracts.AssertValue(nameToCol);
_slicer = slicer;
_nameToCol = nameToCol;
}
public override bool TryGetColumnIndex(string name, out int col)
{
Contracts.CheckValueOrNull(name);
return Utils.TryGetValue(_nameToCol, name, out col);
}
public override string GetColumnName(int col)
{
Contracts.CheckParam(0 <= col && col < ColumnCount, nameof(col));
int splitInd;
int splitCol;
_slicer.OutputColumnToSplitterIndices(col, out splitInd, out splitCol);
return _slicer._splitters[splitInd].GetColumnName(splitCol);
}
public override ColumnType GetColumnType(int col)
{
Contracts.CheckParam(0 <= col && col < ColumnCount, nameof(col));
int splitInd;
int splitCol;
_slicer.OutputColumnToSplitterIndices(col, out splitInd, out splitCol);
return _slicer._splitters[splitInd].GetColumnType(splitCol);
}
}
/// <summary>
/// Very simple schema base that surfaces no metadata, since I have a couple schema
/// implementations neither of which I care about surfacing metadata.
/// </summary>
private abstract class NoMetadataSchema : ISchema
{
public abstract int ColumnCount { get; }
public abstract bool TryGetColumnIndex(string name, out int col);
public abstract string GetColumnName(int col);
public abstract ColumnType GetColumnType(int col);
public IEnumerable<KeyValuePair<string, ColumnType>> GetMetadataTypes(int col)
{
Contracts.CheckParam(0 <= col && col < ColumnCount, nameof(col));
return Enumerable.Empty<KeyValuePair<string, ColumnType>>();
}
public ColumnType GetMetadataTypeOrNull(string kind, int col)
{
Contracts.CheckParam(0 <= col && col < ColumnCount, nameof(col));
return null;
}
public void GetMetadata<TValue>(string kind, int col, ref TValue value)
{
Contracts.CheckParam(0 <= col && col < ColumnCount, nameof(col));
throw MetadataUtils.ExceptGetMetadata();
}
}
/// <summary>
/// There is one instance of these per column, implementing the possible splitting
/// of one column from a <see cref="IDataView"/> into multiple columns. The instance
/// describes the resulting split columns through its implementation of
/// <see cref="ISchema"/>, and then can be bound to an <see cref="IRow"/> to provide
/// that splitting functionality.
/// </summary>
private abstract class Splitter : NoMetadataSchema
{
private readonly IDataView _view;
private readonly int _col;
public int SrcCol { get { return _col; } }
protected Splitter(IDataView view, int col)
{
Contracts.AssertValue(view);
Contracts.Assert(0 <= col && col < view.Schema.ColumnCount);
_view = view;
_col = col;
}
/// <summary>
/// Creates a splitter for a given row.
/// </summary>
public static Splitter Create(IDataView view, int col)
{
var type = view.Schema.GetColumnType(col);
Contracts.Assert(type.IsPrimitive || type.VectorSize > 0);
const int defaultSplitThreshold = 16;
if (type.VectorSize <= defaultSplitThreshold)
return Utils.MarshalInvoke(CreateCore<int>, type.RawType, view, col);
else
{