Modules
Adapters for loading and saving data.
Initially we have CSV files locally, and Google Docs Spreadsheets.
CSVFileDataSource
¶
Bases: AbstractDataSource
Source code in src/sortition_algorithms/adapters.py
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 | |
CSVStringDataSource
¶
Bases: AbstractDataSource
Source code in src/sortition_algorithms/adapters.py
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 | |
GSheetDataSource
¶
Bases: AbstractDataSource
Source code in src/sortition_algorithms/adapters.py
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 | |
delete_old_output_tabs(dry_run=False)
¶
Find and delete all tabs with names starting with the tab stubs for selected or remaining
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dry_run
|
bool
|
If True, report what would be deleted without actually deleting. |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of tab names that were deleted (or would be deleted in dry_run mode). |
Source code in src/sortition_algorithms/adapters.py
generate_dupes(people_remaining_rows, people_selected_rows, settings, already_selected=None)
¶
Generate a list of indexes of people who share an address with someone else in this set of rows.
Note that the first row of people_remaining_rows is the column headers. The indexes generated are for the rows in this table, so the index takes account of the first row being the header.
So if we had people_remaining_rows:
id,name,address_line_1,postcode 1,Alice,33 Acacia Avenue,W1A 1AA 1,Bob,31 Acacia Avenue,W1A 1AA 1,Charlotte,33 Acacia Avenue,W1A 1AA 1,David,33 Acacia Avenue,W1B 1BB
And settings with check_same_address_columns = ["address_line_1", "postcode"]
Then we should return [1, 3]
Source code in src/sortition_algorithms/adapters.py
find_any_committee(features, people, number_people_wanted, check_same_address_columns)
¶
Find any single feasible committee that satisfies the quotas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
columns to check for same address, or empty list if not checking addresses. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[frozenset[str]], RunReport]
|
tuple of (list containing one committee as frozenset of person_ids, empty report) |
Raises:
| Type | Description |
|---|---|
InfeasibleQuotasError
|
If quotas are infeasible |
SelectionError
|
If solver fails for other reasons |
Source code in src/sortition_algorithms/committee_generation/__init__.py
find_distribution_leximin(features, people, number_people_wanted, check_same_address_columns)
¶
Find a distribution over feasible committees that maximizes the minimum probability of an agent being selected (just like maximin), but breaks ties to maximize the second-lowest probability, breaks further ties to maximize the third-lowest probability and so forth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
Address columns for household identification, or empty if no address checking to be done. |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committees, probabilities, output_lines) |
list[float]
|
|
RunReport
|
|
tuple[list[frozenset[str]], list[float], RunReport]
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If Gurobi is not available |
Source code in src/sortition_algorithms/committee_generation/leximin.py
find_distribution_maximin(features, people, number_people_wanted, check_same_address_columns)
¶
Find a distribution over feasible committees that maximizes the minimum probability of an agent being selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
Address columns for household identification, or empty if no address checking to be done. |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committees, probabilities, output_lines) |
list[float]
|
|
RunReport
|
|
tuple[list[frozenset[str]], list[float], RunReport]
|
|
Source code in src/sortition_algorithms/committee_generation/maximin.py
find_distribution_nash(features, people, number_people_wanted, check_same_address_columns)
¶
Find a distribution over feasible committees that maximizes the Nash welfare, i.e., the product of selection probabilities over all persons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
Address columns for household identification, or empty if no address checking to be done. |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committees, probabilities, output_lines) |
list[float]
|
|
RunReport
|
|
tuple[list[frozenset[str]], list[float], RunReport]
|
|
The algorithm maximizes the product of selection probabilities Πᵢ pᵢ by equivalently maximizing log(Πᵢ pᵢ) = Σᵢ log(pᵢ). If some person i is not included in any feasible committee, their pᵢ is 0, and this sum is -∞. We maximize Σᵢ log(pᵢ) where i is restricted to range over persons that can possibly be included.
Source code in src/sortition_algorithms/committee_generation/nash.py
find_random_sample_legacy(people, features, number_people_wanted, check_same_address_columns=None)
¶
Legacy stratified random selection algorithm.
Implements the original algorithm that uses greedy selection based on priority ratios. Always selects from the most urgently needed category first (highest ratio of (min-selected)/remaining), then randomly picks within that category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
people
|
People
|
People collection |
required |
features
|
FeatureCollection
|
Feature definitions with min/max targets |
required |
number_people_wanted
|
int
|
Number of people to select |
required |
check_same_address_columns
|
list[str] | None
|
Address columns for household identification, or empty if no address checking to be done. |
None
|
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
Tuple of (selected_committees, output_messages) where: |
RunReport
|
|
tuple[list[frozenset[str]], RunReport]
|
|
Raises:
| Type | Description |
|---|---|
SelectionError
|
If selection becomes impossible (not enough people, etc.) |
Source code in src/sortition_algorithms/committee_generation/legacy.py
standardize_distribution(committees, probabilities)
¶
Remove committees with zero probability and renormalize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
committees
|
list[frozenset[str]]
|
list of committees |
required |
probabilities
|
list[float]
|
corresponding probabilities |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[frozenset[str]], list[float]]
|
tuple of (filtered_committees, normalized_probabilities) |
Source code in src/sortition_algorithms/committee_generation/__init__.py
generate_initial_committees(new_committee_model, agent_vars, multiplicative_weights_rounds)
¶
To speed up the main iteration of the maximin and Nash algorithms, start from a diverse set of feasible committees. In particular, each agent that can be included in any committee will be included in at least one of these committees.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_committee_model
|
Model
|
MIP model for finding committees |
required |
agent_vars
|
dict[str, Var]
|
dict mapping agent_id to binary MIP variables |
required |
multiplicative_weights_rounds
|
int
|
number of rounds for the multiplicative weights phase |
required |
Returns:
| Type | Description |
|---|---|
set[frozenset[str]]
|
tuple of (committees, covered_agents, output_lines) |
frozenset[str]
|
|
RunReport
|
|
tuple[set[frozenset[str]], frozenset[str], RunReport]
|
|
tuple[set[frozenset[str]], frozenset[str], RunReport]
|
|
Source code in src/sortition_algorithms/committee_generation/common.py
ilp_results_to_committee(variables)
¶
Extract the selected committee from ILP solver variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables
|
dict[str, Var]
|
dict mapping person_id to binary MIP variables |
required |
Returns:
| Type | Description |
|---|---|
frozenset[str]
|
frozenset of person_ids who are selected (have variable value > 0.5) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If variables don't have values (solver failed) |
Source code in src/sortition_algorithms/committee_generation/common.py
setup_committee_generation(features, people, number_people_wanted, check_same_address_columns)
¶
Set up the integer linear program for committee generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
columns to check for same address, or empty list if not checking addresses. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Model, dict[str, Var]]
|
tuple of (MIP model, dict mapping person_id to binary variables) |
Raises:
| Type | Description |
|---|---|
InfeasibleQuotasError
|
If quotas are infeasible, includes suggested relaxations |
SelectionError
|
If solver fails for other reasons |
Source code in src/sortition_algorithms/committee_generation/common.py
Selection algorithms for stratified sampling.
find_random_sample_legacy(people, features, number_people_wanted, check_same_address_columns=None)
¶
Legacy stratified random selection algorithm.
Implements the original algorithm that uses greedy selection based on priority ratios. Always selects from the most urgently needed category first (highest ratio of (min-selected)/remaining), then randomly picks within that category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
people
|
People
|
People collection |
required |
features
|
FeatureCollection
|
Feature definitions with min/max targets |
required |
number_people_wanted
|
int
|
Number of people to select |
required |
check_same_address_columns
|
list[str] | None
|
Address columns for household identification, or empty if no address checking to be done. |
None
|
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
Tuple of (selected_committees, output_messages) where: |
RunReport
|
|
tuple[list[frozenset[str]], RunReport]
|
|
Raises:
| Type | Description |
|---|---|
SelectionError
|
If selection becomes impossible (not enough people, etc.) |
Source code in src/sortition_algorithms/committee_generation/legacy.py
find_distribution_leximin(features, people, number_people_wanted, check_same_address_columns)
¶
Find a distribution over feasible committees that maximizes the minimum probability of an agent being selected (just like maximin), but breaks ties to maximize the second-lowest probability, breaks further ties to maximize the third-lowest probability and so forth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
Address columns for household identification, or empty if no address checking to be done. |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committees, probabilities, output_lines) |
list[float]
|
|
RunReport
|
|
tuple[list[frozenset[str]], list[float], RunReport]
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If Gurobi is not available |
Source code in src/sortition_algorithms/committee_generation/leximin.py
find_distribution_maximin(features, people, number_people_wanted, check_same_address_columns)
¶
Find a distribution over feasible committees that maximizes the minimum probability of an agent being selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
Address columns for household identification, or empty if no address checking to be done. |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committees, probabilities, output_lines) |
list[float]
|
|
RunReport
|
|
tuple[list[frozenset[str]], list[float], RunReport]
|
|
Source code in src/sortition_algorithms/committee_generation/maximin.py
find_distribution_nash(features, people, number_people_wanted, check_same_address_columns)
¶
Find a distribution over feasible committees that maximizes the Nash welfare, i.e., the product of selection probabilities over all persons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
Address columns for household identification, or empty if no address checking to be done. |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committees, probabilities, output_lines) |
list[float]
|
|
RunReport
|
|
tuple[list[frozenset[str]], list[float], RunReport]
|
|
The algorithm maximizes the product of selection probabilities Πᵢ pᵢ by equivalently maximizing log(Πᵢ pᵢ) = Σᵢ log(pᵢ). If some person i is not included in any feasible committee, their pᵢ is 0, and this sum is -∞. We maximize Σᵢ log(pᵢ) where i is restricted to range over persons that can possibly be included.
Source code in src/sortition_algorithms/committee_generation/nash.py
find_random_sample(features, people, number_people_wanted, check_same_address_columns, selection_algorithm='maximin', test_selection=False, number_selections=1)
¶
Main algorithm to find one or multiple random committees.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas |
required |
people
|
People
|
People object with pool members |
required |
number_people_wanted
|
int
|
desired size of the panel |
required |
check_same_address_columns
|
list[str]
|
columns for the address to check, or empty list if no check required |
required |
selection_algorithm
|
str
|
one of "legacy", "maximin", "leximin", or "nash" |
'maximin'
|
test_selection
|
bool
|
if set, do not do a random selection, but just return some valid panel. Useful for quickly testing whether quotas are satisfiable, but should always be false for actual selection! |
False
|
number_selections
|
int
|
how many panels to return. Most of the time, this should be set to 1, which means that a single panel is chosen. When specifying a value n ≥ 2, the function will return a list of length n, containing multiple panels (some panels might be repeated in the list). In this case the eventual panel should be drawn uniformly at random from the returned list. |
1
|
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
tuple of (committee_lottery, report) |
RunReport
|
|
tuple[list[frozenset[str]], RunReport]
|
|
Raises:
| Type | Description |
|---|---|
InfeasibleQuotasError
|
if the quotas cannot be satisfied, which includes a suggestion for how to modify them |
SelectionError
|
in multiple other failure cases |
ValueError
|
for invalid parameters |
RuntimeError
|
if required solver is not available |
Source code in src/sortition_algorithms/core.py
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 | |
lottery_rounding(committees, probabilities, number_selections)
¶
Convert probability distribution over committees to a discrete lottery.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
committees
|
list[frozenset[str]]
|
list of committees |
required |
probabilities
|
list[float]
|
corresponding probabilities (must sum to 1) |
required |
number_selections
|
int
|
number of committees to return |
required |
Returns:
| Type | Description |
|---|---|
list[frozenset[str]]
|
list of committees (may contain duplicates) of length number_selections |
Source code in src/sortition_algorithms/core.py
pipage_rounding(marginals)
¶
Pipage rounding algorithm for converting fractional solutions to integer solutions.
Takes a list of (object, probability) pairs and randomly rounds them to a set of objects such that the expected number of times each object appears equals its probability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
marginals
|
list[tuple[int, float]]
|
list of (object, probability) pairs where probabilities sum to an integer |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list of objects that were selected |
Source code in src/sortition_algorithms/core.py
run_stratification(features, people, number_people_wanted, settings, *, test_selection=False, number_selections=1, already_selected=None)
¶
Run stratified random selection with retry logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
FeatureCollection
|
FeatureCollection with min/max quotas for each feature value |
required |
people
|
People
|
People object containing the pool of candidates |
required |
number_people_wanted
|
int
|
Desired size of the panel |
required |
settings
|
Settings
|
Settings object containing configuration |
required |
test_selection
|
bool
|
If True, don't randomize (for testing only) |
False
|
number_selections
|
int
|
Number of panels to return (default: 1) |
1
|
already_selected
|
People | None
|
People who have already been selected (optional) |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
Tuple of (success, selected_committees, report) |
list[frozenset[str]]
|
|
RunReport
|
|
tuple[bool, list[frozenset[str]], RunReport]
|
|
Raises:
| Type | Description |
|---|---|
Exception
|
If number_people_wanted is outside valid range for any feature |
ValueError
|
For invalid parameters |
RuntimeError
|
If required solver is not available |
InfeasibleQuotasError
|
If quotas cannot be satisfied |
Source code in src/sortition_algorithms/core.py
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 | |
selected_remaining_tables(full_people, people_selected, features, settings, already_selected=None, exclude_matching_addresses=True)
¶
write some text
people_selected is a single frozenset[str] - it must be unwrapped before being passed to this function.
Source code in src/sortition_algorithms/core.py
BadDataError
¶
Bases: SortitionBaseError
Error for when bad data is found while reading things in
Source code in src/sortition_algorithms/errors.py
InfeasibleQuotasCantRelaxError
¶
Bases: SortitionBaseError
The quotas can't be met, and no feasible relaxation was found
Source code in src/sortition_algorithms/errors.py
InfeasibleQuotasError
¶
Bases: SelectionMultilineError
The quotas can't be met, and a feasible relaxation was found.
The details of what relaxations are recommended are included in the error.
Source code in src/sortition_algorithms/errors.py
ParseErrorsCollector
¶
Class that we can add errors to, but errors with empty messages will be dropped
Source code in src/sortition_algorithms/errors.py
ParseTableMultiError
¶
Bases: SelectionMultilineError
Specifically for collecting errors from parsing a table
This has information that can be collected at a low level. Then higher level code can read the errors and make a SelectionMultilineError instance with strings with more context, relating to a CSV file, Spreadsheet etc.
Source code in src/sortition_algorithms/errors.py
RetryableSelectionError
¶
Bases: SelectionError
For errors where the selection should be retried.
The main case is when the legacy selection algorithm fails, it can be worth retrying as it might find something the next time around.
Source code in src/sortition_algorithms/errors.py
SelectionError
¶
Bases: SortitionBaseError
Generic error for things that happen in selection
Source code in src/sortition_algorithms/errors.py
SelectionMultilineError
¶
Bases: SelectionError
Generic error for things that happen in selection - multiline
Source code in src/sortition_algorithms/errors.py
SortitionBaseError
¶
Bases: Exception
A base class that allows all errors to be caught easily.
Source code in src/sortition_algorithms/errors.py
check_desired(fc, desired_number)
¶
Check if the desired number of people is within the min/max of every feature.
Source code in src/sortition_algorithms/features.py
check_min_max(fc, number_to_select=0, feature_column_name='feature')
¶
If the min is bigger than the max we're in trouble i.e. there's an input error
Source code in src/sortition_algorithms/features.py
iterate_feature_collection(features)
¶
Helper function to iterate over feature collection.
Source code in src/sortition_algorithms/features.py
maximum_selection(fc)
¶
The maximum selection for this set of features is the smallest maximum selection of any individual feature.
Source code in src/sortition_algorithms/features.py
minimum_selection(fc)
¶
The minimum selection for this set of features is the largest minimum selection of any individual feature.
Source code in src/sortition_algorithms/features.py
read_in_features(features_head, features_body, number_to_select=0)
¶
Read in stratified selection features and values
Note we do want features_head to ensure we don't have multiple columns with the same name
Source code in src/sortition_algorithms/features.py
report_min_max_against_number_to_select(fc, number_to_select, feature_column_name)
¶
If any combined minimum is > number_to_select we have a problem. If any combined maximum is < number_to_select we have a problem.
Source code in src/sortition_algorithms/features.py
report_min_max_error_details(fc, feature_column_name='feature')
¶
Return a list of problems in detail, so that the user can debug the errors in detail
Source code in src/sortition_algorithms/features.py
set_default_max_flex(fc)
¶
Note this only sets it if left at the default value
Source code in src/sortition_algorithms/features.py
MaxRatioResult
¶
Result from finding the category with maximum selection ratio.
Source code in src/sortition_algorithms/people_features.py
PeopleFeatures
¶
This class manipulates people and features together, making a deepcopy on init.
It is only used by the legacy method.
Source code in src/sortition_algorithms/people_features.py
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 | |
delete_all_with_feature_value(feature_name, feature_value)
¶
When a feature/value is "full" we delete everyone else in it. "Full" means that the number selected equals the "max" amount - that is detected elsewhere and then this method is called. Returns count of those deleted, and count of those left
Source code in src/sortition_algorithms/people_features.py
find_max_ratio_category()
¶
Find the feature/value combination with the highest selection ratio.
The ratio is calculated as: (min - selected) / remaining This represents how urgently we need people from this category. Higher ratio = more urgent need (fewer people available relative to what we still need).
Returns:
| Type | Description |
|---|---|
MaxRatioResult
|
MaxRatioResult containing the feature name, value, and a random person index |
Raises:
| Type | Description |
|---|---|
SelectionError
|
If insufficient people remain to meet minimum requirements |
Source code in src/sortition_algorithms/people_features.py
handle_category_full_deletions(selected_person_data)
¶
Check if any categories are now full after a selection and delete remaining people.
When a person is selected, some categories may reach their maximum quota. This method identifies such categories and removes all remaining people from them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selected_person_data
|
MutableMapping[str, str]
|
Dictionary of the selected person's feature values |
required |
Returns:
| Type | Description |
|---|---|
RunReport
|
RunReport containing messages about categories that became full and people deleted |
Raises:
| Type | Description |
|---|---|
SelectionError
|
If deletions would violate minimum constraints |
Source code in src/sortition_algorithms/people_features.py
prune_for_feature_max_0()
¶
Check if any feature_value.max is set to zero. if so delete everyone with that feature value NOT DONE: could then check if anyone is left.
Source code in src/sortition_algorithms/people_features.py
select_person(person_key)
¶
Selecting a person means:
- remove the person from our copy of People
- update the selected and remaining counts of the FeatureCollection
- if check_same_address_columns has columns, also remove household members (without adding to selected)
Returns:
| Type | Description |
|---|---|
list[str]
|
List of additional people removed due to same address (empty if check_same_address_columns is empty) |
Source code in src/sortition_algorithms/people_features.py
SelectCounts
¶
Source code in src/sortition_algorithms/people_features.py
hit_target
property
¶
Return true if selected is between min and max (inclusive)
people_still_needed
property
¶
The number of extra people to select to get to the minimum - it should never be negative
sufficient_people()
¶
Return true if we can still make the minimum. So either: - we have already selected at least the minimum, or - the remaining number is at least as big as the number still required
Source code in src/sortition_algorithms/people_features.py
WeightedSample
¶
Source code in src/sortition_algorithms/people_features.py
__init__(features)
¶
This produces a set of lists of feature values for each feature. Each value
is in the list fv_minmax.max times - so a random choice with represent the max.
So if we had feature "ethnicity", value "white" w max 4, "asian" w max 3 and "black" with max 2 we'd get:
["white", "white", "white", "white", "asian", "asian", "asian", "black", "black"]
Then making random choices from that list produces a weighted sample.
Source code in src/sortition_algorithms/people_features.py
iterate_select_collection(select_collection)
¶
Helper function to iterate over select_collection.
Source code in src/sortition_algorithms/people_features.py
simple_add_selected(person_keys, people, features)
¶
Just add the person to the selected counts for the feature values for that person. Don't do the more complex handling of the full PeopleFeatures.add_selected()
Source code in src/sortition_algorithms/people_features.py
People
¶
Source code in src/sortition_algorithms/people.py
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 | |
find_person_by_position_in_category(feature_name, feature_value, position)
¶
Find the nth person (1-indexed) in a specific feature category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_name
|
str
|
Name of the feature (e.g., "gender") |
required |
feature_value
|
str
|
Value of the feature (e.g., "male") |
required |
position
|
int
|
1-indexed position within the category |
required |
Returns:
| Type | Description |
|---|---|
str
|
Person key of the person at the specified position |
Raises:
| Type | Description |
|---|---|
SelectionError
|
If no person is found at the specified position |
Source code in src/sortition_algorithms/people.py
households(address_columns)
¶
Generates a dict with: - keys: a tuple containing the address strings - values: a list of person_key for each person at that address
Source code in src/sortition_algorithms/people.py
matching_address(person_key, address_columns)
¶
Returns a list of person keys for all people who have an address matching the address of the person passed in.
Source code in src/sortition_algorithms/people.py
check_enough_people_for_every_feature_value(features, people)
¶
For each feature/value, if the min>0, check there are enough people who have that feature/value
Source code in src/sortition_algorithms/people.py
check_for_duplicate_people(people_body, settings)
¶
If we have rows with duplicate IDs things are going to go bad. First check for any duplicate IDs. If we find any, check if the duplicates are identical.
Returns:
| Type | Description |
|---|---|
RunReport
|
RunReport containing warnings about duplicate people |
Raises:
| Type | Description |
|---|---|
SelectionMultilineError
|
If duplicate IDs have different data |
Source code in src/sortition_algorithms/people.py
exclude_matching_selected_addresses(people, already_selected, settings)
¶
If we are checking the same addresses, then we should start by excluding people who have the same address as someone who is already selected.
Source code in src/sortition_algorithms/people.py
Settings
¶
Settings to use when selecting committees. Note that only the first two are required. A minimal example would be:
Settings(id_column="my_id", columns_to_keep=["name", "email"])
Source code in src/sortition_algorithms/settings.py
full_columns_to_keep
property
¶
We always need to keep the address columns, so in case they are not listed in self.columns_to_keep we have this property to have the combined list.
normalised_address_columns
property
¶
Returns an empty list if address columns should not be checked (or if the columns specified was an empty list). Otherwise return the columns. That way other code can just check if the columns are empty rather than checking the bool separately.
RandomProvider
¶
Bases: ABC
This is something of a hack. Mostly we want to use the secrets module.
But for repeatable testing we might want to set the random.seed sometimes.
So we have a global _random_provider which can be switched between an
instance of this class that uses the secrets module and an instance that
uses random with a seed. The switch is done by the set_random_provider()
function.
Then every time we want some randomness, we call random_provider() to get
the current version of the global.
Source code in src/sortition_algorithms/utils.py
RunReport
¶
A class to hold a report to show to the user at the end
Source code in src/sortition_algorithms/utils.py
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 | |
__bool__()
¶
Basically, False is the report is empty, or True if there is some content. So you can do
things like
```
if run_report:
print(f"Run Report
{run_report.as_text()}") ```
Source code in src/sortition_algorithms/utils.py
add_line(line, level=ReportLevel.NORMAL, message_code=None, message_params=None)
¶
Add a line of text, and a level - so important/critical messages can be highlighted in the HTML report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The English message text (for backward compatibility and standalone use) |
required |
level
|
ReportLevel
|
Importance level of the message |
NORMAL
|
message_code
|
str | None
|
Optional translation key for i18n (e.g., "loading_features_from_file") |
None
|
message_params
|
dict[str, Any] | None
|
Optional parameters for message translation (e.g., {"file_path": "features.csv"}) |
None
|
Source code in src/sortition_algorithms/utils.py
add_line_and_log(line, log_level, message_code=None, message_params=None)
¶
Add a line of text, and a level - so important/critical messages can be highlighted in the HTML report.
This method will also log the message to the user_logger. This message can be shown to the user as
the run is happening, so the user has feedback on what is going on while the run is in progress.
When generating the report we can skip those messages, to avoid duplication. But if the user_logger has not been set up to be shown to the user during the run, we do want those messages to be in the final report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The English message text (for backward compatibility and standalone use) |
required |
log_level
|
int
|
Logging level for the message |
required |
message_code
|
str | None
|
Optional translation key for i18n (e.g., "trial_number") |
None
|
message_params
|
dict[str, Any] | None
|
Optional parameters for message translation (e.g., {"trial": 3}) |
None
|
Source code in src/sortition_algorithms/utils.py
add_lines(lines, level=ReportLevel.NORMAL)
¶
Add multiple lines of text with the same level.
.. deprecated:: (next version) This method is deprecated. Functions should return RunReport instead of list[str], and callers should use add_report() to merge them. This provides better support for translation and structured reporting.
Source code in src/sortition_algorithms/utils.py
add_message(code, level=ReportLevel.NORMAL, **params)
¶
Add a translatable message using a message code and parameters.
This is a convenience method that combines get_message() and add_line() in one call, making it simpler to add messages with translation support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The message code from REPORT_MESSAGES (e.g., "loading_features_from_file") |
required |
level
|
ReportLevel
|
Importance level of the message |
NORMAL
|
**params
|
Any
|
Parameters to substitute into the message template |
{}
|
Example
report.add_message("features_found", count=5) report.add_message("trial_number", ReportLevel.IMPORTANT, trial=3)
Source code in src/sortition_algorithms/utils.py
add_message_and_log(code, log_level, **params)
¶
Add a translatable message using a message code and parameters, and log it.
This is a convenience method that combines get_message() and add_line_and_log() in one call, making it simpler to add messages with translation support that are also logged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The message code from REPORT_MESSAGES (e.g., "trial_number") |
required |
log_level
|
int
|
Logging level for the message |
required |
**params
|
Any
|
Parameters to substitute into the message template |
{}
|
Example
report.add_message_and_log("trial_number", logging.WARNING, trial=3) report.add_message_and_log("basic_solution_warning", logging.WARNING, algorithm="maximin", num_panels=150, num_agents=100, min_probs=0.001)
Source code in src/sortition_algorithms/utils.py
has_content()
¶
False is the report is empty, or True if there is some content. So you can do
things like
```
if run_report.has_content():
print(f"Run Report
{run_report.as_text()}") ```
Source code in src/sortition_algorithms/utils.py
default_logging_setup()
¶
Set both logger and user_logger to send output to stdout
Source code in src/sortition_algorithms/utils.py
get_cell_name(row, col_name, headers)
¶
Given the column_name, get the spreadsheet cell name, eg "A5"
Source code in src/sortition_algorithms/utils.py
normalise_dict(original)
¶
Wraps a dict, and whenever we get a value from it, we convert to str and strip() whitespace
Source code in src/sortition_algorithms/utils.py
override_logging_handlers(user_logger_handlers, logger_handlers)
¶
Replace the default handlers with other ones