-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCategory.cs
More file actions
183 lines (160 loc) · 6.1 KB
/
Copy pathCategory.cs
File metadata and controls
183 lines (160 loc) · 6.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace JSONstat.Models;
/// <summary>
/// The <c>category</c> object of a dimension: ordered ids plus per-category
/// labels, hierarchies, coordinates and units. Source: <c>../wiki/dimensions.md</c>.
/// </summary>
public sealed class Category
{
/// <summary>
/// Category ordering. Accepts the array form (<c>["M","F"]</c>) or the
/// object form (<c>{"M":0,"F":1}</c>) on read and always writes the object
/// form. <c>null</c> for constant dimensions without an index.
/// </summary>
[JsonPropertyName("index")]
[JsonConverter(typeof(CategoryIndexConverter))]
public Dictionary<string, int>? Index { get; set; }
/// <summary>Per-category labels (falls back to the id when absent).</summary>
[JsonPropertyName("label")]
public Dictionary<string, string>? Label { get; set; }
/// <summary>Hierarchical relationships (parent id -> child ids).</summary>
[JsonPropertyName("child")]
public Dictionary<string, string[]>? Child { get; set; }
/// <summary>Geographic coordinates [longitude, latitude].</summary>
[JsonPropertyName("coordinates")]
public Dictionary<string, double[]>? Coordinates { get; set; }
/// <summary>Units of measure for metric-role categories.</summary>
[JsonPropertyName("unit")]
public Dictionary<string, Unit>? Unit { get; set; }
/// <summary>Provider-specific extension properties.</summary>
[JsonExtensionData]
public IDictionary<string, JsonElement>? ExtensionData { get; set; }
private string[] _orderedIds = System.Array.Empty<string>();
private readonly Dictionary<string, int> _idToPos = new Dictionary<string, int>();
private bool _built;
/// <summary>Canonicalizes the category order. Called by the owning dimension.</summary>
internal void Build(int size)
{
if (_built) return;
if (Index != null && Index.Count > 0)
{
_orderedIds = Index.OrderBy(kv => kv.Value).Select(kv => kv.Key).ToArray();
}
else if (Label != null && Label.Count > 0)
{
_orderedIds = Label.Keys.ToArray();
}
else
{
int n = size > 0 ? size : 1;
_orderedIds = Enumerable.Range(0, n).Select(_ => "").ToArray();
}
_idToPos.Clear();
for (int i = 0; i < _orderedIds.Length; i++) _idToPos[_orderedIds[i]] = i;
_built = true;
}
private void EnsureBuilt()
{
if (!_built) Build(0);
}
private string LabelOf(string id) =>
Label != null && Label.TryGetValue(id, out var l) ? l : id;
private double[]? CoordinatesOf(string id) =>
Coordinates != null && Coordinates.TryGetValue(id, out var c) ? c : null;
private Unit? UnitOf(string id) =>
Unit != null && Unit.TryGetValue(id, out var u) ? u : null;
/// <summary>The category ids in order.</summary>
[JsonIgnore]
public IReadOnlyList<string> Ids
{
get { EnsureBuilt(); return _orderedIds; }
}
/// <summary>The category labels in order.</summary>
[JsonIgnore]
public IReadOnlyList<string> Labels
{
get { EnsureBuilt(); return _orderedIds.Select(LabelOf).ToArray(); }
}
/// <summary>The categories as entries.</summary>
[JsonIgnore]
public IReadOnlyList<CategoryEntry> Entries
{
get
{
EnsureBuilt();
return _orderedIds
.Select((id, i) => new CategoryEntry(id, LabelOf(id), i, CoordinatesOf(id), UnitOf(id)))
.ToArray();
}
}
/// <summary>Gets the category at the given index, or <c>null</c>.</summary>
public CategoryEntry? Entry(int index)
{
EnsureBuilt();
if (index < 0 || index >= _orderedIds.Length) return null;
var id = _orderedIds[index];
return new CategoryEntry(id, LabelOf(id), index, CoordinatesOf(id), UnitOf(id));
}
/// <summary>Gets the category with the given id, or <c>null</c>.</summary>
public CategoryEntry? Entry(string id)
{
EnsureBuilt();
if (!_idToPos.TryGetValue(id, out var i)) return null;
return new CategoryEntry(id, LabelOf(id), i, CoordinatesOf(id), UnitOf(id));
}
/// <summary>Position of a category id, or <c>null</c> when unknown.</summary>
public int? PositionOf(string id)
{
EnsureBuilt();
return _idToPos.TryGetValue(id, out var i) ? (int?)i : null;
}
}
/// <summary>
/// Reads a category <c>index</c> in either array or object form into a
/// <see cref="Dictionary{TKey, TValue}"/> of id -> position, and writes the
/// canonical object form.
/// </summary>
internal sealed class CategoryIndexConverter : JsonConverter<Dictionary<string, int>>
{
public override Dictionary<string, int> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dict = new Dictionary<string, int>();
if (reader.TokenType == JsonTokenType.StartArray)
{
int pos = 0;
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
dict[reader.GetString()!] = pos++;
}
}
else if (reader.TokenType == JsonTokenType.StartObject)
{
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject) break;
string key = reader.GetString()!;
if (!reader.Read()) throw new JsonException("Unexpected end of category index.");
dict[key] = reader.GetInt32();
}
}
else
{
throw new JsonException("category index must be an array or an object.");
}
return dict;
}
public override void Write(Utf8JsonWriter writer, Dictionary<string, int> value, JsonSerializerOptions options)
{
writer.WriteStartObject();
foreach (var kv in value.OrderBy(p => p.Value))
{
writer.WritePropertyName(kv.Key);
writer.WriteNumberValue(kv.Value);
}
writer.WriteEndObject();
}
}