diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 63e8a1d..2660147 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,6 @@ Our methods based on the True Geometric Median, computed here by `gmedian`, are ### Implementation -Rstats is a lean minimalistic library that only depends on *anyhow* (for its simple error handling). - The constituent parts of Rstats are Rust traits grouping together functions applicable to vectors of data of relevant end types.End type f64 is most commonly used. Facilities for other end types are limited. For lots of data of other end types, it is always possible to clone to f64, see for example the included utility function `vecu8asvecf64`. ### Documentation diff --git a/src/lib.rs b/src/lib.rs index e58227a..c9d46e7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -74,7 +74,7 @@ impl std::fmt::Display for Med { } } -/// Mean and standard deviation (or std ratio for geometric mean). +/// Mean and standard deviation (or std ratio for geometric mean) #[derive(Default)] pub struct MStats { pub mean: f64, @@ -188,7 +188,10 @@ pub trait Vecf64 { fn minmax(self) -> (f64, usize, f64, usize); /// Linear transformation to [0,1] fn lintrans(self) -> Vec; + /// Sort vector in a standard way + fn sortf(self) -> Vec; + /* /// Binary search for insert index I in sorted vector fn binsearch(self, v: f64) -> usize; /// Merges two ascending sorted vectors @@ -197,8 +200,7 @@ pub trait Vecf64 { fn merge_immutable(self, idx1: &[usize], v2: &[f64], idx2: &[usize]) -> ( Vec,Vec ); /// merge indices of two already concatenated sorted vectors fn merge_indices(self, idx1:&[usize], idx2:&[usize]) -> Vec; - /// Sort vector in a standard way - fn sortf(self) -> Vec; + /// Sorted vector, is wrapper for mergesort below fn sortm(self, ascending:bool) -> Vec; @@ -206,6 +208,7 @@ pub trait Vecf64 { fn rank(self, ascending:bool) -> Vec; /// Immutable merge sort, makes a sort index fn mergesort(self, i:usize, n:usize) -> Vec; + */ } /// Some support for Vec (vector of bytes) diff --git a/src/vecf64.rs b/src/vecf64.rs index 18e1998..1d611d9 100644 --- a/src/vecf64.rs +++ b/src/vecf64.rs @@ -1,5 +1,5 @@ -use crate::{MutVectors, Vecf64, here}; -use indxvec::{Indices}; +use crate::{MutVectors, Vecf64}; +use indxvec::{merge::*,Indices}; impl Vecf64 for &[f64] { @@ -206,8 +206,8 @@ impl Vecf64 for &[f64] { /// assert_eq!(v1.spearmancorr(&v2),-0.1076923076923077); /// ``` fn spearmancorr(self, v: &[f64]) -> f64 { - let xvec = self.rank(true); - let yvec = v.rank(true); + let xvec = rank(&self,true); + let yvec = rank(&v,true); // It is just Pearson's correlation of ranks xvec.ucorrelation(&yvec) } @@ -258,161 +258,6 @@ impl Vecf64 for &[f64] { self.iter().map(|&x|(x-min)/range).collect() } - /// Returns index to the first item that is strictly greater than v, - /// using binary search of an ascending sorted list. - /// When none are greater, returns self.len(). - /// User must check for this index overflow: if the returned index == 0, then v was below the list, - /// else use index-1 as a valid index to the last item that is less than or equal to v. - /// This then is the right index to use for looking up cummulative probability density functions. - fn binsearch(self, v: f64) -> usize { - let n = self.len(); - if n < 2 { panic!("{} list is too short!",here!()) } - if v < self[0] { return 0_usize }; // v is smaller than the first item - let mut hi = n-1; // valid index of the last item - if v > self[hi] { return n }; // indicates that v is greater than the last item - let mut lo = 0_usize; // initial index of the low limit - - loop { - let gap = hi - lo; - if gap <= 1 { return hi } - let tryi = lo+gap/2; - // if tryi index's value is above v, reduce the high index - if self[tryi] > v { hi = tryi; continue } - // else indexed value is not greater than v, raise the low index; - // jumps also repeating equal values. - lo = tryi - } - } - - /// Merges two ascending sorted vectors &[f64] - fn merge(self, v: &[f64]) -> Vec { - let mut resvec:Vec = Vec::new(); - let l1 = self.len(); - let l2 = v.len(); - let mut i1 = 0; - let mut i2 = 0; - loop { - if i1 == l1 { // self is now processed - for i in i2..l2 { resvec.push(v[i]) } // copy out the rest of v - break // and terminate - } - if i2 == l2 { // v is now processed - for i in i1..l1 { resvec.push(self[i])} // copy out the rest of self - break // and terminate - } - if self[i1] < v[i2] { resvec.push(self[i1]); i1 += 1; continue }; - if self[i1] > v[i2] { resvec.push(v[i2]); i2 += 1; continue }; - // here they are equal, so consume both - resvec.push(self[i1]); i1 += 1; - resvec.push(v[i2]); i2 += 1 - } - resvec - } - - /// Merges two ascending sorted vectors' indices, returns concatenated Vec and new index into it. - /// Mostly just a wrapper for merge_indices() - fn merge_immutable(self, idx1: &[usize], v2: &[f64], idx2: &[usize]) -> ( Vec,Vec ) { - let resvec = [self,v2].concat(); // no sorting, just concatenation - let l = idx1.len(); - let idx2shifted:Vec = idx2.iter().map(|x| l+x ).collect(); // shift up the second index - let residx = resvec.merge_indices(idx1,&idx2shifted); - ( resvec, residx ) - } - - /// Merges indices of two already concatenated sorted vectors: - /// self is untouched, only sort indices are merged. - /// Used by `mergesort` and `merge_immutable`. - fn merge_indices(self, idx1:&[usize], idx2:&[usize]) -> Vec { - let l1 = idx1.len(); - let l2 = idx2.len(); - let mut residx:Vec = Vec::new(); - let mut i1 = 0; let mut i2 = 0; - let mut head1 = self[idx1[i1]]; let mut head2 = self[idx2[i2]]; - loop { - if head1 < head2 { - residx.push(idx1[i1]); - i1 += 1; - if i1 == l1 { // idx1 is now fully processed - for i in i2..l2 { residx.push(idx2[i]) } // copy out the rest of idx2 - break // and terminate - } - head1 = self[idx1[i1]]; // else move to the next value - continue - } - if head1 > head2 { - residx.push(idx2[i2]); - i2 += 1; - if i2 == l2 { // idx2 is now processed - for i in i1..l1 { residx.push(idx1[i]) } // copy out the rest of idx1 - break // and terminate - } - head2 = self[idx2[i2]]; - continue - } - // here the heads are equal, so consume both - residx.push(idx1[i1]); - i1 += 1; - if i1 == l1 { // idx1 is now fully processed - for i in i2..l2 { residx.push(idx2[i]) } // copy out the rest of idx2 - break // and terminate - } - head1 = self[idx1[i1]]; - residx.push(idx2[i2]); - i2 += 1; - if i2 == l2 { // idx2 is now processed - for i in i1..l1 { residx.push(idx1[i]) } // copy out the rest of idx1 - break // and terminate - } - head2 = self[idx2[i2]]; - } - residx - } - - /// Immutable sort. Returns new sorted vector, just like 'sortf' above - /// but using our indexing 'mergesort' below. - /// Simply passes the boolean flag 'ascending' onto 'unindex'. - fn sortm(self, ascending:bool) -> Vec { - self.mergesort(0,self.len()).unindex(ascending,&self) - } - - /// Ranking of self by inverting the (merge) sort index. - /// Sort index is in sorted order, giving indices to the original data positions. - /// Ranking is in original data order, giving their positions in the sorted order (sort index). - /// Thus they are in an inverse relationship, easily converted by `.invindex()` - /// Fast ranking of many f64 items, ranking `self` with only n*(log(n)+1) complexity. - fn rank(self, ascending:bool) -> Vec { - let n = self.len(); - let sortindex = self.mergesort(0,n); - let mut rankvec:Vec = vec![0;n]; - if ascending { - for (i,&sortpos) in sortindex.iter().enumerate() { - rankvec[sortpos] = i - } - } else { // rank in the order of descending values - for (i,&sortpos) in sortindex.iter().enumerate() { - rankvec[sortpos] = n-i-1 - } - } - rankvec - } - - /// Doubly recursive non-destructive merge sort. The data is read-only, it is not moved or mutated. - /// Returns vector of indices to self from i to i+n, such that the indexed values are in sort order. - /// Thus we are moving only the index (key) values instead of the actual values. - fn mergesort(self, i:usize, n:usize) -> Vec { - - if n == 1 { let res = vec![i]; return res }; // recursion termination - if n == 2 { // also terminate with two sorted items (for efficiency) - if self[i+1] < self[i] { return vec![i+1,i] } else { return vec![i,i+1] } - } - let n1 = n / 2; // the first half - let n2 = n - n1; // the remaining second half - let sv1 = self.mergesort(i, n1); // recursively sort the first half - let sv2 = self.mergesort(i+n1, n2); // recursively sort the second half - // Now we will merge the two sorted indices into one - self.merge_indices(&sv1,&sv2) - } - /// New sorted vector. Immutable sort. /// Copies self and then sorts it in place, leaving self unchanged. /// Calls mutsortf and that calls the standard self.sort_unstable_by. diff --git a/src/vecvecf64.rs b/src/vecvecf64.rs index 6e82f7d..d79ae0e 100644 --- a/src/vecvecf64.rs +++ b/src/vecvecf64.rs @@ -1,5 +1,5 @@ use crate::{Med, MStats, MutVectors, Stats, VecVecf64, Vecf64}; -use indxvec::{Indices}; +use indxvec::{merge::*,Indices}; impl VecVecf64 for &[Vec] { /// acentroid = simple multidimensional arithmetic mean @@ -189,7 +189,7 @@ impl VecVecf64 for &[Vec] { for v in self { // collect raw ecentricities magnitudes eccs.push(gm.vdist(&v)) } - ( gm, eccs.sortm(ascending) ) + ( gm, sortm(&eccs,ascending) ) } /// Weighted geometric median, sorted eccentricities magnitudes, @@ -203,7 +203,7 @@ impl VecVecf64 for &[Vec] { // Apply linear transform // eccs = eccs.lintrans(); // create sort index of the eccs - let index = eccs.mergesort(0,self.len()); + let index = sortidx(&eccs); // pick the associated points weights in the reverse order of the sorted eccs let mut weights = index.unindex(true,&ws); let mut sumw = 0_f64; @@ -228,7 +228,7 @@ impl VecVecf64 for &[Vec] { // Apply linear transform // coses = coses.lintrans(); // create sort index of the coses - let index = coses.mergesort(0,self.len()); + let index = sortidx(&coses); // pick the associated points weights in the same order as the sorted coses let mut weights = index.unindex(true,&ws); let mut sumw = 0_f64; diff --git a/tests/tests.rs b/tests/tests.rs index 3fa9230..73deba9 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -4,6 +4,7 @@ use devtimer::DevTime; use anyhow::{Result}; +use indxvec::{merge::*}; use rstats::{Stats,MutVectors,Vecf64,VecVecf64,Vecu8,VecVecu8,GI,GV}; use rstats::functions::{genvec,genvecu8}; @@ -126,7 +127,7 @@ fn vecvec() -> Result<()> { println!("Eccentricities\t{}",eccmed); let (_, seccs) = pt.sortedeccs(true,EPS); println!("Sorted eccs: {}\n", GV(&seccs)); - let medcnt = seccs.binsearch(eccmed.median); + let medcnt = binsearch(&seccs,eccmed.median); println!("Items smaller or equal to median of eccs: {} last value: {}", GI(medcnt), GI(seccs[medcnt-1])); let mut weights = Vec::new(); for i in 1..n+1 { weights.push(i as f64) }; // create test weights data