plotters/coord/ranged1d/combinators/
group_by.rs1use crate::coord::ranged1d::{
2 AsRangedCoord, DiscreteRanged, KeyPointHint, NoDefaultFormatting, Ranged, ValueFormatter,
3};
4use std::ops::Range;
5
6#[derive(Clone)]
27pub struct GroupBy<T: DiscreteRanged>(T, usize);
28
29pub trait ToGroupByRange: AsRangedCoord + Sized
32where
33 Self::CoordDescType: DiscreteRanged,
34{
35 fn group_by(self, value: usize) -> GroupBy<<Self as AsRangedCoord>::CoordDescType> {
40 GroupBy(self.into(), value)
41 }
42}
43
44impl<T: AsRangedCoord + Sized> ToGroupByRange for T where T::CoordDescType: DiscreteRanged {}
45
46impl<T: DiscreteRanged> DiscreteRanged for GroupBy<T> {
47 fn size(&self) -> usize {
48 (self.0.size() + self.1 - 1) / self.1
49 }
50 fn index_of(&self, value: &Self::ValueType) -> Option<usize> {
51 self.0.index_of(value).map(|idx| idx / self.1)
52 }
53 fn from_index(&self, index: usize) -> Option<Self::ValueType> {
54 self.0.from_index(index * self.1)
55 }
56}
57
58impl<T, R: DiscreteRanged<ValueType = T> + ValueFormatter<T>> ValueFormatter<T> for GroupBy<R> {
59 fn format(value: &T) -> String {
60 R::format(value)
61 }
62}
63
64impl<T: DiscreteRanged> Ranged for GroupBy<T> {
65 type FormatOption = NoDefaultFormatting;
66 type ValueType = T::ValueType;
67 fn map(&self, value: &T::ValueType, limit: (i32, i32)) -> i32 {
68 self.0.map(value, limit)
69 }
70 fn range(&self) -> Range<T::ValueType> {
71 self.0.range()
72 }
73 fn key_points<HintType: KeyPointHint>(&self, hint: HintType) -> Vec<T::ValueType> {
75 let range = 0..(self.0.size() + self.1) / self.1;
76 let interval =
79 ((range.end - range.start + hint.bold_points() - 1) / hint.bold_points()).max(1);
80 let count = (range.end - range.start) / interval;
81
82 let idx_iter = (0..hint.bold_points()).map(|x| x * interval);
83
84 if hint.weight().allow_light_points() && count < hint.bold_points() * 2 {
85 let outer_ticks = idx_iter;
86 let outer_tick_size = interval * self.1;
87 let inner_ticks_per_group = hint.max_num_points() / outer_ticks.len();
88 let inner_ticks = (outer_tick_size + inner_ticks_per_group - 1) / inner_ticks_per_group;
89 let inner_ticks: Vec<_> = (0..(outer_tick_size / inner_ticks))
90 .map(move |x| x * inner_ticks)
91 .collect();
92 let size = self.0.size();
93 return outer_ticks
94 .flat_map(|base| inner_ticks.iter().map(move |&ofs| base * self.1 + ofs))
95 .take_while(|&idx| idx < size)
96 .map(|x| self.0.from_index(x).unwrap())
97 .collect();
98 }
99
100 idx_iter
101 .map(|x| self.0.from_index(x * self.1).unwrap())
102 .collect()
103 }
104}
105
106#[cfg(test)]
107mod test {
108 use super::*;
109 #[test]
110 fn test_group_by() {
111 let coord = (0..100).group_by(10);
112 assert_eq!(coord.size(), 11);
113 for (idx, val) in (0..).zip(coord.values()) {
114 assert_eq!(val, idx * 10);
115 assert_eq!(coord.from_index(idx as usize), Some(val));
116 }
117 }
118}