weighted-gss 0.2.2

Persistent weighted graph-structured stacks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use crate::nodes::{UKind, URef, WKind, WRef, u_id, w_id};
use crate::{Weight, WeightedGss as CoreWeightedGss};
use pyo3::basic::CompareOp;
use pyo3::exceptions::{PyOverflowError, PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyDict, PyList, PyModule, PySet, PyTuple, PyType};
use rustc_hash::FxHashMap;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

thread_local! {
    static PENDING_CALLBACK_ERROR: RefCell<Option<PyErr>> = const { RefCell::new(None) };
}

fn record_callback_error(error: PyErr) {
    PENDING_CALLBACK_ERROR.with(|slot| {
        let mut slot = slot.borrow_mut();
        if slot.is_none() {
            *slot = Some(error);
        }
    });
}

fn callback_error_pending() -> bool {
    PENDING_CALLBACK_ERROR.with(|slot| slot.borrow().is_some())
}

fn run_callbacks<T>(operation: impl FnOnce() -> T) -> PyResult<T> {
    PENDING_CALLBACK_ERROR.with(|slot| {
        slot.borrow_mut().take();
    });
    let result = operation();
    match PENDING_CALLBACK_ERROR.with(|slot| slot.borrow_mut().take()) {
        Some(error) => Err(error),
        None => Ok(result),
    }
}

struct PyKey {
    object: Py<PyAny>,
    hash: isize,
}

impl PyKey {
    fn new(py: Python<'_>, object: Py<PyAny>) -> PyResult<Self> {
        let hash = object
            .bind(py)
            .hash()
            .map_err(|_| PyTypeError::new_err("stack values must be hashable"))?;
        Ok(Self { object, hash })
    }
}

impl Clone for PyKey {
    fn clone(&self) -> Self {
        Python::attach(|py| Self {
            object: self.object.clone_ref(py),
            hash: self.hash,
        })
    }
}

impl PartialEq for PyKey {
    fn eq(&self, other: &Self) -> bool {
        Python::attach(|py| {
            if self.object.bind(py).is(other.object.bind(py)) {
                return true;
            }
            match self
                .object
                .bind(py)
                .rich_compare(other.object.bind(py), CompareOp::Eq)
                .and_then(|result| result.is_truthy())
            {
                Ok(equal) => equal,
                Err(error) => {
                    record_callback_error(error);
                    false
                }
            }
        })
    }
}

impl Eq for PyKey {}

impl Hash for PyKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.hash.hash(state);
    }
}

struct PyWeight(Py<PyAny>);

impl PyWeight {
    fn new(py: Python<'_>, object: Py<PyAny>) -> PyResult<Self> {
        if !object.bind(py).is_none() && !object.bind(py).hasattr("join")? {
            return Err(PyTypeError::new_err(
                "weights must be None or provide join(other)",
            ));
        }
        Ok(Self(object))
    }
}

impl Clone for PyWeight {
    fn clone(&self) -> Self {
        Python::attach(|py| Self(self.0.clone_ref(py)))
    }
}

impl PartialEq for PyWeight {
    fn eq(&self, other: &Self) -> bool {
        Python::attach(|py| self.0.bind(py).is(other.0.bind(py)))
    }
}

impl Weight for PyWeight {
    fn join(&self, other: &Self) -> Self {
        Python::attach(|py| {
            if self.0.bind(py).is_none() && other.0.bind(py).is_none() {
                return Self(py.None());
            }
            if callback_error_pending() {
                return self.clone();
            }
            match self.0.call_method1(py, "join", (other.0.clone_ref(py),)) {
                Ok(joined) => Self(joined),
                Err(error) => {
                    record_callback_error(error);
                    self.clone()
                }
            }
        })
    }
}

fn enqueue_weighted_node(
    node: &WRef<PyKey, PyWeight>,
    ids: &mut FxHashMap<usize, usize>,
    queue: &mut VecDeque<WRef<PyKey, PyWeight>>,
) -> usize {
    let pointer = w_id(node);
    if let Some(id) = ids.get(&pointer) {
        return *id;
    }
    let id = ids.len();
    ids.insert(pointer, id);
    queue.push_back(node.clone());
    id
}

fn enqueue_unweighted_node(
    node: &URef<PyKey>,
    ids: &mut FxHashMap<usize, usize>,
    queue: &mut VecDeque<URef<PyKey>>,
) -> usize {
    let pointer = u_id(node);
    if let Some(id) = ids.get(&pointer) {
        return *id;
    }
    let id = ids.len();
    ids.insert(pointer, id);
    queue.push_back(node.clone());
    id
}

fn weight_reference(
    py: Python<'_>,
    weight: &Arc<PyWeight>,
    ids: &mut FxHashMap<usize, usize>,
    output: &Bound<'_, PyList>,
) -> PyResult<String> {
    let pointer = Arc::as_ptr(weight) as usize;
    if let Some(id) = ids.get(&pointer) {
        return Ok(format!("a{id}"));
    }
    let id = ids.len();
    ids.insert(pointer, id);
    let entry = PyDict::new(py);
    entry.set_item("id", format!("a{id}"))?;
    entry.set_item("value", weight.0.clone_ref(py))?;
    output.append(entry)?;
    Ok(format!("a{id}"))
}

/// A persistent collection of weighted stack alternatives.
///
/// Stacks are ordered bottom-to-top. Stack values must be immutable and
/// hashable. Weights may be ``None`` or objects whose ``join(other)`` method is
/// associative, commutative, and idempotent.
#[pyclass(
    name = "WeightedGSS",
    module = "weighted_gss._native",
    unsendable,
    skip_from_py_object
)]
struct PyWeightedGss {
    inner: CoreWeightedGss<PyKey, PyWeight>,
}

impl Clone for PyWeightedGss {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl PyWeightedGss {
    fn convert_stack(py: Python<'_>, stack: Vec<Py<PyAny>>) -> PyResult<Vec<PyKey>> {
        stack
            .into_iter()
            .map(|value| PyKey::new(py, value))
            .collect()
    }

    fn to_python_stacks(&self, py: Python<'_>, max_stacks: usize) -> PyResult<Py<PyAny>> {
        let stacks = run_callbacks(|| self.inner.to_stacks(max_stacks))?.map_err(|_| {
            PyOverflowError::new_err(format!(
                "the GSS contains more than {max_stacks} distinct stacks; increase max_stacks"
            ))
        })?;
        let result = PyList::empty(py);
        for (stack, weight) in stacks {
            let values = PyList::new(py, stack.into_iter().map(|value| value.object))?;
            let pair = PyTuple::new(py, [values.into_any().unbind(), weight.0])?;
            result.append(pair)?;
        }
        Ok(result.into_any().unbind())
    }

    fn dump_structure(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let result = PyDict::new(py);
        let nodes = PyList::empty(py);
        let edges = PyList::empty(py);
        let weights = PyList::empty(py);

        let mut weighted_ids = FxHashMap::default();
        let mut unweighted_ids = FxHashMap::default();
        let mut weight_ids = FxHashMap::default();
        let mut weighted_queue = VecDeque::new();
        let mut unweighted_queue = VecDeque::new();

        let root_id =
            enqueue_weighted_node(&self.inner.root, &mut weighted_ids, &mut weighted_queue);

        while let Some(node) = weighted_queue.pop_front() {
            let source_id = weighted_ids[&w_id(&node)];
            let node_output = PyDict::new(py);
            node_output.set_item("id", format!("w{source_id}"))?;
            node_output.set_item("enum", "WKind")?;
            node_output.set_item("layer", "weighted")?;
            node_output.set_item("paths", node.paths)?;
            node_output.set_item("max_depth", node.max_depth)?;

            match &node.kind {
                WKind::Branch { empty, children } => {
                    node_output.set_item("variant", "Branch")?;
                    let empty_weights = PyList::empty(py);
                    for weight in empty {
                        empty_weights.append(weight_reference(
                            py,
                            weight,
                            &mut weight_ids,
                            &weights,
                        )?)?;
                    }
                    node_output.set_item("empty_weights", empty_weights)?;

                    for (value, alternatives) in children {
                        for (alternative, child) in alternatives.iter().enumerate() {
                            let target_id = enqueue_weighted_node(
                                child,
                                &mut weighted_ids,
                                &mut weighted_queue,
                            );
                            let edge = PyDict::new(py);
                            edge.set_item("from", format!("w{source_id}"))?;
                            edge.set_item("to", format!("w{target_id}"))?;
                            edge.set_item("kind", "stack")?;
                            edge.set_item("value", value.object.clone_ref(py))?;
                            edge.set_item("alternative", alternative)?;
                            edges.append(edge)?;
                        }
                    }
                }
                WKind::Segment { values, next } => {
                    node_output.set_item("variant", "Segment")?;
                    let segment_values =
                        PyList::new(py, values.iter().map(|value| value.object.clone_ref(py)))?;
                    node_output.set_item("values_top_first", segment_values)?;
                    let target_id =
                        enqueue_weighted_node(next, &mut weighted_ids, &mut weighted_queue);
                    let edge = PyDict::new(py);
                    edge.set_item("from", format!("w{source_id}"))?;
                    edge.set_item("to", format!("w{target_id}"))?;
                    edge.set_item("kind", "segment_next")?;
                    edges.append(edge)?;
                }
                WKind::Shared { weight, stacks } => {
                    node_output.set_item("variant", "Shared")?;
                    node_output.set_item(
                        "weight",
                        weight_reference(py, weight, &mut weight_ids, &weights)?,
                    )?;
                    let target_id =
                        enqueue_unweighted_node(stacks, &mut unweighted_ids, &mut unweighted_queue);
                    let edge = PyDict::new(py);
                    edge.set_item("from", format!("w{source_id}"))?;
                    edge.set_item("to", format!("u{target_id}"))?;
                    edge.set_item("kind", "shared_stacks")?;
                    edges.append(edge)?;
                }
            }
            nodes.append(node_output)?;
        }

        while let Some(node) = unweighted_queue.pop_front() {
            let source_id = unweighted_ids[&u_id(&node)];
            let node_output = PyDict::new(py);
            node_output.set_item("id", format!("u{source_id}"))?;
            node_output.set_item("enum", "UKind")?;
            node_output.set_item("layer", "unweighted")?;
            node_output.set_item("paths", node.paths)?;
            node_output.set_item("max_depth", node.max_depth)?;

            match &node.kind {
                UKind::Branch { empty, children } => {
                    node_output.set_item("variant", "Branch")?;
                    node_output.set_item("empty", *empty)?;
                    for (value, alternatives) in children {
                        for (alternative, child) in alternatives.iter().enumerate() {
                            let target_id = enqueue_unweighted_node(
                                child,
                                &mut unweighted_ids,
                                &mut unweighted_queue,
                            );
                            let edge = PyDict::new(py);
                            edge.set_item("from", format!("u{source_id}"))?;
                            edge.set_item("to", format!("u{target_id}"))?;
                            edge.set_item("kind", "stack")?;
                            edge.set_item("value", value.object.clone_ref(py))?;
                            edge.set_item("alternative", alternative)?;
                            edges.append(edge)?;
                        }
                    }
                }
                UKind::Segment { values, next } => {
                    node_output.set_item("variant", "Segment")?;
                    let segment_values =
                        PyList::new(py, values.iter().map(|value| value.object.clone_ref(py)))?;
                    node_output.set_item("values_top_first", segment_values)?;
                    let target_id =
                        enqueue_unweighted_node(next, &mut unweighted_ids, &mut unweighted_queue);
                    let edge = PyDict::new(py);
                    edge.set_item("from", format!("u{source_id}"))?;
                    edge.set_item("to", format!("u{target_id}"))?;
                    edge.set_item("kind", "segment_next")?;
                    edges.append(edge)?;
                }
            }
            nodes.append(node_output)?;
        }

        result.set_item("schema", "weighted-gss/internal-structure/v1")?;
        result.set_item("root", format!("w{root_id}"))?;
        result.set_item("nodes", nodes)?;
        result.set_item("edges", edges)?;
        result.set_item("weights", weights)?;
        Ok(result.into_any().unbind())
    }
}

#[pymethods]
impl PyWeightedGss {
    /// Construct an empty weighted GSS.
    #[new]
    fn new() -> Self {
        Self {
            inner: CoreWeightedGss::new(),
        }
    }

    /// Construct one bottom-to-top stack.
    #[classmethod]
    #[pyo3(signature = (stack, weight = None))]
    fn from_stack(
        _cls: &Bound<'_, PyType>,
        py: Python<'_>,
        stack: Vec<Py<PyAny>>,
        weight: Option<Py<PyAny>>,
    ) -> PyResult<Self> {
        let stack = Self::convert_stack(py, stack)?;
        let weight = PyWeight::new(py, weight.unwrap_or_else(|| py.None()))?;
        Ok(Self {
            inner: run_callbacks(|| CoreWeightedGss::from_stack(stack, weight))?,
        })
    }

    /// Construct from ``(stack, weight)`` pairs.
    #[classmethod]
    fn from_stacks(
        _cls: &Bound<'_, PyType>,
        py: Python<'_>,
        entries: &Bound<'_, PyAny>,
    ) -> PyResult<Self> {
        let mut converted = Vec::new();
        for entry in entries.try_iter()? {
            let (stack, weight): (Vec<Py<PyAny>>, Py<PyAny>) = entry?.extract()?;
            converted.push((Self::convert_stack(py, stack)?, PyWeight::new(py, weight)?));
        }
        Ok(Self {
            inner: run_callbacks(|| CoreWeightedGss::from_stacks(converted))?,
        })
    }

    /// Construct unweighted stacks, represented by the shared weight ``None``.
    #[classmethod]
    fn from_unweighted(
        _cls: &Bound<'_, PyType>,
        py: Python<'_>,
        stacks: &Bound<'_, PyAny>,
    ) -> PyResult<Self> {
        let mut converted = Vec::new();
        for stack in stacks.try_iter()? {
            converted.push(Self::convert_stack(py, stack?.extract()?)?);
        }
        let weight = PyWeight(py.None());
        Ok(Self {
            inner: run_callbacks(|| CoreWeightedGss::from_stacks_with_weight(converted, weight))?,
        })
    }

    /// Return a new value containing the existing alternatives plus ``stack``.
    #[pyo3(signature = (stack, weight = None))]
    fn with_stack(
        &self,
        py: Python<'_>,
        stack: Vec<Py<PyAny>>,
        weight: Option<Py<PyAny>>,
    ) -> PyResult<Self> {
        let stack = Self::convert_stack(py, stack)?;
        let weight = PyWeight::new(py, weight.unwrap_or_else(|| py.None()))?;
        Ok(Self {
            inner: run_callbacks(|| self.inner.with_stack(stack, weight))?,
        })
    }

    /// Merge another weighted GSS into this one.
    fn merge(&self, other: &Self) -> PyResult<Self> {
        Ok(Self {
            inner: run_callbacks(|| self.inner.merge(&other.inner))?,
        })
    }

    /// Merge an iterable of weighted GSS values.
    #[classmethod]
    fn merge_all(_cls: &Bound<'_, PyType>, values: &Bound<'_, PyAny>) -> PyResult<Self> {
        let mut converted = Vec::new();
        for value in values.try_iter()? {
            let value = value?;
            let value: PyRef<'_, Self> = value.extract()?;
            converted.push(value.inner.clone());
        }
        Ok(Self {
            inner: run_callbacks(|| CoreWeightedGss::merge_all(converted))?,
        })
    }

    /// Push ``value`` onto every represented stack.
    fn push(&self, py: Python<'_>, value: Py<PyAny>) -> PyResult<Self> {
        let value = PyKey::new(py, value)?;
        Ok(Self {
            inner: run_callbacks(|| self.inner.push(value))?,
        })
    }

    /// Pop one value, discarding empty alternatives.
    fn pop(&self) -> PyResult<Self> {
        Ok(Self {
            inner: run_callbacks(|| self.inner.pop())?,
        })
    }

    /// Pop ``count`` values, discarding alternatives that underflow.
    fn popn(&self, count: isize) -> PyResult<Self> {
        let count = usize::try_from(count)
            .map_err(|_| PyValueError::new_err("count must be non-negative"))?;
        Ok(Self {
            inner: run_callbacks(|| self.inner.popn(count))?,
        })
    }

    /// Return the unique non-empty top value.
    ///
    /// Raises ``ValueError`` when the GSS is empty, has multiple possible tops,
    /// or also contains an empty-stack alternative.
    fn top(&self) -> PyResult<Py<PyAny>> {
        run_callbacks(|| self.inner.top())?
            .map(|value| value.object)
            .ok_or_else(|| PyValueError::new_err("the GSS does not have one exclusive top value"))
    }

    /// Return the distinct non-empty top values.
    fn tops(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let tops = run_callbacks(|| self.inner.tops().collect::<Vec<_>>())?;
        let values = tops
            .into_iter()
            .map(|value| value.object)
            .collect::<Vec<_>>();
        Ok(PySet::new(py, &values)?.into_any().unbind())
    }

    /// Return whether an empty-stack alternative is present.
    fn has_empty_stack(&self) -> bool {
        self.inner.has_empty_stack()
    }

    /// Retain alternatives whose top equals ``value`` without popping it.
    fn retain_top(&self, py: Python<'_>, value: Py<PyAny>) -> PyResult<Self> {
        let value = PyKey::new(py, value)?;
        Ok(Self {
            inner: run_callbacks(|| self.inner.retain_top(&value))?,
        })
    }

    /// Retain only empty-stack alternatives.
    fn retain_empty(&self) -> PyResult<Self> {
        Ok(Self {
            inner: run_callbacks(|| self.inner.retain_empty())?,
        })
    }

    /// Retain alternatives with matching top ``value`` and pop that top.
    fn pop_top(&self, py: Python<'_>, value: Py<PyAny>) -> PyResult<Self> {
        let value = PyKey::new(py, value)?;
        Ok(Self {
            inner: run_callbacks(|| self.inner.pop_top(&value))?,
        })
    }

    /// Return ``(top, remainder)`` pairs for every non-empty top branch.
    fn pop_branches(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let branches = run_callbacks(|| self.inner.pop_branches())?;
        let result = PyList::empty(py);
        for (top, remainder) in branches {
            let remainder = Py::new(py, Self { inner: remainder })?;
            let pair = PyTuple::new(py, [top.object, remainder.into_any()])?;
            result.append(pair)?;
        }
        Ok(result.into_any().unbind())
    }

    /// Join every represented path weight.
    ///
    /// Raises ``ValueError`` when the GSS is empty. The returned weight may
    /// itself be ``None`` for an unweighted GSS.
    fn joined_weight(&self) -> PyResult<Py<PyAny>> {
        run_callbacks(|| self.inner.joined_weight())?
            .map(|weight| weight.0)
            .ok_or_else(|| PyValueError::new_err("the GSS is empty"))
    }

    /// Return the joined weight of the empty stack.
    ///
    /// Raises ``ValueError`` when no empty-stack alternative exists. The
    /// returned weight may itself be ``None`` for an unweighted GSS.
    fn empty_weight(&self) -> PyResult<Py<PyAny>> {
        run_callbacks(|| self.inner.empty_weight())?
            .map(|weight| weight.0)
            .ok_or_else(|| PyValueError::new_err("the GSS has no empty-stack alternative"))
    }

    /// Materialize extensional ``(stack, weight)`` pairs.
    ///
    /// Raises ``OverflowError`` instead of silently truncating when more than
    /// ``max_stacks`` distinct stacks would be materialized.
    #[pyo3(signature = (max_stacks = 4096))]
    fn to_stacks(&self, py: Python<'_>, max_stacks: usize) -> PyResult<Py<PyAny>> {
        self.to_python_stacks(py, max_stacks)
    }

    /// Return whether no alternatives are represented.
    fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Return the maximum represented stack depth.
    fn max_depth(&self) -> usize {
        self.inner.max_depth()
    }

    /// Return the internal shared graph as Python dictionaries and lists.
    ///
    /// This private diagnostic method exposes implementation details and may
    /// change without notice.
    fn _dump_structure(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        self.dump_structure(py)
    }

    /// Return the internal shared graph as JSON.
    ///
    /// Values that are not directly JSON serializable are represented with
    /// ``repr``. This private diagnostic format may change without notice.
    #[pyo3(signature = (indent = 2))]
    fn _dump_json(&self, py: Python<'_>, indent: usize) -> PyResult<String> {
        let structure = self.dump_structure(py)?;
        let json = PyModule::import(py, "json")?;
        let builtins = PyModule::import(py, "builtins")?;
        let kwargs = PyDict::new(py);
        kwargs.set_item("indent", indent)?;
        kwargs.set_item("default", builtins.getattr("repr")?)?;
        json.call_method("dumps", (structure,), Some(&kwargs))?
            .extract()
    }

    fn __bool__(&self) -> bool {
        !self.inner.is_empty()
    }

    fn __repr__(&self) -> String {
        format!(
            "WeightedGSS(is_empty={}, max_depth={})",
            self.inner.is_empty(),
            self.inner.max_depth()
        )
    }
}

#[pymodule]
fn _native(module: &Bound<'_, PyModule>) -> PyResult<()> {
    module.add_class::<PyWeightedGss>()?;
    module.add("__version__", env!("CARGO_PKG_VERSION"))?;
    Ok(())
}