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

Feat/update map #26

Merged
merged 19 commits into from
Sep 19, 2023
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
57 changes: 29 additions & 28 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,36 +21,37 @@ permissions:
contents: read # This is required for actions/checkout

jobs:
# tests:
# runs-on: ubuntu-latest
# strategy:
# matrix:
# python-version: ['3.8', '3.9', '3.10', '3.11']

# steps:
# - uses: actions/checkout@v3
# - name: Set up Python ${{ matrix.python-version }}
# uses: actions/setup-python@v4
# with:
# python-version: ${{ matrix.python-version }}

# - name: Install dependencies
# run: |
# python -m pip install --upgrade pip
# python -m pip install -e .["test"]

# - name: run pre-commit
# if: ${{ matrix.python-version == env.LATEST_PY_VERSION }}
# run: |
# python -m pip install pre-commit
# pre-commit run --all-files

# - name: Run tests
# run: python -m pytest --cov titiler.xarray --cov-report term-missing -s -vv
tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.8', '3.9', '3.10', '3.11']

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install -e .["test"]

- name: run pre-commit
if: ${{ matrix.python-version == env.LATEST_PY_VERSION }}
run: |
python -m pip install pre-commit
pre-commit run --all-files

- name: Run tests
run: python -m pytest --cov titiler.xarray --cov-report term-missing -s -vv

deploy:
# needs: [tests]
needs: [tests]
runs-on: ubuntu-latest
# if: startsWith(github.event.ref, 'refs/tags') || github.event_name == 'release'
#if: github.ref == 'refs/heads/main'

defaults:
run:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Tests use data generated locally by using `tests/fixtures/generate_test_*.py` sc
To run all the tests:

```bash
python -m pip install -e .["tests"]
python -m pip install -e ".[tests]"
python -m pytest --cov titiler.xarray --cov-report term-missing -s -vv
```

Expand Down Expand Up @@ -81,7 +81,7 @@ An example of Cloud Stack is available for AWS
STACK_STAGE=staging npm --prefix infrastructure/aws run cdk -- deploy titiler-xarray-staging

# Deploy in specific region
AWS_DEFAULT_REGION=eu-central-1 AWS_REGION=eu-central-1 AWS_PROFILE=myprofile STACK_STAGE=staging npm --prefix infrastructure/aws run cdk -- deploy titiler-xarray-staging
AWS_DEFAULT_REGION=us-west-2 AWS_REGION=us-west-2 AWS_PROFILE=smce-veda STACK_STAGE=production npm --prefix infrastructure/aws run cdk -- deploy titiler-xarray-production
```


Expand Down
82 changes: 64 additions & 18 deletions titiler/xarray/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
from typing import Dict, List, Literal, Optional, Tuple, Type
from urllib.parse import urlencode

import jinja2
import numpy as np
from fastapi import Depends, Path, Query
from rio_tiler.models import Info
from starlette.requests import Request
from starlette.responses import HTMLResponse, Response
from starlette.templating import Jinja2Templates

from titiler.core.dependencies import RescalingParams
from titiler.core.factory import BaseTilerFactory, img_endpoint_params
Expand Down Expand Up @@ -184,7 +187,6 @@ def tiles_endpoint( # type: ignore

if colormap:
image = image.apply_colormap(colormap)

if not format:
format = ImageType.jpeg if image.mask.all() else ImageType.png

Expand Down Expand Up @@ -309,13 +311,42 @@ def tilejson_endpoint( # type: ignore
[-180, -90, 180, 90], list(src_dst.geographic_bounds)
)
bounds = [max(minx), max(miny), min(maxx), min(maxy)]

return {
"bounds": bounds,
"minzoom": minzoom if minzoom is not None else src_dst.minzoom,
"maxzoom": maxzoom if maxzoom is not None else src_dst.maxzoom,
"tiles": [tiles_url],
}

@self.router.get(
"/histogram",
response_class=JSONResponse,
responses={200: {"description": "Return histogram for this data variable"}},
response_model_exclude_none=True,
)
def histogram(
url: str = Query(..., description="Dataset URL"),
variable: str = Query(..., description="Variable"),
reference: bool = Query(
False,
title="reference",
description="Whether the src_path is a kerchunk reference",
),
):
with self.reader(url, variable=variable, reference=reference) as src_dst:
boolean_mask = ~np.isnan(src_dst.input)
data_values = src_dst.input.values[boolean_mask]
counts, values = np.histogram(data_values, bins=10)
counts, values = counts.tolist(), values.tolist()
buckets = list(
zip(values, [values[i + 1] for i in range(len(values) - 1)])
)
hist_dict = []
for idx, bucket in enumerate(buckets):
hist_dict.append({"bucket": bucket, "value": counts[idx]})
return hist_dict

@self.router.get("/map", response_class=HTMLResponse)
@self.router.get("/{TileMatrixSetId}/map", response_class=HTMLResponse)
def map_viewer(
Expand All @@ -324,7 +355,7 @@ def map_viewer(
self.default_tms,
description=f"TileMatrixSet Name (default: '{self.default_tms}')",
), # noqa
url: str = Query(..., description="Dataset URL"), # noqa
url: Optional[str] = Query(None, description="Dataset URL"), # noqa
group: Optional[int] = Query( # noqa
None, description="Select a specific Zarr Group (Zoom Level)."
),
Expand All @@ -341,7 +372,9 @@ def map_viewer(
decode_times: Optional[bool] = Query( # noqa
True, title="decode_times", description="Whether to decode times"
),
variable: str = Query(..., description="Xarray Variable"), # noqa
variable: Optional[str] = Query(
None, description="Xarray Variable"
), # noqa
drop_dim: Optional[str] = Query(
None, description="Dimension to drop"
), # noqa
Expand Down Expand Up @@ -377,20 +410,33 @@ def map_viewer(
env=Depends(self.environment_dependency), # noqa
):
"""Return map Viewer."""
tilejson_url = self.url_for(
request, "tilejson_endpoint", TileMatrixSetId=TileMatrixSetId
templates = Jinja2Templates(
directory="",
loader=jinja2.ChoiceLoader([jinja2.PackageLoader(__package__, ".")]),
)
if request.query_params._list:
tilejson_url += f"?{urlencode(request.query_params._list)}"
if url:
tilejson_url = self.url_for(
request, "tilejson_endpoint", TileMatrixSetId=TileMatrixSetId
)
if request.query_params._list:
tilejson_url += f"?{urlencode(request.query_params._list)}"

tms = self.supported_tms.get(TileMatrixSetId)
return self.templates.TemplateResponse(
name="map.html",
context={
"request": request,
"tilejson_endpoint": tilejson_url,
"tms": tms,
"resolutions": [tms._resolution(matrix) for matrix in tms],
},
media_type="text/html",
)
tms = self.supported_tms.get(TileMatrixSetId)
return templates.TemplateResponse(
name="map.html",
context={
"request": request,
"tilejson_endpoint": tilejson_url,
"tms": tms,
"resolutions": [tms._resolution(matrix) for matrix in tms],
},
media_type="text/html",
)
else:
return templates.TemplateResponse(
name="map-form.html",
context={
"request": request,
},
media_type="text/html",
)
Loading