-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathTextLoader.cs
1648 lines (1425 loc) · 73.9 KB
/
TextLoader.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.Linq;
using System.Reflection;
using System.Text;
using Microsoft.ML;
using Microsoft.ML.CommandLine;
using Microsoft.ML.Data;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Runtime;
[assembly: LoadableClass(TextLoader.Summary, typeof(ILegacyDataLoader), typeof(TextLoader), typeof(TextLoader.Options), typeof(SignatureDataLoader),
"Text Loader", "TextLoader", "Text", DocName = "loader/TextLoader.md")]
[assembly: LoadableClass(TextLoader.Summary, typeof(ILegacyDataLoader), typeof(TextLoader), null, typeof(SignatureLoadDataLoader),
"Text Loader", TextLoader.LoaderSignature)]
[assembly: LoadableClass(TextLoader.Summary, typeof(TextLoader), null, typeof(SignatureLoadModel),
"Text Loader", TextLoader.LoaderSignature)]
namespace Microsoft.ML.Data
{
/// <summary>
/// Loads a text file into an IDataView. Supports basic mapping from input columns to <see cref="IDataView"/> columns.
/// </summary>
public sealed partial class TextLoader : IDataLoader<IMultiStreamSource>
{
/// <summary>
/// Describes how an input column should be mapped to an <see cref="IDataView"/> column.
/// </summary>
public sealed class Column
{
// Examples of how a column is defined in command line API:
// Scalar column of <seealso cref="DataKind"/> I4 sourced from 2nd column
// col=ColumnName:I4:1
// Vector column of <seealso cref="DataKind"/> I4 that contains values from columns 1, 3 to 10
// col=ColumnName:I4:1,3-10
// Key range column of KeyType with underlying storage type U4 that contains values from columns 1, 3 to 10, that can go from 1 to 100 (0 reserved for out of range)
// col=ColumnName:U4[100]:1,3-10
/// <summary>
/// Describes how an input column should be mapped to an <see cref="IDataView"/> column.
/// </summary>
public Column() { }
/// <summary>
/// Describes how an input column should be mapped to an <see cref="IDataView"/> column.
/// </summary>
/// <param name="name">Name of the column.</param>
/// <param name="dataKind"><see cref="Data.DataKind"/> of the items in the column.</param>
/// <param name="index">Index of the column.</param>
public Column(string name, DataKind dataKind, int index)
: this(name, dataKind.ToInternalDataKind(), new[] { new Range(index) })
{
}
/// <summary>
/// Describes how an input column should be mapped to an <see cref="IDataView"/> column.
/// </summary>
/// <param name="name">Name of the column.</param>
/// <param name="dataKind"><see cref="Data.DataKind"/> of the items in the column.</param>
/// <param name="minIndex">The minimum inclusive index of the column.</param>
/// <param name="maxIndex">The maximum-inclusive index of the column.</param>
public Column(string name, DataKind dataKind, int minIndex, int maxIndex)
: this(name, dataKind.ToInternalDataKind(), new[] { new Range(minIndex, maxIndex) })
{
}
/// <summary>
/// Describes how an input column should be mapped to an <see cref="IDataView"/> column.
/// </summary>
/// <param name="name">Name of the column.</param>
/// <param name="dataKind"><see cref="Data.DataKind"/> of the items in the column.</param>
/// <param name="source">Source index range(s) of the column.</param>
/// <param name="keyCount">For a key column, this defines the range of values.</param>
public Column(string name, DataKind dataKind, Range[] source, KeyCount keyCount = null)
: this(name, dataKind.ToInternalDataKind(), source, keyCount)
{
}
/// <summary>
/// Describes how an input column should be mapped to an <see cref="IDataView"/> column.
/// </summary>
/// <param name="name">Name of the column.</param>
/// <param name="kind"><see cref="InternalDataKind"/> of the items in the column.</param>
/// <param name="source">Source index range(s) of the column.</param>
/// <param name="keyCount">For a key column, this defines the range of values.</param>
private Column(string name, InternalDataKind kind, Range[] source, KeyCount keyCount = null)
{
Contracts.CheckValue(name, nameof(name));
Contracts.CheckValue(source, nameof(source));
Name = name;
Type = kind;
Source = source;
KeyCount = keyCount;
}
/// <summary>
/// Name of the column.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Name of the column")]
public string Name;
/// <summary>
/// <see cref="InternalDataKind"/> of the items in the column. It defaults to float.
/// Although <see cref="InternalDataKind"/> is internal, <see cref="Type"/>'s information can be publicly accessed by <see cref="DataKind"/>.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Type of the items in the column")]
[BestFriend]
internal InternalDataKind Type = InternalDataKind.R4;
/// <summary>
/// <see cref="Data.DataKind"/> of the items in the column.
/// </summary>
/// It's a public interface to access the information in an internal DataKind.
public DataKind DataKind
{
get { return Type.ToDataKind(); }
set { Type = value.ToInternalDataKind(); }
}
/// <summary>
/// Source index range(s) of the column.
/// </summary>
[Argument(ArgumentType.Multiple, HelpText = "Source index range(s) of the column", ShortName = "src")]
public Range[] Source;
/// <summary>
/// For a key column, this defines the range of values.
/// </summary>
[Argument(ArgumentType.Multiple, HelpText = "For a key column, this defines the range of values", ShortName = "key")]
public KeyCount KeyCount;
internal static Column Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new Column();
if (res.TryParse(str))
return res;
return null;
}
private bool TryParse(string str)
{
Contracts.AssertNonEmpty(str);
// Allow name:srcs and name:type:srcs
var rgstr = str.Split(':');
if (rgstr.Length < 2 || rgstr.Length > 3)
return false;
int istr = 0;
if (string.IsNullOrWhiteSpace(Name = rgstr[istr++]))
return false;
if (rgstr.Length == 3)
{
InternalDataKind kind;
if (!TypeParsingUtils.TryParseDataKind(rgstr[istr++], out kind, out KeyCount))
return false;
Type = kind == default ? InternalDataKind.R4 : kind;
}
return TryParseSource(rgstr[istr++]);
}
private bool TryParseSource(string str) => TryParseSourceEx(str, out Source);
internal static bool TryParseSourceEx(string str, out Range[] ranges)
{
ranges = null;
var strs = str.Split(',');
if (str.Length == 0)
return false;
ranges = new Range[strs.Length];
for (int i = 0; i < strs.Length; i++)
{
if ((ranges[i] = Range.Parse(strs[i])) == null)
return false;
}
return true;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (string.IsNullOrWhiteSpace(Name))
return false;
if (CmdQuoter.NeedsQuoting(Name))
return false;
if (Utils.Size(Source) == 0)
return false;
int ich = sb.Length;
sb.Append(Name);
sb.Append(':');
if (Type != default || KeyCount != null)
{
if (Type != default)
sb.Append(Type.GetString());
if (KeyCount != null)
{
sb.Append('[');
if (!KeyCount.TryUnparse(sb))
{
sb.Length = ich;
return false;
}
sb.Append(']');
}
sb.Append(':');
}
string pre = "";
foreach (var src in Source)
{
sb.Append(pre);
if (!src.TryUnparse(sb))
{
sb.Length = ich;
return false;
}
pre = ",";
}
return true;
}
/// <summary>
/// Returns <c>true</c> iff the ranges are disjoint, and each range satisfies 0 <= min <= max.
/// </summary>
internal bool IsValid()
{
if (Utils.Size(Source) == 0)
return false;
var sortedRanges = Source.OrderBy(x => x.Min).ToList();
var first = sortedRanges[0];
if (first.Min < 0 || first.Min > first.Max)
return false;
for (int i = 1; i < sortedRanges.Count; i++)
{
var cur = sortedRanges[i];
if (cur.Min > cur.Max)
return false;
var prev = sortedRanges[i - 1];
if (prev.Max == null && (prev.AutoEnd || prev.VariableEnd))
return false;
if (cur.Min <= prev.Max)
return false;
}
return true;
}
}
/// <summary>
/// Specifies the range of indices of input columns that should be mapped to an output column.
/// </summary>
public sealed class Range
{
public Range() { }
/// <summary>
/// A range representing a single value. Will result in a scalar column.
/// </summary>
/// <param name="index">The index of the field of the text file to read.</param>
public Range(int index)
{
Contracts.CheckParam(index >= 0, nameof(index), "Must be non-negative");
Min = index;
Max = index;
}
/// <summary>
/// A range representing a set of values. Will result in a vector column.
/// </summary>
/// <param name="min">The minimum inclusive index of the column.</param>
/// <param name="max">The maximum-inclusive index of the column. If <c>null</c>
/// indicates that the <see cref="TextLoader"/> should auto-detect the legnth
/// of the lines, and read until the end.</param>
public Range(int min, int? max)
{
Contracts.CheckParam(min >= 0, nameof(min), "Must be non-negative");
Contracts.CheckParam(!(max < min), nameof(max), "If specified, must be greater than or equal to " + nameof(min));
Min = min;
Max = max;
// Note that without the following being set, in the case where there is a single range
// where Min == Max, the result will not be a vector valued but a scalar column.
ForceVector = true;
AutoEnd = max == null;
}
/// <summary>
/// The minimum index of the column, inclusive.
/// </summary>
[Argument(ArgumentType.Required, HelpText = "First index in the range")]
public int Min;
/// <summary>
/// The maximum index of the column, inclusive. If <see langword="null"/>
/// indicates that the <see cref="TextLoader"/> should auto-detect the legnth
/// of the lines, and read until the end.
/// If max is specified, the fields <see cref="AutoEnd"/> and <see cref="VariableEnd"/> are ignored.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Last index in the range")]
public int? Max;
/// <summary>
/// Whether this range extends to the end of the line, but should be a fixed number of items.
/// If <see cref="Max"/> is specified, the fields <see cref="AutoEnd"/> and <see cref="VariableEnd"/> are ignored.
/// </summary>
[Argument(ArgumentType.AtMostOnce,
HelpText = "This range extends to the end of the line, but should be a fixed number of items",
ShortName = "auto")]
public bool AutoEnd;
/// <summary>
/// Whether this range extends to the end of the line, which can vary from line to line.
/// If <see cref="Max"/> is specified, the fields <see cref="AutoEnd"/> and <see cref="VariableEnd"/> are ignored.
/// If <see cref="AutoEnd"/> is <see langword="true"/>, then <see cref="VariableEnd"/> is ignored.
/// </summary>
[Argument(ArgumentType.AtMostOnce,
HelpText = "This range extends to the end of the line, which can vary from line to line",
ShortName = "var")]
public bool VariableEnd;
/// <summary>
/// Whether this range includes only other indices not specified.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "This range includes only other indices not specified", ShortName = "other")]
public bool AllOther;
/// <summary>
/// Force scalar columns to be treated as vectors of length one.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Force scalar columns to be treated as vectors of length one", ShortName = "vector")]
public bool ForceVector;
internal static Range Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new Range();
if (res.TryParse(str))
return res;
return null;
}
private bool TryParse(string str)
{
Contracts.AssertNonEmpty(str);
int ich = str.IndexOfAny(new char[] { '-', '~' });
if (ich < 0)
{
// No "-" or "~". Single integer.
if (!int.TryParse(str, out Min))
return false;
Max = Min;
return true;
}
AllOther = str[ich] == '~';
ForceVector = true;
if (ich == 0)
{
if (!AllOther)
return false;
Min = 0;
}
else if (!int.TryParse(str.Substring(0, ich), out Min))
return false;
string rest = str.Substring(ich + 1);
if (string.IsNullOrEmpty(rest) || rest == "*")
{
AutoEnd = true;
return true;
}
if (rest == "**")
{
VariableEnd = true;
return true;
}
int tmp;
if (!int.TryParse(rest, out tmp))
return false;
Max = tmp;
return true;
}
internal bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
char dash = AllOther ? '~' : '-';
if (Min < 0)
return false;
sb.Append(Min);
if (Max != null)
{
if (Max != Min || ForceVector || AllOther)
sb.Append(dash).Append(Max);
}
else if (AutoEnd)
sb.Append(dash).Append("*");
else if (VariableEnd)
sb.Append(dash).Append("**");
return true;
}
}
/// <summary>
/// The settings for <see cref="TextLoader"/>
/// </summary>
public class Options
{
/// <summary>
/// Whether the input may include double-quoted values. This parameter is used to distinguish separator characters
/// in an input value from actual separators. When <see langword="true"/>, separators within double quotes are treated as part of the
/// input value. When <see langword="false"/>, all separators, even those within quotes, are treated as delimiting a new column.
/// </summary>
[Argument(ArgumentType.AtMostOnce,
HelpText =
"Whether the input may include quoted values, which can contain separator characters, colons," +
" and distinguish empty values from missing values. When true, consecutive separators denote a" +
" missing value and an empty value is denoted by \"\". When false, consecutive separators" +
" denote an empty value.",
ShortName = "quote")]
public bool AllowQuoting = Defaults.AllowQuoting;
/// <summary>
/// Whether the input may include sparse representations. For example, a row containing
/// "5 2:6 4:3" means that there are 5 columns, and the only non-zero are columns 2 and 4, which have values 6 and 3,
/// respectively. Column indices are zero-based, so columns 2 and 4 represent the 3rd and 5th columns.
/// A column may also have dense values followed by sparse values represented in this fashion. For example,
/// a row containing "1 2 5 2:6 4:3" represents two dense columns with values 1 and 2, followed by 5 sparsely represented
/// columns with values 0, 0, 6, 0, and 3. The indices of the sparse columns start from 0, even though 0 represents the third column.
///
/// In addition, <see cref="InputSize"/> should be used when the number of sparse elements (5 in this example) is not present in each line.
/// It should specify the total size, not just the size of the sparse part. However, indices of the spars part are relative to where the sparse part begins.
/// If <see cref="InputSize"/> is set to 7, the line "1 2 2:6 4:3" will be mapped to "1 2 0 0 6 0 4", but if set to 10, the same line will
/// be mapped to "1 2 0 0 6 0 4 0 0 0".
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Whether the input may include sparse representations", ShortName = "sparse")]
public bool AllowSparse = Defaults.AllowSparse;
/// <summary>
/// Number of source columns in the text data. Default is that sparse rows contain their size information.
/// </summary>
[Argument(ArgumentType.AtMostOnce,
HelpText = "Number of source columns in the text data. Default is that sparse rows contain their size information.",
ShortName = "size")]
public int? InputSize;
[Argument(ArgumentType.AtMostOnce, Visibility = ArgumentAttribute.VisibilityType.CmdLineOnly, HelpText = "Source column separator. Options: tab, space, comma, single character", ShortName = "sep")]
// this is internal as it only serves the command line interface
internal string Separator = Defaults.Separator.ToString();
/// <summary>
/// The characters that should be used as separators column separator.
/// </summary>
[Argument(ArgumentType.AtMostOnce, Name = nameof(Separator), Visibility = ArgumentAttribute.VisibilityType.EntryPointsOnly, HelpText = "Source column separator.", ShortName = "sep")]
public char[] Separators = new[] { Defaults.Separator };
/// <summary>
/// The character that should be used as the decimal marker. Default value is '.'. Only '.' and ',' are allowed to be decimal markers.
/// </summary>
[Argument(ArgumentType.AtMostOnce, Name = "Decimal Marker", HelpText = "Character symbol used to separate the integer part from the fractional part of a number written in decimal form.", ShortName = "decimal")]
public char DecimalMarker = Defaults.DecimalMarker;
/// <summary>
/// Specifies the input columns that should be mapped to <see cref="IDataView"/> columns.
/// </summary>
[Argument(ArgumentType.Multiple, HelpText = "Column groups. Each group is specified as name:type:numeric-ranges, eg, col=Features:R4:1-17,26,35-40",
Name = "Column", ShortName = "col", SortOrder = 1)]
public Column[] Columns;
/// <summary>
/// Wheter to remove trailing whitespace from lines.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Remove trailing whitespace from lines", ShortName = "trim")]
public bool TrimWhitespace = Defaults.TrimWhitespace;
/// <summary>
/// Whether the file has a header with feature names. When <see langword="true"/>, the loader will skip the first line when
/// <see cref="TextLoader.Load(IMultiStreamSource)"/> is called. The sample can be used to infer slot name annotations if present.
/// </summary>
[Argument(ArgumentType.AtMostOnce, ShortName = "header",
HelpText = "Data file has header with feature names. Header is read only if options 'hs' and 'hf' are not specified.")]
public bool HasHeader = Defaults.HasHeader;
/// <summary>
/// Whether to use separate parsing threads.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Use separate parsing threads?", ShortName = "threads", Hide = true)]
public bool UseThreads = true;
/// <summary>
/// If true, new line characters are acceptable inside a quoted field, and thus one field can have multiple lines of text inside it
/// If <see cref="TextLoader.Options.AllowQuoting"/> is false, this option is ignored.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Escape new line characters inside a quoted field? If AllowQuoting is false, this argument is ignored.", ShortName = "multilines", Hide = true)]
public bool ReadMultilines = Defaults.ReadMultilines;
/// <summary>
/// File containing a header with feature names. If specified, the header defined in the data file is ignored regardless of <see cref="HasHeader"/>.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "File containing a header with feature names. If specified, header defined in the data file (header+) is ignored.",
ShortName = "hf", IsInputFileName = true)]
public string HeaderFile;
/// <summary>
/// Maximum number of rows to produce.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Maximum number of rows to produce", ShortName = "rows", Hide = true)]
public long? MaxRows;
/// <summary>
/// Character to use to escape quotes inside quoted fields. It can't be a character used as separator.
/// </summary>
[Argument(ArgumentType.AtMostOnce, HelpText = "Character to use to escape quotes inside quoted fields. It can't be a character used as separator.", ShortName = "escapechar")]
public char EscapeChar = Defaults.EscapeChar;
/// <summary>
/// Checks that all column specifications are valid (that is, ranges are disjoint and have min<=max).
/// </summary>
internal bool IsValid()
{
return Utils.Size(Columns) == 0 || Columns.All(x => x.IsValid());
}
}
internal static class Defaults
{
internal const bool AllowQuoting = false;
internal const bool AllowSparse = false;
internal const char Separator = '\t';
internal const char DecimalMarker = '.';
internal const bool HasHeader = false;
internal const bool TrimWhitespace = false;
internal const bool ReadMultilines = false;
internal const char EscapeChar = '"';
}
/// <summary>
/// Used as an input column range.
/// A variable length segment (extending to the end of the input line) is represented by Lim == SrcLim.
/// </summary>
internal struct Segment
{
public int Min;
public int Lim;
public bool ForceVector;
public bool IsVariable { get { return Lim == SrcLim; } }
/// <summary>
/// Be careful with this ctor. lim == SrcLim means that this segment extends to
/// the end of the input line. If that is not the intent, pass in Min(lim, SrcLim - 1).
/// </summary>
public Segment(int min, int lim, bool forceVector)
{
Contracts.Assert(0 <= min & min < lim & lim <= SrcLim);
Min = min;
Lim = lim;
ForceVector = forceVector;
}
/// <summary>
/// Defines a segment that extends from min to the end of input.
/// </summary>
public Segment(int min)
{
Contracts.Assert(0 <= min & min < SrcLim);
Min = min;
Lim = SrcLim;
ForceVector = true;
}
}
/// <summary>
/// Information for an output column.
/// </summary>
internal sealed class ColInfo
{
public readonly string Name;
// REVIEW: Fix this for keys.
public readonly InternalDataKind Kind;
public readonly DataViewType ColType;
public readonly Segment[] Segments;
// There is at most one variable sized segment, the one at IsegVariable (-1 if none).
// BaseSize is the sum of the sizes of non-variable segments.
public readonly int IsegVariable;
public readonly int SizeBase;
private ColInfo(string name, DataViewType colType, Segment[] segs, int isegVar, int sizeBase)
{
Contracts.AssertNonEmpty(name);
Contracts.AssertNonEmpty(segs);
Contracts.Assert(sizeBase > 0 || isegVar >= 0);
Contracts.Assert(isegVar >= -1);
Name = name;
Kind = colType.GetItemType().GetRawKind();
Contracts.Assert(Kind != 0);
ColType = colType;
Segments = segs;
SizeBase = sizeBase;
IsegVariable = isegVar;
}
public static ColInfo Create(string name, PrimitiveDataViewType itemType, Segment[] segs, bool user)
{
Contracts.AssertNonEmpty(name);
Contracts.AssertValue(itemType);
Contracts.AssertNonEmpty(segs);
var order = Utils.GetIdentityPermutation(segs.Length);
Array.Sort(order, (x, y) => segs[x].Min.CompareTo(segs[y].Min));
// Check that the segments are disjoint.
// REVIEW: Should we insist that they are disjoint? Is there any reason to allow overlapping?
for (int i = 1; i < order.Length; i++)
{
int a = order[i - 1];
int b = order[i];
Contracts.Assert(segs[a].Min <= segs[b].Min);
if (segs[a].Lim > segs[b].Min)
{
throw user ?
Contracts.ExceptUserArg(nameof(Column.Source), "Intervals specified for column '{0}' overlap", name) :
Contracts.ExceptDecode("Intervals specified for column '{0}' overlap", name);
}
}
// Note: since we know that the segments don't overlap, we're guaranteed that
// the sum of their sizes doesn't overflow.
int isegVar = -1;
int size = 0;
for (int i = 0; i < segs.Length; i++)
{
var seg = segs[i];
if (seg.IsVariable)
{
Contracts.Assert(isegVar == -1);
isegVar = i;
}
else
size += seg.Lim - seg.Min;
}
Contracts.Assert(size >= segs.Length || size >= segs.Length - 1 && isegVar >= 0);
DataViewType type = itemType;
if (isegVar >= 0)
type = new VectorDataViewType(itemType);
else if (size > 1 || segs[0].ForceVector)
type = new VectorDataViewType(itemType, size);
return new ColInfo(name, type, segs, isegVar, size);
}
}
private sealed class Bindings
{
/// <summary>
/// <see cref="Infos"/>[i] stores the i-th column's name and type. Columns are loaded from the input text file.
/// </summary>
public readonly ColInfo[] Infos;
/// <summary>
/// <see cref="Infos"/>[i] stores the i-th column's metadata, named <see cref="AnnotationUtils.Kinds.SlotNames"/>
/// in <see cref="DataViewSchema.Annotations"/>.
/// </summary>
private readonly VBuffer<ReadOnlyMemory<char>>[] _slotNames;
/// <summary>
/// Empty if <see cref="Options.HasHeader"/> is <see langword="false"/>, no header presents, or upon load
/// there was no header stored in the model.
/// </summary>
private readonly ReadOnlyMemory<char> _header;
public DataViewSchema OutputSchema { get; }
public Bindings(TextLoader parent, Column[] cols, IMultiStreamSource headerFile, IMultiStreamSource dataSample)
{
Contracts.AssertNonEmpty(cols);
Contracts.AssertValueOrNull(headerFile);
Contracts.AssertValueOrNull(dataSample);
using (var ch = parent._host.Start("Binding"))
{
// Make sure all columns have at least one source range.
// Also determine if any columns have a range that extends to the end. If so, then we need
// to look at some data to determine the number of source columns.
bool needInputSize = false;
foreach (var col in cols)
{
if (Utils.Size(col.Source) == 0)
throw ch.ExceptUserArg(nameof(Column.Source), "Must specify some source column indices");
if (!needInputSize && col.Source.Any(r => r.AutoEnd && r.Max == null))
needInputSize = true;
}
int inputSize = parent._inputSize;
ch.Assert(0 <= inputSize & inputSize < SrcLim);
List<ReadOnlyMemory<char>> lines = null;
if (headerFile != null)
Cursor.GetSomeLines(headerFile, 1, parent.ReadMultilines, parent._separators, parent._escapeChar, ref lines);
if (needInputSize && inputSize == 0)
Cursor.GetSomeLines(dataSample, 100, parent.ReadMultilines, parent._separators, parent._escapeChar, ref lines);
else if (headerFile == null && parent.HasHeader)
Cursor.GetSomeLines(dataSample, 1, parent.ReadMultilines, parent._separators, parent._escapeChar, ref lines);
if (needInputSize && inputSize == 0)
{
int min = 0;
int max = 0;
if (Utils.Size(lines) > 0)
Parser.GetInputSize(parent, lines, out min, out max);
if (max == 0)
throw ch.ExceptUserArg(nameof(Column.Source), "Can't determine the number of source columns without valid data");
ch.Assert(min <= max);
if (min < max)
throw ch.ExceptUserArg(nameof(Column.Source), "The size of input lines is not consistent");
// We reserve SrcLim for variable.
inputSize = Math.Min(min, SrcLim - 1);
}
int iinfoOther = -1;
PrimitiveDataViewType typeOther = null;
Segment[] segsOther = null;
int isegOther = -1;
Infos = new ColInfo[cols.Length];
// This dictionary is used only for detecting duplicated column names specified by user.
var nameToInfoIndex = new Dictionary<string, int>(Infos.Length);
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
var col = cols[iinfo];
ch.CheckNonWhiteSpace(col.Name, nameof(col.Name));
string name = col.Name.Trim();
if (iinfo == nameToInfoIndex.Count && nameToInfoIndex.ContainsKey(name))
ch.Info("Duplicate name(s) specified - later columns will hide earlier ones");
PrimitiveDataViewType itemType;
InternalDataKind kind;
if (col.KeyCount != null)
{
itemType = TypeParsingUtils.ConstructKeyType(col.Type, col.KeyCount);
}
else
{
kind = col.Type == default ? InternalDataKind.R4 : col.Type;
ch.CheckUserArg(Enum.IsDefined(typeof(InternalDataKind), kind), nameof(Column.Type), "Bad item type");
itemType = ColumnTypeExtensions.PrimitiveTypeFromKind(kind);
}
// This was checked above.
ch.Assert(Utils.Size(col.Source) > 0);
var segs = new Segment[col.Source.Length];
for (int i = 0; i < segs.Length; i++)
{
var range = col.Source[i];
// Check for remaining range, raise flag.
if (range.AllOther)
{
ch.CheckUserArg(iinfoOther < 0, nameof(Range.AllOther), "At most one all other range can be specified");
iinfoOther = iinfo;
isegOther = i;
typeOther = itemType;
segsOther = segs;
}
// Falling through this block even if range.allOther is true to capture range information.
int min = range.Min;
ch.CheckUserArg(0 <= min && min < SrcLim - 1, nameof(range.Min));
Segment seg;
if (range.Max != null)
{
int max = range.Max.Value;
ch.CheckUserArg(min <= max && max < SrcLim - 1, nameof(range.Max));
seg = new Segment(min, max + 1, range.ForceVector);
ch.Assert(!seg.IsVariable);
}
else if (range.AutoEnd)
{
ch.Assert(needInputSize && 0 < inputSize && inputSize < SrcLim);
if (min >= inputSize)
throw ch.ExceptUserArg(nameof(range.Min), "Column #{0} not found in the dataset (it only has {1} columns)", min, inputSize);
seg = new Segment(min, inputSize, true);
ch.Assert(!seg.IsVariable);
}
else if (range.VariableEnd)
{
seg = new Segment(min);
ch.Assert(seg.IsVariable);
}
else
{
seg = new Segment(min, min + 1, range.ForceVector);
ch.Assert(!seg.IsVariable);
}
segs[i] = seg;
}
// Defer ColInfo generation if the column contains all other indexes.
if (iinfoOther != iinfo)
Infos[iinfo] = ColInfo.Create(name, itemType, segs, true);
nameToInfoIndex[name] = iinfo;
}
// Note that segsOther[isegOther] is not a real segment to be included.
// It only persists segment information such as Min, Max, autoEnd, variableEnd for later processing.
// Process all other range.
if (iinfoOther >= 0)
{
ch.Assert(0 <= isegOther && isegOther < segsOther.Length);
// segsAll is the segments from all columns.
var segsAll = new List<Segment>();
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
if (iinfo == iinfoOther)
segsAll.AddRange(segsOther.Where((s, i) => i != isegOther));
else
segsAll.AddRange(Infos[iinfo].Segments);
}
// segsNew is where we build the segs for the column iinfoOther.
var segsNew = new List<Segment>();
var segOther = segsOther[isegOther];
for (int i = 0; i < segsOther.Length; i++)
{
if (i != isegOther)
{
segsNew.Add(segsOther[i]);
continue;
}
// Sort all existing segments by Min, there is no guarantee that segments do not overlap.
segsAll.Sort((s1, s2) => s1.Min.CompareTo(s2.Min));
int min = segOther.Min;
int lim = segOther.Lim;
foreach (var seg in segsAll)
{
// At this step, all indices less than min is contained in some segment, either in
// segsAll or segsNew.
ch.Assert(min < lim);
if (min < seg.Min)
segsNew.Add(new Segment(min, seg.Min, true));
if (min < seg.Lim)
min = seg.Lim;
if (min >= lim)
break;
}
if (min < lim)
segsNew.Add(new Segment(min, lim, true));
}
ch.CheckUserArg(segsNew.Count > 0, nameof(Range.AllOther), "No index is selected as all other indexes.");
Infos[iinfoOther] = ColInfo.Create(cols[iinfoOther].Name.Trim(), typeOther, segsNew.ToArray(), true);
}
_slotNames = new VBuffer<ReadOnlyMemory<char>>[Infos.Length];
if ((parent.HasHeader || headerFile != null) && Utils.Size(lines) > 0)
_header = lines[0];
if (!_header.IsEmpty)
Parser.ParseSlotNames(parent, _header, Infos, _slotNames);
}
OutputSchema = ComputeOutputSchema();
}
public Bindings(ModelLoadContext ctx, TextLoader parent)
{
Contracts.AssertValue(ctx);
// *** Binary format ***
// int: number of columns
// foreach column:
// int: id of column name
// byte: DataKind
// byte: bool of whether this is a key type
// for a key type:
// ulong: count for key range
// int: number of segments
// foreach segment:
// int: min
// int: lim
// byte: force vector (verWrittenCur: verIsVectorSupported)
int cinfo = ctx.Reader.ReadInt32();
Contracts.CheckDecode(cinfo > 0);
Infos = new ColInfo[cinfo];
// This dictionary is used only for detecting duplicated column names specified by user.
var nameToInfoIndex = new Dictionary<string, int>(Infos.Length);
for (int iinfo = 0; iinfo < cinfo; iinfo++)
{
string name = ctx.LoadNonEmptyString();
PrimitiveDataViewType itemType;
var kind = (InternalDataKind)ctx.Reader.ReadByte();
Contracts.CheckDecode(Enum.IsDefined(typeof(InternalDataKind), kind));
bool isKey = ctx.Reader.ReadBoolByte();
if (isKey)
{
ulong count;
Contracts.CheckDecode(KeyDataViewType.IsValidDataType(kind.ToType()));
// Special treatment for versions that had Min and Contiguous fields in KeyType.
if (ctx.Header.ModelVerWritten < VersionNoMinCount)
{
bool isContig = ctx.Reader.ReadBoolByte();
// We no longer support non contiguous values and non zero Min for KeyType.
Contracts.CheckDecode(isContig);
ulong min = ctx.Reader.ReadUInt64();
Contracts.CheckDecode(min == 0);
int cnt = ctx.Reader.ReadInt32();
Contracts.CheckDecode(cnt >= 0);
count = (ulong)cnt;
// Since we removed the notion of unknown cardinality (count == 0), we map to the maximum value.
if (count == 0)
count = kind.ToMaxInt();
}
else
{
count = ctx.Reader.ReadUInt64();
Contracts.CheckDecode(0 < count);
}
itemType = new KeyDataViewType(kind.ToType(), count);
}
else
itemType = ColumnTypeExtensions.PrimitiveTypeFromKind(kind);
int cseg = ctx.Reader.ReadInt32();
Contracts.CheckDecode(cseg > 0);
var segs = new Segment[cseg];
for (int iseg = 0; iseg < cseg; iseg++)
{
int min = ctx.Reader.ReadInt32();
int lim = ctx.Reader.ReadInt32();
Contracts.CheckDecode(0 <= min && min < lim && lim <= SrcLim);
bool forceVector = false;
if (ctx.Header.ModelVerWritten >= VerForceVectorSupported)
forceVector = ctx.Reader.ReadBoolByte();
segs[iseg] = new Segment(min, lim, forceVector);
}
// Note that this will throw if the segments are ill-structured, including the case
// of multiple variable segments (since those segments will overlap and overlapping
// segments are illegal).
Infos[iinfo] = ColInfo.Create(name, itemType, segs, false);
nameToInfoIndex[name] = iinfo;
}
_slotNames = new VBuffer<ReadOnlyMemory<char>>[Infos.Length];
string result = null;
ctx.TryLoadTextStream("Header.txt", reader => result = reader.ReadLine());
if (!string.IsNullOrEmpty(result))
Parser.ParseSlotNames(parent, _header = result.AsMemory(), Infos, _slotNames);
OutputSchema = ComputeOutputSchema();
}
internal void Save(ModelSaveContext ctx)
{
Contracts.AssertValue(ctx);
// *** Binary format ***
// int: number of columns
// foreach column:
// int: id of column name
// byte: DataKind
// byte: bool of whether this is a key type
// for a key type:
// ulong: count for key range