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
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 | |
CSVStringDataSource
¶
Bases: AbstractDataSource
Source code in src/sortition_algorithms/adapters.py
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 | |
GSheetDataSource
¶
Bases: AbstractDataSource
Source code in src/sortition_algorithms/adapters.py
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 | |
__init__(*, feature_tab_name, people_tab_name, already_selected_tab_name='', id_column='not_set', auth_json_path)
¶
Args: - feature_tab_name - the name of the tab/worksheet containing the features (aka categories) - people_tab_name - the name of the tab/worksheet containing the people to select from - already_selected_tab_name (optional) - the name of the tab/worksheet containing people who have already been selected - id_column (optional) - the name of the column containing the ID. Only required if already_selected_tab_name is set - auth_json_path - path to the file containing the google service account details.
Source code in src/sortition_algorithms/adapters.py
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
find_header_row(all_values, id_column, min_headers=5)
staticmethod
¶
Find the first row that looks like a header row in the worksheet.
A row is considered a header row if it has at least min_headers non-empty cells. This helps skip over title rows, empty rows, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_values
|
ValueRange | list[list[Any]]
|
The values from the worksheet to search |
required |
id_column
|
str
|
The text for the id_column - from settings |
required |
min_headers
|
int
|
Minimum number of non-empty cells to consider a row as headers (default: 3) |
5
|
Returns:
| Type | Description |
|---|---|
tuple[int, list[str]]
|
Tuple of (row_number, header_values) where row_number is 1-indexed |
Source code in src/sortition_algorithms/adapters.py
get_valid_people_rows(entire_sheet, header_row_num, min_values=5)
staticmethod
¶
Find all rows under the header row that contain at least 3 values.
Sometimes in the spreadsheet there will be a comment in a cell underneath all the valid rows. We should ignore such rows rather than attempt to convert them into an element of People.
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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list Note: The dual LP still uses Gurobi. |
DEFAULT_BACKEND
|
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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
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
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 | |
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(solver, 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 |
|---|---|---|---|
solver
|
Solver
|
Solver for finding committees |
required |
agent_vars
|
dict[str, Any]
|
dict mapping agent_id to binary 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(solver, variables)
¶
Extract the selected committee from ILP solver variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solver
|
Solver
|
Solver with solved model |
required |
variables
|
dict[str, Any]
|
dict mapping person_id to binary 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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
Returns:
| Type | Description |
|---|---|
tuple[Solver, dict[str, Any]]
|
tuple of (Solver, 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
DiversityOptimizer
¶
Source code in src/sortition_algorithms/committee_generation/diversimax.py
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 290 291 292 293 294 295 | |
create_all_one_hot_encodings()
¶
For every intersection of features - one hot encode who is in which intersection. Rows are the different people. Columns are the different possible intersections. The values are 0/1 if the person is in that intersection or not. i.e. The number of columns is the number of combinations we have between the features: product of their sizes.
Source code in src/sortition_algorithms/committee_generation/diversimax.py
optimize(max_seconds=30, accepted_gap=0.1)
¶
Uses solver to optimize based on the categories constraints
For the optimization goal, for every dims intersection: Take the one hot encoded of who is in which intersection for these dims Take the binary vector of who is selected and multiply and sum to get the sizes of each intersection of categories Figure out the "best" value - if all intersections were of equal size Take the abs for each intersection from that value Minimize sum of abs
Returns:
| Type | Description |
|---|---|
tuple[SolverStatus, frozenset[str], float]
|
tuple of (status, selected_ids, gap) |
Source code in src/sortition_algorithms/committee_generation/diversimax.py
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 | |
prepare_all_data()
¶
For each combination of features, prepares the intersection data. The data is a dict where key is the combination of category names (e.g. (age, income, education level)) and value is the IntersectionData for that combination. all_dims_combs is a list of all the intersections of all categories of all features. (e.g. [(age,), (income,), (education level,), (income, education level), (age, income, education level)])
Source code in src/sortition_algorithms/committee_generation/diversimax.py
find_distribution_diversimax(features, people, number_people_wanted, check_same_address_columns, max_seconds=30, solver_backend=DEFAULT_BACKEND)
¶
Find a committee using the Diversimax algorithm.
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 |
max_seconds
|
int
|
maximum seconds to spend searching |
30
|
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
Returns:
| Type | Description |
|---|---|
tuple[frozenset[str], RunReport]
|
tuple of (selected_ids, report) |
Source code in src/sortition_algorithms/committee_generation/diversimax.py
Selection algorithms for stratified sampling.
MaxRatioResult
¶
Result from finding the category with maximum selection ratio.
Source code in src/sortition_algorithms/committee_generation/legacy.py
PeopleFeatures
¶
This class manipulates people and features together, making a deepcopy on init.
It is only used by the legacy algorithm.
Source code in src/sortition_algorithms/committee_generation/legacy.py
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 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 | |
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/committee_generation/legacy.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/committee_generation/legacy.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/committee_generation/legacy.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/committee_generation/legacy.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/committee_generation/legacy.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
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 | |
find_distribution_leximin(features, people, number_people_wanted, check_same_address_columns, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list Note: The dual LP still uses Gurobi. |
DEFAULT_BACKEND
|
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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
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, solver_backend=DEFAULT_BACKEND)
¶
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 |
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
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
HighsSolver
¶
Bases: Solver
HiGHS solver implementation using highspy.
Source code in src/sortition_algorithms/committee_generation/solver.py
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 | |
__init__(verbose=False, seed=None, time_limit=None, mip_gap=None)
¶
Create a new HiGHS solver instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
If True, enable solver output |
False
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
time_limit
|
float | None
|
Maximum solve time in seconds |
None
|
mip_gap
|
float | None
|
Acceptable MIP gap (e.g., 0.1 for 10%) |
None
|
Source code in src/sortition_algorithms/committee_generation/solver.py
MipSolver
¶
Bases: Solver
python-mip solver implementation.
Source code in src/sortition_algorithms/committee_generation/solver.py
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 | |
__init__(verbose=False, seed=None, time_limit=None, mip_gap=None, solver_name='CBC')
¶
Create a new python-mip solver instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
If True, enable solver output |
False
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
time_limit
|
float | None
|
Maximum solve time in seconds |
None
|
mip_gap
|
float | None
|
Acceptable MIP gap (e.g., 0.1 for 10%) |
None
|
solver_name
|
str
|
switch solver - options "CBC" or "HIGHS" or "GUROBI" |
'CBC'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If python-mip is not installed |
Source code in src/sortition_algorithms/committee_generation/solver.py
Solver
¶
Bases: ABC
Abstract base class for LP/MIP solvers.
Provides a unified interface for committee generation algorithms to use different solver backends (HiGHS, python-mip, Gurobi) interchangeably.
Source code in src/sortition_algorithms/committee_generation/solver.py
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 | |
add_binary_var(name='')
abstractmethod
¶
Add a binary (0/1) variable to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Optional name for the variable |
''
|
Returns:
| Type | Description |
|---|---|
Any
|
A variable object that can be used in constraints and objectives |
Source code in src/sortition_algorithms/committee_generation/solver.py
add_constr(constraint)
abstractmethod
¶
Add a constraint to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constraint
|
Any
|
A constraint expression (e.g., var1 + var2 <= 5) |
required |
add_continuous_var(lb=0.0, ub=1.0, name='')
abstractmethod
¶
Add a continuous variable to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lb
|
float
|
Lower bound (default 0.0) |
0.0
|
ub
|
float
|
Upper bound (default 1.0) |
1.0
|
name
|
str
|
Optional name for the variable |
''
|
Returns:
| Type | Description |
|---|---|
Any
|
A variable object that can be used in constraints and objectives |
Source code in src/sortition_algorithms/committee_generation/solver.py
add_integer_var(lb=0.0, ub=None, name='')
abstractmethod
¶
Add an integer variable to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lb
|
float
|
Lower bound (default 0.0) |
0.0
|
ub
|
float | None
|
Upper bound (default None means infinity) |
None
|
name
|
str
|
Optional name for the variable |
''
|
Returns:
| Type | Description |
|---|---|
Any
|
A variable object that can be used in constraints and objectives |
Source code in src/sortition_algorithms/committee_generation/solver.py
get_gap()
abstractmethod
¶
Get the MIP gap after optimization.
Returns:
| Type | Description |
|---|---|
float
|
The optimality gap (0.0 for optimal, higher for feasible solutions) |
get_objective_value()
abstractmethod
¶
Get the objective value after optimization.
Returns:
| Type | Description |
|---|---|
float
|
The optimal objective value |
get_value(var)
abstractmethod
¶
Get the value of a variable after optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
Any
|
The variable to query |
required |
Returns:
| Type | Description |
|---|---|
float
|
The optimal value of the variable |
Source code in src/sortition_algorithms/committee_generation/solver.py
get_var_by_name(name)
abstractmethod
¶
Get a variable by its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the variable |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The variable object, or None if not found |
Source code in src/sortition_algorithms/committee_generation/solver.py
optimize()
abstractmethod
¶
set_objective(expr, sense)
abstractmethod
¶
Set the objective function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Any
|
The expression to optimize |
required |
sense
|
SolverSense
|
MINIMIZE or MAXIMIZE |
required |
SolverSense
¶
SolverStatus
¶
Bases: Enum
Status returned by solver after optimization.
Source code in src/sortition_algorithms/committee_generation/solver.py
create_solver(backend=DEFAULT_BACKEND, verbose=False, seed=None, time_limit=None, mip_gap=None)
¶
Create a solver instance with the specified backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
verbose
|
bool
|
If True, enable solver output |
False
|
seed
|
int | None
|
Random seed for reproducibility |
None
|
time_limit
|
float | None
|
Maximum solve time in seconds |
None
|
mip_gap
|
float | None
|
Acceptable MIP gap (e.g., 0.1 for 10%) |
None
|
Returns:
| Type | Description |
|---|---|
Solver
|
A Solver instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unknown backend is specified |
Source code in src/sortition_algorithms/committee_generation/solver.py
solver_sum(terms)
¶
Sum a collection of solver expressions.
This provides a backend-agnostic way to sum terms. Both highspy and mip support Python's built-in sum() for their expression objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
terms
|
Any
|
An iterable of solver expressions/variables |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A sum expression |
Source code in src/sortition_algorithms/committee_generation/solver.py
find_random_sample(features, people, number_people_wanted, check_same_address_columns, *, selection_algorithm='maximin', solver_backend=DEFAULT_BACKEND, test_selection=False, number_selections=1, max_seconds=30)
¶
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'
|
solver_backend
|
str
|
solver backend to use - see settings.SOLVER_BACKENDS for full list |
DEFAULT_BACKEND
|
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
|
max_seconds
|
int
|
the maximum number of seconds to spend searching, for those algorithms that support it. Currently only diversimax supports this. |
30
|
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
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 | |
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, max_seconds=30)
¶
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
|
max_seconds
|
int
|
Maximum seconds to try and find optimal answer (diversimax only) |
30
|
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
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 | |
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
N_(message)
¶
No-op marker for translation extraction.
This function does nothing at runtime but marks strings for extraction by babel/gettext tools. It's a common pattern for libraries that want to be translation-ready without depending on translation frameworks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The message string to mark for extraction |
required |
Returns:
| Type | Description |
|---|---|
str
|
The same message string, unchanged |
Source code in src/sortition_algorithms/error_messages.py
get_message(code, **params)
¶
Get a formatted error message by code.
This is a helper function for creating error messages that supports both English output and provides structured data for translation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The error code to look up in ERROR_MESSAGES |
required |
**params
|
Any
|
Parameters to substitute into the message template |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
The formatted message string |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the error code is not found in ERROR_MESSAGES |
Example
get_message('missing_column', column='id', error_label='for people', data_container='CSV file') "No 'id' column for people found in CSV file!"
Source code in src/sortition_algorithms/error_messages.py
BadDataError
¶
Bases: SortitionBaseError
Error for when bad data is found while reading things in
Source code in src/sortition_algorithms/errors.py
ConfigurationError
¶
Bases: SortitionBaseError
Error for invalid configuration or settings
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
__reduce__()
¶
Support pickling by returning constructor and arguments.
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
__reduce__()
¶
Support pickling by returning constructor and arguments.
SortitionBaseError
¶
Bases: Exception
A base class that allows all errors to be caught easily.
Source code in src/sortition_algorithms/errors.py
__reduce__()
¶
Support pickling by returning constructor and arguments.
MinMaxCrossFeatureIssue
¶
A structured result for a cross-feature min/max validation issue.
For 'inconsistent_min_max' issues (from report_min_max_error_details): - smallest_maximum_feature/value and largest_minimum_feature/value are set - feature_name, feature_sum, and limit are not used
For 'min_exceeds_number_to_select' and 'max_below_number_to_select' issues: - feature_name, feature_sum, and limit are set - smallest_maximum_/largest_minimum_ are not used
Source code in src/sortition_algorithms/features.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_against_number_to_select_structured(fc, number_to_select, feature_column_name='feature')
¶
Return structured data about features whose min/max conflict with number_to_select.
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
report_min_max_error_details_structured(fc, feature_column_name='feature')
¶
Return structured data about inconsistent min/max across features.
Returns an empty list if features are consistent (minimum_selection <= maximum_selection).
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
write_features(fc)
¶
Convert a FeatureCollection back to tabular format (inverse of read_in_features).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fc
|
FeatureCollection
|
The FeatureCollection to convert |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
A tuple of (headers, body) where: |
list[dict[str, str]]
|
|
tuple[list[str], list[dict[str, str]]]
|
|
The output format uses modern column names ("feature", "value", "min", "max"). Flex columns ("min_flex", "max_flex") are included only if any feature value has non-default flex values.
Source code in src/sortition_algorithms/features.py
FeatureValueCountCheck
¶
A structured result for a feature value where there are not enough people.
Source code in src/sortition_algorithms/people.py
People
¶
Source code in src/sortition_algorithms/people.py
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 167 168 | |
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
WeightedSample
¶
Source code in src/sortition_algorithms/people.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.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
check_people_per_feature_value(features, people)
¶
Return structured data about feature values with insufficient people.
Unlike check_enough_people_for_every_feature_value(), this does not raise an exception — it returns a list of issues that callers can inspect.
Source code in src/sortition_algorithms/people.py
count_people_per_feature_value(features, people)
¶
Return {feature_name: {value_name: count}} for all feature values.
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
SelectCounts
¶
Note that remaining and most of the methods are only used by the legacy algorithm. But to avoid duplication we also use this class, and the associated methods for both reporting and the legacy algorithm. Maybe at some point we will duplicate the code and have separate versions for the two purposes.
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
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
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
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 | |
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
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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
__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