rankmodels 0.0.1__tar.gz

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.
@@ -0,0 +1,2 @@
1
+ # ALL FILES
2
+ * @RektPunk
@@ -0,0 +1,37 @@
1
+ name: Python CI
2
+
3
+ on:
4
+ pull_request:
5
+ types: [opened, reopened, synchronize]
6
+ paths:
7
+ - "python/**/*.py"
8
+ - "src/**/*.rs"
9
+ - "pyproject.toml"
10
+ - "uv.lock"
11
+ push:
12
+ branches:
13
+ - main
14
+ paths:
15
+ - "python/**/*.py"
16
+ - "src/**/*.rs"
17
+ - "pyproject.toml"
18
+ - "uv.lock"
19
+
20
+ jobs:
21
+ run-python-ci:
22
+ runs-on: ubuntu-latest
23
+ steps:
24
+ - name: Checkout code
25
+ uses: actions/checkout@v7
26
+ - name: Install Rust
27
+ uses: dtolnay/rust-toolchain@stable
28
+ - name: Rust Cache
29
+ uses: Swatinem/rust-cache@v2
30
+ - name: Install uv
31
+ uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d
32
+ - name: Install dependencies
33
+ run: uv sync --all-extras --dev
34
+ - name: Build and Install Extension
35
+ run: uvx maturin develop --release
36
+ - name: Run tests
37
+ run: uv run pytest python/tests/
@@ -0,0 +1,65 @@
1
+ name: Release to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*.*.*"
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build_wheels:
13
+ name: Build wheels on ${{ matrix.os }}
14
+ runs-on: ${{ matrix.os }}
15
+ strategy:
16
+ matrix:
17
+ os: [ubuntu-latest, windows-latest, macos-latest]
18
+
19
+ steps:
20
+ - uses: actions/checkout@v7
21
+ - uses: actions/setup-python@v7
22
+ with:
23
+ python-version: "3.10"
24
+
25
+ - name: Build wheels
26
+ uses: PyO3/maturin-action@v1
27
+ with:
28
+ command: build
29
+ args: --release --out dist
30
+ manylinux: auto
31
+ sccache: "true"
32
+
33
+ - name: Upload wheels
34
+ uses: actions/upload-artifact@v7
35
+ with:
36
+ name: wheels-${{ matrix.os }}
37
+ path: dist
38
+
39
+ publish:
40
+ name: Publish to PyPI
41
+ runs-on: ubuntu-latest
42
+ needs: [build_wheels]
43
+ steps:
44
+ - uses: actions/checkout@v7
45
+
46
+ - name: Download all wheels
47
+ uses: actions/download-artifact@v8
48
+ with:
49
+ path: dist
50
+ pattern: wheels-*
51
+ merge-multiple: true
52
+
53
+ - name: Build sdist
54
+ uses: PyO3/maturin-action@v1
55
+ with:
56
+ command: sdist
57
+ args: --out dist
58
+
59
+ - name: Publish to PyPI
60
+ uses: PyO3/maturin-action@v1
61
+ env:
62
+ MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
63
+ with:
64
+ command: upload
65
+ args: --non-interactive --skip-existing dist/*
@@ -0,0 +1,40 @@
1
+ name: Rust CI
2
+
3
+ on:
4
+ pull_request:
5
+ types: [opened, reopened, synchronize]
6
+ paths:
7
+ - "src/**/*.rs"
8
+ - "tests/**/*.rs"
9
+ - "Cargo.toml"
10
+ - "Cargo.lock"
11
+ push:
12
+ branches:
13
+ - main
14
+ paths:
15
+ - "src/**/*.rs"
16
+ - "tests/**/*.rs"
17
+ - "Cargo.toml"
18
+ - "Cargo.lock"
19
+
20
+ env:
21
+ CARGO_TERM_COLOR: always
22
+
23
+ jobs:
24
+ run-rust-ci:
25
+ runs-on: ubuntu-latest
26
+ steps:
27
+ - name: Checkout code
28
+ uses: actions/checkout@v7
29
+ - name: Install Rust
30
+ uses: dtolnay/rust-toolchain@stable
31
+ with:
32
+ components: rustfmt, clippy
33
+ - name: Rust Cache
34
+ uses: Swatinem/rust-cache@v2
35
+ - name: Check Formatting
36
+ run: cargo fmt --check
37
+ - name: Run Clippy
38
+ run: cargo clippy -- -D warnings
39
+ - name: Run Tests
40
+ run: cargo test --verbose --release
@@ -0,0 +1,7 @@
1
+ /target
2
+ /.venv/
3
+ *.so
4
+ .python-version
5
+ __pycache__/
6
+ .pytest_cache/
7
+ .ruff_cache/
@@ -0,0 +1,132 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "heck"
7
+ version = "0.5.0"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
10
+
11
+ [[package]]
12
+ name = "libc"
13
+ version = "0.2.191"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
16
+
17
+ [[package]]
18
+ name = "once_cell"
19
+ version = "1.21.4"
20
+ source = "registry+https://github.com/rust-lang/crates.io-index"
21
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
22
+
23
+ [[package]]
24
+ name = "portable-atomic"
25
+ version = "1.15.0"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
28
+
29
+ [[package]]
30
+ name = "proc-macro2"
31
+ version = "1.0.107"
32
+ source = "registry+https://github.com/rust-lang/crates.io-index"
33
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
34
+ dependencies = [
35
+ "unicode-ident",
36
+ ]
37
+
38
+ [[package]]
39
+ name = "pyo3"
40
+ version = "0.30.1"
41
+ source = "registry+https://github.com/rust-lang/crates.io-index"
42
+ checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
43
+ dependencies = [
44
+ "libc",
45
+ "once_cell",
46
+ "portable-atomic",
47
+ "pyo3-build-config",
48
+ "pyo3-ffi",
49
+ "pyo3-macros",
50
+ ]
51
+
52
+ [[package]]
53
+ name = "pyo3-build-config"
54
+ version = "0.30.1"
55
+ source = "registry+https://github.com/rust-lang/crates.io-index"
56
+ checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
57
+ dependencies = [
58
+ "target-lexicon",
59
+ ]
60
+
61
+ [[package]]
62
+ name = "pyo3-ffi"
63
+ version = "0.30.1"
64
+ source = "registry+https://github.com/rust-lang/crates.io-index"
65
+ checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
66
+ dependencies = [
67
+ "libc",
68
+ "pyo3-build-config",
69
+ ]
70
+
71
+ [[package]]
72
+ name = "pyo3-macros"
73
+ version = "0.30.1"
74
+ source = "registry+https://github.com/rust-lang/crates.io-index"
75
+ checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
76
+ dependencies = [
77
+ "proc-macro2",
78
+ "pyo3-macros-backend",
79
+ "quote",
80
+ "syn",
81
+ ]
82
+
83
+ [[package]]
84
+ name = "pyo3-macros-backend"
85
+ version = "0.30.1"
86
+ source = "registry+https://github.com/rust-lang/crates.io-index"
87
+ checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
88
+ dependencies = [
89
+ "heck",
90
+ "proc-macro2",
91
+ "quote",
92
+ "syn",
93
+ ]
94
+
95
+ [[package]]
96
+ name = "quote"
97
+ version = "1.0.47"
98
+ source = "registry+https://github.com/rust-lang/crates.io-index"
99
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
100
+ dependencies = [
101
+ "proc-macro2",
102
+ ]
103
+
104
+ [[package]]
105
+ name = "rankmodels"
106
+ version = "0.0.1"
107
+ dependencies = [
108
+ "pyo3",
109
+ ]
110
+
111
+ [[package]]
112
+ name = "syn"
113
+ version = "3.0.10"
114
+ source = "registry+https://github.com/rust-lang/crates.io-index"
115
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
116
+ dependencies = [
117
+ "proc-macro2",
118
+ "quote",
119
+ "unicode-ident",
120
+ ]
121
+
122
+ [[package]]
123
+ name = "target-lexicon"
124
+ version = "0.13.6"
125
+ source = "registry+https://github.com/rust-lang/crates.io-index"
126
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
127
+
128
+ [[package]]
129
+ name = "unicode-ident"
130
+ version = "1.0.27"
131
+ source = "registry+https://github.com/rust-lang/crates.io-index"
132
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
@@ -0,0 +1,12 @@
1
+ [package]
2
+ name = "rankmodels"
3
+ version = "0.0.1"
4
+ edition = "2024"
5
+ readme = "README.md"
6
+
7
+ [lib]
8
+ name = "rankmodels"
9
+ crate-type = ["cdylib", "rlib"]
10
+
11
+ [dependencies]
12
+ pyo3 = { version = "0.30.1", features = ["extension-module", "abi3-py310"] }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RektPunk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.4
2
+ Name: rankmodels
3
+ Version: 0.0.1
4
+ Requires-Dist: numpy>=2.2.6
5
+ License-File: LICENSE
6
+ Summary: Probabilistic ranking models and statistical methods.
7
+ Author-email: RektPunk <rektpunk@gmail.com>
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
10
+
11
+ # rankmodels
12
+
13
+ Probabilistic ranking models and statistical methods.
14
+
15
+ `rankmodels` is a collection of implementations and statistical methods for modeling and analyzing ranked data.
16
+
17
+ The project explores different probabilistic approaches to ranking, including pairwise preference models, distance-based ranking models, and extensions for more flexible ranking structures.
18
+
@@ -0,0 +1,7 @@
1
+ # rankmodels
2
+
3
+ Probabilistic ranking models and statistical methods.
4
+
5
+ `rankmodels` is a collection of implementations and statistical methods for modeling and analyzing ranked data.
6
+
7
+ The project explores different probabilistic approaches to ranking, including pairwise preference models, distance-based ranking models, and extensions for more flexible ranking structures.
@@ -0,0 +1,20 @@
1
+ [project]
2
+ name = "rankmodels"
3
+ version = "0.0.1"
4
+ description = "Probabilistic ranking models and statistical methods."
5
+ readme = "README.md"
6
+ authors = [{ name = "RektPunk", email = "rektpunk@gmail.com" }]
7
+ requires-python = ">=3.10"
8
+ dependencies = ["numpy>=2.2.6"]
9
+
10
+ [build-system]
11
+ requires = ["maturin>=1.9,<2.0"]
12
+ build-backend = "maturin"
13
+
14
+ [tool.maturin]
15
+ python-source = "python"
16
+ module-name = "rankmodels"
17
+ include = ["python/rankmodels/*.pyi", "python/rankmodels/py.typed"]
18
+
19
+ [dependency-groups]
20
+ dev = ["pytest>=9.2.0"]
@@ -0,0 +1,3 @@
1
+ from .mallows import Mallows
2
+
3
+ __all__ = ["Mallows"]
@@ -0,0 +1,47 @@
1
+ from collections.abc import Sequence
2
+ from typing import Self
3
+
4
+ import numpy as np
5
+ from numpy.typing import NDArray
6
+
7
+ from .rankmodels import mallows_fit, mallows_log_prob
8
+
9
+
10
+ class Mallows:
11
+ center: list[str]
12
+ phi: float
13
+ distance: int
14
+ log_likelihood: float
15
+ n_items: int
16
+ n_rankings: int
17
+
18
+ def __init__(self) -> None:
19
+ self._fitted = False
20
+
21
+ def fit(self, rankings: Sequence[Sequence[str]]) -> Self:
22
+ """Estimate the central ranking and dispersion from complete rankings."""
23
+ rows = [list(row) for row in rankings]
24
+ result = mallows_fit(rows)
25
+ self.center = list(result.center)
26
+ self.phi = float(result.phi)
27
+ self.distance = int(result.distance)
28
+ self.log_likelihood = float(result.log_likelihood)
29
+ self.n_items = len(self.center)
30
+ self.n_rankings = len(rows)
31
+ self._fitted = True
32
+ return self
33
+
34
+ def log_prob(self, rankings: Sequence[Sequence[str]]) -> NDArray[np.float64]:
35
+ """Return each ranking's fitted log probability in the input order."""
36
+ if not self._fitted:
37
+ raise RuntimeError("fit must be called before evaluating rankings")
38
+
39
+ rows = [list(row) for row in rankings]
40
+ return np.asarray(mallows_log_prob(rows, self.center, self.phi), dtype=float)
41
+
42
+ def score(self, rankings: Sequence[Sequence[str]]) -> float:
43
+ """Return mean log probability, following estimator score conventions."""
44
+ log_prob = self.log_prob(rankings)
45
+ if log_prob.size == 0:
46
+ raise ValueError("rankings must contain at least one ranking")
47
+ return float(log_prob.mean())
File without changes
@@ -0,0 +1,78 @@
1
+ import math
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from rankmodels import Mallows
6
+
7
+
8
+ def test_perfect_agreement_fits_zero_dispersion():
9
+ rankings = [["a", "b", "c"], ["a", "b", "c"]]
10
+ model = Mallows()
11
+ model.fit(rankings)
12
+
13
+ assert model.center == ["a", "b", "c"]
14
+ assert model.phi == 0.0
15
+ assert model.distance == 0
16
+ assert model.log_likelihood == 0.0
17
+ np.testing.assert_array_equal(model.log_prob(rankings), [0.0, 0.0])
18
+ assert np.isneginf(model.log_prob([["c", "b", "a"]])[0])
19
+
20
+
21
+ def test_uniform_sample_fits_uniform_distribution():
22
+ rankings = [
23
+ ["a", "b", "c"],
24
+ ["a", "c", "b"],
25
+ ["b", "a", "c"],
26
+ ["b", "c", "a"],
27
+ ["c", "a", "b"],
28
+ ["c", "b", "a"],
29
+ ]
30
+ model = Mallows()
31
+ model.fit(rankings)
32
+
33
+ assert model.phi == 1.0
34
+ assert model.distance == 9
35
+ assert model.log_likelihood == pytest.approx(-6 * math.log(6))
36
+ np.testing.assert_allclose(model.log_prob(rankings), -math.log(6))
37
+ assert model.score(rankings) == pytest.approx(-math.log(6))
38
+
39
+
40
+ def test_fit_finds_central_ranking_and_interior_dispersion():
41
+ rankings = [
42
+ ["a", "b", "c"],
43
+ ["a", "b", "c"],
44
+ ["b", "a", "c"],
45
+ ]
46
+ model = Mallows()
47
+ model.fit(rankings)
48
+
49
+ assert model.center == ["a", "b", "c"]
50
+ assert 0.0 < model.phi < 1.0
51
+ assert model.distance == 1
52
+ assert math.isfinite(model.log_likelihood)
53
+
54
+
55
+ @pytest.mark.parametrize(
56
+ "rankings",
57
+ [
58
+ [],
59
+ [[]],
60
+ [["a", "a"]],
61
+ [["a", "b"], ["a", "c"]],
62
+ [["a", "b"], ["a"]],
63
+ ],
64
+ )
65
+ def test_fit_rejects_invalid_rankings(rankings):
66
+ with pytest.raises(ValueError):
67
+ Mallows().fit(rankings)
68
+
69
+
70
+ def test_log_prob_requires_a_fitted_model():
71
+ with pytest.raises(RuntimeError, match="fit must be called"):
72
+ Mallows().log_prob([["a", "b"]])
73
+
74
+
75
+ def test_fit_rejects_more_items_than_exact_solver_supports():
76
+ ranking = [f"item-{i}" for i in range(19)]
77
+ with pytest.raises(ValueError, match="at most 18 items"):
78
+ Mallows().fit([ranking])
@@ -0,0 +1,10 @@
1
+ use pyo3::prelude::*;
2
+
3
+ pub mod mallows;
4
+
5
+ #[pymodule]
6
+ fn rankmodels(m: &Bound<'_, PyModule>) -> PyResult<()> {
7
+ m.add_function(wrap_pyfunction!(mallows::python::mallows_fit, m)?)?;
8
+ m.add_function(wrap_pyfunction!(mallows::python::mallows_log_prob, m)?)?;
9
+ Ok(())
10
+ }
@@ -0,0 +1,37 @@
1
+ use std::collections::HashMap;
2
+
3
+ pub const MAX_EXACT_ITEMS: usize = 18;
4
+ pub const MIN_EXACT_ITEMS: usize = 2;
5
+
6
+ pub fn validate_ranking(ranking: &[String], items: &HashMap<&str, usize>) -> Result<(), String> {
7
+ if ranking.len() != items.len() {
8
+ return Err("each ranking must contain the same items".to_string());
9
+ }
10
+ let mut seen = vec![false; items.len()];
11
+ for item in ranking {
12
+ let position = items
13
+ .get(item.as_str())
14
+ .ok_or_else(|| "each ranking must contain the same items".to_string())?;
15
+ if seen[*position] {
16
+ return Err("rankings must not contain duplicate items".to_string());
17
+ }
18
+ seen[*position] = true;
19
+ }
20
+
21
+ Ok(())
22
+ }
23
+
24
+ pub fn log_partition(phi: f64, n_items: usize) -> f64 {
25
+ (1..=n_items)
26
+ .map(|length| {
27
+ let mut power = 1.0;
28
+ let mut sum = 1.0;
29
+ for _ in 1..length {
30
+ power *= phi;
31
+ sum += power;
32
+ }
33
+
34
+ sum.ln()
35
+ })
36
+ .sum()
37
+ }