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
//! Infer ValueProperties from a public Value
//!
//! When public arguments are provided, the properties about those public arguments are not known.
//! These utility functions provide a conversion from Value to ValueProperties.

use crate::errors::*;

use crate::{Float, Integer};
use ndarray::Axis;
use ndarray::prelude::*;
use ndarray_stats::QuantileExt;

use itertools::Itertools;
use crate::base::{Array, Value, Jagged, Nature, Vector1DNull, NatureContinuous, NatureCategorical, ValueProperties, ArrayProperties, DataType, JaggedProperties, IndexKey, DataframeProperties, PartitionsProperties};

use crate::utilities::deduplicate;
use indexmap::map::IndexMap;

pub fn infer_lower(value: &Value) -> Result<Vector1DNull> {
    Ok(match value {
        Value::Array(array) => {
            match array.shape().len() as i64 {
                0 => match array {
                    Array::Float(array) =>
                        Vector1DNull::Float(vec![Some(array.first()
                            .ok_or_else(|| Error::from("lower bounds may not be length zero"))?.to_owned())]),
                    Array::Int(array) =>
                        Vector1DNull::Int(vec![Some(array.first()
                            .ok_or_else(|| Error::from("lower bounds may not be length zero"))?.to_owned())]),
                    _ => return Err("Cannot infer numeric lower bounds on a non-numeric vector".into())
                },
                1 => match array {
                    Array::Float(array) =>
                        Vector1DNull::Float(array.iter().map(|v| Some(*v)).collect()),
                    Array::Int(array) =>
                        Vector1DNull::Int(array.iter().map(|v| Some(*v)).collect()),
                    _ => return Err("Cannot infer numeric lower bounds on a non-numeric vector".into())
                },
                2 => match array {
                    Array::Float(array) =>
                        Vector1DNull::Float(array.lanes(Axis(0)).into_iter()
                            .map(|col| col.min().map(|v| *v).map_err(|e| e.into()))
                            .collect::<Result<Vec<Float>>>()?
                            .into_iter().map(Some).collect()),
                    Array::Int(array) =>
                        Vector1DNull::Int(array.lanes(Axis(0)).into_iter()
                            .map(|col| col.min().map(|v| *v).map_err(|e| e.into()))
                            .collect::<Result<Vec<Integer>>>()?
                            .into_iter().map(Some).collect()),
                    _ => return Err("Cannot infer numeric lower bounds on a non-numeric vector".into())
                },
                _ => return Err("arrays may have max dimensionality of 2".into())
            }
        }
        Value::Jagged(jagged) => {
            match jagged {
                Jagged::Float(jagged) => Vector1DNull::Float(jagged.iter()
                    .map(|col| col.iter().copied().fold1(|l, r| l.min(r))
                        .ok_or_else(|| Error::from("attempted to infer lower bounds on an empty value")))
                    .collect::<Result<Vec<Float>>>()?.into_iter().map(Some).collect()),
                Jagged::Int(jagged) => Vector1DNull::Int(jagged.iter()
                    .map(|col| col.iter().min()
                        .ok_or_else(|| Error::from("attempted to infer lower bounds on an empty value")))
                    .collect::<Result<Vec<&Integer>>>()?.into_iter().copied().map(Some).collect()),
                _ => return Err("Cannot infer numeric lower bounds on a non-numeric vector".into())
            }
        }
        _ => return Err("bounds inference is only implemented for arrays and jagged arrays".into())
    })
}

pub fn infer_upper(value: &Value) -> Result<Vector1DNull> {
    Ok(match value {
        Value::Array(array) => {
            match array.shape().len() as i64 {
                0 => match array {
                    Array::Float(array) =>
                        Vector1DNull::Float(vec![Some(array.first()
                            .ok_or_else(|| Error::from("upper bounds may not be length zero"))?.to_owned())]),
                    Array::Int(array) =>
                        Vector1DNull::Int(vec![Some(array.first()
                            .ok_or_else(|| Error::from("upper bounds may not be length zero"))?.to_owned())]),
                    _ => return Err("Cannot infer numeric upper bounds on a non-numeric vector".into())
                },
                1 => match array {
                    Array::Float(array) =>
                        Vector1DNull::Float(array.iter().map(|v| Some(*v)).collect()),
                    Array::Int(array) =>
                        Vector1DNull::Int(array.iter().map(|v| Some(*v)).collect()),
                    _ => return Err("Cannot infer numeric upper bounds on a non-numeric vector".into())
                },
                2 => match array {
                    Array::Float(array) =>
                        Vector1DNull::Float(array.lanes(Axis(0)).into_iter()
                            .map(|col| col.max().map(|v| *v).map_err(|e| e.into()))
                            .collect::<Result<Vec<Float>>>()?
                            .into_iter().map(Some).collect()),
                    Array::Int(array) =>
                        Vector1DNull::Int(array.lanes(Axis(0)).into_iter()
                            .map(|col| col.max().map(|v| *v).map_err(|e| e.into()))
                            .collect::<Result<Vec<Integer>>>()?
                            .into_iter().map(Some).collect()),
                    _ => return Err("Cannot infer numeric upper bounds on a non-numeric vector".into())
                },
                _ => return Err("arrays may have max dimensionality of 2".into())
            }
        }
        Value::Jagged(jagged) => {
            match jagged {
                Jagged::Float(jagged) => Vector1DNull::Float(jagged.iter()
                    .map(|col| col.iter().copied().fold1(|l, r| l.max(r))
                        .ok_or_else(|| Error::from("attempted to infer lower bounds on an empty value")))
                    .collect::<Result<Vec<Float>>>()?.into_iter().map(Some).collect()),
                Jagged::Int(jagged) => Vector1DNull::Int(jagged.iter()
                    .map(|col| col.iter().max()
                        .ok_or_else(|| Error::from("attempted to infer lower bounds on an empty value")))
                    .collect::<Result<Vec<&Integer>>>()?.into_iter().copied().map(Some).collect()),
                _ => return Err("Cannot infer numeric upper bounds on a non-numeric vector".into())
            }
        }
        _ => return Err("bounds inference is only implemented for arrays and jagged arrays".into())
    })
}

pub fn infer_categories(value: &Value) -> Result<Jagged> {
    match value {
        Value::Array(array) => match array {
            Array::Bool(array) =>
                Jagged::Bool(array.gencolumns().into_iter().map(|col|
                    Ok(col.into_dyn().into_dimensionality::<Ix1>()?.to_vec()))
                    .collect::<Result<Vec<_>>>()?),
            Array::Float(array) =>
                Jagged::Float(array.gencolumns().into_iter().map(|col|
                    Ok(col.into_dyn().into_dimensionality::<Ix1>()?.to_vec()))
                    .collect::<Result<Vec<_>>>()?),
            Array::Int(array) =>
                Jagged::Int(array.gencolumns().into_iter().map(|col|
                    Ok(col.into_dyn().into_dimensionality::<Ix1>()?.to_vec()))
                    .collect::<Result<Vec<_>>>()?),
            Array::Str(array) =>
                Jagged::Str(array.gencolumns().into_iter().map(|col|
                    Ok(col.into_dyn().into_dimensionality::<Ix1>()?.to_vec()))
                    .collect::<Result<Vec<_>>>()?),
        }
        Value::Jagged(jagged) => match jagged {
            Jagged::Bool(array) =>
                Jagged::Bool(array.iter().cloned().map(deduplicate).collect()),
            Jagged::Float(_array) =>
                return Err("categories are not defined for floats".into()),
            Jagged::Int(array) =>
                Jagged::Int(array.iter().cloned().map(deduplicate).collect()),
            Jagged::Str(array) =>
                Jagged::Str(array.iter().cloned().map(deduplicate).collect()),
        }
        _ => return Err("category inference is only implemented for arrays and jagged arrays".into()),
    }.deduplicate()
}

pub fn infer_nature(
    value: &Value, prior_property: Option<&ValueProperties>
) -> Result<Option<Nature>> {
    Ok(match value {
        Value::Array(array) => match array {
            Array::Float(array) => Some(Nature::Continuous(NatureContinuous {
                lower: infer_lower(&array.clone().into())?,
                upper: infer_upper(&array.clone().into())?,
            })),
            Array::Int(array) => {
                let is_categorical = match prior_property {
                    Some(p) => p.array()?.clone().nature.map(|nature| match nature {
                        Nature::Categorical(_) => true,
                        Nature::Continuous(_) => false
                    }).unwrap_or(false),
                    None => false
                };
                if is_categorical {
                    Some(Nature::Categorical(NatureCategorical {
                        categories: infer_categories(&array.clone().into())?
                    }))
                } else {
                    Some(Nature::Continuous(NatureContinuous {
                        lower: infer_lower(&array.clone().into())?,
                        upper: infer_upper(&array.clone().into())?,
                    }))
                }

            },
            Array::Bool(array) => Some(Nature::Categorical(NatureCategorical {
                categories: infer_categories(&array.clone().into())?,
            })),
            Array::Str(array) => Some(Nature::Categorical(NatureCategorical {
                categories: infer_categories(&array.clone().into())?,
            })),
        },
        Value::Jagged(jagged) => match jagged {
            Jagged::Float(_) => None,
            _ => Some(Nature::Categorical(NatureCategorical {
                categories: infer_categories(value)?,
            }))
        },
        _ => return Err("nature inference is only implemented for arrays and jagged arrays".into())
    })
}

pub fn infer_nullity(value: &Value) -> Result<bool> {
    match value {
        Value::Array(value) => match value {
            Array::Float(value) => Ok(value.iter().any(|v| !v.is_finite())),
            _ => Ok(false)
        },
        _ => Ok(false)
    }
}

pub fn infer_property(
    value: &Value, prior_property: Option<&ValueProperties>, node_id: u32
) -> Result<ValueProperties> {

    Ok(match value {
        Value::Array(array) => {
            let prior_prop_arr = match prior_property {
                Some(p) => Some(p.array()?),
                None => None
            };
            ArrayProperties {
                nullity: infer_nullity(&value)?,
                releasable: true,
                nature: infer_nature(&value, prior_property)?,
                c_stability: prior_prop_arr
                    .map(|prop| prop.c_stability)
                    .unwrap_or(1),
                num_columns: Some(array.num_columns()? as i64),
                num_records: Some(array.num_records()? as i64),
                aggregator: prior_prop_arr.and_then(|p| p.aggregator.clone()),
                data_type: match array {
                    Array::Bool(_) => DataType::Bool,
                    Array::Float(_) => DataType::Float,
                    Array::Int(_) => DataType::Int,
                    Array::Str(_) => DataType::Str,
                },
                dataset_id: prior_prop_arr.and_then(|p| p.dataset_id),
                node_id: node_id as i64,
                is_not_empty: array.num_records()? != 0,
                dimensionality: Some(array.shape().len() as i64),
                group_id: prior_prop_arr
                    .map(|v| v.group_id.clone())
                    .unwrap_or_else(Vec::new),
                naturally_ordered: true,
                sample_proportion: prior_prop_arr.and_then(|p| p.sample_proportion)
            }.into()
        },
        Value::Dataframe(dataframe) => match prior_property {
            Some(ValueProperties::Dataframe(prior_property)) =>
                DataframeProperties {
                    children: dataframe.iter()
                        .zip(prior_property.children.values())
                        .map(|((name, value), prop)|
                            infer_property(value, Some(prop), node_id)
                                .map(|v| (name.clone(), v)))
                        .collect::<Result<IndexMap<IndexKey, ValueProperties>>>()?,
                }.into(),
            Some(_) => return Err("the prior properties for the dataframe do not match the actual data".into()),
            None =>
                DataframeProperties {
                    children: dataframe.iter()
                        .map(|(name, value)| infer_property(value, None, node_id)
                            .map(|v| (name.clone(), v)))
                        .collect::<Result<IndexMap<IndexKey, ValueProperties>>>()?,
                }.into()
        }
        Value::Partitions(partitions) => match prior_property {
            Some(ValueProperties::Partitions(prior_property)) =>
                PartitionsProperties {
                    children: partitions.iter()
                        .zip(prior_property.children.values())
                        .map(|((name, value), prop)|
                            infer_property(value, Some(prop), node_id)
                                .map(|v| (name.clone(), v)))
                        .collect::<Result<IndexMap<IndexKey, ValueProperties>>>()?,
                }.into(),
            Some(_) => return Err("the prior properties for the partitions do not match the actual data".into()),
            None =>
                PartitionsProperties {
                    children: partitions.iter()
                        .map(|(name, value)| infer_property(value, None, node_id)
                            .map(|v| (name.clone(), v)))
                        .collect::<Result<IndexMap<IndexKey, ValueProperties>>>()?,
                }.into()
        }
        Value::Jagged(jagged) => JaggedProperties {
            num_records: Some(jagged.num_records()),
            nullity: match &jagged {
                Jagged::Float(jagged) => jagged.iter()
                    .any(|col| col.iter()
                        .any(|elem| !elem.is_finite())),
                _ => false
            },
            aggregator: None,
            nature: infer_nature(value, prior_property)?,
            data_type: match jagged {
                Jagged::Bool(_) => DataType::Bool,
                Jagged::Float(_) => DataType::Float,
                Jagged::Int(_) => DataType::Int,
                Jagged::Str(_) => DataType::Str,
            },
            releasable: true
        }.into(),
        // TODO: custom properties for Functions (may not be needed)
        Value::Function(_function) => unreachable!()
    })
}