Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpolate palette colors in order to ensure colormaps always have the same number of colors #249

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions arpav_ppcv/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ class ArpavPpcvSettings(BaseSettings): # noqa
static_dir: Optional[Path] = Path(__file__).parent / "webapp/static"
thredds_server: ThreddsServerSettings = ThreddsServerSettings()
palettes_dir: Path = Path(__file__).parents[1] / "data/palettes"
palette_num_stops: int = 5
prefect: PrefectSettings = PrefectSettings()
martin_tile_server_base_url: str = "http://localhost:3000"
nearest_station_radius_meters: int = 200
Expand Down
42 changes: 29 additions & 13 deletions arpav_ppcv/palette.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,38 @@
import logging
from pathlib import Path
from typing import Optional
from typing import (
Optional,
Sequence,
)

import matplotlib as mpl

logger = logging.getLogger(__name__)


def apply_palette(
colors: Sequence[str], minimum: float, maximum: float, num_stops: int
) -> list[tuple[float, str]]:
# this converts from the AARRGGBB format which is what the .pal files have
# to RRGGBB
rgb_colors = [f"#{c[3:]}" for c in colors]
cmap = mpl.colors.ListedColormap(rgb_colors)
result = []
step = (maximum - minimum) / (num_stops - 1)
for current_stop in range(num_stops):
interval_stop = minimum + current_stop * step
normalized_stop = current_stop * step / abs(maximum - minimum)
color = mpl.colors.to_hex(cmap(normalized_stop), True)
thredds_representation = "#{alpha}{red}{green}{blue}".format(
red=color[1:3],
green=color[3:5],
blue=color[5:7],
alpha=color[7:9],
)
result.append((interval_stop, thredds_representation))
return result


def parse_palette(palette: str, palettes_dir: Path) -> Optional[list[str]]:
palette_name = palette.split("/")[-1].lower()
if is_inverted := "-inv" in palette_name:
Expand All @@ -28,15 +56,3 @@ def parse_palette(palette: str, palettes_dir: Path) -> Optional[list[str]]:
if is_inverted:
colors.reverse()
return colors if len(colors) > 0 else None


def apply_palette(
colors: list[str], minimum: float, maximum: float
) -> list[tuple[float, str]]:
minmax_range = maximum - minimum
step_increment = minmax_range / (len(colors) - 1)
result = []
for i, current_color in enumerate(colors):
current_value = minimum + i * step_increment
result.append((current_value, current_color))
return result
20 changes: 14 additions & 6 deletions arpav_ppcv/webapp/api_v2/routers/coverages.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,14 +188,22 @@ def get_coverage_configuration(
palette_colors = palette.parse_palette(
db_coverage_configuration.palette, settings.palettes_dir
)
applied_colors = []
if palette_colors is not None:
applied_colors = palette.apply_palette(
palette_colors,
db_coverage_configuration.color_scale_min,
db_coverage_configuration.color_scale_max,
)
minimum = db_coverage_configuration.color_scale_min
maximum = db_coverage_configuration.color_scale_max
if abs(maximum - minimum) > 0.001:
applied_colors = palette.apply_palette(
palette_colors, minimum, maximum, num_stops=settings.palette_num_stops
)
else:
logger.warning(
f"Cannot calculate applied colors for coverage "
f"configuration {db_coverage_configuration.name!r} - check the "
f"colorscale min and max values"
)
else:
applied_colors = []
logger.warning(f"Unable to parse palette {db_coverage_configuration.palette!r}")
return coverage_schemas.CoverageConfigurationReadDetail.from_db_instance(
db_coverage_configuration, allowed_coverage_identifiers, applied_colors, request
)
Expand Down
73 changes: 42 additions & 31 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ cftime = "^1.6.4"
babel = "^2.15.0"
pyloess = "^0.1.0"
prefect = {version = "^3.0.0rc14", allow-prereleases = true}
matplotlib = "^3.9.2"


[tool.poetry.group.dev]
Expand Down
Loading