-
Notifications
You must be signed in to change notification settings - Fork 539
Expand file tree
/
Copy pathNest.cs
More file actions
485 lines (457 loc) · 15.1 KB
/
Nest.cs
File metadata and controls
485 lines (457 loc) · 15.1 KB
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
using System;
using System.Collections.Generic;
using System.Text;
using Tensorflow.Common.Extensions;
namespace Tensorflow.Common.Types
{
public enum NestType
{
Empty,
Node,
List,
Dictionary
}
/// <summary>
/// A nested structure which may inclulde value, list and dictionary.
/// Note that dictionary does not ensure the data order. When using it as IEnumerable,
/// its order is depth-first.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Nest<T> : INestStructure<T>, IEnumerable<T>
{
private static readonly Nest<T> _empty = new Nest<T>()
{
NestType = NestType.Empty,
};
public static Nest<T> Empty => _empty;
public NestType NestType { get; protected set; }
public string? Name { get; set; }
public T? NodeValue { get; protected set; }
public List<INestStructure<T>>? ListValue { get; protected set; }
public Dictionary<string, INestStructure<T>>? DictValue { get; protected set; }
public int ShallowNestedCount
{
get
{
if (NestType == NestType.Empty)
{
return 0;
}
else if (NestType == NestType.Node)
{
return 1;
}
else if (NestType == NestType.List)
{
return ListValue!.Count;
}
else // dict
{
return DictValue!.Count;
}
}
}
public int TotalNestedCount
{
get
{
return Flatten().Count();
}
}
protected Nest() { }
public Nest(T value, string? name = null)
{
NodeValue = value;
Name = name;
NestType = NestType.Node;
}
public Nest(IEnumerable<INestStructure<T>> values, string? name = null)
{
ListValue = values.ToList();
Name = name;
NestType = NestType.List;
}
public Nest(Dictionary<string, INestStructure<T>> value, string? name = null)
{
DictValue = value;
Name = name;
NestType = NestType.Dictionary;
}
public Nest(Nest<T> other)
{
NestType = other.NestType;
NodeValue = other.NodeValue;
DictValue = other.DictValue;
ListValue = other.ListValue;
Name = other.Name;
}
public virtual IEnumerable<T> Flatten()
{
return FlattenInternal(this);
}
public virtual INestStructure<TOut> MapStructure<TOut>(Func<T, TOut> func)
{
return MapStructureInternal(func);
}
/// <summary>
/// Pack the flat items to a nested sequence by the template.
/// </summary>
/// <param name="flatItems"></param>
/// <returns></returns>
public virtual Nest<TOut> PackSequence<TOut>(TOut[] flatItems)
{
if(flatItems.Length == 0)
{
return Nest<TOut>.Empty;
}
int index = 0;
return PackSequenceInternal(this, flatItems, ref index);
}
private static Nest<TOut> PackSequenceInternal<TOut>(Nest<T> template, TOut[] flatItems, ref int index)
{
if(template.NestType == NestType.Node)
{
if(index >= flatItems.Length)
{
throw new InvalidArgumentError("The template and flat items are not matched.");
}
return new Nest<TOut>(flatItems[index++]);
}
else if(template.NestType == NestType.List)
{
List<Nest<TOut>> nestedObjects = new List<Nest<TOut>>();
for (int i = 0; i < template.ListValue!.Count; i++)
{
nestedObjects.Add(PackSequenceInternal(template.ListValue![i].AsNest(), flatItems, ref index));
}
return new Nest<TOut>(nestedObjects);
}
else if(template.NestType == NestType.Node)
{
Dictionary<string, INestStructure<TOut>> dict = new Dictionary<string, INestStructure<TOut>>();
foreach(var (key, value) in template.DictValue!)
{
dict[key] = PackSequenceInternal(value.AsNest(), flatItems, ref index);
}
return new Nest<TOut>(dict);
}
// Consider Empty as invalid type.
throw new InvalidArgumentError("When using `PackSequenceAs`, the template cannot contain empty node.");
}
public virtual Nest<T> AsNest()
{
return this;
}
public virtual Nest<T> MergeWith(Nest<T>? other)
{
if(other is null || other == Nest<T>.Empty)
{
return this;
}
if(this == Nest<T>.Empty)
{
return other;
}
if(NestType == NestType.Node && other.NestType == NestType.Node)
{
return new Nest<T>(new Nest<T>[] { this, other });
}
else if(NestType == NestType.List && other.NestType == NestType.List)
{
return new Nest<T>(this.ListValue!.Concat(other.ListValue!));
}
else if(NestType == NestType.Dictionary && other.NestType == NestType.Dictionary)
{
return new Nest<T>(this.DictValue!.Concat(other.DictValue!).ToDictionary(x => x.Key, x => x.Value));
}
else
{
return new Nest<T>(new Nest<T>[] { this, other });
}
}
/// <summary>
/// To see if the nested object is really nested. Despite being called `Nest`, sometimes it's actually not
/// nested. For example, [1, 2, 3] is not nested, while [1, [2, 3]] is nested.
/// </summary>
/// <returns></returns>
public bool IsNested()
{
if(NestType is NestType.Empty or NestType.Node)
{
return false;
}
else if(NestType is NestType.List)
{
return ListValue!.Count > 0;
}
else
{
return DictValue!.Count > 0;
}
}
[Obsolete("The indexer of Tensors is not encouraged because it leads to unclear meanings.")]
public T this[int index]
{
get
{
bool success = FindInternal(this, index, out var result);
if (success)
{
return result;
}
else
{
throw new IndexOutOfRangeException();
}
}
set
{
bool success = SetInternal(this, index, value);
if (!success)
{
throw new IndexOutOfRangeException();
}
}
}
/// <summary>
/// If the existing nested structure if of type `Nest[INestStructure[T]]`, we can reduce it
/// to `Nest[T]`.
/// </summary>
/// <typeparam name="TOut"></typeparam>
/// <param name="input"></param>
/// <returns></returns>
public static Nest<T> ReduceFrom<TOut>(INestStructure<TOut> input) where TOut: INestStructure<T>
{
var nested = input.AsNest();
return ReduceInternal(nested).AsNest();
}
private static INestStructure<T> ReduceInternal<TOut>(Nest<TOut> node) where TOut : INestStructure<T>
{
if(node.NestType == NestType.Empty)
{
return Nest<T>.Empty;
}
else if(node.NestType == NestType.Node)
{
return node.NodeValue!.AsNest();
}
else if(node.NestType == NestType.List)
{
return new Nest<T>(node.ListValue!.Select(x => ReduceInternal(x.AsNest())));
}
else // Dictionary type
{
return new Nest<T>(node.DictValue!.ToDictionary(x => x.Key, x => ReduceInternal(x.Value.AsNest())));
}
}
private static bool FindInternal(Nest<T> node, int index, out T? result)
{
if (node.NestType == NestType.Node)
{
if(index == 0)
{
result = node.NodeValue!;
return true;
}
result = default(T);
return false;
}
else if (node.NestType == NestType.List)
{
foreach (var item in node.ListValue!)
{
if(index == 0)
{
return FindInternal(item.AsNest(), index, out result);
}
index--;
}
result = default(T);
return false;
}
else if(node.NestType == NestType.Dictionary)
{
foreach (var item in node.DictValue!.Values)
{
if (index == 0)
{
return FindInternal(item.AsNest(), index, out result);
}
index--;
}
result = default(T);
return false;
}
else
{
result = default(T);
return false;
}
}
private static bool SetInternal(Nest<T> node, int index, T newValue)
{
if (node.NestType == NestType.Node)
{
if (index == 0)
{
node.NodeValue = newValue;
return true;
}
return false;
}
else if (node.NestType == NestType.List)
{
foreach (var item in node.ListValue!)
{
if (index == 0)
{
return SetInternal(item.AsNest(), index, newValue);
}
index--;
}
return false;
}
else if (node.NestType == NestType.Dictionary)
{
foreach (var item in node.DictValue!.Values)
{
if (index == 0)
{
return SetInternal(item.AsNest(), index, newValue);
}
index--;
}
return false;
}
else
{
return false;
}
}
private static IEnumerable<T> FlattenInternal(Nest<T> node)
{
if (node.NestType == NestType.Node)
{
yield return node.NodeValue!;
}
else if (node.NestType == NestType.List)
{
foreach (var item in node.ListValue!)
{
foreach(var val in FlattenInternal(item.AsNest()))
{
yield return val;
}
}
}
else if (node.NestType == NestType.Dictionary)
{
foreach (var item in node.DictValue!.Values)
{
foreach (var val in FlattenInternal(item.AsNest()))
{
yield return val;
}
}
}
}
private Nest<TOut> MapStructureInternal<TOut>(Func<T, TOut> func)
{
if (NestType == NestType.Node)
{
return new Nest<TOut>(func(NodeValue!));
}
else if (NestType == NestType.List)
{
List<Nest<TOut>> outs = new List<Nest<TOut>>();
foreach (var item in ListValue!)
{
outs.Add(item.AsNest().MapStructureInternal(func));
}
return new Nest<TOut>(outs);
}
else if (NestType == NestType.Dictionary)
{
Dictionary<string, INestStructure<TOut>> outs = new Dictionary<string, INestStructure<TOut>>();
foreach (var (key, value) in DictValue!)
{
outs.Add(key, value.AsNest().MapStructureInternal(func));
}
return new Nest<TOut>(outs);
}
else
{
return Nest<TOut>.Empty;
}
}
public IEnumerator<T> GetEnumerator()
{
return Flatten().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
WriteString(this, sb);
sb.Append(")");
return sb.ToString();
}
private static void WriteString(Nest<T> node, StringBuilder sb)
{
if (!string.IsNullOrEmpty(node.Name))
{
sb.Append($"{node.Name}: ");
}
if (node.NestType == NestType.Node)
{
sb.Append(node.NodeValue!.ToString());
}
else if (node.NestType == NestType.List)
{
sb.Append("[");
for(int i = 0; i < node.ListValue!.Count; i++)
{
WriteString(node.ListValue![i].AsNest(), sb);
if(i != node.ListValue!.Count - 1)
{
sb.Append(", ");
}
}
sb.Append("]");
}
else if (node.NestType == NestType.Dictionary)
{
sb.Append("{");
int count = node.DictValue!.Count;
int i = 0;
foreach (var (key, value) in node.DictValue!)
{
sb.Append($"{key}: ");
WriteString(value.AsNest(), sb);
if (i != count - 1)
{
sb.Append(", ");
}
i++;
}
sb.Append("}");
}
else
{
sb.Append("<empty>");
}
}
public static implicit operator Nest<T>((INestStructure<T>, INestStructure<T>) inputs)
{
return new Nest<T>(new INestStructure<T>[] { inputs.Item1, inputs.Item2 });
}
public static implicit operator Nest<T>((INestStructure<T>, INestStructure<T>, INestStructure<T>) inputs)
{
return new Nest<T>(new INestStructure<T>[] { inputs.Item1, inputs.Item2, inputs.Item3 });
}
}
}