lythonic.symmetric¶
Square, string-keyed matrices whose two axes are one universe.
Square, string-keyed matrices whose two axes are one universe.
A SymmetricMatrix holds a value per unordered pair of keys drawn from a
single Universe: a correlation or covariance matrix, a distance matrix, a
similarity or adjacency matrix. ExposureMatrix cannot express these - its two
axes are different universes with different semantics, nothing keeps them
aligned, and nothing keeps the two halves of the matrix in agreement.
Symmetry here is structural rather than validated. Only a lower triangle is stored, so there is no slot in which an asymmetric value could be put. That removes the questions a validating design would have to answer: no symmetry check, no tolerance for how symmetric is symmetric enough, and no rule for which half wins when the two disagree.
>>> b = SymmetricMatrixBuilder()
>>> b.set_diagonal({"a": 1.0, "b": 1.0})
>>> b.set_value("a", "b", 0.5)
>>> m = b.build()
>>> m.value("b", "a")
0.5
>>> m.values_of("a")
{'a': 1.0, 'b': 0.5}
The type is generic, not correlation- or covariance-specific: it enforces
squareness and symmetry and claims nothing else. In particular it makes no
positive semi-definiteness promise - that is a question answered on demand
through the numpy facade, which keeps numpy optional and keeps an
eigendecomposition off the deserialization path. See
docs/adr/0004-psd-is-a-query.md. The cost is that the type cannot catch a
correlation matrix whose diagonal is not one, or a covariance matrix with a
negative variance; correlation and covariance are usages of this type, not
variants of it.
Every key needs an explicit diagonal value and build() raises naming any key
that has none. There is deliberately no default-diagonal policy: the failure it
would prevent is silent, since a correlation matrix built with a zero diagonal
is not merely wrong but not positive semi-definite, so the definiteness query
would report a data problem that is really a defaulting problem.
An absent off-diagonal pair reads as 0.0. That is fixed, not configurable -
see docs/adr/0003-symmetric-storage-canonical-union.md, which also covers the
two storage encodings, why the caller cannot choose between them, and why the
choice is invisible in the interface.
Immutable, with all growth in SymmetricMatrixBuilder, following
docs/adr/0001-immutable-matrix-with-builder.md.
SymmetricMatrix
¶
Bases: BaseModel
Immutable square matrix over one universe, keyed by unordered pairs.
Reads by key raise KeyError for a key outside the universe. An
off-diagonal pair with no stored value reads as 0.0; the diagonal is
always present, since a matrix cannot be built without it.
Source code in src/lythonic/symmetric.py
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 | |
np = LibAccess(MatrixNpIn, MatrixNpOut)
class-attribute
¶
Numpy facade. Class access gives constructors, instance access conversions.
value(a, b)
¶
Value at the pair {a, b}, regardless of the order they are named.
diagonal()
¶
values_of(key)
¶
Every value involving key, keyed by the other key.
An entry per key in the universe, absent pairs materialized as 0.0,
so the answer never depends on how the matrix happens to be stored.
Source code in src/lythonic/symmetric.py
pairs()
¶
Every pair once, in universe order, with the earlier key first.
Includes self-pairs and pairs whose value is zero, so the sequence is the same for the same content however it is stored.
Source code in src/lythonic/symmetric.py
cast(universe)
¶
A new matrix over universe, dropping keys outside it.
A subset-and-reorder projection. Dropping is silent, as in
ExposureMatrix.cast, but a key the cast would introduce raises: the
type cannot invent a diagonal value for it, which is the same reason
diagonals are explicit everywhere else. Growth goes through
to_builder.
Source code in src/lythonic/symmetric.py
to_builder()
¶
A builder seeded with this matrix, universe frozen.
Freezing is the safe default for amending an existing matrix; thaw explicitly to grow it.
Source code in src/lythonic/symmetric.py
SymmetricMatrixBuilder
¶
Mutable accumulator that produces a SymmetricMatrix.
The universe grows in first-mention order unless it was declared, which
freezes it. Growth only ever appends - nothing permutes an existing
position, which matters more here than in ExposureMatrixBuilder, since a
permutation would invalidate every triangle offset rather than merely
relabel a row.
There is deliberately no row-wise write. Under symmetry the values in one key's row are values in every other key's row, so a row-replace would silently delete entries a caller thinks of as belonging elsewhere.
Source code in src/lythonic/symmetric.py
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 | |
np
property
¶
Array-shaped writers, valid only against a frozen universe.
universe
property
¶
The universe accumulated so far.
universe_frozen
property
¶
Whether the universe rejects keys outside itself.
freeze()
¶
thaw()
¶
set_value(a, b, value)
¶
Set the value at the pair {a, b}, growing the universe if needed.
Argument order is irrelevant. Writing zero to an off-diagonal pair removes it, keeping storage canonical; a zero on the diagonal is kept, since the diagonal is dense and every key needs one.
Source code in src/lythonic/symmetric.py
set_diagonal(values)
¶
Set many diagonal values at once, growing the universe if needed.
value(a, b)
¶
Value at the pair {a, b} so far, or 0.0 if none is set.
Source code in src/lythonic/symmetric.py
diagonal()
¶
build()
¶
Snapshot the current state as an immutable matrix.
Raises when any key has no diagonal value, naming them: with an open universe a key arriving through an off-diagonal write has no diagonal yet, so this is the normal end state of a naive ingest loop rather than an exotic one.
The builder stays usable afterwards, which requires the copies made here - without them the returned matrix would alias mutable builder state. See ADR 0001.
Source code in src/lythonic/symmetric.py
DenseTriangle
¶
Bases: BaseModel
Every lower-triangle cell, flat and row-major, including the diagonal.
Source code in src/lythonic/symmetric.py
SparseTriangle
¶
Bases: BaseModel
A dense diagonal plus only the off-diagonal cells that are non-zero.
Source code in src/lythonic/symmetric.py
MatrixNpIn
¶
Class-access numpy facade: constructors that take dense arrays.
Source code in src/lythonic/symmetric.py
from_matrix(arr, universe)
¶
Build from a dense square array, reading the lower triangle only.
The upper triangle is ignored rather than checked. Rejecting on
asymmetry would need the comparison tolerance the triangle layout
exists to avoid, and averaging the halves would silently absorb a
transposed-block bug; ignoring one half is at least predictable. The
hazard that survives is recorded in docs/open-questions.md: nothing
here can detect a transposed input, because every input is square.
Source code in src/lythonic/symmetric.py
MatrixNpOut
¶
Instance-access numpy facade: dense views and definiteness queries.
Source code in src/lythonic/symmetric.py
matrix()
¶
Full square array with symmetry materialized.
Source code in src/lythonic/symmetric.py
diagonal()
¶
vector(key)
¶
eigenvalues()
¶
min_eigenvalue()
¶
is_psd(tol=None)
¶
Whether the matrix is positive semi-definite within tol.
The default tolerance is n * eps * max(|lambda|), scaled to the
matrix's own magnitude and dimension, following the convention
numpy.linalg.matrix_rank uses for its singular-value cutoff. Some
tolerance is mandatory: a mathematically valid sample covariance
routinely returns a smallest eigenvalue around -1e-15 after a
floating-point round trip, so a bare non-negativity test rejects good
data.
eigvalsh rather than cholesky, which tests positive definite and
would reject a rank-deficient covariance - more variables than
observations - that is legitimately semi-definite.
Source code in src/lythonic/symmetric.py
BuilderNpAccess
¶
Array-shaped writers, valid only against a frozen universe.
Source code in src/lythonic/symmetric.py
set_matrix(arr)
¶
Write every pair from a dense square array, lower triangle only.