libtma 0.3.13-dev.9013
QE C++ library
Loading...
Searching...
No Matches
nanobind.hpp
Go to the documentation of this file.
1
19#ifndef LIBTMA_BIND_NANOBIND_HPP
20#define LIBTMA_BIND_NANOBIND_HPP
21
22#include <libqe/bind/nanobind.hpp>
24
25#include <nanobind/stl/string.h>
26#include <nanobind/stl/variant.h>
27#include <nanobind/stl/vector.h>
28#include <string>
29#include <variant>
30#include <vector>
31
32namespace qe {
33namespace bind {
34namespace py {
35
37inline ::nanobind::dict to_dict(const qe::UnitNetworks& r) {
38 ::nanobind::dict out;
39 out["networks"] = from_rowvec(r.networks);
40 out["row_networks"] = from_mat(r.row_networks);
41 return out;
42}
43
46inline ::nanobind::dict to_dict(const qe::TensorNetworks& r) {
47 ::nanobind::dict out;
48 out["connection_counts"] = from_rowvec(r.connection_counts);
49 out["row_connection_counts"] = from_mat(r.row_connection_counts);
50 if (r.miss_counts.n_elem > 0) {
51 out["miss_counts"] = from_rowvec(r.miss_counts);
52 out["row_miss_counts"] = from_mat(r.row_miss_counts);
53 }
54 return out;
55}
56
57// ── Registration ──────────────────────────────────────────────────────────────
58// Moved from qe-tma's python/src/libtma_ext.cpp (itself from qe-lib's qe.cpp).
59
62inline qe::WeightModel weight_model_from_variant(const std::variant<bool, std::string>& w) {
63 return std::holds_alternative<bool>(w)
64 ? qe::weight_model_from_bool(std::get<bool>(w))
65 : qe::weight_model_from_string(std::get<std::string>(w));
66}
67
68inline void def_connection_matrix(::nanobind::module_& m) {
69 namespace nb = ::nanobind;
70 using namespace ::nanobind::literals;
71 m.def("connection_matrix", [](NpVec ground, NpVec response,
72 double response_weight, bool ordered) {
73 return from_mat(qe::connection_matrix(
74 to_rowvec(ground), to_rowvec(response), response_weight, ordered));
75 }, "ground"_a, "response"_a, "response_weight"_a = 1.0, "ordered"_a = true,
76 "Connection matrix for one ground+response event pair.\n"
77 "ordered=True (directed): ground→response cross-product\n"
78 "ordered=False (undirected): symmetric outer-product");
79}
80
81inline void def_accumulate_stanza(::nanobind::module_& m) {
82 namespace nb = ::nanobind;
83 using namespace ::nanobind::literals;
84 m.def("accumulate_stanza", [](NpMat codes, int window_back,
85 int window_forward, bool binary, bool ordered) {
86 return from_mat(qe::accumulate_stanza(
87 to_mat(codes), window_back, window_forward, binary, ordered));
88 }, "codes"_a, "window_back"_a = 1, "window_forward"_a = 0, "binary"_a = true,
89 "ordered"_a = false,
90 "Stanza-window accumulation.\n"
91 "ordered=False (default): upper-tri co-occurrences, returns (n_rows × choose_two(n_codes)).\n"
92 "ordered=True: directed — focal row as response, prior window rows as ground,\n"
93 "returns (n_rows × n_codes²). window_forward is ignored when ordered=True.");
94}
95
96inline void def_row_connections(::nanobind::module_& m) {
97 namespace nb = ::nanobind;
98 using namespace ::nanobind::literals;
99 m.def("row_connections", [](NpMat codes, bool binary) {
100 return from_mat(qe::row_connections(to_mat(codes), binary));
101 }, "codes"_a, "binary"_a = true,
102 "Per-row upper-triangle co-occurrence.\n"
103 "Each row is processed independently (no cross-row accumulation).\n"
104 "Returns (n_rows × choose_two(n_codes)) matrix.");
105}
106
107inline void def_rolling_window_sum(::nanobind::module_& m) {
108 namespace nb = ::nanobind;
109 using namespace ::nanobind::literals;
110 m.def("rolling_window_sum", [](NpMat codes, int window_size) {
111 return from_mat(qe::rolling_window_sum(to_mat(codes), window_size));
112 }, "codes"_a, "window_size"_a = 1,
113 "Rolling backward window sum of a raw code matrix.\n"
114 "Row k = sum of rows [max(0, k - window_size + 1), k].\n"
115 "Returns matrix of same shape as input.");
116}
117
118inline void def_flat_index(::nanobind::module_& m) {
119 namespace nb = ::nanobind;
120 using namespace ::nanobind::literals;
121 m.def("flat_index", [](std::vector<int> indices, std::vector<int> dims) {
122 return qe::flat_index(indices, dims);
123 }, "indices"_a, "dims"_a,
124 "Linear index into a column-major multi-dimensional array "
125 "(equivalent to sub2ind with Fortran/column-major ordering).");
126}
127
128inline void def_accumulate_unit(::nanobind::module_& m) {
129 namespace nb = ::nanobind;
130 using namespace ::nanobind::literals;
131 m.def("accumulate_unit",
132 [](NpMat codes, std::vector<int> unit_rows, nb::object decay_fn, bool ordered) {
133 auto cpp_decay = [&decay_fn](arma::vec distances) -> arma::vec {
134 auto np_dist = from_vec(distances);
135 auto result = decay_fn(np_dist);
136 return to_vec(nb::cast<NpVec>(result));
137 };
138 return from_rowvec(qe::accumulate_unit(
139 to_mat(codes), unit_rows, cpp_decay, ordered));
140 },
141 "codes"_a, "unit_rows"_a, "decay_fn"_a, "ordered"_a = false,
142 "Ground/response accumulation for one unit (tma model).\n\n"
143 "Parameters\n----------\n"
144 "codes : ndarray (n_context_rows x n_codes)\n"
145 "unit_rows : list[int] 0-based row indices belonging to this unit\n"
146 "decay_fn : callable(distances: ndarray 1-D) -> ndarray 1-D\n"
147 " Maps distance vector to weight vector.\n"
148 "ordered : bool True = directed full matrix, False = undirected upper-tri\n\n"
149 "Returns ndarray 1-D — flat connection vector.");
150}
151
152inline void def_accumulate_unit_with_rows(::nanobind::module_& m) {
153 namespace nb = ::nanobind;
154 using namespace ::nanobind::literals;
155 m.def("accumulate_unit_with_rows",
156 [](NpMat codes, std::vector<int> unit_rows, nb::object decay_fn, bool ordered) {
157 auto cpp_decay = [&decay_fn](int unit_row, arma::uvec ground_indices) -> arma::vec {
158 auto np_gi = from_uvec(ground_indices);
159 auto result = decay_fn(unit_row, np_gi);
160 return to_vec(nb::cast<NpVec>(result));
161 };
163 to_mat(codes), unit_rows, cpp_decay, ordered));
164 },
165 "codes"_a, "unit_rows"_a, "decay_fn"_a, "ordered"_a = false,
166 "Ground/response accumulation returning per-row connection data (tma model).\n\n"
167 "decay_fn : callable(unit_row: int, ground_indices: ndarray int64 1-D) -> ndarray float64 1-D\n"
168 "Returns a dict (UnitNetworks in tma.libtma) with .networks (1-D) and .row_networks (2-D).");
169}
170
171inline void def_apply_tensor_unit(::nanobind::module_& m) {
172 namespace nb = ::nanobind;
173 using namespace ::nanobind::literals;
174 m.def("apply_tensor_unit",
175 [](NpVec tensor, std::vector<int> dims,
176 std::vector<int> dims_sender, std::vector<int> dims_receiver,
177 std::vector<int> dims_mode,
178 NpIMat context_lookup, std::vector<int> unit_rows,
179 NpMat codes, NpVec times, bool ordered, bool misses) {
181 to_vec(tensor), dims, dims_sender, dims_receiver, dims_mode,
182 to_imat(context_lookup), unit_rows,
183 to_mat(codes), to_vec(times), ordered,
184 /*return_members=*/false, /*return_misses=*/misses));
185 },
186 "tensor"_a, "dims"_a,
187 "dims_sender"_a, "dims_receiver"_a, "dims_mode"_a,
188 "context_lookup"_a, "unit_rows"_a,
189 "codes"_a, "times"_a, "ordered"_a = true, "misses"_a = false,
190 "Tensor-based multi-modal accumulation for one unit (tma model).\n\n"
191 "tensor : ndarray 1-D flat column-major tensor of weights/windows\n"
192 "dims : list[int] shape of the tensor\n"
193 "dims_sender : list[int] tensor axis indices for sender factors\n"
194 "dims_receiver : list[int] tensor axis indices for receiver factors\n"
195 "dims_mode : list[int] tensor axis indices for mode factors\n"
196 "context_lookup : ndarray int32 2-D (n_rows x n_factors) factor indices\n"
197 "unit_rows : list[int] 0-based response-row indices for this unit\n"
198 "codes : ndarray 2-D (n_rows x n_codes) code matrix\n"
199 "times : ndarray 1-D timestamp per context row\n"
200 "ordered : bool True = directed, False = undirected upper-tri\n"
201 "misses : bool True = also return missed co-occurrences (ground i\n"
202 " present, response j absent; directed p^2 rows)\n\n"
203 "Returns a dict (TensorNetworks in tma.libtma) with .connection_counts (1-D) and .row_connection_counts (2-D);\n"
204 "with misses=True also .miss_counts (1-D) and .row_miss_counts (2-D).\n\n"
205 "Default mode: when dims=[2] and tensor has 2 elements [weight, window], uses\n"
206 "a simplified single-weight/window path (equivalent to tma's default tensor).");
207}
208
209inline void def_aggregate_row_connections(::nanobind::module_& m) {
210 namespace nb = ::nanobind;
211 using namespace ::nanobind::literals;
212 m.def("aggregate_row_connections",
213 [](NpMat row_conn, int n_codes, bool ordered,
214 std::variant<bool, std::string> weight, bool diagonal) {
215 return from_rowvec(qe::aggregate_row_connections(
216 to_mat(row_conn), n_codes, ordered, weight_model_from_variant(weight), diagonal));
217 },
218 "row_conn"_a, "n_codes"_a, "ordered"_a = false, "weight"_a = "binary", "diagonal"_a = false,
219 "Aggregate apply_tensor_unit's row_connection_counts into a unit vector,\n"
220 "matching tma's R aggregation (as.unordered + colSums.ena.matrix), with the\n"
221 "weight model applied per row before the sum (= rENA's weight.by).\n\n"
222 "row_conn : ndarray 2-D (n_response_rows x n_codes^2) per-row directed counts\n"
223 "n_codes : int number of codes p\n"
224 "ordered : bool True = directed p^2 rows; False = fold each row to choose(p,2)\n"
225 "weight : str | bool 'binary' (unordered: clamp to 1; ordered: raw counts),\n"
226 " 'product' (raw counts), 'sqrt', 'log1p' (alias 'log');\n"
227 " a bool is the legacy binary flag (True = 'binary',\n"
228 " False = 'product')\n\n"
229 "diagonal : bool unordered only: keep self-connections (A & A, A & B, B & B, ...)\n\n"
230 "Returns a 1-D ndarray of length p^2 (ordered), choose(p,2) (unordered) or\n"
231 "p(p+1)/2 (unordered with diagonal).");
232}
233
234inline void def_finalize_row_connections(::nanobind::module_& m) {
235 namespace nb = ::nanobind;
236 using namespace ::nanobind::literals;
237 m.def("finalize_row_connections",
238 [](NpMat row_conn, int n_codes, bool ordered,
239 std::variant<bool, std::string> weight, bool diagonal) {
240 return from_mat(qe::finalize_row_connections(
241 to_mat(row_conn), n_codes, ordered, weight_model_from_variant(weight), diagonal));
242 },
243 "row_conn"_a, "n_codes"_a, "ordered"_a = false, "weight"_a = "binary", "diagonal"_a = false,
244 "Per-row step of aggregate_row_connections (fold + weight model) without\n"
245 "the sum; its rows sum to aggregate_row_connections.\n\n"
246 "Returns a 2-D ndarray (n_response_rows x p^2 ordered, or x choose(p,2)).");
247}
248
249inline void def_finalize_self_connections(::nanobind::module_& m) {
250 using namespace ::nanobind::literals;
251 m.def("finalize_self_connections",
252 [](NpMat row_conn, int n_codes, bool ordered,
253 std::variant<bool, std::string> weight) {
254 return from_mat(qe::finalize_self_connections(
255 to_mat(row_conn), n_codes, ordered, weight_model_from_variant(weight)));
256 },
257 "row_conn"_a, "n_codes"_a, "ordered"_a = false, "weight"_a = "binary",
258 "Per-line self-connections: the diagonal (ground i x response i) of each\n"
259 "directed row of apply_tensor_unit's row_connection_counts (or\n"
260 "row_miss_counts, for self-misses), weighted per line as\n"
261 "finalize_row_connections weights it.\n\n"
262 "Returns a 2-D ndarray (n_response_rows x p).");
263}
264
265inline void def_aggregate_self_connections(::nanobind::module_& m) {
266 using namespace ::nanobind::literals;
267 m.def("aggregate_self_connections",
268 [](NpMat row_conn, int n_codes, bool ordered,
269 std::variant<bool, std::string> weight) {
270 return from_rowvec(qe::aggregate_self_connections(
271 to_mat(row_conn), n_codes, ordered, weight_model_from_variant(weight)));
272 },
273 "row_conn"_a, "n_codes"_a, "ordered"_a = false, "weight"_a = "binary",
274 "finalize_self_connections summed over the lines.\n\n"
275 "Returns a 1-D ndarray of length p.");
276}
277
280inline ::nanobind::dict to_dict(const qe::UnitAccumulation& r) {
281 ::nanobind::dict out;
282 out["connection_counts"] = from_rowvec(r.connection_counts);
283 out["row_connection_counts"] = from_mat(r.row_connection_counts);
284 out["self_connection_counts"] = from_rowvec(r.self_connection_counts);
285 out["row_self_connection_counts"] = from_mat(r.row_self_connection_counts);
286 if (r.miss_counts.n_elem > 0) {
287 out["miss_counts"] = from_rowvec(r.miss_counts);
288 out["row_miss_counts"] = from_mat(r.row_miss_counts);
289 out["self_miss_counts"] = from_rowvec(r.self_miss_counts);
290 out["row_self_miss_counts"] = from_mat(r.row_self_miss_counts);
291 }
292 return out;
293}
294
295inline void def_weight_rows(::nanobind::module_& m) {
296 using namespace ::nanobind::literals;
297 m.def("weight_rows",
298 [](NpMat rows, bool ordered, std::variant<bool, std::string> weight) {
299 return from_mat(qe::weight_rows(to_mat(rows), ordered, weight_model_from_variant(weight)));
300 },
301 "rows"_a, "ordered"_a = false, "weight"_a = "binary",
302 "Apply the weight model per line to already-finalised rows (folded when\n"
303 "unordered), e.g. accumulate_unit_networks' raw row_connection_counts.\n\n"
304 "Returns a 2-D ndarray of the same shape.");
305}
306
307inline void def_accumulate_unit_networks(::nanobind::module_& m) {
308 using namespace ::nanobind::literals;
309 m.def("accumulate_unit_networks",
310 [](NpVec tensor, std::vector<int> dims,
311 std::vector<int> dims_sender, std::vector<int> dims_receiver,
312 std::vector<int> dims_mode,
313 NpIMat context_lookup, std::vector<int> unit_rows,
314 NpMat codes, NpVec times, bool ordered,
315 std::variant<bool, std::string> weight, bool misses, bool diagonal) {
317 to_vec(tensor), dims, dims_sender, dims_receiver, dims_mode,
318 to_imat(context_lookup), unit_rows,
319 to_mat(codes), to_vec(times), ordered,
320 weight_model_from_variant(weight), misses, diagonal));
321 },
322 "tensor"_a, "dims"_a,
323 "dims_sender"_a, "dims_receiver"_a, "dims_mode"_a,
324 "context_lookup"_a, "unit_rows"_a,
325 "codes"_a, "times"_a, "ordered"_a = false, "weight"_a = "binary",
326 "misses"_a = true, "diagonal"_a = false,
327 "One unit's networks end to end: apply_tensor_unit, then fold (unordered),\n"
328 "per-line weight model, unit sum and the self-connection diagonal, for hits\n"
329 "and (misses=True, default) missed co-occurrences.\n\n"
330 "Returns a dict with connection_counts, row_connection_counts (raw; folded\n"
331 "when unordered), self_connection_counts, row_self_connection_counts, and\n"
332 "with misses miss_counts, row_miss_counts, self_miss_counts,\n"
333 "row_self_miss_counts. diagonal=True (unordered only) also puts the\n"
334 "self-connections into the connection / miss vectors: A & A, A & B, B & B, ...");
335}
336
354
355} // namespace py
356} // namespace bind
357} // namespace qe
358
359#endif // LIBTMA_BIND_NANOBIND_HPP
Accumulation primitives shared between the rENA stanza-window model and the tma ground/response/tenso...
inline ::nanobind::dict to_dict(const qe::UnitNetworks &r)
{networks (1-D), row_networks (2-D)}
Definition nanobind.hpp:37
void def_apply_tensor_unit(::nanobind::module_ &m)
Definition nanobind.hpp:171
void def_rolling_window_sum(::nanobind::module_ &m)
Definition nanobind.hpp:107
void def_finalize_self_connections(::nanobind::module_ &m)
Definition nanobind.hpp:249
void def_accumulate_unit_networks(::nanobind::module_ &m)
Definition nanobind.hpp:307
void def_connection_matrix(::nanobind::module_ &m)
Definition nanobind.hpp:68
void def_row_connections(::nanobind::module_ &m)
Definition nanobind.hpp:96
void def_accumulate_unit(::nanobind::module_ &m)
Definition nanobind.hpp:128
void def_flat_index(::nanobind::module_ &m)
Definition nanobind.hpp:118
void def_libtma(::nanobind::module_ &m)
All of libtma's functions.
Definition nanobind.hpp:338
void def_aggregate_row_connections(::nanobind::module_ &m)
Definition nanobind.hpp:209
void def_weight_rows(::nanobind::module_ &m)
Definition nanobind.hpp:295
qe::WeightModel weight_model_from_variant(const std::variant< bool, std::string > &w)
Definition nanobind.hpp:62
void def_finalize_row_connections(::nanobind::module_ &m)
Definition nanobind.hpp:234
void def_accumulate_unit_with_rows(::nanobind::module_ &m)
Definition nanobind.hpp:152
void def_aggregate_self_connections(::nanobind::module_ &m)
Definition nanobind.hpp:265
void def_accumulate_stanza(::nanobind::module_ &m)
Definition nanobind.hpp:81
Definition accumulation.hpp:21
arma::rowvec aggregate_self_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight)
Unit self-connection vector: finalize_self_connections() summed over the lines.
Definition accumulation.hpp:784
arma::mat finalize_self_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight)
Per-line self-connections: the diagonal of each directed row.
Definition accumulation.hpp:760
arma::mat accumulate_stanza(arma::mat codes, int window_back=1, int window_forward=0, bool binary=true, bool ordered=false)
Accumulate connection vectors for every row in one conversation using a stanza window.
Definition accumulation.hpp:95
arma::rowvec accumulate_unit(const arma::mat &codes, const std::vector< int > &unit_rows, std::function< arma::vec(arma::vec)> decay_fn, bool ordered=false)
Accumulate connections for a single unit from its context rows.
Definition accumulation.hpp:210
int flat_index(const std::vector< int > &indices, const std::vector< int > &dims)
Compute the linear index into a column-major multi-dimensional array.
Definition accumulation.hpp:337
TensorNetworks apply_tensor_unit(const arma::vec &tensor, const std::vector< int > &dims, const std::vector< int > &dims_sender, const std::vector< int > &dims_receiver, const std::vector< int > &dims_mode, const arma::imat &context_lookup, const std::vector< int > &unit_rows, const arma::mat &codes, const arma::vec &times, bool ordered=true, bool return_members=false, bool return_misses=false)
Pure-C++ port of the tma apply_tensor() inner logic.
Definition accumulation.hpp:433
arma::mat row_connections(const arma::mat &codes, bool binary=true)
Compute the upper-triangle co-occurrence vector for each row.
Definition accumulation.hpp:912
WeightModel weight_model_from_string(const std::string &name)
Parse a weight-model name (case-insensitive).
Definition accumulation.hpp:602
UnitAccumulation accumulate_unit_networks(const arma::vec &tensor, const std::vector< int > &dims, const std::vector< int > &dims_sender, const std::vector< int > &dims_receiver, const std::vector< int > &dims_mode, const arma::imat &context_lookup, const std::vector< int > &unit_rows, const arma::mat &codes, const arma::vec &times, bool ordered=false, WeightModel weight=WeightModel::Binary, bool misses=true, bool diagonal=false)
Accumulate one unit's networks end to end.
Definition accumulation.hpp:860
WeightModel
Transform applied to each line's connection counts before the per-unit sum.
Definition accumulation.hpp:594
arma::mat weight_rows(const arma::mat &rows, bool ordered, WeightModel weight)
Apply the weight model per line to already-finalised rows.
Definition accumulation.hpp:806
arma::mat finalize_row_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight, bool diagonal=false)
Finalise each per-response-row tensor connection vector.
Definition accumulation.hpp:668
WeightModel weight_model_from_bool(bool binary)
Map the legacy binary flag to a weight model (true → Binary, false → Product).
Definition accumulation.hpp:618
arma::rowvec aggregate_row_connections(const arma::mat &row_conn, int n_codes, bool ordered, WeightModel weight, bool diagonal=false)
Aggregate per-response-row tensor connections into a unit vector.
Definition accumulation.hpp:714
arma::mat connection_matrix(arma::rowvec ground, arma::rowvec response, double response_weight=1.0, bool ordered=true)
Compute the connection matrix for one ground + response event pair.
Definition accumulation.hpp:43
UnitNetworks accumulate_unit_with_rows(const arma::mat &codes, const std::vector< int > &unit_rows, std::function< arma::vec(int, arma::uvec)> decay_fn, bool ordered=false)
Like accumulate_unit() but also returns the per-response-row connection matrix needed by tma's accumu...
Definition accumulation.hpp:284
arma::mat rolling_window_sum(const arma::mat &codes, int window_size=1)
Rolling backward window sum of the raw code matrix.
Definition accumulation.hpp:940
Result of apply_tensor_unit().
Definition accumulation.hpp:356
arma::rowvec connection_counts
Unit-level flat vector (p²).
Definition accumulation.hpp:357
arma::mat row_connection_counts
Definition accumulation.hpp:358
arma::mat row_miss_counts
Definition accumulation.hpp:372
arma::rowvec miss_counts
Definition accumulation.hpp:369
Result of accumulate_unit_networks(): a unit's finished vectors plus its raw per-line rows.
Definition accumulation.hpp:830
arma::rowvec self_connection_counts
p
Definition accumulation.hpp:833
arma::rowvec self_miss_counts
p (misses only)
Definition accumulation.hpp:837
arma::mat row_self_miss_counts
n_lines × p, raw (misses only)
Definition accumulation.hpp:838
arma::mat row_miss_counts
as row_connection_counts (misses only)
Definition accumulation.hpp:836
arma::rowvec miss_counts
as connection_counts (misses only)
Definition accumulation.hpp:835
arma::rowvec connection_counts
p² (ordered) or n_connections(p, diagonal)
Definition accumulation.hpp:831
arma::mat row_self_connection_counts
n_lines × p, raw
Definition accumulation.hpp:834
arma::mat row_connection_counts
n_lines × (p² or n_connections(p, diagonal)), raw
Definition accumulation.hpp:832
Result of accumulate_unit_with_rows().
Definition accumulation.hpp:257
arma::mat row_networks
Per-response-row directed p² matrix (n_unit_rows × p²), whatever ordered.
Definition accumulation.hpp:259
arma::rowvec networks
Flat connection vector (choose_two(p) or p²).
Definition accumulation.hpp:258