1use crate::prelude::*;
2use num_traits::{self};
3use std::collections::{HashMap, HashSet};
4use std::hash::Hash;
5use num_traits::Num;
6
7pub trait BroadcastIndex<T> {
9 fn bi(&self, i: usize) -> &T;
10}
11impl<T: Num> BroadcastIndex<T> for T {
12 fn bi(&self, _i: usize) -> &T {
13 self
14 }
15}
16impl<T: Num> BroadcastIndex<T> for [T] {
17 fn bi(&self, i: usize) -> &T {
18 &self[i]
19 }
20}
21
22impl<T: Num> BroadcastIndex<T> for &Vec<T> {
23 fn bi(&self, i: usize) -> &T {
24 &self[i]
25 }
26}
27pub trait Unique<'a, T: 'a>: AsRef<[T]> {
31 fn unique(&self) -> Vec<T>
32 where
33 T: PartialEq + Clone,
34 {
35 let mut res: Vec<T> = vec![];
36 for i in self.as_ref().iter() {
37 if res.contains(i) {
38 continue;
39 }
40 res.push(i.clone());
41 }
42 res
43 }
44 fn unique_by<F, N>(&self, f: F) -> Vec<N>
45 where
46 F: Fn(&T) -> N,
47 N: PartialEq + Clone,
48 {
49 self.as_ref()
50 .iter()
51 .map(f)
52 .collect_vec()
53 .unique()
54 }
55 fn get_list_index(&self, i: &[usize]) -> Vec<T>
56 where
57 T: Clone,
58 {
59 i.iter().map(|x| self.as_ref()[*x].clone()).collect_vec()
60 }
61 fn position(&self, target: &T) -> usize
62 where
63 T: PartialEq,
64 {
65 self.as_ref().iter().position(|x| x == target).unwrap()
66 }
67 fn filter_position<F: Fn(&T) -> bool>(&self, f: F) -> vuz {
68 self.as_ref()
69 .iter()
70 .enumerate()
71 .filter_map(|(i, x)| if f(x) { Some(i) } else { None })
72 .collect_vec()
73 }
74 fn index_out<N: Clone>(&self, data: &[N]) -> Vec<N>
75 where
76 T: Into<usize> + Clone,
77 {
78 let index: Vec<usize> = self.as_ref().map(|x| x.clone().into());
79 data.get_list_index(&index)
80
81 }
82 fn value_count(&self) -> HashMap<T, usize>
83 where
84 T: std::hash::Hash + Eq + Clone,
85 {
86 let mut res = HashMap::new();
87 for x in self.as_ref().iter() {
88 if !res.contains_key(x) {
89 res.insert(x.clone(), 0);
90 }
91 *res.get_mut(x).unwrap() += 1;
92 }
93 res
94 }
95 fn value_positions(&self) -> HashMap<T, vuz>
96 where
97 T: std::hash::Hash + Eq + Clone,
98 {
99 let mut res = HashMap::new();
100 for (i, x) in self.as_ref().iter().enumerate() {
101 if !res.contains_key(x) {
102 res.insert(x.clone(), vec![]);
103 }
104 res.get_mut(x).unwrap().push(i);
105 }
106 res
107 }
108 fn drop_nan(&self) -> Vec<T>
109 where
110 T: num_traits::Float,
111 {
112 self.as_ref()
113 .iter()
114 .filter_map(|x| if x.is_nan() { None } else { Some(*x) })
115 .collect_vec()
116 }
117 fn map<F: Fn(&T) -> N, N>(&self, f: F) -> Vec<N> {
118 self.as_ref().iter().map(f).collect_vec()
119 }
120 fn into_map<F: Fn(T) -> N, N>(self, f: F) -> Vec<N>
121 where
122 Self: IntoIterator<Item = T> + Sized,
123 {
124 self.into_iter().map(f).collect_vec()
125 }
126 fn filter_map<F>(&self, f: F) -> Vec<T>
127 where
128 F: Fn(&T) -> bool,
129 T: Clone,
130 {
131 self
132 .as_ref()
133 .iter()
134 .filter_map(|x| if f(x) { Some(x.clone()) } else { None })
135 .collect_vec()
136 }
137 fn to_ref(&self) -> Vec<&T> {
138 self.as_ref().iter().collect_vec()
139 }
140 fn nlast(&self, n: usize) -> &[T] {
141 let l = self.as_ref().len();
142 &self.as_ref()[(l - l.min(n)) .. l]
143 }
144 fn cumsum(&'a self) -> Vec<T>
145 where
146 T: Default + std::ops::AddAssign<&'a T> + Copy + 'static,
147 {
148 self.as_ref()
149 .iter()
150 .scan(T::default(), |acc, x| {
151 *acc += x;
152 Some(*acc)
153 })
154 .collect()
155 }
156
157 fn cum_fn<F, B>(&self, f: F, init: B) -> Vec<B>
158 where
159 F: Fn(&B, &T) -> B,
160 B: Clone,
161 {
162 self.as_ref()
163 .iter()
164 .scan(init, |accu, x| {
165 *accu = f(accu, x);
166 Some(accu.clone())
167 })
168 .collect()
169 }
170 fn cum_max(&self) -> Vec<T>
171 where
172 T: PartialOrd + Clone,
173 {
174 self.cum_fn(|accu: &T, x: &T| -> T {
175 if x.gt(accu) { x.clone()} else { accu.clone() }
176 }, self.as_ref()[0].clone())
177 }
178 fn cum_min(&self) -> Vec<T>
179 where
180 T: PartialOrd + Clone,
181 {
182 self.cum_fn(|accu: &T, x: &T| -> T {
183 if x.lt(accu) { x.clone() } else { accu.clone() }
184 }, self.as_ref()[0].clone())
185 }
186 fn ema(&self, i: usize) -> v32
187 where
188 T: Copy + Into<f32>,
189 {
190 let data = self.as_ref();
191 let mut res = vec![f32::NAN; data.len()];
192 let mul = 2f32 / i as f32;
193 res[0] = <T as Into<f32>>::into(data[0]);
194 for i in 1..data.len() {
195 res[i] = mul * <T as Into<f32>>::into(data[i]) + (1.0 - mul) * res[i - 1];
196 }
197 res
198 }
199 fn union_vecs<N>(&self) -> Vec<N>
200 where
201 T: AsRef<[N]>,
202 N: Eq + std::hash::Hash + Clone + std::cmp::Ord,
203 {
204 let data_set =
205 HashSet::<N>::from_iter(self.as_ref().iter().flat_map(|x| x.as_ref()).cloned());
206 let mut data_vec: Vec<N> = data_set.into_iter().collect();
207 data_vec.sort();
208 data_vec
209 }
210 fn quantile(&self, n: f32) -> T
211 where
212 T: Clone,
213 for<'g> &'g T: PartialOrd,
214 {
215 let mut b = self.as_ref().to_vec();
216 b.sort_by(|a, b| a.partial_cmp(&b).unwrap());
217 b[(self.as_ref().len() as f32 * n) as usize].clone()
218 }
219 fn sort_perm(self, indices: &[usize]) -> Vec<T>
221 where
222 Self: Sized + IntoIterator<Item = T>,
223 {
224 self.into_iter()
225 .zip(indices.iter())
226 .sorted_by_key(|(_, &y)| y)
227 .map(|(x, _)| x)
228 .collect_vec()
229 }
230 fn sort_rtn_position(&self) -> Vec<usize>
231 where
232 T: std::cmp::PartialOrd,
233 {
234 self
235 .as_ref()
236 .iter()
237 .enumerate()
238 .sorted_by(|a, b| a.1.partial_cmp(b.1).unwrap())
239 .map(|(x, _)| x)
240 .collect_vec()
241 }
242 fn get_perm(&self) -> vuz
243 where
244 T: std::cmp::PartialOrd
245 {
246 self
247 .sort_rtn_position()
248 .into_iter()
249 .enumerate()
250 .sorted_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
251 .map(|(x, _)| x)
252 .collect_vec()
253 }
254 fn mmap<K, E, G>(&self, f: K) -> Vec<Vec<G>>
255 where
256 K: Fn(&E) -> G + Clone,
257 T: AsRef<[E]>,
258 {
259 self.as_ref()
260 .iter()
261 .map(|x| {
262 x.as_ref()
263 .iter()
264 .map(f.clone())
265 .collect_vec()
266 })
267 .collect_vec()
268 }
269 fn if_else<F, N, K, G>(&self, f: F, true_side: N, false_side: K) -> Vec<G>
270 where
271 F: Fn(&T) -> bool,
272 N: BroadcastIndex<G>,
273 K: BroadcastIndex<G>,
274 G: Default + Clone,
275 {
276 let data = self.as_ref();
277 let mut res = vec![G::default(); data.len()];
278 for i in 0..res.len() {
279 if f(&data[i]) {
280 res[i] = true_side.bi(i).clone();
281 } else {
282 res[i] = false_side.bi(i).clone();
283 }
284 }
285 res
286 }
287
288 fn filter_thre<F, N, F2>(self, f: F, fi: F2) -> Vec<T>
289 where
290 F: Fn(&T) -> N,
291 F2: Fn(&N, &[N]) -> bool,
292 Self: std::iter::IntoIterator<Item = T> + Sized,
293 {
294 let f_res = self.map(f);
295 let res = izip!(self.into_iter(), f_res.iter())
296 .filter_map(|(x, y)| {
297 if (fi)(y, &f_res) {
298 Some(x)
299 } else {
300 None
301 }
302 })
303 .collect_vec();
304 println!("origin: {} -> res: {}", f_res.len(), res.len());
305 res
306 }
307 fn find_first_ele<F, N>(&self, f: F) -> Vec<T>
308 where
309 F: Fn(&T) -> N,
310 N: Eq,
311 T: Clone,
312 {
313 self
314 .as_ref()
315 .iter()
316 .fold((vec![], f(&self.as_ref()[0])), |mut accu, x| {
317 let n_now = f(x);
318 if accu.0.is_empty() || n_now != accu.1 {
319 accu.1 = n_now;
320 accu.0.push(x.clone());
321 }
322 accu
323 })
324 .0
325 }
326 fn similar_init<N>(&self) -> Vec<Vec<N>>
327 where
328 T: AsRef<Vec<N>>,
329 N: Clone,
330 {
331 let inner_size = self.as_ref()[0].as_ref().len();
332 let outer_size = self.as_ref().len();
333 init_a_matrix(inner_size, outer_size)
334 }
335 fn vcat_other<N>(&mut self, other: &mut Vec<Vec<N>>)
336 where
337 Self: AsMut<Vec<Vec<N>>>,
338 {
339 self
340 .as_mut()
341 .iter_mut()
342 .zip(other.iter_mut())
343 .for_each(|(x, y)| {
344 x.append(y);
345 });
346 }
347 fn extract_one<F>(&self, f: F) -> Option<T>
348 where
349 F: Fn(&T) -> bool,
350 T: Clone,
351 {
352 let position = self.as_ref().iter().position(f)?;
353 Some(self.as_ref()[position].clone())
354 }
355
356 fn check_all<F>(&self, f: F) -> bool
357 where
358 F: Fn(&T) -> bool,
359 {
360 for x in self.as_ref() {
361 if !f(x) {
362 return false;
363 }
364 }
365 true
366 }
367
368 fn is_last_distinct(&self) -> Vec<bool>
369 where
370 T: Eq,
371 for<'b> &'b T: Hash,
372 {
373 let mut res = Vec::with_capacity(self.as_ref().len());
374 let mut unique_pool: HashSet<&T> = HashSet::new();
375 for data in self.as_ref().iter().rev() {
376 if unique_pool.contains(&data) {
377 res.push(false);
378 } else {
379 res.push(true);
380 unique_pool.insert(data);
381 }
382 }
383 res.into_iter().rev().collect()
384 }
385}
386impl<'a, T: 'a> Unique<'a, T> for [T] {}
387impl<'a, T: 'a> Unique<'a, T> for Vec<T> {}
388
389pub fn init_a_matrix<T>(inner_size: usize, outer_size: usize) -> Vec<Vec<T>> {
390 std::iter
391 ::repeat_with(|| Vec::with_capacity(inner_size))
392 .take(outer_size)
393 .collect_vec()
394}
395pub fn repeat_to_vec<T: FnMut() -> A, A>(f: T, size: usize) -> Vec<A> {
396 std::iter::repeat_with(f).take(size).collect_vec()
397}
398pub trait RowIndex<T: Num> {
402 type Slice<'a>
403 where
404 Self: 'a;
405 fn slice_index(&self, start: usize, end: usize) -> Self::Slice<'_>;
406}
407
408impl<T: Num> RowIndex<T> for Vec<T> {
409 type Slice<'a> = &'a [T] where Self: 'a;
410 fn slice_index(&self, start: usize, end: usize) -> Self::Slice<'_> {
411 &self[start..end]
412 }
413}
414
415impl<'s, T: Num> RowIndex<T> for Vec<&'s Vec<T>> {
416 type Slice<'a> = Vec<&'s [T]> where Self: 'a;
417 fn slice_index(&self, start: usize, end: usize) -> Self::Slice<'_> {
418 self.iter().map(|x| &x[start..end]).collect()
419 }
420}
421
422impl<T: Num> RowIndex<T> for Vec<Vec<T>> {
423 type Slice<'a> = Vec<&'a [T]> where T: 'a;
424 fn slice_index(&self, start: usize, end: usize) -> Self::Slice<'_> {
425 self.iter().map(|x| &x[start..end]).collect()
426 }
427}
428pub struct Grp<T>(pub T);
432
433impl<T: PartialEq + Clone> Grp<Vec<T>> {
434 pub fn apply<P: Fn(&[N]) -> K, K, N>(&self, data: &[N], func: P) -> (Vec<T>, Vec<K>) {
435 let mut start_i = 0usize;
436 let mut index = vec![];
437 let mut res = vec![];
438 for i in 1..self.0.len() + 1 {
439 if i == self.0.len() || self.0[i] != self.0[i - 1] {
440 index.push(self.0[i - 1].clone());
441 let res_ = func(&data[start_i..i]);
442 res.push(res_);
443 start_i = i;
444 }
445 }
446 (index, res)
447 }
448
449 pub fn transform<P: Fn(&[N]) -> K, K, N>(&self, data: &[N], func: P) -> Vec<Option<K>>
450 where
451 T: PartialOrd,
452 K: Copy,
453 {
454 let grp_res = self.apply(data, func);
455 let ri = Reindex::new(&grp_res.0[..], &self.0[..]);
456 ri.reindex(&grp_res.1[..])
457 }
458
459 pub fn unique(&self) -> usize {
460 let mut res = 0;
461 for i in 0..self.0.len() {
462 if i == 0 || self.0[i] != self.0[i - 1] {
463 res += 1;
464 }
465 }
466 res
467 }
468
469 pub fn sum(&self, data: &[f32]) -> (Vec<T>, v32) {
470 self.apply(data, <[f32] as AggFunc>::sum)
471 }
472 pub fn max(&self, data: &[f32]) -> (Vec<T>, v32) {
473 self.apply(data, <[f32] as AggFunc>::max)
474 }
475}
476
477impl<T: PartialOrd + Clone> Grp<(Vec<T>, Vec<vuz>)> {
478 pub fn new_without_order(data: &[T]) -> Self {
479 let mut k_vec = data.unique();
480 k_vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
481 let v_vec = k_vec
482 .iter()
483 .map(|x| {
484 data.iter()
485 .enumerate()
486 .filter_map(|(i, y)| if x == y { Some(i) } else { None })
487 .collect_vec()
488 })
489 .collect_vec();
490 Grp((k_vec, v_vec))
491 }
492
493 pub fn apply_without_order<P: Fn(&[N]) -> K, K, N: Clone>(
494 &self,
495 data: &[N],
496 func: P,
497 ) -> (Vec<T>, Vec<K>) {
498 izip!(self.0 .0.iter(), self.0 .1.iter()).fold((vec![], vec![]), |mut accu, (x, y)| {
499 accu.0.push(x.clone());
500 let b = y.iter().map(|i| data[*i].clone()).collect_vec();
501 accu.1.push(func(&b));
502 accu
503 })
504 }
505}
506#[derive(Debug)]
510pub struct Reindex {
511 pub loc_i: Vec<Option<usize>>,
512}
513
514impl Reindex {
515 pub fn new<T: PartialOrd>(ori: &[T], target: &[T]) -> Self {
516 let mut res = Vec::with_capacity(target.len());
517 let mut ori_index = 0usize;
518 let mut ori_value = &ori[ori_index];
519 let mut tar_index = 0usize;
520 let mut tar_value = &target[tar_index];
521 let mut posi;
522 loop {
523 if tar_value < ori_value {
524 posi = None;
525 } else if tar_value == ori_value {
526 posi = Some(ori_index);
527 } else {
528 loop {
529 if ori_index >= ori.len() - 1 {
530 posi = None;
531 break;
532 }
533 ori_index += 1;
534 ori_value = &ori[ori_index];
535 if ori_value < tar_value {
536 continue;
537 } else if ori_value == tar_value {
538 posi = Some(ori_index);
539 break;
540 } else {
541 posi = None;
542 break;
543 }
544 }
545 }
546 res.push(posi);
547 tar_index += 1;
548 if tar_index >= target.len() {
549 break;
550 }
551 tar_value = &target[tar_index];
552 }
553 Reindex { loc_i: res }
554 }
555 pub fn reindex<T: Clone>(&self, data: &[T]) -> Vec<Option<T>> {
556 let mut res = Vec::with_capacity(self.loc_i.len());
557 for loc_i in self.loc_i.iter() {
558 let res_ = loc_i.as_ref().map(|i| data[*i].clone());
559 res.push(res_);
560 }
561 res
562 }
563}
564pub trait Fillna<T: Clone> {
568 fn fillna(&self, data: T) -> Vec<T>;
569 fn ffill(&self, data: T) -> Vec<T>;
570}
571
572impl<T: Clone> Fillna<T> for [Option<T>] {
573 fn fillna(&self, data: T) -> Vec<T> {
574 self.iter()
575 .map(|x| match x {
576 Some(i) => i.clone(),
577 None => data.clone(),
578 })
579 .collect()
580 }
581 fn ffill(&self, data: T) -> Vec<T> {
582 let mut res = Vec::with_capacity(self.len());
583 let mut last_data = data;
584 for data in self.iter() {
585 if let Some(i) = data {
586 last_data = i.clone();
587 }
588 res.push(last_data.clone());
589 }
590 res
591 }
592}
593
594pub trait FillnaMut<T: Copy> {
595 fn fillna(&mut self, data: T);
596 fn ffill(&mut self);
597}
598
599impl FillnaMut<f32> for v32 {
600 fn fillna(&mut self, data: f32) {
601 for data_ in self.iter_mut() {
602 if data_.is_nan() {
603 *data_ = data
604 }
605 }
606 }
607 fn ffill(&mut self) {
608 if self.is_empty() {
609 return;
610 };
611 let mut last_value = self[0];
612 for data_ in self.iter_mut().skip(1) {
613 if data_.is_nan() {
614 *data_ = last_value;
615 } else {
616 last_value = *data_;
617 }
618 }
619 }
620}
621pub trait LagFor {
625 type R;
626 fn lag_for(&self) -> Vec<Self::R>;
627}
628
629impl<'a, T> LagFor for (&'a [T], usize)
630where
631 T: Clone + Default,
632{
633 type R = T;
634 fn lag_for(&self) -> Vec<Self::R> {
635 (self.0, (self.1, T::default())).lag_for()
636 }
637}
638
639impl<'a, T> LagFor for (&'a [T], f32)
640where
641 T: Clone,
642{
643 type R = T;
644 fn lag_for(&self) -> Vec<Self::R> {
645 (self.0, (self.1 as usize, self.0[0].clone())).lag_for()
646 }
647}
648
649impl<'a, T> LagFor for (&'a [T], (usize, T))
650where
651 T: Clone,
652{
653 type R = T;
654 fn lag_for(&self) -> Vec<Self::R> {
655 let mut res = self.0.to_owned();
656 res.rotate_right(self.1 .0.min(self.0.len()));
657 res
658 .iter_mut()
659 .take(self.1 .0.min(self.0.len()))
660 .for_each(|x| *x = self.1 .1.clone());
661 res
662 }
663}
664
665pub trait Lag {
666 type R;
667 fn lag<'a, T>(&'a self, l: T) -> Vec<Self::R>
668 where
669 (&'a Self, T): LagFor<R = Self::R>,
670 {
671 (self, l).lag_for()
672 }
673}
674
675impl<T> Lag for [T]
676where
677 T: Clone + Default,
678{
679 type R = T;
680}
681pub trait Agg2D<T> {
685 fn sum2d(&self) -> Vec<T>;
686 fn mean2d(&self) -> Vec<T>;
687 fn max2d(&self) -> Vec<T>;
688 fn min2d(&self) -> Vec<T>;
689 fn nansum2d(&self) -> Vec<T>
690 where
691 T: num_traits::Float;
692 fn nanmean2d(&self) -> Vec<T>
693 where
694 T: num_traits::Float;
695}
696
697impl<T, N> Agg2D<T> for Vec<N>
698where
699 T: Copy + From<u8> + std::ops::AddAssign<T> + std::ops::Div<T, Output = T> + PartialOrd,
700 N: AsRef<[T]>,
701 Vec<T>: FromIterator<<T as std::ops::Div>::Output>,
702{
703 fn sum2d(&self) -> Vec<T> {
704 let col_len = self[0].as_ref().len();
705 self.iter()
706 .fold(vec![T::from(0u8); col_len], |mut res, row| {
707 row.as_ref()
708 .iter()
709 .enumerate()
710 .for_each(|(i, cell)| res[i] += *cell);
711 res
712 })
713 }
714 fn mean2d(&self) -> Vec<T> {
715 let sum_data = self.sum2d();
716 let col_len = T::from(self.len() as u8);
717 sum_data.iter().map(|x| *x / col_len).collect()
718 }
719 fn max2d(&self) -> Vec<T> {
720 self.iter().fold(self[0].as_ref().to_vec(), |mut res, row| {
721 row.as_ref().iter().enumerate().for_each(|(i, cell)| {
722 if res[i] < *cell {
723 res[i] = *cell
724 }
725 });
726 res
727 })
728 }
729 fn min2d(&self) -> Vec<T> {
730 self.iter().fold(self[0].as_ref().to_vec(), |mut res, row| {
731 row.as_ref().iter().enumerate().for_each(|(i, cell)| {
732 if res[i] > *cell {
733 res[i] = *cell
734 }
735 });
736 res
737 })
738 }
739 fn nansum2d(&self) -> Vec<T>
740 where
741 T: num_traits::Float,
742 {
743 let col_len = self[0].as_ref().len();
744 self.iter()
745 .fold(vec![<T as From<u8>>::from(0u8); col_len], |mut res, row| {
746 row.as_ref().iter().enumerate().for_each(|(i, cell)| {
747 if !cell.is_nan() {
748 res[i] += *cell
749 };
750 });
751 res
752 })
753 }
754 fn nanmean2d(&self) -> Vec<T>
755 where
756 T: num_traits::Float + Div<T, Output = T>,
757 {
758 let col_len = self[0].as_ref().len();
759 let zz_ = <T as From<u8>>::from(1u8);
760 let nan_count =
761 self.iter()
762 .fold(vec![<T as From<u8>>::from(0u8); col_len], |mut res, row| {
763 row.as_ref().iter().enumerate().for_each(|(i, cell)| {
764 if !cell.is_nan() {
765 res[i] += zz_;
766 }
767 });
768 res
769 });
770 let nan_sum_value = self.nansum2d();
771 nan_sum_value
772 .iter()
773 .zip(nan_count.iter())
774 .map(|(x, y)| *x / *y)
775 .collect()
776 }
777}
778use std::ops::{Add, Div, Mul, Sub};
782
783pub struct S<'a, T>(pub &'a T);
784
785macro_rules! V32_f32 {
787 ($ops1: ident, $ops2: ident, $x: ty, $y: ty) => {
788 impl $ops1<$x> for S<'_, $y> {
789 type Output = v32;
790 fn $ops2(self, rhs: $x) -> Self::Output {
791 self.0.iter().map(|x| x.$ops2(rhs)).collect()
792 }
793 }
794 };
795}
796macro_rules! V32_V32 {
800 ($ops1: ident, $ops2: ident, $x: ty, $y: ty) => {
801 impl $ops1<$x> for S<'_, $y> {
802 type Output = v32;
803 fn $ops2(self, rhs: $x) -> Self::Output {
804 self.0
805 .iter()
806 .zip(rhs.iter())
807 .map(|(x, y)| x.$ops2(y))
808 .collect()
809 }
810 }
811 };
812}
813macro_rules! VV32_f32 {
817 ($ops1: ident, $ops2: ident, $x: ty, $y: ty) => {
818 impl $ops1<$x> for S<'_, $y> {
819 type Output = Vec<v32>;
820 fn $ops2(self, rhs: $x) -> Self::Output {
821 self.0.iter().map(|x| S(x).$ops2(rhs)).collect()
822 }
823 }
824 };
825}
826macro_rules! VV32_VV32 {
830 ($ops1: ident, $ops2: ident, $x: ty, $y: ty) => {
831 impl $ops1<$x> for S<'_, $y> {
832 type Output = Vec<v32>;
833 fn $ops2(self, rhs: $x) -> Self::Output {
834 self.0
835 .iter()
836 .zip(rhs.iter())
837 .map(|(x, y)| S(x).$ops2(y))
838 .collect()
839 }
840 }
841 };
842}
843macro_rules! vec_ops {
847 ($ops1: ident, $ops2: ident) => {
848 V32_f32!($ops1, $ops2, f32, v32);
849 V32_f32!($ops1, $ops2, f32, &v32);
850 V32_f32!($ops1, $ops2, f32, &[f32]);
851
852 V32_V32!($ops1, $ops2, &'_ v32, v32);
853 V32_V32!($ops1, $ops2, &'_ [f32], v32);
854 V32_V32!($ops1, $ops2, &'_ v32, &[f32]);
855 V32_V32!($ops1, $ops2, &'_ [f32], &[f32]);
856 V32_V32!($ops1, $ops2, &'_ v32, &'_ v32);
857 V32_V32!($ops1, $ops2, &'_ [f32], &'_ v32);
858
859 VV32_f32!($ops1, $ops2, f32, Vec<v32>);
860 VV32_f32!($ops1, $ops2, f32, Vec<&'_ v32>);
861 VV32_f32!($ops1, $ops2, f32, Vec<&'_ [f32]>);
862
863 VV32_f32!($ops1, $ops2, &'_ v32, Vec<v32>);
864 VV32_f32!($ops1, $ops2, &'_ v32, Vec<&'_ v32>);
865 VV32_f32!($ops1, $ops2, &'_ v32, Vec<&'_ [f32]>);
866
867 VV32_f32!($ops1, $ops2, &'_ [f32], Vec<v32>);
868 VV32_f32!($ops1, $ops2, &'_ [f32], Vec<&'_ v32>);
869 VV32_f32!($ops1, $ops2, &'_ [f32], Vec<&'_ [f32]>);
870
871 VV32_VV32!($ops1, $ops2, &'_ Vec<v32>, Vec<v32>);
872 VV32_VV32!($ops1, $ops2, &'_ Vec<v32>, Vec<&'_ v32>);
873 VV32_VV32!($ops1, $ops2, &'_ Vec<v32>, Vec<&'_ [f32]>);
874 };
875}
876
877vec_ops!(Add, add);
878vec_ops!(Sub, sub);
879vec_ops!(Mul, mul);
880vec_ops!(Div, div);
881
882pub trait SetIndex {
887 fn set_index<T: Copy>(&self, data: &mut [T], value: &[T]);
888}
889
890impl SetIndex for vuz {
891 fn set_index<T: Copy>(&self, data: &mut [T], value: &[T]) {
892 for (&i, &v) in self.iter().zip(value.iter()) {
893 data[i] = v;
894 }
895 }
896}
897
898impl SetIndex for Vec<bool> {
899 fn set_index<T: Copy>(&self, data: &mut [T], value: &[T]) {
900 let mut v_iter = value.iter();
901 for i in 0..self.len() {
902 if self[i] {
903 data[i] = *v_iter.next().unwrap();
904 }
905 }
906 }
907}
908
909pub trait Product {
910 type T;
911 fn product<K: Fn(Self::T) -> N, N>(self, x: K) -> Vec<N>;
912}
913
914impl<A1: Clone, A2: Clone> Product for (Vec<A1>, Vec<A2>) {
915 type T = (A1, A2);
916 fn product<K: Fn(Self::T) -> N, N>(self, x: K) -> Vec<N> {
917 self.0
918 .into_iter()
919 .flat_map(|a1| {
920 self.1
921 .clone()
922 .into_iter()
923 .map(|a2| x((a1.clone(), a2)))
924 .collect_vec()
925 })
926 .collect_vec()
927 }
928}
929
930
931pub trait IndexProduct {
932 fn index_product(&self, data: usize) -> Vec<Vec<usize>>;
933}
934
935impl IndexProduct for Vec<Vec<usize>> {
936 fn index_product(&self, data: usize) -> Vec<Vec<usize>> {
937 let mut res = vec![];
938 for x in 0..data {
939 for y in self.iter() {
940 if &x <= y.last().unwrap() {
941 continue
942 }
943 let mut z = y.clone();
944 z.push(x);
945 res.push(z);
946 }
947 }
948 res
949 }
950}
951
952impl IndexProduct for Vec<usize> {
953 fn index_product(&self, data: usize) -> Vec<Vec<usize>> {
954 self
955 .iter()
956 .map(|x| vec![*x])
957 .collect_vec()
958 .index_product(data)
959 }
960}
961
962impl IndexProduct for usize {
963 fn index_product(&self, data: usize) -> Vec<Vec<usize>> {
964 (0..*self).collect_vec().index_product(data)
965 }
966}
967
968pub trait InnerProduct {
969 type Output;
970 fn inner_product(&self, data: usize) -> Vec<Vec<Self::Output>>;
971 fn inner_product_recur(&self, data: usize) -> Vec<Vec<Self::Output>> {
972 (1..data + 1)
973 .fold(vec![], |mut accu, x| {
974 let mut c = self.inner_product(x);
975 accu.append(&mut c);
976 accu
977 })
978
979 }
980}
981
982impl<T: Clone> InnerProduct for [T] {
983 type Output = T;
984 fn inner_product(&self, data: usize) -> Vec<Vec<Self::Output>> {
985 (1..data)
986 .fold(
987 (0..self.len()).map(|x| vec![x]).collect_vec(),
988 |mut accu, _| {
989 accu = accu.index_product(self.len());
990 accu
991 }
992 )
993 .into_iter()
994 .map(|x| self.get_list_index(&x))
995 .collect_vec()
996 }
997}
998
999pub trait InnerProduct2 {
1000 type Output;
1001 fn inner_product2(self) -> Option<Self::Output>;
1002}
1003
1004impl InnerProduct2 for vv32 {
1005 type Output = vv32;
1006 fn inner_product2(self) -> Option<Self::Output> {
1007 let mut g = self.into_iter().rev().collect_vec();
1008 let g_start = g.pop()?;
1009 let mut g_start = g_start.into_iter().map(|x| vec![x]).collect_vec();
1010 while let Some(g_next) = g.pop() {
1011 g_start = g_start
1012 .into_tuple(g_next)
1013 .product(|(mut x, y)| {
1014 x.push(y);
1015 x
1016 });
1017 }
1018 Some(g_start)
1019 }
1020}
1021
1022
1023