opendp 0.14.2-dev.20260401.2

A library of differential privacy algorithms for the statistical analysis of sensitive private data.
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
use std::any::Any;
use std::fmt::Debug;
use std::sync::Arc;

use crate::core::MetricSpace;
use crate::error::Fallible;
use crate::transformations::traits::UnboundedMetric;
use crate::{core::Domain, traits::CheckAtom};

use chrono::{NaiveDate, NaiveTime};
use polars::prelude::*;

use crate::domains::{AtomDomain, CategoricalDomain, DatetimeDomain, OptionDomain};

use super::{ArrayDomain, EnumDomain};

#[cfg(feature = "ffi")]
mod ffi;

#[cfg(test)]
mod test;

/// # Proof Definition
/// `SeriesDomain` describes the domain of all polars `Series`.
///
/// # Example
/// ```
/// use opendp::domains::AtomDomain;
/// use opendp::domains::SeriesDomain;
/// // Create a SeriesDomain with column `A` and `i32` AtomDomain.
/// let series = SeriesDomain::new("A", AtomDomain::<i32>::default());
/// // Create a SeriesDomain with column `B` and `f64` AtomDomain with bounds `[1.0, 2.0]`.
/// let series_with_bounds = SeriesDomain::new("B", AtomDomain::<f64>::new_closed((1.0, 2.0))?);
/// # opendp::error::Fallible::Ok(())
/// ```
#[derive(Clone)]
pub struct SeriesDomain {
    /// The name of series in the domain.
    pub name: PlSmallStr,
    /// Domain of each element in the series.
    pub element_domain: Arc<dyn DynSeriesElementDomain>,
    /// Indicates if elements can be null.
    pub nullable: bool,
}

impl PartialEq for SeriesDomain {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.element_domain.eq(&other.element_domain)
            && self.nullable == other.nullable
    }
}

impl Domain for SeriesDomain {
    type Carrier = Series;
    fn member(&self, value: &Self::Carrier) -> Fallible<bool> {
        if &self.name != &value.name() {
            return Ok(false);
        }

        macro_rules! atom_member {
            ($ty:ty, $polars_ty:ty) => {{
                let atom_domain = self.atom_domain::<<$ty as ToOwned>::Owned>()?;

                let chunked = value.0.unpack::<$polars_ty>()?;
                if !self.nullable && chunked.null_count() > 0 {
                    return Ok(false);
                }

                for arr in chunked.downcast_iter() {
                    for v in arr.values_iter() {
                        if !atom_domain.member(&v.to_owned())? {
                            return Ok(false);
                        }
                    }
                }
                Ok(true)
            }};
        }

        match self.dtype() {
            DataType::UInt8 => atom_member!(u8, UInt8Type),
            DataType::UInt16 => atom_member!(u16, UInt16Type),
            DataType::UInt32 => atom_member!(u32, UInt32Type),
            DataType::UInt64 => atom_member!(u64, UInt64Type),
            DataType::Int8 => atom_member!(i8, Int8Type),
            DataType::Int16 => atom_member!(i16, Int16Type),
            DataType::Int32 => atom_member!(i32, Int32Type),
            DataType::Int64 => atom_member!(i64, Int64Type),
            DataType::Float32 => atom_member!(f32, Float32Type),
            DataType::Float64 => atom_member!(f64, Float64Type),
            DataType::Boolean => atom_member!(bool, BooleanType),
            DataType::String => atom_member!(str, StringType),
            _ => return fallible!(NotImplemented, "unsupported dtype: {:?}", self.dtype()),
        }
    }
}

impl SeriesDomain {
    /// # Proof Definition
    /// Returns a series domain spanning all series whose name is `name`
    /// and elements of the series are members of `element_domain`.
    pub fn new<S: Into<PlSmallStr>, DA: 'static + SeriesElementDomain>(
        name: S,
        element_domain: DA,
    ) -> Self {
        SeriesDomain {
            name: name.into(),
            element_domain: Arc::new(element_domain.inner_domain().clone()),
            nullable: DA::NULLABLE,
        }
    }

    /// # Proof Definition
    /// Returns the datatype of rows in members of `self`.
    pub fn dtype(&self) -> DataType {
        self.element_domain.dtype()
    }

    /// # Proof Definition
    /// Modifies `self` such that rows of members are members of `element_domain`.
    pub fn set_element_domain<DA: 'static + SeriesElementDomain<InnerDomain = DA>>(
        &mut self,
        element_domain: DA,
    ) {
        self.element_domain = Arc::new(element_domain);
    }

    fn new_element_domain(dtype: DataType) -> Fallible<Arc<dyn DynSeriesElementDomain>> {
        Ok(match dtype {
            DataType::Boolean => Arc::new(AtomDomain::<bool>::default()),
            DataType::UInt32 => Arc::new(AtomDomain::<u32>::default()),
            DataType::UInt64 => Arc::new(AtomDomain::<u64>::default()),
            DataType::Int8 => Arc::new(AtomDomain::<i8>::default()),
            DataType::Int16 => Arc::new(AtomDomain::<i16>::default()),
            DataType::Int32 => Arc::new(AtomDomain::<i32>::default()),
            DataType::Int64 => Arc::new(AtomDomain::<i64>::default()),
            DataType::Float32 => Arc::new(AtomDomain::<f64>::default()),
            DataType::Float64 => Arc::new(AtomDomain::<f64>::default()),
            DataType::String => Arc::new(AtomDomain::<String>::default()),
            DataType::Date => Arc::new(AtomDomain::<NaiveDate>::default()),
            DataType::Datetime(time_unit, time_zone) => Arc::new(DatetimeDomain {
                time_unit,
                time_zone,
            }),
            DataType::Time => Arc::new(AtomDomain::<NaiveTime>::default()),
            DataType::Categorical(_, _) => Arc::new(CategoricalDomain::default()),
            DataType::Enum(categories, _) => {
                let categories = categories.categories().non_null_values_iter().collect();
                Arc::new(EnumDomain::new(categories)?)
            }
            DataType::Array(dtype, size) => {
                let element_domain = Self::new_element_domain(*dtype)?;
                Arc::new(ArrayDomain {
                    element_domain,
                    size,
                })
            }
            dtype => return fallible!(MakeDomain, "unsupported type {}", dtype),
        })
    }

    pub fn set_dtype(&mut self, dtype: DataType) -> Fallible<()> {
        self.element_domain = Self::new_element_domain(dtype)?;
        Ok(())
    }
    /// Instantiates the broadest possible domain given the limited information available from a field.
    /// The data could have NaNs or nulls, and is not bounded.
    ///
    /// # Proof Definition
    /// Returns a series domain spanning all series
    /// whose name and data type of elements are specified by `field`.
    pub fn new_from_field(field: Field) -> Fallible<Self> {
        Ok(SeriesDomain {
            name: field.name,
            element_domain: Self::new_element_domain(field.dtype)?,
            nullable: true,
        })
    }

    /// # Proof Definition
    /// Removes the bounds domain descriptor from `self`,
    /// and returns an error if the type of elements is not a recognized type.
    pub fn drop_bounds(&mut self) -> Fallible<()> {
        macro_rules! drop_bounds {
            ($ty:ty) => {{
                let mut element_domain = (self.element_domain.as_any())
                    .downcast_ref::<AtomDomain<$ty>>()
                    .ok_or_else(|| {
                        err!(
                            FailedFunction,
                            "unrecognized element domain. Expected AtomDomain<{}>",
                            stringify!($ty)
                        )
                    })?
                    .clone();
                element_domain.bounds = None;
                self.element_domain = Arc::new(element_domain) as Arc<dyn DynSeriesElementDomain>;
            }};
        }

        match self.dtype() {
            DataType::UInt32 => drop_bounds!(u32),
            DataType::UInt64 => drop_bounds!(u64),
            DataType::Int8 => drop_bounds!(i8),
            DataType::Int16 => drop_bounds!(i16),
            DataType::Int32 => drop_bounds!(i32),
            DataType::Int64 => drop_bounds!(i64),
            DataType::Float32 => drop_bounds!(f32),
            DataType::Float64 => drop_bounds!(f64),
            _ => return fallible!(FailedFunction, "cannot drop bounds on: {:?}", self.dtype()),
        }
        Ok(())
    }

    /// # Proof Definition
    /// If the domain of elements is of type `AtomDomain<T>`, then returns the domain as that type,
    /// otherwise returns an error.
    pub fn atom_domain<T: 'static + CheckAtom>(&self) -> Fallible<&AtomDomain<T>> {
        self.element_domain::<AtomDomain<T>>()
    }

    /// # Proof Definition
    /// If the domain of elements is of type `D`, then returns the domain as that type,
    /// otherwise returns an error.
    pub fn element_domain<D: 'static>(&self) -> Fallible<&D> {
        (self.element_domain.as_any())
            .downcast_ref::<D>()
            .ok_or_else(|| err!(FailedCast, "domain downcast failed"))
    }

    pub fn set_non_nan(&mut self) -> Fallible<()> {
        match self.dtype() {
            DataType::Float64 => {
                let atom_domain = self.atom_domain::<f64>()?.clone();
                self.set_element_domain(AtomDomain::<f64>::new(atom_domain.bounds, None));
            }
            DataType::Float32 => {
                let atom_domain = self.atom_domain::<f32>()?.clone();
                self.set_element_domain(AtomDomain::<f32>::new(atom_domain.bounds, None));
            }
            _ => {
                return fallible!(
                    MakeTransformation,
                    "only floating point types can be made non-NaN"
                );
            }
        }
        Ok(())
    }
}

impl Debug for SeriesDomain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SeriesDomain(\"{}\", {})", self.name, self.dtype())
    }
}

impl<D: UnboundedMetric> MetricSpace for (SeriesDomain, D) {
    fn check_space(&self) -> Fallible<()> {
        Ok(())
    }
}

// BEGIN UTILITY TRAITS

/// Common trait for domains that can be used to describe the space of typed elements within a series.
pub trait SeriesElementDomain: Domain + Send + Sync {
    type InnerDomain: SeriesElementDomain<InnerDomain = Self::InnerDomain>;
    /// # Proof Definition
    /// Returns the [`DataType`] of elements in the series.
    fn dtype(&self) -> DataType;

    /// # Proof Definition
    /// Returns the domain elements in the physical backing store.
    ///
    /// Polars Series represents nullity via a separate validity bit vector,
    /// so that non-null data can be stored contiguously.
    /// This function returns specifically the domain of non-null elements.
    fn inner_domain(&self) -> &Self::InnerDomain;

    /// # Proof Definition
    /// True if Series domains may contain null elements, otherwise False.
    const NULLABLE: bool;
}
impl<T: CheckAtom + PrimitiveDataType> SeriesElementDomain for AtomDomain<T> {
    type InnerDomain = Self;

    fn dtype(&self) -> DataType {
        T::dtype()
    }
    fn inner_domain(&self) -> &Self {
        self
    }

    const NULLABLE: bool = false;
}
impl<D: SeriesElementDomain<InnerDomain = D>> SeriesElementDomain for OptionDomain<D> {
    type InnerDomain = D;

    fn dtype(&self) -> DataType {
        self.inner_domain().dtype()
    }
    fn inner_domain(&self) -> &D {
        &self.element_domain
    }

    const NULLABLE: bool = true;
}

impl SeriesElementDomain for CategoricalDomain {
    type InnerDomain = Self;

    fn dtype(&self) -> DataType {
        let categories = Categories::global();
        DataType::Categorical(categories.clone(), categories.mapping())
    }
    fn inner_domain(&self) -> &Self {
        self
    }

    const NULLABLE: bool = false;
}

impl SeriesElementDomain for EnumDomain {
    type InnerDomain = Self;

    fn dtype(&self) -> DataType {
        let categories = self.categories().str().unwrap().iter().map(|v| v.unwrap());
        let categories = FrozenCategories::new(categories).unwrap();
        DataType::Enum(categories.clone(), categories.mapping().clone())
    }
    fn inner_domain(&self) -> &Self {
        self
    }

    const NULLABLE: bool = false;
}

impl SeriesElementDomain for DatetimeDomain {
    type InnerDomain = Self;

    fn dtype(&self) -> DataType {
        DataType::Datetime(self.time_unit.clone(), self.time_zone.clone())
    }
    fn inner_domain(&self) -> &Self {
        self
    }

    const NULLABLE: bool = false;
}

impl SeriesElementDomain for ArrayDomain {
    type InnerDomain = Self;

    fn dtype(&self) -> DataType {
        DataType::Array(Box::new(self.element_domain.dtype()), self.size)
    }
    fn inner_domain(&self) -> &Self {
        self
    }

    const NULLABLE: bool = false;
}

/// Object-safe version of [`SeriesElementDomain`].
pub trait DynSeriesElementDomain: 'static + Send + Sync + Debug {
    /// # Proof Definition
    /// Returns the datatype of rows of members in the domain.
    fn dtype(&self) -> DataType;

    /// This method makes it possible to downcast a trait object of Self
    /// (dyn DynSeriesElementDomain) to its concrete type.
    ///
    /// # Proof Definition
    /// Return a reference to `self` as an Any trait object.
    fn as_any(&self) -> &dyn Any;

    /// # Proof Definition
    /// Returns true if `self` and `other` are equal.
    ///
    /// This is used to check if two [`SeriesDomain`] are equal,
    /// because series domain holds a `Box<dyn DynSeriesAtomDomain>`.
    fn dyn_partial_eq(&self, other: &dyn DynSeriesElementDomain) -> bool;
}
impl<D: 'static + SeriesElementDomain> DynSeriesElementDomain for D {
    fn dtype(&self) -> DataType {
        D::dtype(&self)
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn dyn_partial_eq(&self, other: &dyn DynSeriesElementDomain) -> bool {
        (other.as_any().downcast_ref::<D>()).map_or(false, |a| self == a)
    }
}

impl PartialEq for dyn DynSeriesElementDomain + '_ {
    fn eq(&self, other: &Self) -> bool {
        self.dyn_partial_eq(other)
    }
}

/// Utility trait to construct the Polars runtime data-type indicator from an atomic type.
pub trait NumericDataType:
    NumericNative<PolarsType = Self::NumericPolars> + PrimitiveDataType + Literal
{
    /// Polars has defined its own marker types for elementary data types.
    ///
    /// # Proof Definition
    /// `NumericPolars` is the Polars marker type that corresponds to `Self`.
    type NumericPolars: PolarsDataType + PolarsNumericType<Native = Self>;
}

pub trait PrimitiveDataType: 'static + Send + Sync {
    /// Polars has defined its own marker types for elementary data types.
    ///
    /// # Proof Definition
    /// `Polars` is the Polars marker type that corresponds to `Self`.
    type Polars: PolarsDataType;

    /// # Proof Definition
    /// Return an instance of the DataType enum of the variant that corresponds to `Self`.
    ///
    /// A default implementation is provided because Polars already implements this on the marker type (Self::Polars).
    fn dtype() -> DataType {
        Self::Polars::get_static_dtype()
    }
}

macro_rules! impl_dtype_from {
    ($ty:ty, $dt:ty) => {
        impl NumericDataType for $ty {
            type NumericPolars = $dt;
        }
        impl PrimitiveDataType for $ty {
            type Polars = $dt;
        }
    };
}
impl_dtype_from!(u32, UInt32Type);
impl_dtype_from!(u64, UInt64Type);
impl_dtype_from!(i8, Int8Type);
impl_dtype_from!(i16, Int16Type);
impl_dtype_from!(i32, Int32Type);
impl_dtype_from!(i64, Int64Type);
impl_dtype_from!(f32, Float32Type);
impl_dtype_from!(f64, Float64Type);
impl PrimitiveDataType for bool {
    type Polars = BooleanType;
}
impl PrimitiveDataType for String {
    type Polars = StringType;
}
impl PrimitiveDataType for NaiveDate {
    type Polars = DateType;
}
impl PrimitiveDataType for NaiveTime {
    type Polars = TimeType;
}