probabilistic_machines 0.1.3 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,87 +2,84 @@
2
2
 
3
3
  use std::cell::RefCell;
4
4
 
5
- use bytes::Bytes;
6
- use magnus::scan_args::scan_args;
7
5
  use magnus::typed_data::Obj;
8
- use magnus::{Error, RArray, RHash, RModule, RString, Ruby, Value, function, method, prelude::*};
9
- use probabilistic_machines::TDigest;
10
-
11
- use crate::data::centroid;
12
- use crate::{Whole, codec_error, optional_kwarg, required_kwarg};
13
-
14
- /// Below this the cluster budget is zero, so every point merges into one
15
- /// centroid and a quantile is meaningless.
16
- const MIN_COMPRESSION: u16 = 10;
17
-
18
- /// The compressions this binding answers for, whether the digest is being built
19
- /// or read back.
20
- fn honoured(ruby: &Ruby, compression: u16) -> Result<u16, Error> {
21
- if compression < MIN_COMPRESSION {
22
- return Err(Error::new(
23
- ruby.exception_arg_error(),
24
- format!("compression must be at least {MIN_COMPRESSION}, got {compression}"),
25
- ));
26
- }
27
- Ok(compression)
28
- }
6
+ use magnus::{Error, RArray, RModule, RString, Ruby, Value, function, method, prelude::*};
7
+ use matryona_machines::ruby::{integer, real};
8
+ use probabilistic_machines::{MIN_COMPRESSION, TDigest};
9
+
10
+ use crate::data::{bytes, centroid, centroid_class};
11
+ use crate::{Pinned, answer, decoded_or_refused, define_class, partner, pin};
12
+
13
+ /// The class, pinned at init.
14
+ static CLASS: Pinned = Pinned::new("probabilistic_machines");
29
15
 
30
16
  #[magnus::wrap(class = "ProbabilisticMachines::TDigest", free_immediately, size)]
31
17
  struct Wrapper(RefCell<TDigest>);
32
18
 
33
19
  impl Wrapper {
34
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
35
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
36
- let Whole(compression) = required_kwarg::<Whole<u16>>(args.keywords, "compression")?;
37
- Ok(Self(RefCell::new(TDigest::new(honoured(
20
+ /// `TDigest.new(compression)`. `RangeError` where `TDigest::new` answers
21
+ /// `None`, below [`MIN_COMPRESSION`], or past 65535.
22
+ fn new(ruby: &Ruby, compression: Value) -> Result<Self, Error> {
23
+ let compression: u16 = integer(compression, "compression")?;
24
+ TDigest::new(compression)
25
+ .map(|digest| Self(RefCell::new(digest)))
26
+ .ok_or_else(|| {
27
+ Error::new(
28
+ ruby.exception_range_error(),
29
+ format!("compression must be at least {MIN_COMPRESSION}, got {compression}"),
30
+ )
31
+ })
32
+ }
33
+
34
+ /// `TDigest.decode(bytes)`: a digest, or the refusal symbol.
35
+ fn decode(ruby: &Ruby, bytes: Value) -> Result<Value, Error> {
36
+ let bytes = self::bytes(bytes, "bytes")?;
37
+ Ok(decoded_or_refused(
38
38
  ruby,
39
- compression,
40
- )?))))
41
- }
42
-
43
- fn load(ruby: &Ruby, blob: Bytes) -> Result<Self, Error> {
44
- let digest = TDigest::decode(&blob).map_err(|error| codec_error(ruby, error))?;
45
- honoured(ruby, digest.compression())?;
46
- Ok(Self(RefCell::new(digest)))
39
+ TDigest::decode(&bytes).map(|held| Self(RefCell::new(held))),
40
+ ))
47
41
  }
48
42
 
49
43
  fn compression(&self) -> u16 {
50
44
  self.0.borrow().compression()
51
45
  }
52
46
 
53
- fn add(ruby: &Ruby, rb_self: &Self, args: &[Value]) -> Result<(), Error> {
54
- let args = scan_args::<(f64,), (), (), (), RHash, ()>(args)?;
55
- let (value,) = args.required;
56
- let weight: f64 = optional_kwarg(args.keywords, "weight")?.unwrap_or(1.0);
57
- if !value.is_finite() {
58
- return Err(Error::new(
59
- ruby.exception_arg_error(),
60
- format!("value must be finite, got {value}"),
61
- ));
62
- }
63
- if !weight.is_finite() || weight <= 0.0 {
64
- return Err(Error::new(
65
- ruby.exception_arg_error(),
66
- format!("weight must be finite and positive, got {weight}"),
67
- ));
68
- }
69
- let count = rb_self.0.borrow().count();
70
- if !(count + weight).is_finite() {
47
+ fn add(ruby: &Ruby, this: Obj<Self>, value: Value) -> Result<Value, Error> {
48
+ this.check_frozen()?;
49
+ let value = real(value, "value")?;
50
+ let outcome = this.0.borrow_mut().add(value);
51
+ Ok(answer(ruby, outcome, "added"))
52
+ }
53
+
54
+ fn add_weighted(
55
+ ruby: &Ruby,
56
+ this: Obj<Self>,
57
+ value: Value,
58
+ weight: Value,
59
+ ) -> Result<Value, Error> {
60
+ this.check_frozen()?;
61
+ let value = real(value, "value")?;
62
+ let weight = real(weight, "weight")?;
63
+ let outcome = this.0.borrow_mut().add_weighted(value, weight);
64
+ Ok(answer(ruby, outcome, "added"))
65
+ }
66
+
67
+ /// `RangeError` for a `q` outside `0..=1` (NaN included), where the
68
+ /// core answers NaN: a caller's bug, not an empty digest.
69
+ fn quantile(ruby: &Ruby, this: &Self, q: Value) -> Result<f64, Error> {
70
+ let q = real(q, "q")?;
71
+ if !(0.0..=1.0).contains(&q) {
71
72
  return Err(Error::new(
72
- ruby.exception_arg_error(),
73
- format!("weight {weight} overflows the total weight {count}"),
73
+ ruby.exception_range_error(),
74
+ "q must be in 0..=1",
74
75
  ));
75
76
  }
76
- rb_self.0.borrow_mut().add_weighted(value, weight);
77
- Ok(())
78
- }
79
-
80
- fn quantile(&self, q: f64) -> f64 {
81
- self.0.borrow().quantile(q)
77
+ Ok(this.0.borrow().quantile(q))
82
78
  }
83
79
 
84
- fn cdf(&self, value: f64) -> f64 {
85
- self.0.borrow().cdf(value)
80
+ fn cdf(&self, value: Value) -> Result<f64, Error> {
81
+ let value = real(value, "value")?;
82
+ Ok(self.0.borrow().cdf(value))
86
83
  }
87
84
 
88
85
  fn count(&self) -> f64 {
@@ -105,33 +102,34 @@ impl Wrapper {
105
102
  self.0.borrow().is_empty()
106
103
  }
107
104
 
108
- fn centroids(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
109
- let digest = rb_self.0.borrow();
110
- let clusters = ruby.ary_new_capa(digest.len());
111
- for cluster in digest.centroids() {
112
- clusters.push(centroid(ruby, cluster.mean, cluster.weight)?)?;
105
+ fn centroids(ruby: &Ruby, this: &Self) -> Result<RArray, Error> {
106
+ let class = centroid_class(ruby)?;
107
+ let clusters: Vec<_> = this.0.borrow().centroids().to_vec();
108
+ let array = ruby.ary_new_capa(clusters.len());
109
+ for cluster in &clusters {
110
+ array.push(centroid(class, cluster)?)?;
113
111
  }
114
- Ok(clusters)
112
+ Ok(array)
115
113
  }
116
114
 
117
- fn merge(ruby: &Ruby, rb_self: Obj<Self>, other: &Self) -> Result<Obj<Self>, Error> {
115
+ fn compress(this: Obj<Self>) -> Result<(), Error> {
116
+ this.check_frozen()?;
117
+ this.0.borrow_mut().compress();
118
+ Ok(())
119
+ }
120
+
121
+ /// `:merged`, `:wrong_shape` for a digest of another compression, or
122
+ /// `:overflow`.
123
+ fn merge(ruby: &Ruby, this: Obj<Self>, other: Value) -> Result<Value, Error> {
124
+ this.check_frozen()?;
125
+ let other: Obj<Self> = partner(ruby, &CLASS, other)?;
118
126
  let source = other.0.borrow().clone();
119
- let count = rb_self.0.borrow().count();
120
- if !(count + source.count()).is_finite() {
121
- return Err(Error::new(
122
- ruby.exception_arg_error(),
123
- format!(
124
- "total weight {} overflows the total weight {count}",
125
- source.count()
126
- ),
127
- ));
128
- }
129
- rb_self.0.borrow_mut().merge(&source);
130
- Ok(rb_self)
127
+ let merged = this.0.borrow_mut().merge(&source);
128
+ Ok(answer(ruby, merged, "merged"))
131
129
  }
132
130
 
133
- fn dump(ruby: &Ruby, rb_self: &Self) -> RString {
134
- ruby.str_from_slice(&rb_self.0.borrow().encoded())
131
+ fn encoded(ruby: &Ruby, this: &Self) -> RString {
132
+ ruby.str_from_slice(&this.0.borrow().encoded())
135
133
  }
136
134
 
137
135
  fn inspect(&self) -> String {
@@ -146,11 +144,13 @@ impl Wrapper {
146
144
  }
147
145
 
148
146
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
149
- let class = module.define_class("TDigest", ruby.class_object())?;
150
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
151
- class.define_singleton_method("load", function!(Wrapper::load, 1))?;
147
+ let class = define_class(ruby, module, "TDigest")?;
148
+ class.const_set("MIN_COMPRESSION", MIN_COMPRESSION)?;
149
+ class.define_singleton_method("new", function!(Wrapper::new, 1))?;
150
+ class.define_singleton_method("decode", function!(Wrapper::decode, 1))?;
152
151
  class.define_method("compression", method!(Wrapper::compression, 0))?;
153
- class.define_method("add", method!(Wrapper::add, -1))?;
152
+ class.define_method("add", method!(Wrapper::add, 1))?;
153
+ class.define_method("add_weighted", method!(Wrapper::add_weighted, 2))?;
154
154
  class.define_method("quantile", method!(Wrapper::quantile, 1))?;
155
155
  class.define_method("cdf", method!(Wrapper::cdf, 1))?;
156
156
  class.define_method("count", method!(Wrapper::count, 0))?;
@@ -159,8 +159,9 @@ pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
159
159
  class.define_method("size", method!(Wrapper::size, 0))?;
160
160
  class.define_method("empty?", method!(Wrapper::is_empty, 0))?;
161
161
  class.define_method("centroids", method!(Wrapper::centroids, 0))?;
162
+ class.define_method("compress", method!(Wrapper::compress, 0))?;
162
163
  class.define_method("merge", method!(Wrapper::merge, 1))?;
163
- class.define_method("dump", method!(Wrapper::dump, 0))?;
164
+ class.define_method("encoded", method!(Wrapper::encoded, 0))?;
164
165
  class.define_method("inspect", method!(Wrapper::inspect, 0))?;
165
- Ok(())
166
+ pin::<Wrapper>(ruby, class, &CLASS)
166
167
  }