1use crate::coord::ranged1d::{
2 AsRangedCoord, KeyPointHint, NoDefaultFormatting, Ranged, ReversibleRanged, ValueFormatter,
3};
4use std::ops::Range;
56/// The trait indicates the coordinate is discrete
7/// This means we can bidirectionally map the range value to 0 to N
8/// in which N is the number of distinct values of the range.
9///
10/// This is useful since for a histgoram, this is an abstraction of bucket.
11pub trait DiscreteRanged
12where
13Self: Ranged,
14{
15/// Get the number of element in the range
16 /// Note: we assume that all the ranged discrete coordinate has finite value
17 ///
18 /// - **returns** The number of values in the range
19fn size(&self) -> usize;
2021/// Map a value to the index
22 ///
23 /// Note: This function doesn't guareentee return None when the value is out of range.
24 /// The only way to confirm the value is in the range is to examing the return value isn't
25 /// larger than self.size.
26 ///
27 /// - `value`: The value to map
28 /// - **returns** The index of the value
29fn index_of(&self, value: &Self::ValueType) -> Option<usize>;
3031/// Reverse map the index to the value
32 ///
33 /// Note: This function doesn't guareentee returning None when the index is out of range.
34 ///
35 /// - `value`: The index to map
36 /// - **returns** The value
37fn from_index(&self, index: usize) -> Option<Self::ValueType>;
3839/// Return a iterator that iterates over the all possible values
40 ///
41 /// - **returns** The value iterator
42fn values(&self) -> DiscreteValueIter<'_, Self>
43where
44Self: Sized,
45 {
46 DiscreteValueIter(self, 0, self.size())
47 }
4849/// Returns the previous value in this range
50 ///
51 /// Normally, it's based on the `from_index` and `index_of` function. But for
52 /// some of the coord spec, it's possible that we value faster implementation.
53 /// If this is the case, we can impelemnet the type specific impl for the `previous`
54 /// and `next`.
55 ///
56 /// - `value`: The current value
57 /// - **returns**: The value piror to current value
58fn previous(&self, value: &Self::ValueType) -> Option<Self::ValueType> {
59if let Some(idx) = self.index_of(value) {
60if idx > 0 {
61return self.from_index(idx - 1);
62 }
63 }
64None
65}
6667/// Returns the next value in this range
68 ///
69 /// Normally, it's based on the `from_index` and `index_of` function. But for
70 /// some of the coord spec, it's possible that we value faster implementation.
71 /// If this is the case, we can impelemnet the type specific impl for the `previous`
72 /// and `next`.
73 ///
74 /// - `value`: The current value
75 /// - **returns**: The value next to current value
76fn next(&self, value: &Self::ValueType) -> Option<Self::ValueType> {
77if let Some(idx) = self.index_of(value) {
78if idx + 1 < self.size() {
79return self.from_index(idx + 1);
80 }
81 }
82None
83}
84}
8586/// A `SegmentedCoord` is a decorator on any discrete coordinate specification.
87/// This decorator will convert the discrete coordiante in two ways:
88/// - Add an extra dummy element after all the values in origianl discrete coordinate
89/// - Logically each value `v` from original coordinate system is mapped into an segment `[v, v+1)` where `v+1` denotes the sucessor of the `v`
90/// - Introduce two types of values `SegmentValue::Exact(value)` which denotes the left end of value's segment and `SegmentValue::CenterOf(value)` which refers the center of the segment.
91/// This is used in histogram types, which uses a discrete coordinate as the buckets. The segmented coord always emits `CenterOf(value)` key points, thus it allows all the label and tick marks
92/// of the coordinate rendered in the middle of each segment.
93/// The coresponding trait [IntoSegmentedCoord](trait.IntoSegmentedCoord.html) is used to apply this decorator to coordinates.
94#[derive(Clone)]
95pub struct SegmentedCoord<D: DiscreteRanged>(D);
9697/// The trait for types that can decorated by [SegmentedCoord](struct.SegmentedCoord.html) decorator.
98pub trait IntoSegmentedCoord: AsRangedCoord
99where
100Self::CoordDescType: DiscreteRanged,
101{
102/// Convert current ranged value into a segmented coordinate
103fn into_segmented(self) -> SegmentedCoord<Self::CoordDescType> {
104 SegmentedCoord(self.into())
105 }
106}
107108impl<R: AsRangedCoord> IntoSegmentedCoord for R where R::CoordDescType: DiscreteRanged {}
109110/// The value that used by the segmented coordinate.
111#[derive(Clone, Debug)]
112pub enum SegmentValue<T> {
113/// Means we are referring the exact position of value `T`
114Exact(T),
115/// Means we are referring the center of position `T` and the successor of `T`
116CenterOf(T),
117/// Referring the last dummy element
118Last,
119}
120121impl<T, D: DiscreteRanged + Ranged<ValueType = T>> ValueFormatter<SegmentValue<T>>
122for SegmentedCoord<D>
123where
124D: ValueFormatter<T>,
125{
126fn format(value: &SegmentValue<T>) -> String {
127match value {
128 SegmentValue::Exact(ref value) => D::format(value),
129 SegmentValue::CenterOf(ref value) => D::format(value),
130_ => "".to_string(),
131 }
132 }
133}
134135impl<D: DiscreteRanged> Ranged for SegmentedCoord<D> {
136type FormatOption = NoDefaultFormatting;
137type ValueType = SegmentValue<D::ValueType>;
138139fn map(&self, value: &Self::ValueType, limit: (i32, i32)) -> i32 {
140let margin = ((limit.1 - limit.0) as f32 / self.0.size() as f32).round() as i32;
141142match value {
143 SegmentValue::Exact(coord) => self.0.map(coord, (limit.0, limit.1 - margin)),
144 SegmentValue::CenterOf(coord) => {
145let left = self.0.map(coord, (limit.0, limit.1 - margin));
146if let Some(idx) = self.0.index_of(coord) {
147if idx + 1 < self.0.size() {
148let right = self.0.map(
149&self.0.from_index(idx + 1).unwrap(),
150 (limit.0, limit.1 - margin),
151 );
152return (left + right) / 2;
153 }
154 }
155 left + margin / 2
156}
157 SegmentValue::Last => limit.1,
158 }
159 }
160161fn key_points<HintType: KeyPointHint>(&self, hint: HintType) -> Vec<Self::ValueType> {
162self.0
163.key_points(hint)
164 .into_iter()
165 .map(SegmentValue::CenterOf)
166 .collect()
167 }
168169fn range(&self) -> Range<Self::ValueType> {
170let range = self.0.range();
171 SegmentValue::Exact(range.start)..SegmentValue::Exact(range.end)
172 }
173}
174175impl<D: DiscreteRanged> DiscreteRanged for SegmentedCoord<D> {
176fn size(&self) -> usize {
177self.0.size() + 1
178}
179180fn index_of(&self, value: &Self::ValueType) -> Option<usize> {
181match value {
182 SegmentValue::Exact(value) => self.0.index_of(value),
183 SegmentValue::CenterOf(value) => self.0.index_of(value),
184 SegmentValue::Last => Some(self.0.size()),
185 }
186 }
187188fn from_index(&self, idx: usize) -> Option<Self::ValueType> {
189match idx {
190 idx if idx < self.0.size() => self.0.from_index(idx).map(SegmentValue::Exact),
191 idx if idx == self.0.size() => Some(SegmentValue::Last),
192_ => None,
193 }
194 }
195}
196197impl<T> From<T> for SegmentValue<T> {
198fn from(this: T) -> SegmentValue<T> {
199 SegmentValue::Exact(this)
200 }
201}
202203impl<DC: DiscreteRanged> ReversibleRanged for DC {
204fn unmap(&self, input: i32, limit: (i32, i32)) -> Option<Self::ValueType> {
205let idx = (f64::from(input - limit.0) * (self.size() as f64) / f64::from(limit.1 - limit.0))
206 .floor() as usize;
207self.from_index(idx)
208 }
209}
210211/// The iterator that can be used to iterate all the values defined by a discrete coordinate
212pub struct DiscreteValueIter<'a, T: DiscreteRanged>(&'a T, usize, usize);
213214impl<'a, T: DiscreteRanged> Iterator for DiscreteValueIter<'a, T> {
215type Item = T::ValueType;
216fn next(&mut self) -> Option<T::ValueType> {
217if self.1 >= self.2 {
218return None;
219 }
220let idx = self.1;
221self.1 += 1;
222self.0.from_index(idx)
223 }
224}
225226#[cfg(test)]
227mod test {
228use super::*;
229#[test]
230fn test_value_iter() {
231let range: crate::coord::ranged1d::types::RangedCoordi32 = (-10..10).into();
232233let values: Vec<_> = range.values().collect();
234235assert_eq!(21, values.len());
236237for (expected, value) in (-10..=10).zip(values) {
238assert_eq!(expected, value);
239 }
240assert_eq!(range.next(&5), Some(6));
241assert_eq!(range.next(&10), None);
242assert_eq!(range.previous(&-10), None);
243assert_eq!(range.previous(&10), Some(9));
244 }
245246#[test]
247fn test_centric_coord() {
248let coord = (0..10).into_segmented();
249250assert_eq!(coord.size(), 12);
251for i in 0..=11 {
252match coord.from_index(i as usize) {
253Some(SegmentValue::Exact(value)) => assert_eq!(i, value),
254Some(SegmentValue::Last) => assert_eq!(i, 11),
255_ => panic!(),
256 }
257 }
258259for (kps, idx) in coord.key_points(20).into_iter().zip(0..) {
260match kps {
261 SegmentValue::CenterOf(value) if value <= 10 => assert_eq!(value, idx),
262_ => panic!(),
263 }
264 }
265266assert_eq!(coord.map(&SegmentValue::CenterOf(0), (0, 24)), 1);
267assert_eq!(coord.map(&SegmentValue::Exact(0), (0, 24)), 0);
268assert_eq!(coord.map(&SegmentValue::Exact(1), (0, 24)), 2);
269 }
270}