Utils¶
btorch.utils.bench
¶
Benchmarking utilities.
Performance measurement tools for PyTorch code, supporting both CPU wall-clock and GPU event-based timing with warmup and statistical summarization.
Classes¶
PerfTimer
¶
Context manager for measuring execution time.
Example
with PerfTimer() as timer: ... result = some_function() print(f"Took {timer.elapsed_ms():.2f} ms")
Source code in btorch/utils/bench.py
Functions¶
elapsed_ms()
¶
Return elapsed time in milliseconds.
Returns:
| Type | Description |
|---|---|
float
|
Elapsed time from |
float
|
if |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If timer was never started. |
Source code in btorch/utils/bench.py
Functions¶
do_bench(fn, warmup=25, rep=100, grad_to_none=None, quantiles=None, return_mode='mean', timing_method='cpu', sync_cuda=True)
¶
Benchmark function runtime with warmup and statistics.
Supports both CPU wall-clock timing and GPU CUDA event timing. Warmup and repetition can be specified as iteration counts (int) or durations in milliseconds (float).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable
|
Function to benchmark (callable with no arguments). |
required |
warmup
|
int | float
|
Warmup iterations (int) or duration in ms (float). |
25
|
rep
|
int | float
|
Measurement iterations (int) or duration in ms (float). |
100
|
grad_to_none
|
Optional[Tensor]
|
Optional tensor whose gradient is reset to None between repetitions. |
None
|
quantiles
|
Optional[List[float]]
|
Optional quantiles to compute (e.g., [0.05, 0.95]). |
None
|
return_mode
|
Literal['min', 'max', 'mean', 'median', 'all']
|
Central statistic to return: "min", "max", "mean", "median", or "all" for all stats. |
'mean'
|
timing_method
|
Literal['gpu', 'cpu']
|
"gpu" for CUDA events (if available) or "cpu" for wall-clock timing. |
'cpu'
|
sync_cuda
|
bool
|
Whether to synchronize CUDA before/after timing (only applies to CPU timing). |
True
|
Returns:
| Type | Description |
|---|---|
Union[float, Dict[str, float]]
|
Timing result. Float for single statistics, dict for "all" |
Union[float, Dict[str, float]]
|
or when quantiles are specified. |
Example
def bench_fn(): ... return torch.mm(a, b) do_bench(bench_fn, warmup=10, rep=100, return_mode="median") 0.523
Source code in btorch/utils/bench.py
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 | |
btorch.utils.conf
¶
OmegaConf configuration utilities.
Helpers for loading, manipulating, and comparing structured configs. Provides CLI-style dotlist conversion and diff operations for configuration management workflows.
Attributes¶
ConfigT = TypeVar('ConfigT')
module-attribute
¶
Functions¶
diff_conf(conf_a, conf_b, mode=None)
¶
Compare conf_b to conf_a and return a structured OmegaConf diff.
The returned config contains only the selected changed keys. For removed
keys (when moded by mode), values are set to None so callers can
render these entries via :func:to_dotlist as key=null.
Source code in btorch/utils/conf.py
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 | |
diff_conf_dotlist(conf_a, conf_b, mode=None, removed_prefix='~')
¶
Build CLI-style overrides that transform conf_a into conf_b.
For added and changed entries, this emits "path=value".
For removed entries (when moded by mode), this emits
"{removed_prefix}path".
Source code in btorch/utils/conf.py
diff_conf_records(conf_a, conf_b, mode=None)
¶
Compare conf_b to conf_a and return per-key value-level records.
Each record has the shape {"status": str, "old": object, "new": object}.
status='changed': key exists in both, value differs.status='added': key exists only inconf_b.status='removed': key exists only inconf_a.
This representation is suitable when a caller needs both key names and values, for example to build child-process overrides from a baseline config.
Source code in btorch/utils/conf.py
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 | |
get_dotkey(obj, key, default=None)
¶
Get nested attribute by dot-separated key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to access (supports DictConfig/ListConfig or regular objects). |
required |
key
|
str
|
Dot-separated path (e.g., "a.b.c"). |
required |
default
|
Value to return if key not found. |
None
|
Returns:
| Type | Description |
|---|---|
|
Value at the nested path, or |
Source code in btorch/utils/conf.py
load_config(Param, use_config_file=True, search_path=Path('.'), argv_arglist=None, return_cli=False, make_concrete=True)
¶
load_config(Param: type[ConfigT] | ConfigT, use_config_file: bool = True, search_path: Path = Path('.'), argv_arglist: list[str] | None = None, return_cli: Literal[False] = False, make_concrete: Literal[True] = True) -> ConfigT
load_config(Param: type[ConfigT] | ConfigT, use_config_file: bool = True, search_path: Path = Path('.'), argv_arglist: list[str] | None = None, return_cli: Literal[False] = False, make_concrete: Literal[False] = False) -> DictConfig | ListConfig
Load structured config from defaults, file, and CLI arguments.
Merges configuration in order: dataclass defaults -> config file ->
CLI arguments. Config file path is read from config_path in CLI
arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Param
|
type[ConfigT] | ConfigT
|
Dataclass type or instance defining the configuration schema. |
required |
use_config_file
|
bool
|
Whether to load from file specified by
|
True
|
search_path
|
Path
|
Directory to search for relative config paths. |
Path('.')
|
argv_arglist
|
list[str] | None
|
Optional CLI arguments list (defaults to sys.argv). |
None
|
return_cli
|
bool
|
If True, also return raw CLI config. |
False
|
make_concrete
|
bool
|
If True, convert to Python objects. If False, return OmegaConf containers. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
Loaded configuration. Tuple of (config, cli_config) if |
Any
|
|
Note
Does not support help text or Literal types in the schema.
Source code in btorch/utils/conf.py
set_dotkey(obj, key, value)
¶
Set nested attribute by dot-separated key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to modify (supports DictConfig/ListConfig or regular objects). |
required |
key
|
str
|
Dot-separated path (e.g., "a.b.c"). |
required |
value
|
Value to set. |
required |
Returns:
| Type | Description |
|---|---|
|
None |
Source code in btorch/utils/conf.py
to_dotlist(conf, use_equal=True, include=None, exclude=None, subfield=None, missing_subfield_policy='raise')
¶
Flatten DictConfig/ListConfig to CLI-style dotlist.
Parameters¶
conf:
Root OmegaConf container. Must be DictConfig or ListConfig.
use_equal:
If True, emit ["a.b=1"] form. If False, emit ["a.b", "1"] pairs.
include, exclude:
Optional exact-path filters applied to leaf paths.
Paths are evaluated relative to subfield (if provided), otherwise
relative to the root conf.
subfield:
Optional dotted path used as the flattening start point.
Supports list indices (e.g. "a.b.1").
missing_subfield_policy:
Behavior when subfield cannot be resolved.
"raise" (default) raises KeyError.
"empty" returns [].
Examples¶
{"a": {"b": 1}} -> ["a.b=1"]
subfield="a" -> ["b=1"]
Source code in btorch/utils/conf.py
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 | |
btorch.utils.dict_utils
¶
Dictionary manipulation utilities.
Helpers for transforming, flattening, and mapping nested dictionaries commonly used in configuration and data preprocessing pipelines.
Functions¶
flatten_dict(d, dot=False)
¶
Flatten nested dictionary into single-level dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Nested dictionary to flatten. |
required | |
dot
|
If True, use dot-notation keys ("a.b"). If False, use tuple keys (("a", "b")). |
False
|
Returns:
| Type | Description |
|---|---|
|
Flattened dictionary. |
Example
flatten_dict({"a": {"b": 1}, "c": 2}) {("a", "b"): 1, ("c",): 2} flatten_dict({"a": {"b": 1}}, dot=True)
Source code in btorch/utils/dict_utils.py
recurse_dict(d, mapper, include_sequence=False)
¶
Recursively apply function to dictionary leaf values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
Input dictionary (potentially nested). |
required |
mapper
|
Callable
|
Function called with (key, value) for each leaf. |
required |
include_sequence
|
bool
|
If True, also recurse into tuples and lists. |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
New dictionary with transformed leaf values. |
Source code in btorch/utils/dict_utils.py
reverse_map(map)
¶
Reverse a mapping, handling sequence values.
Flattens sequence values so each item maps to the original key. Non-sequence values map directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
map
|
dict[Any, Any | Sequence[Any]]
|
Dictionary with scalar or sequence values. |
required |
Returns:
| Type | Description |
|---|---|
dict[Any, Any]
|
Reversed mapping where each original value (or sequence item) |
dict[Any, Any]
|
maps to its original key. |
Example
reverse_map({"a": [1, 2], "b": 3})
Source code in btorch/utils/dict_utils.py
unflatten_dict(flattened_dict, dot=False)
¶
Unflatten dictionary with compound keys into nested structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flattened_dict
|
Dictionary with tuple or dot-notation keys. |
required | |
dot
|
If True, split keys on dots. If False, keys are tuples. |
False
|
Returns:
| Type | Description |
|---|---|
|
Nested dictionary. |
Example
unflatten_dict({("a",): 1, ("b", "c"): 2}) {"a": 1, "b": {"c": 2}} unflatten_dict({"a.b": 1}, dot=True) {"a": {"b": 1}}
Source code in btorch/utils/dict_utils.py
btorch.utils.file
¶
File path utilities.
Helpers for resolving figure output paths based on caller location within the repository structure.
Classes¶
FigPathConfig
dataclass
¶
Configuration for figure output directory structure.
Attributes:
| Name | Type | Description |
|---|---|---|
root_dir |
str
|
Root directory for all figures. |
benchmark_dir |
str
|
Subdirectory for benchmark script outputs. |
tests_dir |
str
|
Subdirectory for test script outputs. |
other_dir |
str
|
Subdirectory for other script outputs. |
Source code in btorch/utils/file.py
Functions¶
_is_relative_to(path, base)
¶
_repo_root()
¶
_resolve_cfg(cfg)
¶
Merge user config with defaults.
Source code in btorch/utils/file.py
caller_file(stack_level=2)
¶
Source code in btorch/utils/file.py
fig_path(file=None, cfg=None)
¶
Resolve figure output directory based on caller location.
Places outputs in fig/benchmark/, fig/tests/, or fig/misc/
depending on whether the caller is in the benchmark, tests, or other
directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str | Path | None
|
File path to use for path resolution. If None, uses caller file. |
None
|
cfg
|
FigPathConfig | dict | None
|
Configuration for directory naming. |
None
|
Returns:
| Type | Description |
|---|---|
|
Path object for the figure directory (created if needed). |
Source code in btorch/utils/file.py
save_fig(fig, name=None, path=None, *, file=None, cfg=None, suffix='pdf', transparent=False)
¶
Save matplotlib figure to appropriate directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig
|
Matplotlib figure object. |
required | |
name
|
str | None
|
Output filename (without extension). If None, uses caller stem. |
None
|
path
|
Path | None
|
Output directory. If None, uses |
None
|
file
|
str | Path | None
|
File path for context resolution. If None, uses caller file. |
None
|
cfg
|
FigPathConfig | dict | None
|
Configuration for directory naming. |
None
|
suffix
|
str
|
File extension (default: "pdf"). |
'pdf'
|
transparent
|
bool
|
Save with transparent background. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the saved figure file. |
Source code in btorch/utils/file.py
btorch.utils.grad_checkpoint
¶
btorch.utils.hdf5_utils
¶
HDF5 serialization utilities.
Helpers for saving and loading nested dictionaries containing arrays to HDF5 files with optional Blosc2 compression for large arrays.
Functions¶
load_dict_from_hdf5(folder_or_filename, filename=None)
¶
Load nested dictionary from HDF5 file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_or_filename
|
Directory path if |
required | |
filename
|
Optional[str]
|
Optional filename when |
None
|
Returns:
| Type | Description |
|---|---|
|
Nested dictionary with restored array values. |
Source code in btorch/utils/hdf5_utils.py
save_dict_to_hdf5(folder_or_filename, data, compression=hdf5plugin.Blosc2(), filename=None, compression_threshold=1024 * 1024)
¶
Save nested dictionary with array values to HDF5 file.
Recursively traverses data and saves arrays as datasets.
Datasets larger than compression_threshold are compressed
with the specified compression filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_or_filename
|
Directory path if |
required | |
data
|
Nested dictionary with array-like values to serialize. |
required | |
compression
|
Compression filter (default: Blosc2). |
Blosc2()
|
|
filename
|
Optional[str]
|
Optional filename when |
None
|
compression_threshold
|
Minimum array size in bytes to trigger compression (default: 1 MiB). |
1024 * 1024
|
Returns:
| Type | Description |
|---|---|
|
None |
Source code in btorch/utils/hdf5_utils.py
btorch.utils.hex_utils
¶
Hexagonal lattice coordinate utilities.
Functions for working with hexagonal grid coordinates (axial/cube), conversions between hex and pixel coordinates, and geometric operations on hexagonal lattices.
See Also
https://www.redblobgames.com/grids/hexagons/
Classes¶
HexArray
¶
Bases: ndarray
Flat array holding Hexal's as elements.
Can be constructed with
HexArray(hexals: Iterable, values: Optional[np.nan]) HexArray(u: Iterable, v: Iterable, values: Optional[np.nan])
Source code in btorch/utils/hex_utils.py
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 | |
Functions¶
fill(value)
¶
get_extent(hexals=None, u=None, v=None, center=Hexal(0, 0, 0))
staticmethod
¶
Returns the columnar extent.
Source code in btorch/utils/hex_utils.py
plot(figsize=[3, 3], fill=True)
¶
Plots values in regular hexagonal lattice.
Meant for debugging.
Source code in btorch/utils/hex_utils.py
to_pixel(scale=1, mode='default')
¶
where(value)
¶
Returns a mask of where values are equal to the given one.
Note: value can be np.nan.
with_stride(u_stride=None, v_stride=None)
¶
Returns a sliced instance obeying strides in u- and v-direction.
Source code in btorch/utils/hex_utils.py
HexLattice
¶
Bases: HexArray
Flat array of Hexals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extent
|
Extent of the regular hexagon grid. |
required | |
hexals
|
Existing hexals to initialize with. |
required | |
center
|
Center hexal of the lattice. |
required | |
u_stride
|
Stride in u-direction. |
required | |
v_stride
|
Stride in v-direction. |
required |
Source code in btorch/utils/hex_utils.py
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 | |
Functions¶
circle(radius=None, center=Hexal(0, 0, 0), as_lattice=False)
¶
Draws a circle in hex coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
Radius in columns of the circle. |
None
|
|
center
|
Center of the circle. |
Hexal(0, 0, 0)
|
|
as_lattice
|
Returns the circle on a constrained regular lattice. |
False
|
Source code in btorch/utils/hex_utils.py
filled_circle(radius=None, center=Hexal(0, 0, 0), as_lattice=False)
staticmethod
¶
Draws a circle in hex coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
Radius in columns of the circle. |
None
|
|
center
|
Center of the circle. |
Hexal(0, 0, 0)
|
|
as_lattice
|
Returns the circle on a constrained regular lattice. |
False
|
Source code in btorch/utils/hex_utils.py
hull()
¶
line(angle, center=Hexal(0, 0, 1), as_lattice=False)
¶
Returns a line on a HexLattice or HexArray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
angle
|
In [0, np.pi] |
required | |
center
|
Midpoint of the line |
Hexal(0, 0, 1)
|
|
as_lattice
|
Returns the ring on a constrained regular lattice. |
False
|
Returns:
| Type | Description |
|---|---|
|
HexArray or constrained HexLattice |
Source code in btorch/utils/hex_utils.py
Hexal
¶
Hexal representation containing u, v, z coordinates and value.
Attributes:
| Name | Type | Description |
|---|---|---|
u |
Coordinate in u principal direction (0 degree axis). |
|
v |
Coordinate in v principal direction (60 degree axis). |
|
z |
Coordinate in z principal direction (-60 degree axis). |
|
value |
'Hexal' value. |
|
u_stride |
Stride in u-direction. |
|
v_stride |
Stride in v-direction. |
Source code in btorch/utils/hex_utils.py
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 | |
Functions¶
__add__(other)
¶
Adds u and v coordinates, while keeping the value of the left hexal.
Source code in btorch/utils/hex_utils.py
__eq__(other)
¶
Compares coordinates (not values).
__mul__(other)
¶
Multiplies values, while preserving coordinates.
Source code in btorch/utils/hex_utils.py
angle(other=None, non_negative=False)
¶
Returns the angle to other or the origin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
non_negative
|
bool
|
add 2pi if angle is negative. Default: False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
angle in radians. |
Source code in btorch/utils/hex_utils.py
distance(other=None)
¶
Returns the columnar distance between to hexals.
Source code in btorch/utils/hex_utils.py
eq_val(other)
¶
Compares the values, not the coordinates.
interp(other, t)
¶
Interpolates towards other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
float
|
interpolation step, 0<t<1. |
required |
Returns:
| Type | Description |
|---|---|
|
Hexal |
Source code in btorch/utils/hex_utils.py
is_neighbour(other)
¶
Evaluates if other is a neighbour.
Source code in btorch/utils/hex_utils.py
neighbours()
¶
Returns 6 neighbours sorted CCW, starting from east.
LatticeMask
¶
Boolean masks for lattice dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extent
|
int
|
Extent of the hexagonal lattice. |
15
|
u_stride
|
int
|
Stride in u-direction. |
1
|
v_stride
|
int
|
Stride in v-direction. |
1
|
Source code in btorch/utils/hex_utils.py
Functions¶
crop_to_extent(u, v, color, max_extent)
¶
Crop hexagonal grid data to a specified maximum extent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Array of hex coordinates in u direction. |
required |
v
|
ndarray
|
Array of hex coordinates in v direction. |
required |
color
|
ndarray
|
Array of values associated with each (u, v) coordinate. |
required |
max_extent
|
int
|
Maximum extent to crop the hexagonal grid to. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray, ndarray]
|
Tuple of cropped u, v, and color arrays. |
Source code in btorch/utils/hex_utils.py
get_extent(u, v, astype=int)
¶
Returns extent (integer distance to origin) of arbitrary u, v coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
U-coordinate of hexal. |
required |
v
|
ndarray
|
V-coordinate of hexal. |
required |
astype
|
type
|
Type to cast to. |
int
|
Returns:
| Type | Description |
|---|---|
int
|
Extent of hex-lattice. |
Note
If u and v are arrays, returns the maximum extent.
See Also
https://www.redblobgames.com/grids/hexagons/#distances
Source code in btorch/utils/hex_utils.py
get_hex_coords(extent, astensor=False)
¶
Construct hexagonal coordinates for a regular hex-lattice with extent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extent
|
int
|
Integer radius of hexagonal lattice. 0 returns the single center coordinate. |
required |
astensor
|
bool
|
If True, returns torch.Tensor, else np.array. |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple containing: u: Hex-coordinates in u-direction. v: Hex-coordinates in v-direction. |
Note
Will return get_num_hexals(extent) coordinates.
See Also
https://www.redblobgames.com/grids/hexagons/#range-coordinate
Source code in btorch/utils/hex_utils.py
get_hextent(num_hexals)
¶
Computes the hex-lattice extent from the number of hexals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_hexals
|
int
|
Number of hexals. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Extent of hex-lattice. |
Note
Inverse of get_num_hexals.
Source code in btorch/utils/hex_utils.py
get_num_hexals(extent)
¶
Returns the absolute number of hexals in a hexagonal grid with extent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extent
|
int
|
Extent of hex-lattice. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of hexals. |
Note
Inverse of get_hextent.
Source code in btorch/utils/hex_utils.py
hex_rows(n_rows, n_columns, eps=0.1, mode='pointy')
¶
Return a hex grid in pixel coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rows
|
int
|
Number of rows. |
required |
n_columns
|
int
|
Number of columns. |
required |
eps
|
float
|
Small offset to avoid overlapping hexagons. |
0.1
|
mode
|
Literal['pointy', 'flat']
|
Orientation of hexagons. |
'pointy'
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple containing: x: X-coordinates of hexagon centers. y: Y-coordinates of hexagon centers. |
Source code in btorch/utils/hex_utils.py
hex_to_pixel(u, v, size=1, mode='default')
¶
Returns pixel coordinates from hex coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Hex-coordinates in u-direction. |
required |
v
|
ndarray
|
Hex-coordinates in v-direction. |
required |
size
|
float
|
Size of hexagon. |
1
|
mode
|
Literal['default', 'flat', 'pointy']
|
Coordinate system convention. |
'default'
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple containing: x: Pixel-coordinates in x-direction. y: Pixel-coordinates in y-direction. |
See Also
https://www.redblobgames.com/grids/hexagons/#hex-to-pixel
Source code in btorch/utils/hex_utils.py
max_extent_index(u, v, max_extent)
¶
Returns a mask to constrain u and v axial-hex-coordinates by max_extent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Hex-coordinates in u-direction. |
required |
v
|
ndarray
|
Hex-coordinates in v-direction. |
required |
max_extent
|
int
|
Maximal extent. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean mask. |
Source code in btorch/utils/hex_utils.py
pad_to_regular_hex(u, v, values, extent, value=np.nan)
¶
Pad hexals with coordinates to a regular hex lattice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
U-coordinate of hexal. |
required |
v
|
ndarray
|
V-coordinate of hexal. |
required |
values
|
ndarray
|
Value of hexal with arbitrary shape but last axis must match the hexal dimension. |
required |
extent
|
int
|
Extent of regular hex grid to pad to. |
required |
value
|
float
|
The pad value. |
nan
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray, ndarray]
|
A tuple containing: u_padded: Padded u-coordinate. v_padded: Padded v-coordinate. values_padded: Padded value. |
Note
The canonical use case here is to pad a filter, receptive field, or postsynaptic current field for visualization.
Example
Source code in btorch/utils/hex_utils.py
pixel_to_hex(x, y, size=1, mode='default')
¶
Returns hex coordinates from pixel coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Pixel-coordinates in x-direction. |
required |
y
|
ndarray
|
Pixel-coordinates in y-direction. |
required |
size
|
float
|
Size of hexagon. |
1
|
mode
|
Literal['default', 'flat', 'pointy']
|
Coordinate system convention. |
'default'
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple containing: u: Hex-coordinates in u-direction. v: Hex-coordinates in v-direction. |
See Also
https://www.redblobgames.com/grids/hexagons/#hex-to-pixel
Source code in btorch/utils/hex_utils.py
sort_u_then_v(u, v, values)
¶
Sorts u, v, and values by u and then v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
U-coordinate of hexal. |
required |
v
|
ndarray
|
V-coordinate of hexal. |
required |
values
|
ndarray
|
Value of hexal. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray, ndarray]
|
A tuple containing: u: Sorted u-coordinate of hexal. v: Sorted v-coordinate of hexal. values: Sorted value of hexal. |
Source code in btorch/utils/hex_utils.py
sort_u_then_v_index(u, v)
¶
Index to sort u, v by u and then v.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
U-coordinate of hexal. |
required |
v
|
ndarray
|
V-coordinate of hexal. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Index to sort u and v. |
Source code in btorch/utils/hex_utils.py
btorch.utils.pandas_utils
¶
Pandas DataFrame utilities.
Helpers for common DataFrame operations used in connectome analysis and data aggregation workflows.
Functions¶
groupby_to_dict(df, column_select=None, **groupby_args)
¶
Group DataFrame and return as dictionary mapping keys to subframes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame to group. |
required |
column_select
|
Optional[Sequence[str]]
|
Optional column subset to include in output values. |
None
|
**groupby_args
|
Arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
dict[Any, DataFrame]
|
Dictionary mapping group keys to DataFrame slices. |
Example
df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) groupby_to_dict(df, column_select=["b"], by="a") {1: b 0 3 1 4, 2: b 2 5}
Source code in btorch/utils/pandas_utils.py
btorch.utils.yaml_utils
¶
YAML serialization utilities.
Simple helpers for loading and saving Python objects to YAML files, with automatic directory creation.
Functions¶
load_yaml(folder_or_file, filename=None)
¶
Load object from YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_or_file
|
Directory path if |
required | |
filename
|
Optional filename when |
None
|
Returns:
| Type | Description |
|---|---|
|
Deserialized Python object. |
Source code in btorch/utils/yaml_utils.py
save_yaml(args, folder_or_file, filename=None)
¶
Save object to YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Object to serialize. Tries |
required | |
folder_or_file
|
Directory path if |
required | |
filename
|
Optional filename when |
None
|
Returns:
| Type | Description |
|---|---|
|
None |