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
use geo::{Centroid, GeoFloat, Line};
use geo_types::Geometry;
use geojson::{Feature, FeatureCollection};
use nalgebra_sparse::{coo::CooMatrix, csr::CsrMatrix};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::iter::IntoIterator;

pub enum TransformType {
    Row,
    Binary,
    DoublyStandardized,
}

pub trait WeightBuilder<A>
where
    A: GeoFloat,
{
    fn compute_weights<T>(&self, geoms: &T) -> Weights
    where
        for<'a> &'a T: IntoIterator<Item = &'a Geometry<A>>;
}

/// Structure holding and providing methods to access and query a weights matrix. These are either
/// loaded from external representations or constructed from WeightBuilders.
#[derive(Debug)]
pub struct Weights {
    weights: HashMap<usize, HashMap<usize, f64>>,
    no_elements: usize,
}

impl fmt::Display for Weights {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({:#?})", self.weights())
    }
}

impl Weights {
    /// Create a new weights object from a hashmap indicating origin and destination ids and
    /// weights.
    ///
    /// # Arguments
    ///
    /// * `weights` - A mapping of {origin => dest =>weight}f64
    /// * `no_elements` - The number of elements in the original geometry set (because we want to be
    /// sure of the full length given this is a sparse representation)
    ///
    pub fn new(weights: HashMap<usize, HashMap<usize, f64>>, no_elements: usize) -> Weights {
        Self {
            weights,
            no_elements,
        }
    }

    /// Create a new weights object from a series of lists representing the origin, destinations
    /// and weights of the matrix
    ///
    /// # Arguments
    ///
    /// * `origins` - A  list of the origin ids
    /// * `origins` - A  list of the destination ids
    /// * `weights` - A  list of the weights
    /// * `no_elements` - The number of elements in the original geometry set (because we want to be
    /// sure of the full length given this is a sparse representation)
    ///
    pub fn from_list_rep<T, W>(origins: &T, dests: &T, weights: &W, no_elements: usize) -> Weights
    where
        for<'a> &'a T: std::iter::IntoIterator<Item = &'a usize>,
        for<'a> &'a W: std::iter::IntoIterator<Item = &'a f64>,
    {
        let mut weights_lookup: HashMap<usize, HashMap<usize, f64>> = HashMap::new();

        for ((origin, dest), weight) in origins
            .into_iter()
            .zip(dests.into_iter())
            .zip(weights.into_iter())
        {
            let entry = weights_lookup.entry(*origin).or_insert(HashMap::new());
            entry.insert(*dest, *weight);

            let entry = weights_lookup.entry(*dest).or_insert(HashMap::new());
            entry.insert(*origin, *weight);
        }
        Self {
            weights: weights_lookup,
            no_elements,
        }
    }

    /// Return a reference to the hash map representation of the weights
    pub fn weights(&self) -> &HashMap<usize, HashMap<usize, f64>> {
        &self.weights
    }

    /// Return the total number of elements in the original geometry set
    pub fn no_elements(&self) -> usize {
        self.no_elements
    }

    /// Returns true if the origin and destination are neighbors
    ///
    /// # Arguments
    ///
    /// * `origin` - the id of the origin geometry
    /// * `destination` - the id of the destination geometry
    ///
    pub fn are_neighbors(&self, origin: usize, dest: usize) -> bool {
        self.weights.get(&origin).unwrap().contains_key(&dest)
    }

    /// Returns the ids of a given geometries neighbors
    ///
    /// # Arguments
    ///
    /// * `origin` - the id of the origin geometry
    ///
    pub fn get_neighbor_ids(&self, origin: usize) -> Option<HashSet<usize>> {
        match self.weights.get(&origin) {
            Some(m) => {
                let results: HashSet<usize> = m.keys().into_iter().cloned().collect();
                Some(results)
            }
            None => None,
        }
    }

    /// Returns the weights matrix as a nalgebra sparse matrix
    ///
    /// # Arguments
    ///
    /// * `transfrom` - what transform, if any to apply to the weights matrix as we  transform.
    /// Only TransformType::Row for row normalized is currently implemented.
    ///
    pub fn as_sparse_matrix(&self, transform: Option<TransformType>) -> CsrMatrix<f64> {
        let mut coo_matrix = CooMatrix::new(self.no_elements, self.no_elements);

        for (key, vals) in self.weights.iter() {
            let norm: f64 = match &transform {
                Some(TransformType::Row) => vals.values().sum(),
                _ => 1.0,
            };
            for (key2, weight) in vals.iter() {
                coo_matrix.push(*key, *key2, *weight / norm);
            }
        }

        CsrMatrix::from(&coo_matrix)
    }

    /// Returns the weights matrix in a list format
    ///
    /// Output format is a tuple of origin ids, dest ids, weight values
    ///
    pub fn to_list(&self) -> (Vec<usize>, Vec<usize>, Vec<f64>) {
        let mut origin_list: Vec<usize> = vec![];
        let mut dest_list: Vec<usize> = vec![];
        let mut weight_list: Vec<f64> = vec![];

        for (origin, dests) in self.weights.iter() {
            for (dest, weight) in dests.iter() {
                origin_list.push(*origin);
                dest_list.push(*dest);
                weight_list.push(*weight);
            }
        }
        (origin_list, dest_list, weight_list)
    }

    /// Returns the weights matrix in a list format with geometries
    ///
    /// Output format is a tuple of origin ids, dest ids, weight values, geometry linking origin
    /// and destination
    ///
    /// # Arguments
    ///
    /// * `geoms` - the list of geometries originally used to generate the weights matrix.
    pub fn to_list_with_geom<A: GeoFloat>(
        &self,
        geoms: &[Geometry<A>],
    ) -> Result<(Vec<usize>, Vec<usize>, Vec<f64>, Vec<Geometry<A>>), String> {
        let mut origin_list: Vec<usize> = vec![];
        let mut dest_list: Vec<usize> = vec![];
        let mut weight_list: Vec<f64> = vec![];
        let mut geoms: Vec<Geometry<A>> = vec![];
        let no_geoms = geoms.len();

        for (origin, dests) in self.weights.iter() {
            for (dest, weight) in dests.iter() {
                origin_list.push(*origin);
                dest_list.push(*dest);
                weight_list.push(*weight);
                let origin_centroid = geoms
                    .get(*origin)
                    .ok_or_else(|| format!("Failed to get origin {} {}", origin, no_geoms))?
                    .centroid()
                    .unwrap();
                let dest_centroid = geoms
                    .get(*dest)
                    .ok_or_else(|| format!("Failed to get origin {} {}", dest, no_geoms))?
                    .centroid()
                    .unwrap();
                let line: geo::Geometry<A> =
                    geo::Geometry::Line(Line::new(origin_centroid, dest_centroid));
                geoms.push(line);
            }
        }
        Ok((origin_list, dest_list, weight_list, geoms))
    }

    /// Returns the weights matrix in a GeoJson format with lines between the origin and
    /// destinations
    ///
    /// # Arguments
    ///
    /// * `geoms` - the list of geometries originally used to generate the weights matrix.
    pub fn links_geojson<A: GeoFloat>(&self, geoms: &[Geometry<A>]) -> FeatureCollection {
        let mut features: Vec<Feature> = vec![];

        for (origin, dests) in self.weights.iter() {
            for (dest, _weight) in dests.iter() {
                let origin_centroid = geoms.get(*origin).unwrap().centroid().unwrap();
                let dest_centroid = geoms.get(*dest).unwrap().centroid().unwrap();
                let line: geojson::Geometry =
                    geojson::Value::from(&Line::new(origin_centroid, dest_centroid)).into();

                let mut feature = Feature {
                    geometry: Some(line),
                    ..Default::default()
                };
                feature.set_property("origin", format!("{}", origin));
                feature.set_property("dest", format!("{}", dest));
                features.push(feature);
            }
        }
        FeatureCollection {
            features,
            bbox: None,
            foreign_members: None,
        }
    }

    // pub fn as_geopoalrs(&self, geoms: &[Geometry<A>], ids: &Vec<T>)->Result<DataFrame, Error>{
    //    use polars::io::{SerWriter, SerReader};
    //    use polars::prelude::NamedFromOwned;
    //    use geopolars::geoseries::GeoSeries;

    //    let mut origin_ids : Vec<i32> = Vec::with_capacity(geoms.len());
    //    let mut dests_ids: Vec<i32> = Vec::with_capacity(geoms.len());
    //    let mut weights: Vec<f32> = Vec::with_capacity(geoms.len());
    //    let mut lines: Vec<Line> = Vec::with_capacity(geoms.len());

    //    for (origin, dests) in self.weights().unwrap().iter(){
    //         for (dest, _weight) in dests.iter(){
    //             origin_ids.push(origin);
    //             dest_ids.push(dest);
    //             weights.push(weight);
    //             let origin_index =  ids.iter().position(|a| a == origin).unwrap();
    //             let dest_index =  ids.iter().position(|a| a == dest).unwrap();
    //             let origin_centroid = geoms.get(origin_index).unwrap().centroid().unwrap();
    //             let dest_centroid = geoms.get(dest_index).unwrap().centroid().unwrap();
    //             let line  = Line::new(origin_centroid, dest_centroid);
    //             geoms.push(line);
    //         }
    //    }
    //    let geom_col = Series::from_geom_vec(&lines);
    //    let result = DataFrame:::new([
    //         Series::from_vec("origin_id", origin_ids),
    //         Series::from_vec("dest_id", dests_ids),
    //         Series::from_vec("weight", weights),
    //         Series::from_vec("geom", geoms),
    //    ]);
    //    result
    // }
}