#![allow(clippy::module_name_repetitions, clippy::similar_names, non_snake_case)]
use crate::affine::{Affine, Affine2, Affine4};
use crate::bounds::Bounds1;
use crate::gaussian::GaussianDistribution;
use crate::lp::solve;
use crate::lp::LinearSolution;
use crate::polytope::Polytope;
use crate::tensorshape::TensorShape;
use crate::NNVFloat;
use ndarray::array;
use ndarray::ArrayView1;
use ndarray::Dimension;
use ndarray::Ix4;
use ndarray::{Array1, Array2};
use ndarray::{Array4, ArrayView2};
use ndarray::{Axis, Ix2};
use num::Float;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
pub type Star2 = Star<Ix2>;
pub type Star4 = Star<Ix4>;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Star<D: Dimension> {
representation: Affine<D>,
constraints: Option<Polytope>,
}
impl<D: Dimension> Star<D> {
pub fn ndim(&self) -> usize {
self.representation.ndim()
}
pub fn input_space_polytope(&self) -> Option<&Polytope> {
self.constraints.as_ref()
}
pub fn center(&self) -> ArrayView1<NNVFloat> {
self.representation.shift()
}
pub fn get_representation(&self) -> &Affine<D> {
&self.representation
}
}
impl<D: Dimension> Star<D> {
pub fn num_constraints(&self) -> usize {
match &self.constraints {
Some(polytope) => polytope.num_constraints(),
None => 0,
}
}
#[must_use]
pub fn add_constraint(mut self, coeffs: ArrayView1<NNVFloat>, rhs: NNVFloat) -> Self {
if let Some(ref mut constrs) = self.constraints {
constrs.add_eqn(coeffs, rhs);
} else {
self.constraints =
Polytope::nonempty_new(&coeffs.to_owned().insert_axis(Axis(0)), &array![rhs]);
}
self
}
#[must_use]
pub fn remove_constraint(mut self, idx: usize) -> Self {
if let Some(ref mut constrs) = self.constraints {
constrs.remove_eqn(idx);
} else {
panic!();
}
self
}
}
impl Star2 {
pub fn get_constraint_coeffs(&self) -> Option<Array2<NNVFloat>> {
self.constraints.as_ref().map(|x| x.coeffs().to_owned())
}
#[must_use]
pub fn get_safe_subset(&self, safe_value: NNVFloat) -> Self {
let mut subset = self.clone();
let mut new_constr: Polytope = self.representation.clone().into();
let mut rhs = new_constr.rhs_mut();
rhs *= -1.;
rhs += safe_value;
subset.intersect_input(&new_constr);
subset
}
pub fn intersect_input(&mut self, other: &Polytope) {
self.constraints = self
.constraints
.as_ref()
.map_or(Some(other.clone()), |x| Some(x.intersect(other)));
}
pub fn get_input_trunc_gaussian(
&self,
mu: ArrayView1<NNVFloat>,
sigma: ArrayView2<NNVFloat>,
max_accept_reject_iters: usize,
stability_eps: NNVFloat,
bounds_opt: &Option<Bounds1>,
) -> Option<GaussianDistribution> {
self.constraints
.as_ref()
.and_then(|x| x.reduce_fixed_inputs(bounds_opt))
.map(|poly| {
poly.get_truncnorm_distribution(mu, sigma, max_accept_reject_iters, stability_eps)
})
}
pub fn default(input_shape: &TensorShape) -> Self {
debug_assert_eq!(input_shape.rank(), 1);
debug_assert!(input_shape.is_fully_defined());
let dim = input_shape[0].unwrap();
Self {
representation: Affine2::new(Array2::eye(dim), Array1::zeros(dim)),
constraints: None,
}
}
pub fn new(basis: Array2<NNVFloat>, center: Array1<NNVFloat>) -> Self {
Self {
representation: Affine2::new(basis, center),
constraints: None,
}
}
#[must_use]
pub fn with_constraints(mut self, constraints: Polytope) -> Self {
debug_assert!(self.constraints.is_none(), "explicit panic");
self.constraints = Some(constraints);
self
}
pub fn input_space_dim(&self) -> usize {
self.representation.input_dim()
}
pub fn representation_space_dim(&self) -> usize {
self.representation.output_dim()
}
}
impl Star2 {
#[must_use]
pub fn affine_map2(&self, affine: &Affine<Ix2>) -> Self {
Self {
representation: affine * &self.representation,
constraints: self.constraints.clone(),
}
}
pub fn step_relu2(
&self,
index: usize,
input_bounds_opt: &Option<Bounds1>,
) -> (Option<Self>, Option<Self>) {
let (coeffs, shift) = {
let aff = self.representation.get_eqn(index);
let neg_basis_part: Array2<NNVFloat> = &aff.basis() * -1.;
let shift = aff.shift();
(neg_basis_part.row(0).to_owned(), shift[[0]])
};
let upper_star = self.clone().add_constraint(coeffs.view(), shift);
let mut lower_star = self.clone().add_constraint((&coeffs * -1.).view(), -shift);
lower_star.representation.zero_eqn(index);
let lower_star_opt = if lower_star.is_empty(input_bounds_opt) {
None
} else {
Some(lower_star)
};
let upper_star_opt = if upper_star.is_empty(input_bounds_opt) {
None
} else {
Some(upper_star)
};
(lower_star_opt, upper_star_opt)
}
pub fn step_relu2_dropout(
&self,
index: usize,
input_bounds_opt: &Option<Bounds1>,
) -> (Option<Self>, Option<Self>, Option<Self>) {
let mut dropout_star = self.clone();
dropout_star.representation.zero_eqn(index);
let stars = self.step_relu2(index, input_bounds_opt);
let dropout_star_opt = if dropout_star.is_empty(input_bounds_opt) {
None
} else {
Some(dropout_star)
};
(dropout_star_opt, stars.0, stars.1)
}
pub fn get_output_min(&self, idx: usize, input_bounds: &Bounds1) -> NNVFloat {
let eqn = self.representation.get_eqn(idx);
let shift = eqn.shift()[0];
self.constraints.as_ref().map_or_else(
|| {
crate::util::signed_dot(&eqn.basis(), &input_bounds.lower(), &input_bounds.upper())
[[0]]
+ shift
},
|poly| {
let solved = solve(
poly.coeffs().rows(),
poly.rhs(),
eqn.basis().index_axis(Axis(0), 0),
Some(input_bounds),
);
if let LinearSolution::Solution(_, val) = solved {
shift + val
} else if let LinearSolution::Unbounded(_) = solved {
NNVFloat::neg_infinity()
} else {
panic!("Solution: {:?} on star {:?}", solved, self)
}
},
)
}
pub fn get_output_max(&self, idx: usize, input_bounds: &Bounds1) -> NNVFloat {
let eqn = self.representation.get_eqn(idx);
let shift = eqn.shift()[0];
self.constraints.as_ref().map_or_else(
|| {
crate::util::signed_dot(&eqn.basis(), &input_bounds.upper(), &input_bounds.lower())
[[0]]
+ shift
},
|poly| {
let solved = solve(
poly.coeffs().rows(),
poly.rhs(),
eqn.basis().index_axis(Axis(0), 0).mapv(|x| x * -1.).view(),
Some(input_bounds),
);
if let LinearSolution::Solution(_, val) = solved {
shift - val
} else if let LinearSolution::Unbounded(_) = solved {
NNVFloat::infinity()
} else {
panic!()
}
},
)
}
pub fn can_maximize_output_idx(&self, class_idx: usize) -> bool {
let class_eqn = self.representation.get_eqn(class_idx);
let (class_coeffs, class_shift): (ArrayView1<NNVFloat>, NNVFloat) = {
(
class_eqn.basis().remove_axis(Axis(0)),
class_eqn.shift()[[0]],
)
};
let nvars = class_coeffs.len();
if self.constraints.is_none() {
return true; }
let poly = self.constraints.as_ref().unwrap();
let block_coeffs = poly.coeffs();
let (A, b) = (block_coeffs.rows(), poly.rhs());
let mut coeffs = Vec::new();
let mut shifts = Vec::new();
for idx in 0..self.representation.shift().ndim() {
if idx == class_idx {
continue;
}
{
let (diff_coeffs, diff_shift) = {
let other_class_eqn = self.representation.get_eqn(idx);
(
&other_class_eqn.basis().row(0) - &class_coeffs,
class_shift - other_class_eqn.shift()[[0]],
)
};
coeffs.push(diff_coeffs);
shifts.push(diff_shift);
}
}
let solve_a = A
.into_iter()
.chain(coeffs.iter().map(ndarray::ArrayBase::view));
let solved = solve(
solve_a,
b.iter().chain(shifts.iter()),
Array1::ones(nvars).view(),
Some(&Bounds1::trivial(nvars)),
);
matches!(
solved,
LinearSolution::Solution(..) | LinearSolution::Unbounded(..)
)
}
pub fn calculate_output_axis_aligned_bounding_box(
&self,
input_outer_bounds: &Bounds1,
) -> Bounds1 {
let lbs = Array1::from_iter(
(0..self.representation_space_dim())
.map(|x| self.get_output_min(x, input_outer_bounds)),
);
let ubs = Array1::from_iter(
(0..self.representation_space_dim())
.map(|x| self.get_output_max(x, input_outer_bounds)),
);
Bounds1::new(lbs.view(), ubs.view())
}
pub fn is_empty(&self, input_bounds_opt: &Option<Bounds1>) -> bool {
self.constraints
.as_ref()
.map_or(false, |x| x.is_empty(input_bounds_opt))
}
}
impl Star4 {
pub fn default(input_shape: &TensorShape) -> Self {
debug_assert_eq!(input_shape.rank(), 3);
debug_assert!(input_shape.is_fully_defined());
let shape_slice = input_shape.as_defined_slice().unwrap();
let slice_exact: [usize; 4] = [
shape_slice[0],
shape_slice[1],
shape_slice[2],
shape_slice[3],
];
Self {
representation: Affine4::new(Array4::ones(slice_exact), Array1::zeros(shape_slice[3])),
constraints: None,
}
}
}
#[cfg(test)]
mod test {
}