|
115 | 115 |
|
116 | 116 | # end |
117 | 117 | # end |
| 118 | + |
| 119 | +""" |
| 120 | + populate!(A, table, value) |
| 121 | +
|
| 122 | +Populate A with the contents of the `value` column in a provided table. |
| 123 | +The provided table contain columns corresponding to the keys in A and support row iteration. |
| 124 | +""" |
| 125 | +function populate!(A, table, value::Symbol) |
| 126 | + cols = [value, dimnames(A)...] |
| 127 | + for r in Tables.rows(table) |
| 128 | + setkey!(A, (Tables.getcolumn(r, c) for c in cols)...) |
| 129 | + end |
| 130 | + return A |
| 131 | +end |
| 132 | + |
| 133 | +""" |
| 134 | + KeyedArray(table, value, keys...; default=undef) |
| 135 | + NamedDimsArray(table, value, keys...; default=undef) |
| 136 | +
|
| 137 | +Construct a KeyedArray/NamedDimsArray from a `table` supporting column and row. |
| 138 | +`keys` columns are extracted as is, without sorting, and are assumed to uniquely identify |
| 139 | +each `value`. The `default` value is used in cases where no value is identified for a given |
| 140 | +keypair. |
| 141 | +""" |
| 142 | +function KeyedArray(table, value::Symbol, keys::Symbol...; kwargs...) |
| 143 | + return _construct_from_table(KeyedArray, table, value, keys...; kwargs...) |
| 144 | +end |
| 145 | + |
| 146 | +function NamedDimsArray(table, value::Symbol, keys::Symbol...; kwargs...) |
| 147 | + return _construct_from_table(NamedDimsArray, table, value, keys...; kwargs...) |
| 148 | +end |
| 149 | + |
| 150 | + |
| 151 | +# Internal function for constructing the KeyedArray or NamedDimsArray. |
| 152 | +# This code doesn't care which type we produce so we just pass that along. |
| 153 | +function _construct_from_table( |
| 154 | + T::Type, table, value::Symbol, keys::Symbol...; |
| 155 | + default=undef, issorted=false |
| 156 | +) |
| 157 | + # get columns of the input table source |
| 158 | + cols = Tables.columns(table) |
| 159 | + |
| 160 | + # Extract key columns |
| 161 | + kw = Tuple(k => unique(Tables.getcolumn(cols, k)) for k in keys) |
| 162 | + |
| 163 | + # Extract data/value column |
| 164 | + vals = Tables.getcolumn(cols, value) |
| 165 | + |
| 166 | + # Initialize the KeyedArray |
| 167 | + sz = length.(last.(kw)) |
| 168 | + |
| 169 | + A = if default === undef |
| 170 | + data = similar(vals, sz) |
| 171 | + else |
| 172 | + data = similar(vals, Union{eltype(vals), typeof(default)}, sz) |
| 173 | + fill!(data, default) |
| 174 | + end |
| 175 | + |
| 176 | + A = T(data; kw...) |
| 177 | + populate!(A, table, value) |
| 178 | + return A |
| 179 | +end |
0 commit comments