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
use crate::errors::*;

use crate::{proto, base, Warnable, Integer};

use crate::components::{Component, Expandable};
use crate::base::{IndexKey, Value, Jagged, ValueProperties, ArrayProperties, NodeProperties, PartitionsProperties};
use crate::utilities::{prepend, get_literal, get_argument};
use indexmap::map::IndexMap;
use itertools::Itertools;
use crate::utilities::inference::infer_property;


impl Component for proto::Partition {
    fn propagate_property(
        &self,
        privacy_definition: &Option<proto::PrivacyDefinition>,
        public_arguments: IndexMap<base::IndexKey, &Value>,
        properties: base::NodeProperties,
        node_id: u32,
    ) -> Result<Warnable<ValueProperties>> {
        let data_property = properties.get::<IndexKey>(&"data".into())
            .ok_or("data: missing")?.clone();

        let neighboring = proto::privacy_definition::Neighboring::from_i32(privacy_definition.as_ref()
            .ok_or_else(|| Error::from("privacy_definition must be defined"))?.neighboring)
            .ok_or_else(|| Error::from("neighboring must be defined"))?;

        Ok(ValueProperties::Partitions(match properties.get::<IndexKey>(&"by".into()) {

            // propagate properties when partitioning "by" some array
            Some(by_property) => {
                // TODO: pass non-homogeneously typed keys via indexmap (needs merge component)
                let by_property = by_property.array()
                    .map_err(prepend("by:"))?.clone();
                by_property.num_columns
                    .ok_or_else(|| Error::from("number of columns must be known on by"))?;
                let categories = by_property.categories()
                    .map_err(prepend("by:"))?;

                let partition_keys = make_dense_partition_keys(categories, by_property.dimensionality)?;

                PartitionsProperties {
                    children: broadcast_partitions(partition_keys, &data_property, node_id, neighboring)?,
                }
            }

            // propagate properties when partitioning evenly
            None => {
                let num_partitions = get_argument(&public_arguments, "num_partitions")?
                    .ref_array()?.first_int()?;

                let num_records = match &data_property {
                    ValueProperties::Array(data_property) => data_property.num_records,
                    ValueProperties::Dataframe(data_property) => data_property.num_records()?,
                    _ => return Err("data: must be a dataframe or array".into())
                };
                let lengths = match num_records {
                    Some(num_records) => even_split_lengths(num_records, num_partitions as i64)
                        .into_iter().map(Some).collect(),
                    None => (0..num_partitions)
                        .map(|_| None)
                        .collect::<Vec<Option<i64>>>()
                };

                PartitionsProperties {
                    children: lengths.iter().enumerate()
                        .map(|(index, partition_num_records)| Ok((
                            IndexKey::from(index as Integer),
                            get_partition_properties(
                                &data_property,
                                IndexKey::from(index as Integer),
                                *partition_num_records,
                                node_id,
                                neighboring)?
                        )))
                        .collect::<Result<IndexMap<IndexKey, ValueProperties>>>()?,
                }
            }
        }).into())
    }
}

impl Expandable for proto::Partition {
    fn expand_component(
        &self,
        _privacy_definition: &Option<proto::PrivacyDefinition>,
        component: &proto::Component,
        _public_arguments: &IndexMap<IndexKey, &Value>,
        properties: &NodeProperties,
        component_id: u32,
        mut maximum_id: u32
    ) -> Result<base::ComponentExpansion> {

        let mut expansion = base::ComponentExpansion::default();

        if let Some(by) = properties.get::<IndexKey>(&"by".into()) {
            if !properties.contains_key::<IndexKey>(&"categories".into()) {
                let categories = by.array()?.categories()?;
                maximum_id += 1;
                let id_categories = maximum_id;
                let (patch_node, release) = get_literal(Value::Jagged(categories), component.submission)?;
                expansion.computation_graph.insert(id_categories, patch_node);
                expansion.properties.insert(id_categories, infer_property(&release.value, None, id_categories)?);
                expansion.releases.insert(id_categories, release);

                let mut component = component.clone();
                component.insert_argument(&"categories".into(), id_categories);
                expansion.computation_graph.insert(component_id, component);
            }
        }

        Ok(expansion)
    }
}

pub fn broadcast_partitions(
    partition_keys: Vec<IndexKey>, properties: &ValueProperties, node_id: u32,
    neighboring_definition: proto::privacy_definition::Neighboring
) -> Result<IndexMap<IndexKey, ValueProperties>> {
    // create dense partitioning
    partition_keys.into_iter()
        .map(|v| Ok((v.clone(), get_partition_properties(
            properties,
            v,
            None,
            node_id,
            neighboring_definition)?)))
        .collect()
}

fn get_partition_properties(
    properties: &ValueProperties,
    index: IndexKey, num_records: Option<i64>, node_id: u32,
    neighboring_definition: proto::privacy_definition::Neighboring
) -> Result<ValueProperties> {

    let update_array_properties = |mut properties: ArrayProperties| -> ArrayProperties {
        // update properties
        properties.group_id.push(base::GroupId {
            partition_id: node_id,
            index: index.clone()
        });
        properties.num_records = num_records;
        properties.dataset_id = Some(node_id as i64);
        properties.is_not_empty = num_records.unwrap_or(0) != 0;

        if neighboring_definition == proto::privacy_definition::Neighboring::Substitute {
            properties.c_stability = properties.c_stability * 2
        }

        properties
    };

    Ok(match properties {
        ValueProperties::Array(properties) => ValueProperties::Array(update_array_properties(properties.clone())),
        ValueProperties::Dataframe(properties) => {
            let mut properties = properties.clone();
            properties.children.values_mut()
                .try_for_each(|v| {
                    *v = ValueProperties::Array(update_array_properties(v.array()?.clone()));
                    Ok::<_, Error>(())
                })?;
            ValueProperties::Dataframe(properties)
        }
        _ => return Err("data: must be a dataframe or array".into())
    })
}

pub fn make_dense_partition_keys(categories: Jagged, dimensionality: Option<i64>) -> Result<Vec<IndexKey>> {
    let categories = categories.to_index_keys()?;

    // TODO: sparse partitioning component
    Ok(match dimensionality {
        Some(0) => return Err("categories: must be defined for at least one column".into()),
        Some(1) => {
            if categories.len() != 1 {
                return Err("categories: must be defined for exactly one column".into())
            }
            categories[0].clone()
        }
        _ => categories.into_iter().multi_cartesian_product()
            .map(IndexKey::Tuple).collect()
    })
}

pub fn even_split_lengths(num_records: i64, num_partitions: i64) -> Vec<i64> {
    (0..num_partitions)
        .map(|index| num_records / num_partitions + (if index >= (num_records % num_partitions) { 0 } else { 1 }))
        .collect()
}


#[cfg(test)]
mod test_partition {
    use crate::components::partition::even_split_lengths;

    fn vec_eq(left: &Vec<i64>, right: &Vec<i64>) -> bool {
        (left.len() == right.len()) && left.iter().zip(right)
            .all(|(a, b)| a == b)
    }

    #[test]
    fn test_units() {
        assert!(vec_eq(
            &even_split_lengths(4, 3),
            &vec![2, 1, 1]));
        assert!(vec_eq(
            &even_split_lengths(5, 3),
            &vec![2, 2, 1]));
        assert!(vec_eq(
            &even_split_lengths(3, 3),
            &vec![1, 1, 1]));
        assert!(vec_eq(
            &even_split_lengths(2, 3),
            &vec![1, 1, 0]));
        assert!(vec_eq(
            &even_split_lengths(2, 0),
            &vec![]));
    }
}