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
use crate::errors::CircuitError;
use crate::unitary_decomposition::utils::gray_code;
use rayon::prelude::*;

pub(crate) struct BitPather {
    n: u64,
    reverse_lookup: Vec<u64>,
}

impl BitPather {
    pub(crate) fn new(n: u64) -> Self {
        let encoding = gray_code(n);
        let mut reverse_lookup = vec![];
        reverse_lookup.resize(encoding.len(), 0);

        encoding.into_iter().enumerate().for_each(|(indx, code)| {
            reverse_lookup[code as usize] = indx as u64;
        });

        Self { n, reverse_lookup }
    }

    fn valid_path_to_closest(
        &self,
        valid_index: usize,
        start: u64,
        endpoints: &[u64],
    ) -> Result<Vec<u64>, CircuitError> {
        if endpoints.is_empty() {
            CircuitError::make_str_err("Enpoints must contain a value")
        } else {
            let any_below = endpoints
                .iter()
                .any(|v| (self.reverse_lookup[(*v) as usize] as usize) < valid_index);
            if any_below {
                CircuitError::make_str_err("All endpoints must be in valid region.")
            } else {
                Ok(self.valid_path_helper(valid_index, vec![(start, vec![])], endpoints))
            }
        }
    }

    /// Node is sorted by `self.reverse_lookup[value]` as is endpoints.
    fn valid_path_helper(
        &self,
        valid_index: usize,
        nodes: Vec<(u64, Vec<u64>)>,
        endpoints: &[u64],
    ) -> Vec<u64> {
        let contained_values: Vec<_> = nodes.iter().map(|(c, _)| *c).collect();
        let mut new_vals: Vec<(u64, Vec<u64>)> = nodes
            .into_par_iter()
            .map(|(val, path)| {
                (0..self.n).fold(vec![], |mut entries, indx| {
                    let mask = 1 << indx;
                    let new_val = (val & !mask) | (!val & mask);
                    if self.reverse_lookup[new_val as usize] as usize >= valid_index {
                        let new_val_index = self.reverse_lookup[new_val as usize];
                        let search_result = contained_values
                            .binary_search_by_key(&new_val_index, |c| {
                                self.reverse_lookup[(*c) as usize]
                            });
                        if search_result.is_err() && !path.contains(&new_val) {
                            let mut new_path = path.clone();
                            new_path.push(val);
                            entries.push((new_val, new_path))
                        }
                    }
                    entries
                })
            })
            .flatten()
            .collect();
        new_vals.par_sort_by_key(|(c, _)| self.reverse_lookup[(*c) as usize]);
        let result =
            new_vals
                .into_iter()
                .try_fold((None, vec![]), |(last_c, mut acc_v), (c, path)| {
                    if endpoints.contains(&c) {
                        Err((c, path))
                    } else {
                        Ok(match last_c {
                            Some(last_c) if last_c == c => (Some(last_c), acc_v),
                            _ => {
                                acc_v.push((c, path));
                                (Some(c), acc_v)
                            }
                        })
                    }
                });
        match result {
            Ok((_, new_vals)) => self.valid_path_helper(valid_index, new_vals, endpoints),
            Err((c, path)) => {
                let mut path = path;
                path.push(c);
                path
            }
        }
    }

    /// Take the list of indices with nonzero values and return the path through them
    /// to the target, returns the bits needed to swap (in the form `1 << index`).
    pub(crate) fn path(
        &self,
        target: u64,
        through: &[u64],
    ) -> Result<Vec<(u64, u64)>, CircuitError> {
        if target as usize > self.reverse_lookup.len() {
            CircuitError::make_err(format!(
                "Value to={:?} is greater than encoding length {:?}",
                target,
                self.reverse_lookup.len()
            ))
        } else if through.is_empty() || (through.len() == 1 && through[0] == target) {
            Ok(vec![])
        } else {
            let target_index = self.reverse_lookup[target as usize];

            let mut nonzeros = through.to_vec();
            if !nonzeros.contains(&target) {
                nonzeros.push(target);
            }
            nonzeros.par_sort_by_key(|row| self.reverse_lookup[(*row) as usize]);
            nonzeros.retain(|v| self.reverse_lookup[(*v) as usize] >= target_index);
            let mut path = vec![];
            while !nonzeros.is_empty() {
                let last = nonzeros.pop().unwrap();
                if last == target {
                    continue;
                }
                let sub_path =
                    self.valid_path_to_closest(target_index as usize, last, &nonzeros)?;
                // Should always have start and end in sub_path.
                let step = sub_path[1];
                let step_index = self.reverse_lookup[step as usize];
                let result = nonzeros
                    .binary_search_by_key(&step_index, |c| self.reverse_lookup[(*c) as usize]);
                if let Err(index) = result {
                    nonzeros.insert(index, step);
                }
                path.push((last, step));
            }
            Ok(path)
        }
    }
}

#[cfg(test)]
mod bitpath_tests {
    use super::*;

    fn test_path(mut value_vec: Vec<bool>, path: Vec<(u64, u64)>, target: usize) {
        for (from, to) in path {
            let (from, to) = (from as usize, to as usize);
            value_vec[to] |= value_vec[from];
            value_vec[from] = false;
        }

        let mut expected = vec![];
        expected.resize(value_vec.len(), false);
        expected[target] = true;

        assert_eq!(value_vec, expected);
    }

    #[test]
    fn path_test_single() -> Result<(), CircuitError> {
        let acc = vec![false, false, false, false, false, false, false, true];
        let pather = BitPather::new(3);
        let target = 0;
        let path = pather.path(target, &[7])?;
        println!("{:?}", path);
        test_path(acc, path, target as usize);
        Ok(())
    }

    #[test]
    fn path_test_multi_anyway() -> Result<(), CircuitError> {
        let acc = vec![false, false, false, true, false, false, false, true];
        let pather = BitPather::new(3);
        let target = 0;
        let path = pather.path(target, &[3, 7])?;
        println!("{:?}", path);
        test_path(acc, path, target as usize);
        Ok(())
    }

    #[test]
    fn path_test_multi_outofway() -> Result<(), CircuitError> {
        let acc = vec![false, false, true, false, false, false, false, true];
        let pather = BitPather::new(3);
        let target = 0;
        let path = pather.path(target, &[2, 7])?;
        println!("{:?}", path);
        test_path(acc, path, target as usize);
        Ok(())
    }

    #[test]
    fn path_test_multi_detour() -> Result<(), CircuitError> {
        let acc = vec![false, false, false, false, false, true, false, true];
        let pather = BitPather::new(3);
        let target = 0;
        let path = pather.path(target, &[5, 7])?;
        println!("{:?}", path);
        test_path(acc, path, target as usize);
        Ok(())
    }
}