popoto.fields.co_occurrence_field¶
popoto.fields.co_occurrence_field
¶
CoOccurrenceField — weighted association edges with graph propagation.
Maintains weighted bidirectional (or unidirectional) edges between model instances using Redis sorted sets. Weights strengthen via co-retrieval and decay when not reinforced. BFS graph propagation with exponential weight decay per hop enables multi-hop associative retrieval.
Each CoOccurrenceField instance owns per-PK sorted sets
$CoOcF:{ClassName}:{field_name}:{pk} -> ZSET { target_pk: weight, ... }
When symmetric=True (default), link/strengthen/unlink operations mirror on both source and target sorted sets.
Example
class Memory(Model): key = UniqueKeyField() content = StringField() associations = CoOccurrenceField(symmetric=True, max_edges=100)
Create edges¶
CoOccurrenceField.link(Memory, "pk_a", "pk_b", initial_weight=0.1) CoOccurrenceField.strengthen(Memory, "pk_a", "pk_b", delta=0.05)
Query associations¶
linked = CoOccurrenceField.get_linked(Memory, "pk_a")
=> [("pk_b", 0.15)]¶
Multi-hop propagation¶
scores = CoOccurrenceField.propagate(Memory, ["pk_a"], depth=2)
=> {"pk_b": 0.5, "pk_c": 0.25}¶
CoOccurrenceField
¶
Bases: Field
A field that maintains weighted association edges between model instances.
Uses per-PK Redis sorted sets to store weighted edges to other PKs. Supports symmetric (bidirectional) and asymmetric (unidirectional) modes.
Edge weights are clamped at Defaults.CO_OCCURRENCE_WEIGHT_CAP
(default 1.0) on every strengthen() write via an atomic Lua script,
and a read-time min(edge_weight, cap) in the propagation BFS
handles pre-existing over-cap stored weights as defense-in-depth. This
guarantees the per-hop contraction invariant used by propagate():
decay_per_hop * effective_edge_weight <= decay_per_hop * cap < 1
(at default config, 0.5 * 1.0 = 0.5 < 1), so activation decays
monotonically with hop count and the BFS threshold reliably terminates
the walk. A runtime guard in propagate() raises ValueError if
cap * decay_per_hop >= 1.0 to catch future misconfiguration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symmetric
|
If True, edges are bidirectional. Default True. |
required | |
max_edges
|
Maximum edges per PK. Lowest-weight edges pruned when exceeded. Default 500. |
required | |
decay_factor
|
Multiplicative decay factor for weaken_all(). Default 0.95. |
required |
Example
class Memory(Model): key = UniqueKeyField() content = StringField() associations = CoOccurrenceField(symmetric=True, max_edges=100)
Source code in src/popoto/fields/co_occurrence_field.py
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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | |
export_state(model_instance, field_name, field_value=None, **kwargs)
classmethod
¶
Export this record's association edges.
Returns:
| Type | Description |
|---|---|
Optional[dict[str, Any]]
|
|
Optional[dict[str, Any]]
|
when this record has no edges. |
Source code in src/popoto/fields/co_occurrence_field.py
import_state(model_instance, field_name, state, **kwargs)
classmethod
¶
Restore this record's association edges after import.
Written as a raw DELETE + ZADD, never through link or
strengthen: those apply relative adjustments and NX semantics, and
cannot reproduce an absolute weight. Symmetric mirroring is
deliberately NOT performed -- each record owns its own edge set, so a
partner's mirror edge arrives with the partner record if it is in the
export.
This REPLACES rather than merges. on_save never touches edge keys
(CoOccurrenceField defines no on_save), so there is nothing to
merge with except edges the destination accumulated on its own since
the export was taken -- and under on_conflict="overwrite", whose
contract is that the record is replaced wholesale, keeping those would
leave a graph matching neither side.
Two normalizations to the DESTINATION's configuration are applied, and both are load-bearing rather than cosmetic:
- weights are clamped to
Defaults.CO_OCCURRENCE_WEIGHT_CAP, becausepropagate()depends on a contraction invariant that an over-cap weight would break -- BFS would stop decaying with hop count; - the set is truncated to the destination field's
max_edges, keeping the highest weights, exactly asLINK_WITH_PRUNE_LUAdoes on the normal path.
Source code in src/popoto/fields/co_occurrence_field.py
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 | |
get_edge_key(model_class, pk)
¶
Build the Redis key for a PK's edge sorted set.
Public API for external callers that need direct Redis access to a PK's edge set (e.g., bulk edge inspection, custom graph queries, monitoring). Prefer the higher-level methods (link, get_linked, propagate) for normal operations.
Pattern: $CoOcF:{ClassName}:{field_name}:{pk}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class (or instance). |
required | |
pk
|
The primary key string. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
The Redis key for this PK's edge sorted set. |
Source code in src/popoto/fields/co_occurrence_field.py
get_edge_key_prefix(model_class)
¶
Build the Redis key prefix for BFS propagation.
Public API for external callers that need to scan or iterate over all edge sorted sets for a field (e.g., graph analytics, bulk cleanup).
Pattern: $CoOcF:{ClassName}:{field_name}:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
The key prefix (ending with colon). |
Source code in src/popoto/fields/co_occurrence_field.py
link(model_class, source_pk, target_pk, initial_weight=_UNSET, pipeline=None)
¶
Create a weighted edge between two PKs.
If symmetric=True, creates edges in both directions. Uses an atomic Lua script to handle ZADD + ZCARD + conditional pruning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required | |
source_pk
|
Source primary key string. |
required | |
target_pk
|
Target primary key string. |
required | |
initial_weight
|
Weight for the new edge. Default from
|
_UNSET
|
|
pipeline
|
Optional Redis pipeline (unused for Lua eval). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
The weight of the edge (existing weight if already linked). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source_pk == target_pk (no self-loops), or if
|
Source code in src/popoto/fields/co_occurrence_field.py
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 | |
strengthen(model_class, source_pk, target_pk, delta=0.05, pipeline=None)
¶
Increase the weight of an existing edge.
Uses an atomic Lua script (STRENGTHEN_CLAMP_LUA) to read the
current weight, add delta, and clamp at
Defaults.CO_OCCURRENCE_WEIGHT_CAP so stored weights can never
exceed the cap. This guarantees the per-hop contraction invariant
used by propagate() (decay_per_hop * effective_edge_weight
stays <= decay_per_hop * cap < 1 at default config).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required | |
source_pk
|
Source primary key string. |
required | |
target_pk
|
Target primary key string. |
required | |
delta
|
Amount to increase weight by. Must be > 0. Default 0.05. |
0.05
|
|
pipeline
|
Optional Redis pipeline. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
The new (clamped) weight after increment, or None when called with a pipeline (execution deferred). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If delta <= 0. |
Source code in src/popoto/fields/co_occurrence_field.py
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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 | |
unlink(model_class, source_pk, target_pk, pipeline=None)
¶
Remove an edge between two PKs.
If symmetric=True, removes edges in both directions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required | |
source_pk
|
Source primary key string. |
required | |
target_pk
|
Target primary key string. |
required | |
pipeline
|
Optional Redis pipeline. |
None
|
Source code in src/popoto/fields/co_occurrence_field.py
weaken_all(model_class, pk, factor=None, pipeline=None)
¶
Multiplicatively decay all edge weights for a PK.
Edges that fall below a threshold (factor * 0.01) after weakening are automatically pruned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required | |
pk
|
Primary key whose edges to weaken. |
required | |
factor
|
Decay factor (0 < factor < 1). Defaults to self.decay_factor. factor=0 removes all edges. |
None
|
|
pipeline
|
Optional Redis pipeline (unused for Lua eval). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
Number of edges removed by pruning. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If factor > 1 or factor < 0. |
Source code in src/popoto/fields/co_occurrence_field.py
get_linked(model_class, pk, min_weight=0.01, limit=20)
¶
Get linked PKs sorted by weight descending.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required | |
pk
|
Primary key to get links for. |
required | |
min_weight
|
Minimum weight threshold. Default 0.01. |
0.01
|
|
limit
|
Maximum number of results. Default 20. |
20
|
Returns:
| Type | Description |
|---|---|
|
list[tuple[str, float]]: List of (pk, weight) tuples, sorted by weight descending. |
Source code in src/popoto/fields/co_occurrence_field.py
propagate(model_class, seed_pks, depth=2, decay_per_hop=_UNSET, threshold=0.01)
¶
BFS graph propagation with exponential weight decay per hop.
Traverses edges starting from seed PKs, applying multiplicative decay at each hop. When the same PK is reached via multiple paths, the maximum weight is kept.
Edge weights are clamped at Defaults.CO_OCCURRENCE_WEIGHT_CAP
at read time (defense-in-depth) so pre-existing over-cap stored
weights cannot amplify propagation. A runtime guard raises
ValueError if cap * decay_per_hop >= 1.0 (misconfiguration
that would amplify instead of decay).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
The Model class. |
required | |
seed_pks
|
List of starting primary keys. |
required | |
depth
|
Maximum BFS depth. Default 2. depth=0 returns seeds only. |
2
|
|
decay_per_hop
|
Weight multiplier per hop. Default from
|
_UNSET
|
|
threshold
|
Minimum propagated weight to continue. Default 0.01. |
0.01
|
Returns:
| Type | Description |
|---|---|
|
dict[str, float]: Mapping of discovered PKs to their propagated weights. Seeds are not included in results (except for depth=0). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/popoto/fields/co_occurrence_field.py
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 | |
on_delete(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Clean up edges when a model instance is deleted.
Removes the instance's own edge sorted set AND removes it from all other instances' edge sorted sets via SCAN + ZREM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_instance
|
The Model instance being deleted. |
required | |
field_name
|
Name of this CoOccurrenceField. |
required | |
field_value
|
Current field value (unused). |
required | |
pipeline
|
Optional Redis pipeline. |
None
|
|
**kwargs
|
Additional context. |
{}
|