ndarray-rand-0.14.0/.cargo_vcs_info.json0000644000000001120000000000000134710ustar {
"git": {
"sha1": "abb0f9e97ed6632d4f11bc3f400ec3bbc4fd02e0"
}
}
ndarray-rand-0.14.0/Cargo.toml0000644000000025120000000000000114750ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
edition = "2018"
name = "ndarray-rand"
version = "0.14.0"
authors = ["bluss"]
description = "Constructors for randomized arrays. `rand` integration for `ndarray`."
documentation = "https://docs.rs/ndarray-rand/"
readme = "README.md"
keywords = ["multidimensional", "matrix", "rand", "ndarray"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-ndarray/ndarray"
[package.metadata.release]
no-dev-version = true
tag-name = "ndarray-rand-{{version}}"
[dependencies.ndarray]
version = "0.15"
[dependencies.quickcheck]
version = "0.9"
optional = true
default-features = false
[dependencies.rand]
version = "0.8.0"
features = ["small_rng"]
[dependencies.rand_distr]
version = "0.4.0"
[dev-dependencies.quickcheck]
version = "0.9"
default-features = false
[dev-dependencies.rand_isaac]
version = "0.3.0"
ndarray-rand-0.14.0/Cargo.toml.orig000064400000000000000000000014420000000000000151350ustar 00000000000000[package]
name = "ndarray-rand"
version = "0.14.0"
edition = "2018"
authors = ["bluss"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-ndarray/ndarray"
documentation = "https://docs.rs/ndarray-rand/"
readme = "README.md"
description = "Constructors for randomized arrays. `rand` integration for `ndarray`."
keywords = ["multidimensional", "matrix", "rand", "ndarray"]
[dependencies]
ndarray = { version = "0.15", path = ".." }
rand_distr = "0.4.0"
quickcheck = { version = "0.9", default-features = false, optional = true }
[dependencies.rand]
version = "0.8.0"
features = ["small_rng"]
[dev-dependencies]
rand_isaac = "0.3.0"
quickcheck = { version = "0.9", default-features = false }
[package.metadata.release]
no-dev-version = true
tag-name = "ndarray-rand-{{version}}"
ndarray-rand-0.14.0/LICENSE-APACHE000064400000000000000000000251370000000000000142010ustar 00000000000000 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.
ndarray-rand-0.14.0/LICENSE-MIT000064400000000000000000000021370000000000000137040ustar 00000000000000Copyright (c) 2015 - 2018 Ulrik Sverdrup "bluss",
Jim Turner,
and ndarray developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
ndarray-rand-0.14.0/README.md000064400000000000000000000033160000000000000135270ustar 00000000000000ndarray-rand
============
Constructors for randomized arrays: `rand`'s integration with `ndarray`.
Example
=======
Generate a 2-dimensional array with shape `(2,5)` and elements drawn from a uniform distribution
over the `(0., 10.)` interval:
```rust
use ndarray::Array;
use ndarray_rand::RandomExt;
use ndarray_rand::rand_distr::Uniform;
fn main() {
let a = Array::random((2, 5), Uniform::new(0., 10.));
println!("{:8.4}", a);
// Example Output:
// [[ 8.6900, 6.9824, 3.8922, 6.5861, 2.4890],
// [ 0.0914, 5.5186, 5.8135, 5.2361, 3.1879]]
}
```
Dependencies
============
``ndarray-rand`` depends on ``rand``.
[`rand`](https://docs.rs/rand/) and [`rand-distr`](https://docs.rs/rand_distr/) are
re-exported as sub-modules, `ndarray_rand::rand` and `ndarray_rand::rand_distr` respectively.
Please rely on these submodules for guaranteed version compatibility.
If you want to use a random number generator or distribution from another crate
with `ndarray-rand`, you need to make sure that the other crate also depends on the
same version of `rand`. Otherwise, the compiler may return errors saying
that the items are not compatible (e.g. that a type doesn't implement a
necessary trait).
Recent changes
==============
Check _[RELEASES.md](https://github.com/rust-ndarray/ndarray/blob/master/ndarray-rand/RELEASES.md)_ to see
the changes introduced in previous releases.
License
=======
Dual-licensed to be compatible with the Rust project.
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0 or the MIT license
http://opensource.org/licenses/MIT, at your
option. This file may not be copied, modified, or distributed
except according to those terms.
ndarray-rand-0.14.0/RELEASES.md000064400000000000000000000022750000000000000140000ustar 00000000000000Recent Changes
--------------
- 0.14.0
- Require ndarray 0.15
- Require rand 0.8 (unchanged from previous version)
- The F32 wrapper is now deprecated, it's redundant
- 0.13.0
- Require ndarray 0.14 (unchanged from previous version)
- Require rand 0.8
- Require rand_distr 0.4
- Fix methods `sample_axis` and `sample_axis_using` so that they can be used on array views too.
- 0.12.0
- Require ndarray 0.14
- Require rand 0.7 (unchanged from previous version)
- Require rand_distr 0.3
- 0.11.0
- Require ndarray 0.13
- Require rand 0.7 (unchanged from previous version)
- 0.10.0
- Require `rand` 0.7
- Require Rust 1.32 or later
- Re-export `rand` as a submodule, `ndarray_rand::rand`
- Re-export `rand-distr` as a submodule, `ndarray_rand::rand_distr`
- 0.9.0
- Require rand 0.6
- 0.8.0
- Require ndarray 0.12
- Require rand 0.5
- 0.7.0
- Require ndarray 0.11
- Require rand 0.4
- 0.6.1
- Clean up implementation of ``Array::random`` by @v-shmyhlo
- 0.6.0
- Require ndarray 0.10.0
- 0.5.0
- Require ndarray 0.9
- 0.4.0
- Require ndarray 0.8
- 0.3.0
- Require ndarray 0.7
- 0.2.0
- Require ndarray 0.6
- 0.1.0
- Initial release
ndarray-rand-0.14.0/benches/bench.rs000064400000000000000000000010370000000000000153020ustar 00000000000000#![feature(test)]
extern crate test;
use ndarray::Array;
use ndarray_rand::RandomExt;
use rand_distr::Normal;
use rand_distr::Uniform;
use test::Bencher;
#[bench]
fn uniform_f32(b: &mut Bencher) {
let m = 100;
b.iter(|| Array::random((m, m), Uniform::new(-1f32, 1.)));
}
#[bench]
fn norm_f32(b: &mut Bencher) {
let m = 100;
b.iter(|| Array::random((m, m), Normal::new(0f32, 1.).unwrap()));
}
#[bench]
fn norm_f64(b: &mut Bencher) {
let m = 100;
b.iter(|| Array::random((m, m), Normal::new(0f64, 1.).unwrap()));
}
ndarray-rand-0.14.0/src/lib.rs000064400000000000000000000265650000000000000141660ustar 00000000000000// Copyright 2016-2019 bluss and ndarray developers.
//
// Licensed under the Apache License, Version 2.0 or the MIT license
// , at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Constructors for randomized arrays: `rand` integration for `ndarray`.
//!
//! See [**`RandomExt`**](trait.RandomExt.html) for usage examples.
//!
//! ## Note
//!
//! `ndarray-rand` depends on [`rand` 0.8][rand].
//!
//! [`rand`][rand] and [`rand_distr`][rand_distr]
//! are re-exported as sub-modules, [`ndarray_rand::rand`](rand/index.html)
//! and [`ndarray_rand::rand_distr`](rand_distr/index.html) respectively.
//! You can use these submodules for guaranteed version compatibility or
//! convenience.
//!
//! [rand]: https://docs.rs/rand/0.8
//! [rand_distr]: https://docs.rs/rand_distr/0.4
//!
//! If you want to use a random number generator or distribution from another crate
//! with `ndarray-rand`, you need to make sure that the other crate also depends on the
//! same version of `rand`. Otherwise, the compiler will return errors saying
//! that the items are not compatible (e.g. that a type doesn't implement a
//! necessary trait).
use crate::rand::distributions::{Distribution, Uniform};
use crate::rand::rngs::SmallRng;
use crate::rand::seq::index;
use crate::rand::{thread_rng, Rng, SeedableRng};
use ndarray::{Array, Axis, RemoveAxis, ShapeBuilder};
use ndarray::{ArrayBase, DataOwned, RawData, Data, Dimension};
#[cfg(feature = "quickcheck")]
use quickcheck::{Arbitrary, Gen};
/// `rand`, re-exported for convenience and version-compatibility.
pub mod rand {
pub use rand::*;
}
/// `rand-distr`, re-exported for convenience and version-compatibility.
pub mod rand_distr {
pub use rand_distr::*;
}
/// Constructors for n-dimensional arrays with random elements.
///
/// This trait extends ndarrayâ€™s `ArrayBase` and can not be implemented
/// for other types.
///
/// The default RNG is a fast automatically seeded rng (currently
/// [`rand::rngs::SmallRng`], seeded from [`rand::thread_rng`]).
///
/// Note that `SmallRng` is cheap to initialize and fast, but it may generate
/// low-quality random numbers, and reproducibility is not guaranteed. See its
/// documentation for information. You can select a different RNG with
/// [`.random_using()`](#tymethod.random_using).
pub trait RandomExt~~
where
S: RawData,
D: Dimension,
{
/// Create an array with shape `dim` with elements drawn from
/// `distribution` using the default RNG.
///
/// ***Panics*** if creation of the RNG fails or if the number of elements
/// overflows usize.
///
/// ```
/// use ndarray::Array;
/// use ndarray_rand::RandomExt;
/// use ndarray_rand::rand_distr::Uniform;
///
/// # fn main() {
/// let a = Array::random((2, 5), Uniform::new(0., 10.));
/// println!("{:8.4}", a);
/// // Example Output:
/// // [[ 8.6900, 6.9824, 3.8922, 6.5861, 2.4890],
/// // [ 0.0914, 5.5186, 5.8135, 5.2361, 3.1879]]
/// # }
fn random(shape: Sh, distribution: IdS) -> ArrayBase~~~~
where
IdS: Distribution,
S: DataOwned,
Sh: ShapeBuilder;
/// Create an array with shape `dim` with elements drawn from
/// `distribution`, using a specific Rng `rng`.
///
/// ***Panics*** if the number of elements overflows usize.
///
/// ```
/// use ndarray::Array;
/// use ndarray_rand::RandomExt;
/// use ndarray_rand::rand::SeedableRng;
/// use ndarray_rand::rand_distr::Uniform;
/// use rand_isaac::isaac64::Isaac64Rng;
///
/// # fn main() {
/// // Get a seeded random number generator for reproducibility (Isaac64 algorithm)
/// let seed = 42;
/// let mut rng = Isaac64Rng::seed_from_u64(seed);
///
/// // Generate a random array using `rng`
/// let a = Array::random_using((2, 5), Uniform::new(0., 10.), &mut rng);
/// println!("{:8.4}", a);
/// // Example Output:
/// // [[ 8.6900, 6.9824, 3.8922, 6.5861, 2.4890],
/// // [ 0.0914, 5.5186, 5.8135, 5.2361, 3.1879]]
/// # }
fn random_using(shape: Sh, distribution: IdS, rng: &mut R) -> ArrayBase~~~~
where
IdS: Distribution,
R: Rng + ?Sized,
S: DataOwned,
Sh: ShapeBuilder;
/// Sample `n_samples` lanes slicing along `axis` using the default RNG.
///
/// If `strategy==SamplingStrategy::WithoutReplacement`, each lane can only be sampled once.
/// If `strategy==SamplingStrategy::WithReplacement`, each lane can be sampled multiple times.
///
/// ***Panics*** when:
/// - creation of the RNG fails;
/// - `n_samples` is greater than the length of `axis` (if sampling without replacement);
/// - length of `axis` is 0.
///
/// ```
/// use ndarray::{array, Axis};
/// use ndarray_rand::{RandomExt, SamplingStrategy};
///
/// # fn main() {
/// let a = array![
/// [1., 2., 3.],
/// [4., 5., 6.],
/// [7., 8., 9.],
/// [10., 11., 12.],
/// ];
/// // Sample 2 rows, without replacement
/// let sample_rows = a.sample_axis(Axis(0), 2, SamplingStrategy::WithoutReplacement);
/// println!("{:?}", sample_rows);
/// // Example Output: (1st and 3rd rows)
/// // [
/// // [1., 2., 3.],
/// // [7., 8., 9.]
/// // ]
/// // Sample 2 columns, with replacement
/// let sample_columns = a.sample_axis(Axis(1), 1, SamplingStrategy::WithReplacement);
/// println!("{:?}", sample_columns);
/// // Example Output: (2nd column, sampled twice)
/// // [
/// // [2., 2.],
/// // [5., 5.],
/// // [8., 8.],
/// // [11., 11.]
/// // ]
/// # }
/// ```
fn sample_axis(&self, axis: Axis, n_samples: usize, strategy: SamplingStrategy) -> Array
where
A: Copy,
S: Data,
D: RemoveAxis;
/// Sample `n_samples` lanes slicing along `axis` using the specified RNG `rng`.
///
/// If `strategy==SamplingStrategy::WithoutReplacement`, each lane can only be sampled once.
/// If `strategy==SamplingStrategy::WithReplacement`, each lane can be sampled multiple times.
///
/// ***Panics*** when:
/// - creation of the RNG fails;
/// - `n_samples` is greater than the length of `axis` (if sampling without replacement);
/// - length of `axis` is 0.
///
/// ```
/// use ndarray::{array, Axis};
/// use ndarray_rand::{RandomExt, SamplingStrategy};
/// use ndarray_rand::rand::SeedableRng;
/// use rand_isaac::isaac64::Isaac64Rng;
///
/// # fn main() {
/// // Get a seeded random number generator for reproducibility (Isaac64 algorithm)
/// let seed = 42;
/// let mut rng = Isaac64Rng::seed_from_u64(seed);
///
/// let a = array![
/// [1., 2., 3.],
/// [4., 5., 6.],
/// [7., 8., 9.],
/// [10., 11., 12.],
/// ];
/// // Sample 2 rows, without replacement
/// let sample_rows = a.sample_axis_using(Axis(0), 2, SamplingStrategy::WithoutReplacement, &mut rng);
/// println!("{:?}", sample_rows);
/// // Example Output: (1st and 3rd rows)
/// // [
/// // [1., 2., 3.],
/// // [7., 8., 9.]
/// // ]
///
/// // Sample 2 columns, with replacement
/// let sample_columns = a.sample_axis_using(Axis(1), 1, SamplingStrategy::WithReplacement, &mut rng);
/// println!("{:?}", sample_columns);
/// // Example Output: (2nd column, sampled twice)
/// // [
/// // [2., 2.],
/// // [5., 5.],
/// // [8., 8.],
/// // [11., 11.]
/// // ]
/// # }
/// ```
fn sample_axis_using(
&self,
axis: Axis,
n_samples: usize,
strategy: SamplingStrategy,
rng: &mut R,
) -> Array
where
R: Rng + ?Sized,
A: Copy,
S: Data,
D: RemoveAxis;
}
impl~~~~ RandomExt~~~~ for ArrayBase~~~~
where
S: RawData,
D: Dimension,
{
fn random(shape: Sh, dist: IdS) -> ArrayBase~~~~
where
IdS: Distribution,
S: DataOwned,
Sh: ShapeBuilder,
{
Self::random_using(shape, dist, &mut get_rng())
}
fn random_using(shape: Sh, dist: IdS, rng: &mut R) -> ArrayBase~~~~
where
IdS: Distribution,
R: Rng + ?Sized,
S: DataOwned,
Sh: ShapeBuilder,
{
Self::from_shape_simple_fn(shape, move || dist.sample(rng))
}
fn sample_axis(&self, axis: Axis, n_samples: usize, strategy: SamplingStrategy) -> Array
where
A: Copy,
S: Data,
D: RemoveAxis,
{
self.sample_axis_using(axis, n_samples, strategy, &mut get_rng())
}
fn sample_axis_using(
&self,
axis: Axis,
n_samples: usize,
strategy: SamplingStrategy,
rng: &mut R,
) -> Array
where
R: Rng + ?Sized,
A: Copy,
S: Data,
D: RemoveAxis,
{
let indices: Vec<_> = match strategy {
SamplingStrategy::WithReplacement => {
let distribution = Uniform::from(0..self.len_of(axis));
(0..n_samples).map(|_| distribution.sample(rng)).collect()
}
SamplingStrategy::WithoutReplacement => {
index::sample(rng, self.len_of(axis), n_samples).into_vec()
}
};
self.select(axis, &indices)
}
}
/// Used as parameter in [`sample_axis`] and [`sample_axis_using`] to determine
/// if lanes from the original array should only be sampled once (*without replacement*) or
/// multiple times (*with replacement*).
///
/// [`sample_axis`]: trait.RandomExt.html#tymethod.sample_axis
/// [`sample_axis_using`]: trait.RandomExt.html#tymethod.sample_axis_using
#[derive(Debug, Clone)]
pub enum SamplingStrategy {
WithReplacement,
WithoutReplacement,
}
// `Arbitrary` enables `quickcheck` to generate random `SamplingStrategy` values for testing.
#[cfg(feature = "quickcheck")]
impl Arbitrary for SamplingStrategy {
fn arbitrary(g: &mut G) -> Self {
if bool::arbitrary(g) {
SamplingStrategy::WithReplacement
} else {
SamplingStrategy::WithoutReplacement
}
}
}
fn get_rng() -> SmallRng {
SmallRng::from_rng(thread_rng()).expect("create SmallRng from thread_rng failed")
}
/// A wrapper type that allows casting f64 distributions to f32
///
/// ```
/// use ndarray::Array;
/// use ndarray_rand::{RandomExt, F32};
/// use ndarray_rand::rand_distr::Normal;
///
/// # fn main() {
/// let distribution_f64 = Normal::new(0., 1.).expect("Failed to create normal distribution");
/// let a = Array::random((2, 5), F32(distribution_f64));
/// println!("{:8.4}", a);
/// // Example Output:
/// // [[ -0.6910, 1.1730, 1.0902, -0.4092, -1.7340],
/// // [ -0.6810, 0.1678, -0.9487, 0.3150, 1.2981]]
/// # }
#[derive(Copy, Clone, Debug)]
#[deprecated(since="0.14.0", note="Redundant with rand 0.8")]
pub struct F32~~~~(pub S);
#[allow(deprecated)]
impl~~~~ Distribution for F32~~~~
where
S: Distribution,
{
fn sample(&self, rng: &mut R) -> f32 {
self.0.sample(rng) as f32
}
}
ndarray-rand-0.14.0/tests/tests.rs000064400000000000000000000077470000000000000151360ustar 00000000000000use ndarray::{Array, Array2, ArrayView1, Axis};
#[cfg(feature = "quickcheck")]
use ndarray_rand::rand::{distributions::Distribution, thread_rng};
use ndarray::ShapeBuilder;
use ndarray_rand::rand_distr::Uniform;
use ndarray_rand::{RandomExt, SamplingStrategy};
use quickcheck::quickcheck;
#[test]
fn test_dim() {
let (mm, nn) = (5, 5);
for m in 0..mm {
for n in 0..nn {
let a = Array::random((m, n), Uniform::new(0., 2.));
assert_eq!(a.shape(), &[m, n]);
assert!(a.iter().all(|x| *x < 2.));
assert!(a.iter().all(|x| *x >= 0.));
assert!(a.is_standard_layout());
}
}
}
#[test]
fn test_dim_f() {
let (mm, nn) = (5, 5);
for m in 0..mm {
for n in 0..nn {
let a = Array::random((m, n).f(), Uniform::new(0., 2.));
assert_eq!(a.shape(), &[m, n]);
assert!(a.iter().all(|x| *x < 2.));
assert!(a.iter().all(|x| *x >= 0.));
assert!(a.t().is_standard_layout());
}
}
}
#[test]
fn sample_axis_on_view() {
let m = 5;
let a = Array::random((m, 4), Uniform::new(0., 2.));
let _samples = a.view().sample_axis(Axis(0), m, SamplingStrategy::WithoutReplacement);
}
#[test]
#[should_panic]
fn oversampling_without_replacement_should_panic() {
let m = 5;
let a = Array::random((m, 4), Uniform::new(0., 2.));
let _samples = a.sample_axis(Axis(0), m + 1, SamplingStrategy::WithoutReplacement);
}
quickcheck! {
fn oversampling_with_replacement_is_fine(m: usize, n: usize) -> bool {
let a = Array::random((m, n), Uniform::new(0., 2.));
// Higher than the length of both axes
let n_samples = m + n + 1;
// We don't want to deal with sampling from 0-length axes in this test
if m != 0 {
if !sampling_works(&a, SamplingStrategy::WithReplacement, Axis(0), n_samples) {
return false;
}
}
// We don't want to deal with sampling from 0-length axes in this test
if n != 0 {
if !sampling_works(&a, SamplingStrategy::WithReplacement, Axis(1), n_samples) {
return false;
}
}
true
}
}
#[cfg(feature = "quickcheck")]
quickcheck! {
fn sampling_behaves_as_expected(m: usize, n: usize, strategy: SamplingStrategy) -> bool {
let a = Array::random((m, n), Uniform::new(0., 2.));
let mut rng = &mut thread_rng();
// We don't want to deal with sampling from 0-length axes in this test
if m != 0 {
let n_row_samples = Uniform::from(1..m+1).sample(&mut rng);
if !sampling_works(&a, strategy.clone(), Axis(0), n_row_samples) {
return false;
}
}
// We don't want to deal with sampling from 0-length axes in this test
if n != 0 {
let n_col_samples = Uniform::from(1..n+1).sample(&mut rng);
if !sampling_works(&a, strategy, Axis(1), n_col_samples) {
return false;
}
}
true
}
}
fn sampling_works(
a: &Array2,
strategy: SamplingStrategy,
axis: Axis,
n_samples: usize,
) -> bool {
let samples = a.sample_axis(axis, n_samples, strategy);
samples
.axis_iter(axis)
.all(|lane| is_subset(&a, &lane, axis))
}
// Check if, when sliced along `axis`, there is at least one lane in `a` equal to `b`
fn is_subset(a: &Array2, b: &ArrayView1, axis: Axis) -> bool {
a.axis_iter(axis).any(|lane| &lane == b)
}
#[test]
#[should_panic]
fn sampling_without_replacement_from_a_zero_length_axis_should_panic() {
let n = 5;
let a = Array::random((0, n), Uniform::new(0., 2.));
let _samples = a.sample_axis(Axis(0), 1, SamplingStrategy::WithoutReplacement);
}
#[test]
#[should_panic]
fn sampling_with_replacement_from_a_zero_length_axis_should_panic() {
let n = 5;
let a = Array::random((0, n), Uniform::new(0., 2.));
let _samples = a.sample_axis(Axis(0), 1, SamplingStrategy::WithReplacement);
}
~~