numberlink.level_setup¶
Shared level setup utilities for NumberLink environments.
This module provides helpers to resolve level sources, validate grids, build color palettes, and construct a
LevelTemplate used by the environment creation code. Use build_level_template() as the entry point to
produce reusable static data for a level before creating an environment with the numberlink package.
Note
Type information is provided in function signatures where available and is compatible with static analysis tools.
Module Contents¶
Classes¶
Precomputed static data for a NumberLink level configuration. |
Functions¶
Resolve the effective |
|
Compute grid distance between two coordinates. |
|
Validate that a grid contains valid endpoint pairs and path lengths. |
|
Determine the resolved grid, bridge coordinates, level identifier, and solution. |
|
Validate grid shape and return its height and width. |
|
Generate visually distinguishable RGB colors. |
|
Build a mapping from letter identifiers to RGB colors and return numpy arrays for rendering. |
|
Construct a |
API¶
- class numberlink.level_setup.LevelTemplate[source]¶
Precomputed static data for a NumberLink level configuration.
Instances of this dataclass hold static, precomputed values required to create runtime environments. Fields are documented in the class body via type annotations. Construct instances using
build_level_template()to ensure internal consistency.- variant: numberlink.config.VariantConfig = None[source]¶
- reward_config: numberlink.config.RewardConfig = None[source]¶
- render_config: numberlink.config.RenderConfig = None[source]¶
- numberlink.level_setup.resolve_variant(variant: numberlink.config.VariantConfig | None, generator: numberlink.config.GeneratorConfig | None) numberlink.config.VariantConfig[source]¶
Resolve the effective
VariantConfigto use for level construction.If
variantis provided, return it unchanged. IfvariantisNoneandgeneratoris provided, derive values from the generator configuration while preserving explicit defaults fromVariantConfigwhere applicable. The returned object is safe to use withbuild_level_template()and_resolve_level_source().- Parameters:
variant (VariantConfig or None) – Explicit variant configuration or
Noneto derive one.generator (GeneratorConfig or None) – Generator configuration used to derive variant fields when
variantisNone.
- Returns:
Effective variant configuration.
- Return type:
- numberlink.level_setup._metric(a: Coord, b: Coord, *, allow_diagonal: bool) int[source]¶
Compute grid distance between two coordinates.
Returns the Chebyshev distance when
allow_diagonalisTrueand the Manhattan distance otherwise. This helper is internal and is used by_grid_ok()for validating path lengths between endpoints.
- numberlink.level_setup._grid_ok(grid: collections.abc.Sequence[str], *, min_path_length: int, allow_diagonal: bool) bool[source]¶
Validate that a grid contains valid endpoint pairs and path lengths.
The function checks that every non-
'.'character appears exactly twice. For each pair it verifies that the distance computed by_metric()meets or exceedsmin_path_length. This routine is used by_resolve_level_source()when regenerating candidate levels from aGeneratorConfig.- Parameters:
- Returns:
Truewhen the grid is valid, otherwiseFalse.- Return type:
- numberlink.level_setup._resolve_level_source(*, grid: collections.abc.Sequence[str] | None, level_id: str | None, variant: numberlink.config.VariantConfig, bridges: collections.abc.Iterable[Coord] | None, generator: numberlink.config.GeneratorConfig | None) tuple[list[str], set[Coord], str | None, list[list[Coord]] | None][source]¶
Determine the resolved grid, bridge coordinates, level identifier, and solution.
The resolution order is as follows:
If
generatoris provided, attempt to generate candidate levels usinggenerate_level()until a candidate satisfies_grid_ok()or a maximum number of attempts is reached.If
level_idis provided, load the level from theLEVELSmapping.If
gridis provided, use it directly.Fall back to the built-in level with id
'builtin_5x5_rw_4c'.
Caller-specified
bridgesoverride any bridges from generated or lookup sources. This helper is private and intended for use bybuild_level_template().- Parameters:
grid (Sequence[str] or None) – Optional explicit grid to use.
level_id (str or None) – Optional level identifier to load from
LEVELS.variant (VariantConfig) – Effective
VariantConfigused when validating generated candidates.bridges (Iterable[Coord] or None) – Optional iterable of bridge coordinates to force.
generator (GeneratorConfig or None) – Optional
GeneratorConfigused to generate candidate grids.
- Returns:
Tuple
(resolved_grid, resolved_bridges, resolved_level_id, resolved_solution)whereresolved_gridis a list of row strings,resolved_bridgesis a set of coordinate tuples,resolved_level_idis either the selected level id orNonewhen the grid came from a generator or explicitgridargument, andresolved_solutionis the solution paths orNoneif unavailable.- Return type:
tuple[list[str], set[Coord], str or None, list[list[Coord]] or None]
- numberlink.level_setup._validate_grid(grid: collections.abc.Sequence[str]) Coord[source]¶
Validate grid shape and return its height and width.
The function ensures the grid has at least one row and that all rows are the same width. It returns a tuple
(height, width)for convenience. This helper is used bybuild_level_template()to validate input grids.- Parameters:
grid (Sequence[str]) – Sequence of row strings representing the grid.
- Returns:
Pair of integers
(height, width)describing the grid size.- Return type:
- Raises:
ValueError – If the grid is empty or rows have inconsistent lengths.
- numberlink.level_setup._generate_colors(num_colors: int) list[RGBInt][source]¶
Generate visually distinguishable RGB colors.
The function returns a list of RGB triples where each triple is an
(R, G, B)tuple with values in the range0to255. For small values ofnum_colorsa curated palette of high-contrast colors is returned. For larger values additional colors are generated by sampling HSV space and converting values to RGB.
- numberlink.level_setup._build_palette(letters: list[str], palette: dict[str, RGBInt] | None) tuple[dict[str, RGBInt], list[numpy.typing.NDArray[numpy.uint8]]][source]¶
Build a mapping from letter identifiers to RGB colors and return numpy arrays for rendering.
The function first applies any user-provided mappings from
palette. For letters that remain unassigned it generates visually distinguishable colors using_generate_colors(). The function also returns a list ofnumpyarrays ordered to matchletterswhich is convenient for rendering code.- Parameters:
- Returns:
Tuple of
(palette_map, palette_arrays)wherepalette_mapis a mapping from letter to RGB tuple andpalette_arraysis a list ofnumpy.uint8arrays in the same order asletters.- Return type:
- numberlink.level_setup.build_level_template(*, grid: collections.abc.Sequence[str] | None, level_id: str | None, variant: numberlink.config.VariantConfig | None, bridges: collections.abc.Iterable[Coord] | None, generator: numberlink.config.GeneratorConfig | None, reward_config: numberlink.config.RewardConfig | None, render_config: numberlink.config.RenderConfig | None, palette: dict[str, RGBInt] | None, solution: list[list[Coord]] | None = None) numberlink.level_setup.LevelTemplate[source]¶
Construct a
LevelTemplatefrom configuration inputs.This function resolves the effective variant using
resolve_variant()and chooses a grid using_resolve_level_source(). It validates the resolved grid with_validate_grid(), builds a color palette with_build_palette(), and prepares arrays and masks required by runtime environments.The returned
LevelTemplatecontains precomputed values such as endpoint coordinates, direction vectors, action space sizes, and color palettes. Use the returned object to construct environment instances.- Parameters:
grid (Sequence[str] or None) – Optional explicit grid to use. If
Noneandgeneratoris provided then levels are generated until a valid candidate is found.level_id (str or None) – Optional key into the
LEVELSmapping to select a predefined level.variant (VariantConfig or None) – Optional
VariantConfigto apply. IfNonethe value is derived usingresolve_variant()whengeneratoris present.bridges (Iterable[Coord] or None) – Optional iterable of bridge coordinates to force. If provided these override any bridges from generated or predefined levels.
generator (GeneratorConfig or None) – Optional
GeneratorConfigused to generate levels when a grid is not supplied.reward_config (RewardConfig or None) – Optional
RewardConfigto attach to the template. WhenNonea defaultRewardConfigis used.render_config (RenderConfig or None) – Optional
RenderConfigthat controls rendering parameters. WhenNonea defaultRenderConfigis used.palette (dict[str, RGBInt] or None) – Optional mapping from letters to RGB triples. Missing letters are assigned generated colors by
_build_palette().
- Returns:
A fully populated
LevelTemplatesuitable for environment construction.- Return type:
- Raises:
ValueError – If the resolved grid contains fewer than one color pair or a letter doesn’t appear twice.