API Reference¶
Simulation¶
Core simulation engine.
Workflow¶
- Read the TOML configuration.
- For each generative model x n_voters x n_candidates x iteration: a. Check if the generated profile already exists on disk : load it. b. If not, generate it via the generator registry and persist it.
- Apply every rule to each profile and collect winners.
- Persist the simulation results to
sim_result/.
The directory layout follows::
<output_base>/
gen/<MODEL>_v<NV>_c<NC>/
iter_0001.parquet
…
sim_result/<MODEL>_v<NV>_c<NC>/
iter_0001.parquet
…
generate_data(config_path, show_progress=True)
¶
Generate (or retrieve cached) profiles for every combination defined in the config.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of file paths of generated/cached parquet files. |
Source code in src/vote_simulation/simulation/simulation.py
obtain_data_instance(model, n_v, n_c, *, iteration=0, seed=161, base_path='data', extra_params=None, reload=False)
¶
Load a cached profile or generate + persist it.
If the parquet file already exists AND reload is False, the profile is loaded from disk; otherwise it is (re-)generated with the given seed and saved for future reuse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Generative model code (e.g. "UNI", "IC"). |
required |
n_v
|
int
|
Number of voters. |
required |
n_c
|
int
|
Number of candidates. |
required |
iteration
|
int
|
Iteration index. |
0
|
seed
|
int
|
Random seed for generation (combined with iteration for uniqueness). |
161
|
base_path
|
str
|
Root folder for generated data (see config.output_base_path). |
'data'
|
extra_params
|
dict[str, object] | None
|
Optional dict of extra parameters to pass to the generator (per-model). |
None
|
reload
|
bool
|
When True, ignore any existing cached file and regenerate from the seed. Use this whenever the seed changes to ensure the new seed is actually applied. |
False
|
Source code in src/vote_simulation/simulation/simulation.py
run_rules_on_instance(data_instance, rule_codes, config=None, *, compute_metrics=True)
¶
Apply every rule and collect winners into a SimulationStepResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_instance
|
DataInstance
|
The profile data to run the rules on. |
required |
rule_codes
|
list[str]
|
List of rule codes to apply (e.g. ["RV", "MJ", "AP_T"]). |
required |
config
|
ResultConfig | None
|
Optional :class: |
None
|
compute_metrics
|
bool
|
Whether to compute :class: |
True
|
Source code in src/vote_simulation/simulation/simulation.py
sim(file_path, rule_code)
¶
Execute a single rule on a single file.
Source code in src/vote_simulation/simulation/simulation.py
simulation_from_config(config_path, show_progress=True, *, reload=False, compute_metrics=True)
¶
Full pipeline: generate profiles, apply rules, save results.
For every (model, n_voters, n_candidates, iteration) combination:
1. Obtain (generate or load) the profile.
2. Run all requested rules.
3. Save the result in sim_result/<MODEL>_v<NV>_c<NC>/iter_XXXX.parquet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str
|
Path to the TOML configuration file (see docs for the template). |
required |
show_progress
|
bool
|
Whether to display a progress bar. |
True
|
reload
|
bool
|
When |
False
|
compute_metrics
|
bool
|
Whether to compute :class: |
True
|
Source code in src/vote_simulation/simulation/simulation.py
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 | |
simulation_instance(gen_code, n_v, n_c, rule_codes, n_iteration=1000, seed=161, base_path='data', reload=False, show_progress=True, *, extra_params=None, compute_metrics=True)
¶
Run the workflow on a single (model, voters, candidates) instance.
Each step receives a :class:ResultConfig so that the series
automatically aggregates the simulation context.
Cache logic:
1. Checks for a cached result at <base_path>/results/<base_label>.parquet
(where base_label excludes rules).
2. If found with matching step count and same base parameters:
- If rules are identical: returns cached series (no recomputation).
- If rules differ: loads cached series and applies new rules incrementally.
3. If not found or stale: recomputes from scratch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen_code
|
str
|
Generative model code (list can be found in doc). |
required |
n_v
|
int
|
Number of voters. |
required |
n_c
|
int
|
Number of candidates. |
required |
rule_codes
|
list[str]
|
List of rule codes to apply. |
required |
n_iteration
|
int
|
Number of iterations. Defaults to 1000. |
1000
|
seed
|
int
|
Seed for reproducibility. Defaults to 161. |
161
|
base_path
|
str
|
Root folder for generated data. Defaults to |
'data'
|
reload
|
bool
|
Force re-computation (ignore cache). Defaults to False. |
False
|
show_progress
|
bool
|
Whether to display progress bars. Defaults to True. |
True
|
extra_params
|
dict[str, object] | None
|
Optional dict of extra generator parameters (e.g.
|
None
|
compute_metrics
|
bool
|
Whether to compute :class: |
True
|
Returns:
SimulationSeriesResult with attached :attr:config including all rules.
Source code in src/vote_simulation/simulation/simulation.py
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
simulation_series_from_config(config_path, reload=False, *, compute_metrics=True)
¶
Run simulation instances for every combination in the config.
Iterates over each (model, n_voters, n_candidates) triplet defined
in the TOML configuration, delegates to :func:simulation_instance,
and collects all resulting series into a :class:SimulationTotalResult.
Séquentiel — le travail est CPU-bound Python (svvamp) ; le GIL empêche
toute parallélisation réelle via ThreadPoolExecutor.
En mode UI (Streamlit), le tqdm externe est intercepté par _PatchedTqdm
pour mettre à jour la barre de progression sans toucher à la hot loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str
|
Path to the TOML configuration file. |
required |
reload
|
bool
|
Force re-computation (ignore cache). Defaults to False. |
False
|
compute_metrics
|
bool
|
Whether to compute :class: |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SimulationTotalResult
|
class: |
SimulationTotalResult
|
|
Source code in src/vote_simulation/simulation/simulation.py
simulation_series_from_config_2(config_path, reload=False, *, compute_metrics=True)
¶
Run simulation instances for every combination in the config.
Iterates over each (model, n_voters, n_candidates) triplet defined
in the TOML configuration, delegates to :func:simulation_instance,
and collects all resulting series into a :class:SimulationTotalResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str
|
Path to the TOML configuration file. |
required |
reload
|
bool
|
Force re-computation (ignore cache). Defaults to False. |
False
|
compute_metrics
|
bool
|
Whether to compute :class: |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SimulationTotalResult
|
class: |
SimulationTotalResult
|
|
Source code in src/vote_simulation/simulation/simulation.py
simulation_step(profile, rule_codes, config=None, *, compute_metrics=True)
¶
Run a single profile through all rules and return a :class:SimulationStepResult.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile
|
Profile
|
The profile data to run the rules on. |
required |
candidates
|
List of candidate names. |
required | |
rule_codes
|
list[str]
|
List of rule codes to apply (e.g. ["RV", "MJ", "AP_T"]). |
required |
config
|
ResultConfig | None
|
Optional :class: |
None
|
compute_metrics
|
bool
|
Whether to compute :class: |
True
|
Source code in src/vote_simulation/simulation/simulation.py
Configuration¶
Configuration loading for vote simulations.
SimulationConfig
dataclass
¶
Validated simulation configuration.
Source code in src/vote_simulation/simulation/configuration.py
load_simulation_config(config_path=DEFAULT_CONFIG_PATH)
¶
Load and validate a simulation config file.
Source code in src/vote_simulation/simulation/configuration.py
Rule registry¶
Rule index for mapping short codes to svvamp rule factories.
RuleResult
¶
Bases: Protocol
Protocol for rule results that have been post-processed to include co-winners.
Source code in src/vote_simulation/models/rules/registry.py
get_all_rules_codes()
¶
get_rule_builder(code)
¶
Return rule builder from code
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
rule encoding (detailed index in documentation) |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
if wrong code |
Returns:
| Name | Type | Description |
|---|---|---|
RuleBuilder |
RuleBuilder
|
rule applied |
Source code in src/vote_simulation/models/rules/registry.py
make_rule_builder(rule_factory)
¶
Create a public RuleBuilder from a Profile -> rule result factory.
This helper is intended for external users who want to register custom rules while reusing the registry's profile conversion and co-winner post-processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_factory
|
Callable[[Profile], Any]
|
Callable that takes a |
required |
Returns:
| Type | Description |
|---|---|
RuleBuilder
|
A |
Source code in src/vote_simulation/models/rules/registry.py
register_rule(code, builder)
¶
Register a rule builder under a short code.
Generator registry¶
Generator registry mapping short codes to svvamp GeneratorProfile factories.
Usage examples:
> from vote_simulation.models.data_generation.generator_registry import get_generator_builder
> builder = get_generator_builder("UNI")
> profile = builder(n_v=100, n_c=5, seed=42)
GeneratorBuilder = Callable[..., Profile]
module-attribute
¶
Signature: (n_v, n_c, seed=0, **extra) -> svvamp.Profile
get_generator_builder(code)
¶
Return the generator builder for the given code.
Raises:
| Type | Description |
|---|---|
ValueError
|
If code is not registered. |
Source code in src/vote_simulation/models/data_generation/generator_registry.py
list_generator_codes()
¶
make_generator_builder(generator_factory, **default_kwargs)
¶
Create a public GeneratorBuilder from a generator factory.
This helper is intended for external users who want to register custom generators while reusing the registry's seeding and relabeling logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
generator_factory
|
Callable[..., Any]
|
Callable |
required |
**default_kwargs
|
object
|
Default keyword arguments forwarded to the factory. |
{}
|
Returns:
| Type | Description |
|---|---|
GeneratorBuilder
|
A |
Example::
from svvamp import GeneratorProfileEuclideanBox
builder = make_generator_builder(
GeneratorProfileEuclideanBox,
box_dimensions=[1.0, 1.0, 1.0],
)
register_generator("MY_EUCLID_3D", builder)
Source code in src/vote_simulation/models/data_generation/generator_registry.py
register_generator(code, builder)
¶
Register a generator builder under a short code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Short code - case-insensitive, will be normalized. |
required |
builder
|
GeneratorBuilder
|
Callable |
required |
Source code in src/vote_simulation/models/data_generation/generator_registry.py
Data instance¶
Load or generate election profiles and persist them.
DataInstance
¶
Encapsulates an election profile (utility matrix + candidate labels).
`DataInstance`` can be created in three ways:
From an existing file (CSV or Parquet)::
di = DataInstance("path/to/data.csv")
From a generator (wraps svvamp GeneratorProfile*)::
di = DataInstance.from_generator(
model_code="UNI", n_v=101, n_c=5, seed=42, iteration=0
)
From a raw Profile::
di = DataInstance.from_profile(profile)
Source code in src/vote_simulation/models/data_generation/data_instance.py
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 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 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 | |
n_candidates
property
¶
Number of candidates in this instance.
n_voters
property
¶
Number of voters in this instance.
build_profile(candidates, data)
¶
Build a svvamp.Profile from candidate labels and utility matrix.
Source code in src/vote_simulation/models/data_generation/data_instance.py
denormalize()
¶
Restore the original (pre-normalization) utility values.
Returns:
| Type | Description |
|---|---|
ndarray
|
2-D array with the same shape as |
ndarray
|
the utilities on their original scale. |
Source code in src/vote_simulation/models/data_generation/data_instance.py
from_generator(model_code, n_v, n_c, *, seed=0, iteration=0, **extra_params)
classmethod
¶
Generate an election profile using a registered generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_code
|
str
|
Registered generator short code (e.g. |
required |
n_v
|
int
|
Number of voters. |
required |
n_c
|
int
|
Number of candidates. |
required |
seed
|
int
|
Base random seed for reproducibility. |
0
|
iteration
|
int
|
Iteration index (added to seed). |
0
|
**extra_params
|
object
|
Model-specific keyword arguments forwarded to the generator builder. |
{}
|
Returns:
| Type | Description |
|---|---|
DataInstance
|
A new |
Source code in src/vote_simulation/models/data_generation/data_instance.py
from_profile(profile, file_path='')
classmethod
¶
Wrap an existing svvamp.Profile into a DataInstance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profile
|
Profile
|
An existing |
required |
file_path
|
str
|
Optional file path associated with the profile. |
''
|
Returns:
| Type | Description |
|---|---|
DataInstance
|
A new |
Source code in src/vote_simulation/models/data_generation/data_instance.py
get_csv(file_path)
¶
Load candidate labels and utility matrix from a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the CSV file. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
A tuple containing: - candidates: 1-D array of candidate names. - data: 2-D array of shape (n_voters, n_candidates) with utility values. |
Source code in src/vote_simulation/models/data_generation/data_instance.py
get_data(file_path)
¶
Load data from a CSV or Parquet file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the data file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
candidates |
ndarray
|
1-D array of candidate names. |
data |
ndarray
|
2-D array of shape |
Source code in src/vote_simulation/models/data_generation/data_instance.py
get_parquet(file_path)
¶
Load candidate labels and utility matrix from a Parquet file.
The Parquet file is expected to have one column per candidate (column name = candidate label) and one row per voter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the Parquet file. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
A tuple containing: - candidates: 1-D array of candidate names. - data: 2-D array of shape (n_voters, n_candidates) with utility values. |
Source code in src/vote_simulation/models/data_generation/data_instance.py
plot_heatmap(*, cluster_columns=False, cluster_rows=True, method='average', metric='euclidean', cmap='viridis', title=None, save_path=None, show=True)
¶
Visualize the utility matrix as a heatmap with optional hierarchical clustering.
Values are already in [0, 1]. Columns (candidates) are reordered by hierarchical clustering by default so that similar preference profiles appear next to each other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cluster_columns
|
bool
|
Reorder candidates by hierarchical clustering (default True). |
False
|
cluster_rows
|
bool
|
Reorder voters by hierarchical clustering (default False). |
True
|
method
|
str
|
Linkage method ( |
'average'
|
metric
|
str
|
Distance metric ( |
'euclidean'
|
cmap
|
str
|
Matplotlib colormap name. |
'viridis'
|
title
|
str | None
|
Figure title. Defaults to model code if available. |
None
|
save_path
|
str | None
|
If provided, save the figure to this path. |
None
|
show
|
bool
|
Whether to call |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Dict with keys |
Raises:
| Type | Description |
|---|---|
ImportError
|
If matplotlib is not installed. |
Source code in src/vote_simulation/models/data_generation/data_instance.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
save_csv(file_path)
¶
Persist the utility matrix to a CSV file (same layout as input).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Destination path (should end in |
required |
Returns:
| Type | Description |
|---|---|
str
|
The resolved absolute path of the written file. |
Source code in src/vote_simulation/models/data_generation/data_instance.py
save_parquet(file_path)
¶
Persist the utility matrix to a Parquet file.
Creates parent directories if needed. The file contains one column per candidate and one row per voter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Destination path (should end in |
required |
Returns:
| Type | Description |
|---|---|
str
|
The resolved absolute path of the written file. |
Source code in src/vote_simulation/models/data_generation/data_instance.py
Results¶
SimulationStepResult
dataclass
¶
Result of a simulation step.
The comparison matrix is stored as a symmetric float32 2D array so that
any distance metric (binary, Jaccard, etc.) can be used.
Source code in src/vote_simulation/models/results/step_result.py
18 19 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 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | |
dist_matrix
property
¶
Read-only 2D matrix of pairwise distances between rules.
distance_matrix_frame
property
¶
Distance matrix as a labeled DataFrame for display and analysis.
mean_distance
property
¶
Mean of all off-diagonal pairwise distances (O(1) numpy ops).
metrics_by_rule
property
¶
Mapping from rule code to its :class:WinnerMetrics for this step.
Only rules registered via :meth:add_method_result_with_metrics will
appear here. Rules loaded from disk (without metrics) return an empty
dict for their key.
metrics_frame
property
¶
Metrics for all rules in this step as a tidy DataFrame.
Returns a DataFrame indexed by rule with one column per metric
field (see :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS).
Rules without metrics are omitted.
most_distant_rules
property
¶
Pair of rules with the maximum distance.
Returns:
| Type | Description |
|---|---|
str
|
|
str
|
than two rules are present. |
rule_codes
property
¶
Ordered rule codes matching the matrix axes.
__post_init__()
¶
Normalize any pre-populated data and build the matrix once.
Source code in src/vote_simulation/models/results/step_result.py
__str__()
¶
String representation with a readable matrix block.
Source code in src/vote_simulation/models/results/step_result.py
add_method_result(rule_code, winners)
¶
Add or update winners for one voting method in this step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_code
|
str
|
str - Code of the voting method (e.g., "STV", "IRV", "Borda") |
required |
winners
|
list[str]
|
list[str] - List of winner labels for the given method. Can be multiple in case of ties. |
required |
Source code in src/vote_simulation/models/results/step_result.py
add_method_result_with_metrics(rule_code, winners, metrics)
¶
Add winners and pre-computed :class:WinnerMetrics for one rule.
This is the enriched variant of :meth:add_method_result used by the
simulation engine so that winner-quality metrics can be aggregated
across iterations with no extra recomputation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_code
|
str
|
Voting rule code (e.g. |
required |
winners
|
list[str]
|
List of co-winner labels. |
required |
metrics
|
WinnerMetrics
|
Pre-computed :class: |
required |
Source code in src/vote_simulation/models/results/step_result.py
compute_distance_matrix()
¶
Rebuild the full distance matrix from winners and return it.
Source code in src/vote_simulation/models/results/step_result.py
delete_file(file_path)
staticmethod
¶
Delete a saved step result file.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/vote_simulation/models/results/step_result.py
format_distance_matrix()
¶
Return a printable matrix with row and column labels.
load_from_file(file_path)
¶
Load the step result from a parquet file.
Reads configuration metadata from the parquet schema when available. Winner-quality metrics are restored from metric columns when present (files written before this feature are loaded without metrics).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the parquet file containing the step result. |
required |
Source code in src/vote_simulation/models/results/step_result.py
plot_distance_matrix(ax=None, save_path=None, *, annotate=True, show=True)
¶
Plot the distance matrix as a heatmap.
When save_path is given the plot is written to disk. If save_path
is a directory, the filename is derived automatically from the
attached :attr:config.
Source code in src/vote_simulation/models/results/step_result.py
save_to_file(file_path)
¶
Save the step result to a parquet file.
Configuration metadata is stored via pyarrow schema metadata.
Winner-quality metrics are stored as additional columns so that they
survive the disk round-trip and can be accumulated by
:class:SimulationSeriesResult after loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the output parquet file. |
required |
Source code in src/vote_simulation/models/results/step_result.py
Data models for simulation outputs across multiple iterations.
SimulationSeriesResult
dataclass
¶
Aggregation of simulation steps.
Maintains a running float64 sum of per-step distance matrices so
that the mean can be computed with a single division at any time, regardless
of how many iterations have been added.
The aggregated :attr:config is automatically updated on each
:meth:add_step call and reflects the union of all per-step configs.
Source code in src/vote_simulation/models/results/series_result.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 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 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 | |
config
property
writable
¶
Aggregated configuration across all added steps.
mean_distance
property
¶
Scalar mean of all off-diagonal cells in the mean distance matrix.
Value in [0, 100].
mean_distance_matrix
property
¶
Mean pairwise distance matrix over all accumulated steps.
Returns a float32 array of shape (n_rules, n_rules).
Values are in [0, 100]: 0 means every step agreed, 100 means they never did.
mean_distance_matrix_frame
property
¶
Mean distance matrix as a labeled DataFrame.
metrics_summary_frame
property
¶
Per-rule winner-metric statistics aggregated across all iterations.
Returns a :class:~pandas.DataFrame indexed by rule with two
columns per metric field — one for the mean and one for the standard
deviation across all accumulated steps:
<field>_mean, <field>_std for each field in
:data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS.
Rules for which no metrics were recorded (e.g. loaded from a parquet file without metrics) are omitted from the frame.
An empty DataFrame is returned when no metrics have been accumulated.
most_distant_rules
property
¶
Pair of rules with the maximum mean distance.
Returns:
| Type | Description |
|---|---|
str
|
|
str
|
than two rules are present. |
rule_codes
property
¶
Ordered rule codes currently available in the aggregated result.
step_count
property
¶
Number of recorded steps (equals the iteration count).
add_rules_to_steps(new_rule_codes)
¶
Apply additional rules to all existing steps and update the series.
Does not re-run existing rules, only computes distances for new rules. Rebuilds the accumulated distance matrix with all rules (old + new).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_rule_codes
|
list[str]
|
List of additional rule codes to apply to each step. |
required |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
Source code in src/vote_simulation/models/results/series_result.py
add_step(step_result)
¶
Add one step result to the series and accumulate its distance matrix.
Source code in src/vote_simulation/models/results/series_result.py
delete_file(file_path)
staticmethod
¶
Delete a saved series result file.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/vote_simulation/models/results/series_result.py
export_mean_distance_matrix_csv(folder_save_path)
¶
Export the mean distance matrix as CSV.
Uses the same folder semantics as :meth:plot_mean_distance_matrix:
if folder_save_path is a directory (or ends with a path separator),
the file is written under a config-based sub-directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_save_path
|
str
|
Destination file path or folder path. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The resolved CSV file path. |
Source code in src/vote_simulation/models/results/series_result.py
export_metrics_summary_csv(folder_save_path, *, stat='mean', metrics=None)
¶
Export per-rule winner metrics as CSV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_save_path
|
str
|
Destination file path or folder path. |
required |
stat
|
str
|
Statistic to export, |
'mean'
|
metrics
|
list[str] | None
|
Optional subset of metric field names. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The resolved CSV file path. |
Source code in src/vote_simulation/models/results/series_result.py
filter_rules(rule_codes)
¶
Return a new series restricted to the specified rule codes.
Only the accumulator state is copied — steps are not included in
the returned object. All plot and export methods work identically on
the filtered result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_codes
|
list[str]
|
Rule codes to keep. Unknown codes are silently ignored. Codes are normalised (stripped, upper-cased) before matching. |
required |
Returns:
| Type | Description |
|---|---|
SimulationSeriesResult
|
A new :class: |
SimulationSeriesResult
|
rules. Returns an empty instance if none of the requested rules |
SimulationSeriesResult
|
are present. |
Source code in src/vote_simulation/models/results/series_result.py
load_from_file(file_path)
¶
Load the series result from a parquet file and rebuild the accumulator.
Reads per-step config from row columns and aggregated config from schema metadata. Backwards-compatible with files lacking config columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the parquet file containing the series result. |
required |
Source code in src/vote_simulation/models/results/series_result.py
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 | |
map_rules_2d()
¶
Project rules into 2D using Multi-Dimensional Scaling (MDS).
Uses the mean distance matrix as a precomputed dissimilarity matrix so that pairwise distances in the 2D plane approximate the original rule-to-rule distances.
Returns:
| Type | Description |
|---|---|
MdsProjection
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no steps have been added yet. |
Source code in src/vote_simulation/models/results/series_result.py
map_rules_3d()
¶
Project rules into 3D using Multi-Dimensional Scaling (MDS).
Uses the mean distance matrix as a precomputed dissimilarity matrix so that pairwise distances in the 3D space approximate the original rule-to-rule distances.
Returns:
| Type | Description |
|---|---|
MdsProjection
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no steps have been added yet. |
Source code in src/vote_simulation/models/results/series_result.py
plot_mean_distance_matrix(ax=None, folder_save_path=None, *, annotate=True, show=True)
¶
Plot the mean distance matrix as a heatmap.
Cell values show the percentage of iterations where two rules disagreed. When multi‑config (several models / voter counts / candidate counts), the title mentions all of them.
Source code in src/vote_simulation/models/results/series_result.py
plot_rules_2d(ax=None, *, show=True, save_path=None)
¶
Plot rules as labeled points in a 2D MDS projection.
Distances between points approximate mean pairwise rule distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any | None
|
Optional matplotlib Axes to draw on. A new figure is created when None. |
None
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional path (file or directory) to save the plot. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/series_result.py
plot_rules_3d(ax=None, *, show=True, save_path=None)
¶
Plot rules as labeled points in a 3D MDS projection.
Distances between points approximate mean pairwise rule distances. The normalized MDS stress is shown on the plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any | None
|
Optional matplotlib Axes to draw on. A new figure is created when None. |
None
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional path (file or directory) to save the plot. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/series_result.py
save_to_file(file_path)
¶
Save the series result to a parquet file.
Per-step config is stored in columns GenModel, NVoters,
NCandidates so that each row is self-describing. The aggregated
series config is stored in schema metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the output parquet file. |
required |
Source code in src/vote_simulation/models/results/series_result.py
Total result model for vote_simulation.
Aggregates multiple :class:SimulationSeriesResult instances across a
parameter space defined by generative model, number of voters, and
number of candidates.
Each series is uniquely keyed by (gen_model, n_voters, n_candidates).
Provides filtering, scalar-metric pivots, and comparison plots.
Typical workflow::
total = SimulationTotalResult()
for model in ["UNI", "IC"]:
for n_v in [101, 1001]:
for n_c in [3, 14]:
series = simulation_instance(model, n_v, n_c, rules)
total.add_series(series)
# Fix model, compare across voters x candidates
uni = total.filter(gen_model="UNI")
uni.plot_metric_heatmap(row_param="n_voters", col_param="n_candidates")
# Side-by-side rule distance heatmaps varying candidates
total.filter(gen_model="UNI", n_voters=1001) \
.plot_comparison_grid("n_candidates")
SeriesKey
¶
Bases: NamedTuple
Identifies one series in the (model, voters, candidates) space.
Source code in src/vote_simulation/models/results/total_result.py
SimulationTotalResult
dataclass
¶
Collection of series results spanning a parameter space.
Each series is uniquely keyed by (gen_model, n_voters, n_candidates).
Provides filtering, scalar-metric pivots, and comparison plots.
Source code in src/vote_simulation/models/results/total_result.py
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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 | |
candidate_counts
property
¶
Sorted distinct candidate counts.
gen_models
property
¶
Sorted distinct generative-model codes.
keys
property
¶
Sorted list of all series keys.
rule_codes
property
¶
Distinct rule codes available across stored series.
The order is deterministic and follows the first occurrence when iterating over series in sorted key order.
rules
property
¶
Backward-compatible alias for the distinct rule codes in the result.
series_count
property
¶
Number of stored series.
voter_counts
property
¶
Sorted distinct voter counts.
__iter__()
¶
add_series(series)
¶
Register a series result.
Raises:
| Type | Description |
|---|---|
ValueError
|
If a series with the same key is already present. |
Source code in src/vote_simulation/models/results/total_result.py
delete_dir(dir_path)
staticmethod
¶
Remove a saved total-result directory.
Returns True if the directory existed and was deleted.
Source code in src/vote_simulation/models/results/total_result.py
export_mean_distance_matrix_csv(save_path)
¶
Export :meth:mean_distance_matrix_frame to CSV.
Source code in src/vote_simulation/models/results/total_result.py
export_metrics_rules_matrix_csv(save_path, *, stat='mean', metrics=None)
¶
Export :meth:metrics_rules_matrix_frame to CSV.
Source code in src/vote_simulation/models/results/total_result.py
filter(*, gen_model=None, n_voters=None, n_candidates=None)
¶
Return a new instance containing only the matching series.
Series objects are shared (shallow copy), not deep-copied.
Source code in src/vote_simulation/models/results/total_result.py
filter_rules(rule_codes)
¶
Return a new instance where every series is restricted to rule_codes.
Applies
:meth:~vote_simulation.models.results.series_result.SimulationSeriesResult.filter_rules
to each stored series. Entries whose filtered version contains no
rules are dropped. Series keys are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_codes
|
list[str]
|
Rule codes to keep across all series. Unknown or absent codes are silently ignored per series. |
required |
Returns:
| Type | Description |
|---|---|
SimulationTotalResult
|
A new :class: |
Source code in src/vote_simulation/models/results/total_result.py
get_series(gen_model, n_voters, n_candidates)
¶
Retrieve a single series by its parameter triple.
Raises:
| Type | Description |
|---|---|
KeyError
|
If no matching series exists. |
Source code in src/vote_simulation/models/results/total_result.py
load_from_dir(dir_path)
classmethod
¶
Reconstruct a :class:SimulationTotalResult from a folder of parquet files.
Each .parquet file is loaded as a :class:SimulationSeriesResult
and registered via :meth:add_series.
Source code in src/vote_simulation/models/results/total_result.py
map_rules_2d()
¶
Project rules into 2D using Multi-Dimensional Scaling (MDS).
Uses the global mean distance matrix (averaged over all series) as a precomputed dissimilarity matrix.
Returns:
| Type | Description |
|---|---|
MdsProjection
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no series have been added yet. |
Source code in src/vote_simulation/models/results/total_result.py
map_rules_3d()
¶
Project rules into 3D using Multi-Dimensional Scaling (MDS).
Uses the global mean distance matrix (averaged over all series) as a precomputed dissimilarity matrix.
Returns:
| Type | Description |
|---|---|
MdsProjection
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no series have been added yet. |
Source code in src/vote_simulation/models/results/total_result.py
mean_distance_matrix_frame()
¶
Mean rule-distance matrix averaged across all series as a DataFrame.
Source code in src/vote_simulation/models/results/total_result.py
metric_matrix(row_param='n_voters', col_param='n_candidates', *, metric='mean_distance')
¶
Pivot a scalar metric into a 2D matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row_param
|
str
|
Key field for the row axis. |
'n_voters'
|
col_param
|
str
|
Key field for the column axis. |
'n_candidates'
|
metric
|
str
|
Column name from :meth: |
'mean_distance'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
str
|
human-readable description of the fixed (third) parameter. |
tuple[DataFrame, str]
|
If the third parameter has multiple distinct values, they are |
tuple[DataFrame, str]
|
averaged and the description reflects this. |
Source code in src/vote_simulation/models/results/total_result.py
metrics_comparison_frame(metric_field, rule_code, stat='mean')
¶
Cross-parameter table of one winner metric for one rule.
Builds a long-form :class:~pandas.DataFrame with one row per
(gen_model, n_voters, n_candidates) entry, containing the
requested aggregated statistic for rule_code.
Parameters¶
metric_field:
One of the fields in
:data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS
(e.g. "social_acceptability", "rank_mean").
rule_code:
The normalised rule code to extract (e.g. "COPE").
stat:
Which statistic column to read from
:attr:~vote_simulation.models.results.series_result.SimulationSeriesResult.metrics_summary_frame:
"mean" (default) or "std".
Returns¶
pd.DataFrame
Columns: gen_model, n_voters, n_candidates,
<metric_field>_<stat>. Series without the requested rule's
metrics are omitted.
Source code in src/vote_simulation/models/results/total_result.py
metrics_pivot(metric_field, rule_code, row_param='n_voters', col_param='n_candidates', stat='mean')
¶
Pivot :meth:metrics_comparison_frame into a 2D matrix.
Analogous to :meth:metric_matrix but for winner metrics instead of
rule-distance metrics.
Parameters¶
metric_field:
Metric field name (see :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS).
rule_code:
The rule to inspect.
row_param / col_param:
Which of the three key parameters (gen_model, n_voters,
n_candidates) to use as row/column axes.
stat:
"mean" or "std".
Returns¶
(pivot_df, fixed_description) The pivot DataFrame and a description of the fixed third parameter.
Source code in src/vote_simulation/models/results/total_result.py
metrics_rules_matrix_frame(*, stat='mean', metrics=None)
¶
Winner-metric matrix with rules as rows and metric stats as columns.
Source code in src/vote_simulation/models/results/total_result.py
plot_comparison_grid(vary_param='n_candidates', *, annotate=True, show=True, save_path=None)
¶
Side-by-side rule-distance heatmaps, one per value of vary_param.
The other two parameters must each have a single distinct value
— use :meth:filter first.
Example::
total.filter(gen_model="UNI", n_voters=1001) \
.plot_comparison_grid("n_candidates")
Source code in src/vote_simulation/models/results/total_result.py
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 | |
plot_mean_distance_matrix(ax=None, *, annotate=True, show=True, save_path=None)
¶
Heatmap of the mean rule-distance matrix averaged across all series.
Each cell (i, j) shows the average percentage of iterations where
rules i and j disagreed, averaged over every series currently in
the object. Use :meth:filter to restrict the scope first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any | None
|
Optional matplotlib Axes. A new figure is created when None. |
None
|
annotate
|
bool
|
Whether to print cell values on the heatmap. |
True
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional file path to save the figure. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/total_result.py
plot_metric_heatmap(row_param='n_voters', col_param='n_candidates', *, metric='mean_distance', ax=None, annotate=True, show=True, save_path=None)
¶
Heatmap of a scalar metric pivoted across two parameters.
The remaining (third) parameter must have a single distinct value
— use :meth:filter first if needed.
Source code in src/vote_simulation/models/results/total_result.py
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 | |
plot_metrics_rules_matrix(row_param='n_voters', col_param='n_candidates', *, stat='mean', metrics=None, annotate=True, fmt='.3f', cell_fontsize=None, show=True, save_path=None)
¶
Heatmap with rules as columns and metrics as rows.
Each cell shows the aggregated statistic (stat) for a given
(metric, rule) pair, averaged over all series currently in the
object (use :meth:filter to restrict the scope first).
The color scale is normalised per row (per metric) so that the gradient is uniform within each row and rules can be directly compared regardless of the absolute scale of each metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row_param
|
str
|
Used only to derive a description of fixed parameters in the title. Filtering is the recommended way to narrow down the data. |
'n_voters'
|
col_param
|
str
|
Same as row_param. |
'n_candidates'
|
stat
|
str
|
|
'mean'
|
metrics
|
list[str] | None
|
Explicit list of metric fields (rows). When None all
fields in :data: |
None
|
annotate
|
bool
|
Whether to print raw values inside each cell. |
True
|
fmt
|
str
|
Format string used for annotations (e.g. |
'.3f'
|
cell_fontsize
|
int | None
|
Font size for cell annotations. When None
(default) the size is chosen automatically based on the number
of rules (smaller when there are many rules). Pass an
explicit integer (e.g. |
None
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional file path to save the figure. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/total_result.py
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 | |
plot_rule_pair_heatmap(rule_a, rule_b, row_param='n_voters', col_param='n_candidates', *, ax=None, annotate=True, show=True, save_path=None)
¶
Heatmap of one rule-pair distance across two parameters.
Source code in src/vote_simulation/models/results/total_result.py
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 | |
plot_rules_2d(ax=None, *, show=True, save_path=None)
¶
Plot rules as labeled points in a 2D MDS projection.
Distances between points approximate the global mean pairwise rule
distances, averaged over all series in this result. Use
:meth:filter to restrict the scope first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any | None
|
Optional matplotlib Axes. A new figure is created when None. |
None
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional file path to save the figure. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/total_result.py
plot_rules_3d(ax=None, *, show=True, save_path=None)
¶
Plot rules as labeled points in a 3D MDS projection.
Distances between points approximate the global mean pairwise rule
distances, averaged over all series in this result. Use
:meth:filter to restrict the scope first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any | None
|
Optional matplotlib 3D Axes. A new figure is created when None. |
None
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional file path to save the figure. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/total_result.py
plot_winner_metric_heatmap(metric_field, rule_code, row_param='n_voters', col_param='n_candidates', *, stat='mean', ax=None, annotate=True, show=True, save_path=None)
¶
Heatmap of one winner metric for one rule, pivoted across two parameters.
Analogous to :meth:plot_metric_heatmap but for
:class:~vote_simulation.models.rules.WinnerMetrics fields instead of
rule-distance metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric_field
|
str
|
One of the fields in
:data: |
required |
rule_code
|
str
|
Normalised rule code to inspect (e.g. |
required |
row_param
|
str
|
Row axis — |
'n_voters'
|
col_param
|
str
|
Column axis (same choices). |
'n_candidates'
|
stat
|
str
|
|
'mean'
|
ax
|
Any | None
|
Optional matplotlib Axes. A new figure is created when None. |
None
|
annotate
|
bool
|
Whether to print cell values on the heatmap. |
True
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional file path to save the figure. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The matplotlib Axes used for plotting. |
Source code in src/vote_simulation/models/results/total_result.py
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 | |
plot_winner_metrics_grid(rule_code, row_param='n_voters', col_param='n_candidates', *, stat='mean', metrics=None, annotate=True, show=True, save_path=None)
¶
Grid of heatmaps — one panel per winner metric — for a single rule.
Iterates over every field in
:data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS (or
the subset given by metrics) and draws each as a heatmap panel,
using the same axes as :meth:plot_winner_metric_heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule_code
|
str
|
Normalised rule code to inspect (e.g. |
required |
row_param
|
str
|
Row axis — |
'n_voters'
|
col_param
|
str
|
Column axis (same choices). |
'n_candidates'
|
stat
|
str
|
|
'mean'
|
metrics
|
list[str] | None
|
Explicit list of metric fields to plot. When None all
fields in :data: |
None
|
annotate
|
bool
|
Whether to print cell values on each panel. |
True
|
show
|
bool
|
Whether to call |
True
|
save_path
|
str | None
|
Optional file path to save the whole figure. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The 2-D NumPy array of matplotlib Axes. |
Source code in src/vote_simulation/models/results/total_result.py
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 | |
replace_series(series)
¶
rule_pair_frame(rule_a, rule_b)
¶
Mean distance between two rules in every series.
Returns a DataFrame with columns gen_model, n_voters,
n_candidates, distance.
Source code in src/vote_simulation/models/results/total_result.py
save_to_dir(dir_path)
¶
Persist every series as <label>.parquet inside dir_path.
Source code in src/vote_simulation/models/results/total_result.py
summary_frame()
¶
One-row-per-series DataFrame with key fields and scalar metrics.
Columns: gen_model, n_voters, n_candidates,
step_count, n_iterations, mean_distance,
most_distant_rule_a, most_distant_rule_b,
most_distant_distance.
Source code in src/vote_simulation/models/results/total_result.py
Defines the :class:ResultConfig dataclass for describing simulation contexts.
This class encapsulates the parameters that define a simulation run as such :
- the generation models used,
- the number of voters and candidates,
- the rules applied,
- and the number of iterations.
The class provides for adding rules to existing configs, merging configs, and generating labels for results based on their parameters.
ResultConfig
dataclass
¶
Describes the simulation context attached to a result.
Supports single-valued and multi-valued configurations to express metadata.
All collection fields use :class:frozenset for immutability and
light membership checks.
Source code in src/vote_simulation/models/results/result_config.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 167 168 169 170 171 172 173 174 175 | |
description
property
¶
Human-readable description for plot titles.
Automatically switches between singular and plural phrasing depending on how many distinct values are present.
label
property
¶
Base label suitable for directory / file names (excludes rules).
Used for cache keys and data organization directories. Format depends on how many values are set::
"UNI_v101_c3" (single model, voters, candidates)
"IC_UNI_v11_101_c3_14" (multiple values)
When n_iterations is set, appends _i{n_iterations}.
label_with_rules
property
¶
Full label including rules codes (for complete identification).
Format: {base_label}_r{rules_joined}
base_config()
¶
Return a copy with rules_codes cleared (for cache keys based on data params only).
Source code in src/vote_simulation/models/results/result_config.py
from_dict(data)
staticmethod
¶
Deserialize from a {key: csv_string} mapping.
Source code in src/vote_simulation/models/results/result_config.py
matches_base(other)
¶
Check if two configs have identical base parameters (ignoring rules_codes).
Source code in src/vote_simulation/models/results/result_config.py
merge(other)
¶
Return the union of two configs (idempotent & commutative).
Source code in src/vote_simulation/models/results/result_config.py
single(gen_model='', n_voters=0, n_candidates=0, n_iterations=0, rules_codes=None)
staticmethod
¶
Create a config for a single (model, voters, candidates) combo.
Source code in src/vote_simulation/models/results/result_config.py
to_dict()
¶
Serialize to a {key: csv_string} mapping.