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
|
Any
|
Value to return if key not found. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
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
|
Any
|
Value to set. |
required |
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
|
dict
|
Nested dictionary to flatten. |
required |
dot
|
bool
|
If True, use dot-notation keys ("a.b"). If False, use tuple keys (("a", "b")). |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
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
|
dict
|
Dictionary with tuple or dot-notation keys. |
required |
dot
|
bool
|
If True, split keys on dots. If False, keys are tuples. |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
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
|
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
|
Figure
|
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
|
str | Path
|
Directory path if |
required |
filename
|
Optional[str]
|
Optional filename when |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
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
|
str | Path
|
Directory path if |
required |
data
|
dict
|
Nested dictionary with array-like values to serialize. |
required |
compression
|
Any
|
Compression filter (default: Blosc2). |
Blosc2()
|
filename
|
Optional[str]
|
Optional filename when |
None
|
compression_threshold
|
int
|
Minimum array size in bytes to trigger compression (default: 1 MiB). |
1024 * 1024
|
Source code in btorch/utils/hdf5_utils.py
btorch.utils.hex
¶
Hexagonal grid utilities (Red Blob Games algorithms).
https://www.redblobgames.com/grids/hexagons/ Primary: axial (q, r) with s = -q-r implicit.
Provides both functional API (for performance) and object-oriented struct-of-arrays types (for convenience).
Code adapted from flyvis (MIT License) and Hexy (MIT License).
Attributes¶
DIAGONALS = np.array([[2, -1], [1, -2], [-1, -1], [-2, 1], [-1, 2], [1, 1]])
module-attribute
¶
DIRECTIONS = np.array([[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]])
module-attribute
¶
Orientation = Literal['pointy', 'flat']
module-attribute
¶
__all__ = ['ring', 'disk', 'spiral', 'rectangle', 'disk_count', 'disk_radius', 'cube_from_axial', 'axial_from_cube', 'to_pixel', 'from_pixel', 'round_axial', 'rotate', 'reflect', 'Orientation', 'distance', 'radius', 'within_range', 'mask', 'DIRECTIONS', 'DIAGONALS', 'neighbor', 'neighbors', 'diagonal_neighbor', 'diagonal_neighbors', 'all_neighbors', 'align', 'permute', 'reflect_index', 'axial_to_rect_index', 'rect_index_to_axial', 'axial_to_hex_index', 'hex_index_to_axial', 'axial_to_triangle_index', 'triangle_index_to_axial', 'axial_to_rhombus_index', 'rhombus_index_to_axial', 'line', 'line_n', 'axial_to_odd_r', 'odd_r_to_axial', 'axial_to_even_r', 'even_r_to_axial', 'axial_to_odd_q', 'odd_q_to_axial', 'axial_to_even_q', 'even_q_to_axial', 'axial_to_zigzag', 'flywire_xy_to_pixel', 'flywire_to_pixel', 'zigzag_to_pixel', 'zigzag_to_axial', 'axial_to_doublewidth', 'doublewidth_to_axial', 'axial_to_doubleheight', 'doubleheight_to_axial', 'doublewidth_distance', 'doubleheight_distance', 'doublewidth_to_pixel', 'doubleheight_to_pixel', 'pixel_to_doublewidth', 'pixel_to_doubleheight', 'range_intersection', 'range_union', 'ranges_intersect', 'resolve_hex', 'hex_symbol_for', 'HexCoords', 'HexData', 'HexGrid']
module-attribute
¶
Classes¶
HexCoords
dataclass
¶
Struct-of-arrays for hex coordinates (q, r).
This is the coordinate-only type. Use HexData for coords + values. All methods delegate to functional API for consistency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates, shape (n_hexes,) |
required |
r
|
ndarray
|
Axial r coordinates, shape (n_hexes,) |
required |
Example
coords = HexCoords.from_disk(radius=3) coords_q, coords_r = coords.q, coords.r px, py = coords.to_pixel() neighbors = coords.neighbors() # HexCoords with 6x coords
Source code in btorch/utils/hex/data.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 | |
Attributes¶
extent
property
¶
Maximum distance from origin.
Functions¶
__eq__(other)
¶
Check equality of all coordinates.
__iter__()
¶
__post_init__()
¶
distance(other=None)
¶
Distance to other coords, or from origin if other is None.
Source code in btorch/utils/hex/data.py
from_cube(q, r, s)
classmethod
¶
Create from cube coordinates (validates q+r+s=0).
Source code in btorch/utils/hex/data.py
from_disk(radius, center_q=0, center_r=0)
classmethod
¶
Create from disk of given radius.
from_doubleheight(col, row)
classmethod
¶
Create from double-height coordinates.
from_doublewidth(col, row)
classmethod
¶
Create from double-width coordinates.
from_even_q(col, row)
classmethod
¶
Create from even-q offset coordinates.
from_even_r(col, row)
classmethod
¶
Create from even-r offset coordinates.
from_odd_q(col, row)
classmethod
¶
Create from odd-q offset coordinates.
from_odd_r(col, row)
classmethod
¶
Create from odd-r offset coordinates.
from_pixel(x, y, size=1.0, orientation='pointy')
classmethod
¶
Create from pixel coordinates (rounds to nearest hex).
Source code in btorch/utils/hex/data.py
from_ring(radius, center_q=0, center_r=0)
classmethod
¶
Create from ring of given radius.
from_spiral(radius, center_q=0, center_r=0)
classmethod
¶
Create in spiral order (center, ring1, ring2...).
Source code in btorch/utils/hex/data.py
from_zigzag(x, y)
classmethod
¶
Create from zigzag (x, y) coordinates.
is_equal_elementwise(other)
¶
mask(condition)
¶
neighbors()
¶
Get 6 neighbors for each coordinate.
Returns HexCoords with shape (6 * n_hexes,).
Source code in btorch/utils/hex/data.py
reflect(axis)
¶
rotate(n)
¶
sort()
¶
to_cube()
¶
Convert to cube coordinates (q, r, s) where s = -q - r.
to_doubleheight()
¶
Convert to double-height coordinates (col, row).
to_doublewidth()
¶
Convert to double-width coordinates (col, row).
to_even_q()
¶
to_even_r()
¶
to_odd_q()
¶
to_odd_r()
¶
to_pixel(size=1.0, orientation='pointy')
¶
Convert to pixel coordinates.
to_zigzag()
¶
within_range(center, n)
¶
Boolean mask for coords within n steps of center.
HexData
dataclass
¶
Struct-of-arrays for hex coordinates with associated values.
This is the primary user-facing type for hex grid data. Separates coordinates (coords) from data (values).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
HexCoords
|
HexCoords instance |
required |
values
|
ndarray
|
Data values, shape (n_hexes,) or (n_hexes, n_features) |
required |
Example
coords = HexCoords.from_disk(radius=3) data = HexData(coords, np.random.randn(len(coords))) data_q = data.q # Access coords data_vals = data.values # Access values
Source code in btorch/utils/hex/data.py
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 | |
Functions¶
__post_init__()
¶
Validate values shape matches coords.
fill(value)
¶
from_arrays(q, r, values)
classmethod
¶
mask(condition)
¶
reflect(axis)
¶
rotate(n)
¶
sort()
¶
to_pixel(size=1.0, orientation='pointy')
¶
Convert to pixel coordinates with values.
where_value(value, rtol=0, atol=0)
¶
Boolean mask where values match (supports np.nan).
HexGrid
¶
Regular hexagonal grid with extent.
This is a specialized HexData for regular hexagonal grids where coordinates form a complete disk of given radius.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Grid radius (extent) |
required |
values
|
ndarray | None
|
Optional initial values |
None
|
center_q
|
int
|
Q-coordinate of the center hex |
0
|
center_r
|
int
|
R-coordinate of the center hex |
0
|
Example
grid = HexGrid(radius=5) grid.circle(radius=3) # Get circle of coords grid.hull # Outer ring
Source code in btorch/utils/hex/data.py
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 | |
Attributes¶
data
property
¶
Access as HexData.
extent
property
¶
Maximum distance from center.
hull
property
¶
Outer ring of the grid.
Functions¶
circle(radius=None)
¶
Get circle of given radius from center.
Returns HexData with values=1 on circle, others filtered out.
Source code in btorch/utils/hex/data.py
filled_circle(radius)
¶
Get filled circle of given radius from center.
Source code in btorch/utils/hex/data.py
line(angle)
¶
Get line through center at given angle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
angle
|
float
|
Angle in radians |
required |
Returns HexData with line coordinates and values=1.
Source code in btorch/utils/hex/data.py
to_pixel(size=1.0, orientation='pointy')
¶
Convert to pixel coordinates with values.
valid_neighbors()
¶
Get valid neighbor indices for each hex in grid.
Returns tuple of tuples, where each inner tuple contains indices of valid neighbors within the grid.
Source code in btorch/utils/hex/data.py
Functions¶
align(q_target, r_target, q_source, r_source, values, fill=np.nan, use_numba=True)
¶
Align source values to target coordinates. Missing -> fill.
Uses numba-accelerated implementation if available and use_numba=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q_target
|
ndarray
|
Target q coordinates. |
required |
r_target
|
ndarray
|
Target r coordinates. |
required |
q_source
|
ndarray
|
Source q coordinates. |
required |
r_source
|
ndarray
|
Source r coordinates. |
required |
values
|
ndarray
|
Source values to align. |
required |
fill
|
float
|
Fill value for missing coordinates. |
nan
|
use_numba
|
bool
|
Whether to use numba acceleration if available. |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Aligned values with same length as target coordinates. |
Source code in btorch/utils/hex/storage.py
all_neighbors(q, r)
¶
Get all 12 neighbors (6 cardinal + 6 diagonal).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q_neighbors, r_neighbors) arrays with shape (12, len(q)). |
Source code in btorch/utils/hex/neighbor.py
axial_from_cube(q, r, s)
¶
Cube to axial: drops s.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Cube q coordinates. |
required |
r
|
ndarray
|
Cube r coordinates. |
required |
s
|
ndarray
|
Cube s coordinates (unused, for API consistency). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/transform.py
axial_to_doubleheight(q, r)
¶
Convert axial to double-height coordinates.
Formula: col = q, row = 2*r + q
Double-height is useful for flat-top hexes in rectangular maps. Every other row is used (odd rows are skipped).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) double-height coordinates. |
Example
col, row = axial_to_doubleheight(np.array([0, 1]), np.array([0, 1])) row array([0, 3])
Source code in btorch/utils/hex/doubled.py
axial_to_doublewidth(q, r)
¶
Convert axial to double-width coordinates.
Formula: col = 2*q + r, row = r
Double-width is useful for pointy-top hexes in rectangular maps. Every other column is used (odd columns are skipped).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) double-width coordinates. |
Example
col, row = axial_to_doublewidth(np.array([0, 1]), np.array([0, 1])) col array([0, 3])
Source code in btorch/utils/hex/doubled.py
axial_to_even_q(q, r)
¶
Convert axial to even-q offset coordinates.
Formula: col = q, row = r + (q + (q & 1)) / 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) offset coordinates. |
Source code in btorch/utils/hex/offset.py
axial_to_even_r(q, r)
¶
Convert axial to even-r offset coordinates.
Formula: col = q + (r + (r & 1)) / 2, row = r
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) offset coordinates. |
Source code in btorch/utils/hex/offset.py
axial_to_hex_index(q, r, radius)
¶
Convert axial to array indices for hexagon-shaped map.
Row r (relative to center) has size 2*N+1 - abs(N-r) columns. Store at array[r + N][q - max(0, N-r) + N]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
radius
|
int
|
Map radius (N). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (row, col) array indices. |
Source code in btorch/utils/hex/storage.py
axial_to_odd_q(q, r)
¶
Convert axial to odd-q offset coordinates.
Formula: col = q, row = r + (q - (q & 1)) / 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) offset coordinates. |
Source code in btorch/utils/hex/offset.py
axial_to_odd_r(q, r)
¶
Convert axial to odd-r offset coordinates.
Formula: col = q + (r - (r & 1)) / 2, row = r
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) offset coordinates. |
Example
col, row = axial_to_odd_r(np.array([0, 1]), np.array([0, 1])) col array([0, 1])
Source code in btorch/utils/hex/offset.py
axial_to_rect_index(q, r, orientation='pointy')
¶
Convert axial to rectangular array indices.
For pointy-top: store at array[r][q + floor(r/2)] For flat-top: store at array[q][r + floor(q/2)]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
orientation
|
str
|
"pointy" or "flat". |
'pointy'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (row, col) array indices. |
Example
row, col = axial_to_rect_index(np.array([0, 1]), np.array([0, 1])) row array([0, 1])
Source code in btorch/utils/hex/storage.py
axial_to_rhombus_index(q, r)
¶
Convert axial to array indices for rhombus-shaped map.
Rhombus maps store axial directly: array[r][q]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (row, col) array indices. |
Source code in btorch/utils/hex/storage.py
axial_to_triangle_index(q, r, size, pointing='down')
¶
Convert axial to array indices for triangle-shaped map.
Down-pointing: store at array[r][q], row r has size N+1-r Up-pointing: store at array[r][q - N+1+r], row r has size 1+r
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
size
|
int
|
Triangle size (N). |
required |
pointing
|
str
|
"down" or "up". |
'down'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (row, col) array indices. |
Source code in btorch/utils/hex/storage.py
axial_to_zigzag(q, r)
¶
Convert axial to zigzag offset coordinates (column-skipped layout).
This is the display-friendly version where x alternates cleanly between columns, creating the classic hex zigzag pattern:
col 0 col 1 col 0 col 1
● ● ● ●
● ● ● ●
Formula: x = floor((r - q) / 2), y = q + r
The reverse is exact and bidirectional with integers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (x, y) zigzag offset coordinates. |
Example
axial_to_zigzag(np.array([0, 1, -1]), np.array([0, 0, 0])) (array([0, 0, 0]), array([0, 1, -1]))
axial_to_zigzag(np.array([0, 1, 0, -1]), np.array([0, -1, 1, 0])) (array([0, -1, 0, 0]), array([0, 0, 1, -1]))
Source code in btorch/utils/hex/offset.py
cube_from_axial(q, r)
¶
Axial to cube: (q, r) -> (q, r, s) where s = -q - r.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
Tuple of (q, r, s) cube coordinates. |
Source code in btorch/utils/hex/transform.py
diagonal_neighbor(q, r, direction)
¶
Get diagonal neighbor in direction (0-5).
Diagonal directions are between the 6 cardinal directions: 0: NE-E, 1: E-SE, 2: SE-SW, 3: SW-W, 4: W-NW, 5: NW-NE
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
direction
|
int
|
Direction index (0-5). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Diagonal neighbor coordinates (q, r). |
Source code in btorch/utils/hex/neighbor.py
diagonal_neighbors(q, r)
¶
Get all 6 diagonal neighbors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q_neighbors, r_neighbors) arrays with shape (6, len(q)). |
Source code in btorch/utils/hex/neighbor.py
disk(radius, center_q=0, center_r=0)
¶
All hexes within radius of center. Count: 1 + 3radius(radius+1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Maximum distance from center. |
required |
center_q
|
int
|
Center q coordinate. |
0
|
center_r
|
int
|
Center r coordinate. |
0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays for hex coordinates in the disk. |
See Also
https://www.redblobgames.com/grids/hexagons/#range-coordinate
Source code in btorch/utils/hex/coords.py
disk_count(radius)
¶
Number of hexes in disk: 1 + 3radius(radius+1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Disk radius. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of hexes in the disk. |
disk_radius(count)
¶
Inverse of disk_count. Radius for given count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Number of hexes. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Radius of disk containing approximately count hexes. |
Note
Returns floor of exact value.
Source code in btorch/utils/hex/coords.py
doubleheight_distance(c1, r1, c2, r2)
¶
Distance in double-height coordinates (direct formula).
Formula: dcol + max(0, (drow-dcol)/2) where dcol = |c2-c1|, drow = |r2-r1|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c1
|
int
|
First column coordinate. |
required |
r1
|
int
|
First row coordinate. |
required |
c2
|
int
|
Second column coordinate. |
required |
r2
|
int
|
Second row coordinate. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Hex distance between the two coordinates. |
Example
doubleheight_distance(0, 0, 0, 2) 1
Source code in btorch/utils/hex/doubled.py
doubleheight_to_axial(col, row)
¶
Convert double-height to axial coordinates.
Formula: q = col, r = (row - col) / 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Double-height column coordinates. |
required |
row
|
ndarray
|
Double-height row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/doubled.py
doubleheight_to_pixel(col, row, size=1.0)
¶
Convert double-height to pixel coordinates.
Formula: x = 3/2 * size * col, y = sqrt(3)/2 * size * row
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Double-height column coordinates. |
required |
row
|
ndarray
|
Double-height row coordinates. |
required |
size
|
float
|
Hexagon size (distance from center to corner). |
1.0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (x, y) pixel coordinates. |
Source code in btorch/utils/hex/doubled.py
doublewidth_distance(c1, r1, c2, r2)
¶
Distance in double-width coordinates (direct formula).
Formula: drow + max(0, (dcol-drow)/2) where drow = |r2-r1|, dcol = |c2-c1|
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c1
|
int
|
First column coordinate. |
required |
r1
|
int
|
First row coordinate. |
required |
c2
|
int
|
Second column coordinate. |
required |
r2
|
int
|
Second row coordinate. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Hex distance between the two coordinates. |
Example
doublewidth_distance(0, 0, 2, 0) 1
Source code in btorch/utils/hex/doubled.py
doublewidth_to_axial(col, row)
¶
Convert double-width to axial coordinates.
Formula: q = (col - row) / 2, r = row
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Double-width column coordinates. |
required |
row
|
ndarray
|
Double-width row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/doubled.py
doublewidth_to_pixel(col, row, size=1.0)
¶
Convert double-width to pixel coordinates.
Formula: x = sqrt(3)/2 * size * col, y = 3/2 * size * row
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Double-width column coordinates. |
required |
row
|
ndarray
|
Double-width row coordinates. |
required |
size
|
float
|
Hexagon size (distance from center to corner). |
1.0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (x, y) pixel coordinates. |
Source code in btorch/utils/hex/doubled.py
even_q_to_axial(col, row)
¶
Convert even-q offset to axial coordinates.
Formula: q = col, r = row - (col + (col & 1)) / 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Column coordinates. |
required |
row
|
ndarray
|
Row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/offset.py
even_r_to_axial(col, row)
¶
Convert even-r offset to axial coordinates.
Formula: q = col - (row + (row & 1)) / 2, r = row
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Column coordinates. |
required |
row
|
ndarray
|
Row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/offset.py
flywire_to_pixel(p, q, size=1.0, rotation_deg=0.0)
¶
Convert FlyWire visual-column coords (p,q) to pixel coordinates.
FlyWire visual columns map uses axial (p,q) data coordinates but displays
them on DOM rows using derived zigzag indices:
x = floor((q - p) / 2)y = p + q
The saved HTML/CSS page then lays out those rows with an alternating half-row indentation and fixed row pitch. This helper mirrors that display logic so btorch plots can match the website layout.
Source code in btorch/utils/hex/offset.py
flywire_xy_to_pixel(x_zigzag, y_zigzag, size=1.0, rotation_deg=0.0)
¶
Convert FlyWire official website display indices (x,y) to pixel
positions.
The retina grid is rendered on DOM rows with: - row pitch of 24 px - tile step of 75 px - half-row indentation of 35 px on alternating rows
Values are normalized here relative to size=1.0.
Source code in btorch/utils/hex/offset.py
from_pixel(x, y, size=1.0, orientation='pointy')
¶
Pixel to axial hex (fractional, use round_axial).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Pixel x coordinates. |
required |
y
|
ndarray
|
Pixel y coordinates. |
required |
size
|
float
|
Hexagon size. |
1.0
|
orientation
|
Orientation
|
"pointy" (point up) or "flat" (flat side up). |
'pointy'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) fractional axial coordinates. |
See Also
https://www.redblobgames.com/grids/hexagons/#pixel-to-hex
Source code in btorch/utils/hex/transform.py
hex_index_to_axial(row, col, radius)
¶
Convert array indices back to axial for hexagon-shaped map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
ndarray
|
Array row indices. |
required |
col
|
ndarray
|
Array column indices. |
required |
radius
|
int
|
Map radius (N). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/storage.py
hex_symbol_for(layout)
¶
Return the Plotly hex marker symbol for a given layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layout
|
str
|
One of |
required |
Returns:
| Type | Description |
|---|---|
int
|
Plotly marker symbol int: |
int
|
|
Source code in btorch/utils/hex/resolve.py
line_n(q1, r1, q2, r2, n)
¶
Line with exactly n+1 points including endpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q1
|
ndarray
|
Start q coordinate(s). |
required |
r1
|
ndarray
|
Start r coordinate(s). |
required |
q2
|
ndarray
|
End q coordinate(s). |
required |
r2
|
ndarray
|
End r coordinate(s). |
required |
n
|
int
|
Number of steps (results in n+1 points). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays for hexes on the line. |
Source code in btorch/utils/hex/line.py
mask(q, r, max_radius)
¶
Boolean mask for coords within max_radius of origin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
max_radius
|
int
|
Maximum distance from origin. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean mask for coordinates within max_radius. |
Source code in btorch/utils/hex/distance.py
neighbors(q, r)
¶
Get all 6 neighbors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q_neighbors, r_neighbors) arrays with shape (6, len(q)). |
Source code in btorch/utils/hex/neighbor.py
odd_q_to_axial(col, row)
¶
Convert odd-q offset to axial coordinates.
Formula: q = col, r = row - (col - (col & 1)) / 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Column coordinates. |
required |
row
|
ndarray
|
Row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/offset.py
odd_r_to_axial(col, row)
¶
Convert odd-r offset to axial coordinates.
Formula: q = col - (row - (row & 1)) / 2, r = row
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
ndarray
|
Column coordinates. |
required |
row
|
ndarray
|
Row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/offset.py
permute(radius, n_rot)
¶
Permutation index for rotating spiral-ordered data by n_rot*60°.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Grid radius. |
required |
n_rot
|
int
|
Number of 60° rotations (positive = clockwise). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Permutation indices for rotating data. |
Source code in btorch/utils/hex/storage.py
pixel_to_doubleheight(x, y, size=1.0)
¶
Convert pixel to double-height coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Pixel x coordinates. |
required |
y
|
ndarray
|
Pixel y coordinates. |
required |
size
|
float
|
Hexagon size. |
1.0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) double-height coordinates. |
Source code in btorch/utils/hex/doubled.py
pixel_to_doublewidth(x, y, size=1.0)
¶
Convert pixel to double-width coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Pixel x coordinates. |
required |
y
|
ndarray
|
Pixel y coordinates. |
required |
size
|
float
|
Hexagon size. |
1.0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (col, row) double-width coordinates. |
Source code in btorch/utils/hex/doubled.py
radius(q, r)
¶
Distance from origin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Distance from origin for each coordinate. |
range_intersection(centers, radii)
¶
Hexes that are within ALL of the given ranges.
Uses the algebraic approach from Red Blob Games: - Each range is: center-N <= q <= center+N, etc. - Intersection is: max(lows) <= q <= min(highs)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
centers
|
list[tuple[int, int]]
|
List of (q, r) center coordinates. |
required |
radii
|
list[int]
|
List of radii (one per center). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays for hexes in the intersection. |
Example
Two overlapping disks¶
centers = [(0, 0), (3, 0)] radii = [2, 2] q, r = range_intersection(centers, radii) len(q) # Hexes within both disks 3
Source code in btorch/utils/hex/range.py
range_union(centers, radii)
¶
Hexes that are within ANY of the given ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
centers
|
list[tuple[int, int]]
|
List of (q, r) center coordinates. |
required |
radii
|
list[int]
|
List of radii (one per center). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays for hexes in the union. |
Example
Two overlapping disks¶
centers = [(0, 0), (5, 0)] radii = [2, 2] q, r = range_union(centers, radii) len(q) # Hexes in either disk (overlap counted once) 19
Source code in btorch/utils/hex/range.py
ranges_intersect(center1, radius1, center2, radius2)
¶
Check if two hex ranges intersect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center1
|
tuple[int, int]
|
First center (q, r). |
required |
radius1
|
int
|
First radius. |
required |
center2
|
tuple[int, int]
|
Second center (q, r). |
required |
radius2
|
int
|
Second radius. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the ranges intersect, False otherwise. |
Example
ranges_intersect((0, 0), 2, (3, 0), 2) True ranges_intersect((0, 0), 1, (5, 0), 1) False
Source code in btorch/utils/hex/range.py
rect_index_to_axial(row, col, orientation='pointy')
¶
Convert rectangular array indices back to axial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
ndarray
|
Array row indices. |
required |
col
|
ndarray
|
Array column indices. |
required |
orientation
|
str
|
"pointy" or "flat". |
'pointy'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/storage.py
rectangle(width, height, orientation='pointy')
¶
Rectangular region in axial coords (slanted edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width
|
int
|
Width of rectangle. |
required |
height
|
int
|
Height of rectangle. |
required |
orientation
|
Literal['pointy', 'flat']
|
Hexagon orientation ("pointy" or "flat"). |
'pointy'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays for hex coordinates in rectangle. |
Source code in btorch/utils/hex/coords.py
reflect(q, r, axis)
¶
Reflect across axis.
In cube coordinates: - reflect_q = (q, s, r) - reflect_r = (s, r, q) - reflect_s = (r, q, s)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
axis
|
Literal['q', 'r', 's']
|
Axis to reflect across ("q", "r", or "s"). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Reflected coordinates (q, r). |
Source code in btorch/utils/hex/transform.py
reflect_index(radius, axis)
¶
Permutation index for reflecting spiral-ordered data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Grid radius. |
required |
axis
|
Literal['q', 'r', 's']
|
Axis to reflect across ("q", "r", or "s"). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Permutation indices for reflecting data. |
Source code in btorch/utils/hex/storage.py
resolve_hex(c1, c2, coord_format='axial', layout='pointy', size=1.0, **layout_kw)
¶
Convert any hex input to axial and pixel coordinates.
Single entry point used by all visualisation functions. Handles
the two-stage pipeline: (1) convert input to axial (q, r),
(2) project axial to screen (x, y).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c1
|
ndarray
|
First coordinate. Meaning depends on |
required |
c2
|
ndarray
|
Second coordinate. Meaning depends on |
required |
coord_format
|
str
|
How to interpret |
'axial'
|
layout
|
str
|
Screen projection. One of:
|
'pointy'
|
size
|
float
|
Hexagon size (center-to-corner distance) for pixel projection. |
1.0
|
**layout_kw
|
Any
|
Extra args forwarded to the layout projector
(e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Axial input, pointy-top layout:
>>> q, r, x, y = resolve_hex(
... np.array([0, 1]), np.array([0, 0]),
... coord_format="axial", layout="pointy",
... )
Zigzag input (FlyWire saved-page data):
References
Red Blob Games — Hexagonal Grids: https://www.redblobgames.com/grids/hexagons/
Source code in btorch/utils/hex/resolve.py
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 | |
rhombus_index_to_axial(row, col)
¶
Convert array indices back to axial for rhombus-shaped map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
ndarray
|
Array row indices. |
required |
col
|
ndarray
|
Array column indices. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/storage.py
ring(radius, center_q=0, center_r=0)
¶
Hexes at exactly radius from center (6*radius hexes, or 1 if
radius=0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Distance from center. |
required |
center_q
|
int
|
Center q coordinate. |
0
|
center_r
|
int
|
Center r coordinate. |
0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays for hex coordinates on the ring. |
Source code in btorch/utils/hex/coords.py
rotate(q, r, n)
¶
Rotate by n * 60°. Positive n = clockwise.
Formula: [q,r,s] -> [-r,-s,-q] for 60° cw. Axial: q' = -r, r' = q + r.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
n
|
int
|
Number of 60° rotations (positive = clockwise). |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Rotated coordinates (q, r). |
Source code in btorch/utils/hex/transform.py
round_axial(q, r)
¶
Round fractional axial to nearest hex (RBG algorithm).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Fractional axial q coordinates. |
required |
r
|
ndarray
|
Fractional axial r coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Rounded axial coordinates (q, r). |
Source code in btorch/utils/hex/transform.py
spiral(radius, center_q=0, center_r=0)
¶
Hexes in spiral order: center, ring1, ring2, ..., ring_radius.
This ordering is stable under rotation (permutes by ring).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
int
|
Maximum distance from center. |
required |
center_q
|
int
|
Center q coordinate. |
0
|
center_r
|
int
|
Center r coordinate. |
0
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) arrays in spiral order. |
Source code in btorch/utils/hex/coords.py
to_pixel(q, r, size=1.0, orientation='pointy')
¶
Axial hex to pixel.
Pointy: x = size * (sqrt(3)q + sqrt(3)/2r), y = size * (3/2r) Flat: x = size * (3/2q), y = size * (sqrt(3)/2q + sqrt(3)r)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
size
|
float
|
Hexagon size (distance from center to corner). |
1.0
|
orientation
|
Orientation
|
"pointy" (point up) or "flat" (flat side up). |
'pointy'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (x, y) pixel coordinates. |
See Also
https://www.redblobgames.com/grids/hexagons/#hex-to-pixel
Source code in btorch/utils/hex/transform.py
triangle_index_to_axial(row, col, size, pointing='down')
¶
Convert array indices back to axial for triangle-shaped map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
ndarray
|
Array row indices. |
required |
col
|
ndarray
|
Array column indices. |
required |
size
|
int
|
Triangle size (N). |
required |
pointing
|
str
|
"down" or "up". |
'down'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Source code in btorch/utils/hex/storage.py
within_range(q, r, center_q, center_r, n)
¶
Boolean mask for coords within n steps of center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray
|
Axial q coordinates. |
required |
r
|
ndarray
|
Axial r coordinates. |
required |
center_q
|
int
|
Center q coordinate. |
required |
center_r
|
int
|
Center r coordinate. |
required |
n
|
int
|
Maximum distance from center. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean mask for coordinates within range. |
Source code in btorch/utils/hex/distance.py
zigzag_to_axial(x, y)
¶
Convert zigzag offset coordinates back to axial.
Formula: q = floor((y - 2*x) / 2), r = y - q
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Zigzag column coordinates. |
required |
y
|
ndarray
|
Zigzag row coordinates. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of (q, r) axial coordinates. |
Example
zigzag_to_axial(np.array([0, 0, 0]), np.array([0, 1, -1])) (array([0, 1, -1]), array([0, 0, 0]))
Source code in btorch/utils/hex/offset.py
zigzag_to_pixel(x, y, size=1.0)
¶
Convert zigzag display coordinates to flat-top pixel space.
FlyWire website-style lattice display is a staggered-column layout where every second column is vertically shifted by half a cell.
Formula
pixel_x = 1.5 * size * x pixel_y = sqrt(3) * size * (y + 0.5 * (x mod 2))
Source code in btorch/utils/hex/offset.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
|
Any
|
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
|
str
|
Directory path if |
required |
filename
|
str | None
|
Optional filename when |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
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
|
Any
|
Object to serialize. Tries |
required |
folder_or_file
|
str
|
Directory path if |
required |
filename
|
str | None
|
Optional filename when |
None
|