Skip to content

API reference

Generated from the docstrings.

Bulk API

characterize_roofs

characterize_roofs(polygons, service='fr-lidar', *, crs=None, params=None, split=False, workers=8, id_column=None, meta_prefix='meta_', progress=None, capacity=None, tilt=30.0)

Characterizes the roof planes under a set of polygons.

Parameters:

Name Type Description Default
polygons GeoDataFrame, DataFrame with a geometry column, GeoJSON dict,

list of features / shapely geometries, or a path (GeoJSON, GeoPackage, (Geo)Parquet, ...). See geometry.to_geodataframe.

required
service a DSMService, a service name from pypvroof.catalog
  ("fr-lidar", "nl-ahn"...), a folder of GeoTIFFs, or None for the
  heuristics (constant `tilt`, azimuth from the polygon's minimum
  rotated rectangle, `elongation` column; status "heuristic")
'fr-lidar'
crs CRS of the input when it does not carry one (default EPSG:4326)
None
params dict or TheilSenParams, estimator parameters
None
split split multimodal polygons into homogeneous parts
False
workers number of polygons processed concurrently (threads). The work is

dominated by I/O for remote services; mind their usage limits.

8
id_column column identifying the input polygons, copied into

parent_id (default: the input index)

None
meta_prefix prefix of the columns holding the service metadata
'meta_'
progress optional callable(done, total)
None
capacity None (no capacity), "constant", "linear", "clustered" or a

coefficient in kWp/m²: adds an installed_capacity column (kWp) computed from surface, see pypvroof.capacity.installed_capacity

None
tilt tilt (degrees) given by the heuristics (service=None only)
30.0

Returns:

Type Description
GeoDataFrame with the input columns (renamed with an `_input` suffix when
they clash with the output ones), parent_id, part, the result columns
(tilt, azimuth, status, inspect, surface_proj, surface, diagnostics) and
the service metadata.
Source code in pypvroof/bulk.py
def characterize_roofs(polygons, service="fr-lidar", *, crs=None, params=None, split=False,
                       workers=8, id_column=None, meta_prefix="meta_", progress=None,
                       capacity=None, tilt=30.0):
    """
    Characterizes the roof planes under a set of polygons.

    Parameters
    ----------
    polygons : GeoDataFrame, DataFrame with a geometry column, GeoJSON dict,
        list of features / shapely geometries, or a path (GeoJSON, GeoPackage,
        (Geo)Parquet, ...). See geometry.to_geodataframe.
    service : a DSMService, a service name from pypvroof.catalog
              ("fr-lidar", "nl-ahn"...), a folder of GeoTIFFs, or None for the
              heuristics (constant `tilt`, azimuth from the polygon's minimum
              rotated rectangle, `elongation` column; status "heuristic")
    crs : CRS of the input when it does not carry one (default EPSG:4326)
    params : dict or TheilSenParams, estimator parameters
    split : split multimodal polygons into homogeneous parts
    workers : number of polygons processed concurrently (threads). The work is
        dominated by I/O for remote services; mind their usage limits.
    id_column : column identifying the input polygons, copied into
        `parent_id` (default: the input index)
    meta_prefix : prefix of the columns holding the service metadata
    progress : optional callable(done, total)
    capacity : None (no capacity), "constant", "linear", "clustered" or a
        coefficient in kWp/m²: adds an `installed_capacity` column (kWp)
        computed from `surface`, see pypvroof.capacity.installed_capacity
    tilt : tilt (degrees) given by the heuristics (service=None only)

    Returns
    -------
    GeoDataFrame with the input columns (renamed with an `_input` suffix when
    they clash with the output ones), parent_id, part, the result columns
    (tilt, azimuth, status, inspect, surface_proj, surface, diagnostics) and
    the service metadata.
    """
    gdf = to_geodataframe(polygons, crs=crs)
    in_crs = gdf.crs
    if capacity is not None:
        installed_capacity(1.0, capacity)  # fail early on an unknown method
    if service is None:
        ignored = [k for k, v in (("params", params), ("split", split)) if v]
        if ignored:
            warnings.warn("service=None (heuristics): {} ignored".format(", ".join(ignored)), stacklevel=2)
        results = _heuristic_results(list(gdf.geometry.values), in_crs, tilt)
        if progress:
            progress(len(results), len(results))
        return _assemble(gdf, results, id_column, meta_prefix, capacity)

    service = dsm.get_service(service)
    p = theilsen.TheilSenParams.from_dict(params)

    def work(geom):
        if geom is None or geom.is_empty:
            return [(geom, _empty(ERROR), {"error": "empty geometry"})]
        geom = _polygonal(geom)
        parts = characterize_polygon(reproject(geom, in_crs, service.crs), service, p, split)
        return [(reproject(g, service.crs, in_crs), r, m) for g, r, m in parts]

    geoms = list(gdf.geometry.values)
    total = len(geoms)
    results = [None] * total
    if workers and workers > 1:
        with ThreadPoolExecutor(max_workers=workers) as ex:
            futures = {ex.submit(work, g): i for i, g in enumerate(geoms)}
            for done, fut in enumerate(as_completed(futures), start=1):
                results[futures[fut]] = fut.result()
                if progress:
                    progress(done, total)
    else:
        for i, g in enumerate(geoms):
            results[i] = work(g)
            if progress:
                progress(i + 1, total)
    return _assemble(gdf, results, id_column, meta_prefix, capacity)

Installed capacity

installed_capacity

installed_capacity(surface, method='constant', *, coefficient=DEFAULT_COEFFICIENT, clusters=4, data=None)

Installed capacity (kWp) from the panel surface (m²).

Parameters:

Name Type Description Default
surface float or array - like

Panel surface in m² (surface column of characterize_roofs, i.e. corrected for the tilt). NaN gives NaN.

required
method str or float

"constant", "linear", "clustered", or a coefficient in kWp/m².

'constant'
coefficient float

Coefficient of the "constant" method (kWp/m²).

DEFAULT_COEFFICIENT
clusters int

Number of surface classes of the "clustered" method.

4
data DataFrame

Calibration registry with columns surface (m²) and kWp, for the "linear" and "clustered" methods (default: the BDPV extract shipped with the package).

None

Returns:

Type Description
float for a scalar input, numpy array otherwise.
Source code in pypvroof/capacity.py
def installed_capacity(surface, method="constant", *, coefficient=DEFAULT_COEFFICIENT,
                       clusters=4, data=None):
    """
    Installed capacity (kWp) from the panel surface (m²).

    Parameters
    ----------
    surface : float or array-like
        Panel surface in m² (`surface` column of `characterize_roofs`, i.e.
        corrected for the tilt). NaN gives NaN.
    method : str or float
        "constant", "linear", "clustered", or a coefficient in kWp/m².
    coefficient : float
        Coefficient of the "constant" method (kWp/m²).
    clusters : int
        Number of surface classes of the "clustered" method.
    data : DataFrame, optional
        Calibration registry with columns `surface` (m²) and `kWp`, for the
        "linear" and "clustered" methods (default: the BDPV extract shipped
        with the package).

    Returns
    -------
    float for a scalar input, numpy array otherwise.
    """
    scalar = np.ndim(surface) == 0
    s = np.asarray(surface, dtype=float)
    if not isinstance(method, str):
        coef = np.full(s.shape, float(method))
    elif method == "constant":
        coef = np.full(s.shape, float(coefficient))
    elif method in ("linear", "clustered"):
        bounds, coefs = _fit_registry(method, clusters) if data is None else _fit(data, method, clusters)
        # class i holds surfaces in (bounds[i-1], bounds[i]]; beyond the last bound: last class
        idx = np.minimum(np.searchsorted(bounds, s, side="left"), len(coefs) - 1)
        coef = coefs[idx]
    else:
        raise ValueError("unknown capacity method: {!r} (one of {} or a number)".format(method, METHODS))
    out = s * coef
    return float(out) if scalar else out

Heuristics

bbox_azimuth

bbox_azimuth(geoms)

(azimuth, elongation) of each polygon, from its minimum rotated rectangle.

geoms are shapely geometries in a projected (metric) CRS. The azimuth is in degrees, 0 = north, clockwise, in [90, 270]; the elongation is the long side over the short side of the rectangle. NaN for empty geometries.

Source code in pypvroof/heuristics.py
def bbox_azimuth(geoms):
    """
    (azimuth, elongation) of each polygon, from its minimum rotated rectangle.

    `geoms` are shapely geometries in a projected (metric) CRS. The azimuth is
    in degrees, 0 = north, clockwise, in [90, 270]; the elongation is the long
    side over the short side of the rectangle. NaN for empty geometries.
    """
    geoms = np.asarray(geoms, dtype=object)
    az = np.full(len(geoms), np.nan)
    el = np.full(len(geoms), np.nan)
    if not len(geoms):
        return az, el
    with np.errstate(invalid="ignore", divide="ignore"):  # spurious on axis-aligned rectangles
        mrr = shapely.minimum_rotated_rectangle(geoms)
    for i, r in enumerate(mrr):
        if r is None or r.is_empty or r.geom_type != "Polygon":
            continue
        co = np.asarray(r.exterior.coords)
        if len(co) < 4:
            continue
        e1, e2 = co[1] - co[0], co[2] - co[1]
        l1, l2 = np.hypot(*e1), np.hypot(*e2)
        long_e = e1 if l1 >= l2 else e2
        bearing = np.degrees(np.arctan2(long_e[0], long_e[1])) % 180  # long axis
        n1 = (bearing + 90) % 360
        n2 = (n1 + 180) % 360
        az[i] = n1 if _angdiff(n1, 180) <= _angdiff(n2, 180) else n2
        el[i] = max(l1, l2) / max(min(l1, l2), 1e-9)
    return az, el

Theil-Sen

TheilSenParams dataclass

Parameters of the estimator. Distances in metres, angles in degrees.

estimate

estimate(z, transform, mask, edge_distance=None, params=None, return_labels=False)

Estimates tilt and azimuth from an elevation grid.

z : 2D elevations (NaN = no data) transform : affine transform of the grid (metres) mask : boolean grid, pixels to use (polygon, usually eroded) edge_distance : optional grid, distance (m) of each pixel to the polygon's edge; enables the edge-band test for secondary planes return_labels : also return (rows, cols, labels, planes) for splitting

Returns a dict: status, inspect, tilt, azimuth, n_pixels, n_modes, primary_share, inlier_frac, rmse, roughness, offset_suspected, modes (list of {tilt, azimuth, share}).

Source code in pypvroof/theilsen.py
def estimate(z, transform, mask, edge_distance=None, params=None, return_labels=False):
    """
    Estimates tilt and azimuth from an elevation grid.

    z             : 2D elevations (NaN = no data)
    transform     : affine transform of the grid (metres)
    mask          : boolean grid, pixels to use (polygon, usually eroded)
    edge_distance : optional grid, distance (m) of each pixel to the polygon's
                    edge; enables the edge-band test for secondary planes
    return_labels : also return (rows, cols, labels, planes) for splitting

    Returns a dict: status, inspect, tilt, azimuth, n_pixels, n_modes,
    primary_share, inlier_frac, rmse, roughness, offset_suspected, modes
    (list of {tilt, azimuth, share}).
    """
    p = TheilSenParams.from_dict(params)
    valid = mask & np.isfinite(z)
    rows, cols = np.nonzero(valid)
    n = len(rows)
    if n < p.min_pixels or n * abs(transform.a * transform.e) < p.min_area:
        r = _nan_result(TOO_FEW_POINTS, n)
        return (r, None) if return_labels else r

    x = transform.c + (cols + 0.5) * transform.a
    y = transform.f + (rows + 0.5) * transform.e
    x0, y0 = x.mean(), y.mean()  # centre for numerical stability
    x, y, zz = x - x0, y - y0, z[rows, cols]

    planes, labels = fit_planes(x, y, zz, p)
    if not planes:
        r = _nan_result(FIT_FAILED, n)
        return (r, None) if return_labels else r

    pixel_area = abs(transform.a * transform.e)
    primary = planes[0]
    resid = zz - (primary["gx"] * x + primary["gy"] * y + primary["c"])
    roughness = float(1.4826 * np.median(np.abs(resid - np.median(resid))))

    secondaries = planes[1:]
    offset_suspected = False
    multimodal = False
    real_planes = [0]  # planes considered as genuine roof planes (used to split)
    for k, s in enumerate(secondaries, start=1):
        implausible = s["tilt"] > p.max_tilt
        small = s["n_pixels"] * pixel_area < p.min_part_area
        on_edge = False
        if edge_distance is not None:
            d = edge_distance[rows[labels == k], cols[labels == k]]
            on_edge = (d <= p.edge_band).mean() >= p.edge_frac
        dominated = primary["share"] >= p.dominant_share
        if implausible or small or (on_edge and dominated):
            offset_suspected = True
        else:
            multimodal = True
            real_planes.append(k)

    # parallel planes with the same orientation (roof at several heights):
    # one orientation, measured on the main plane
    def same(a, b):
        if a["tilt"] < p.flat_tilt and b["tilt"] < p.flat_tilt:
            return True
        daz = abs((a["azimuth"] - b["azimuth"] + 180) % 360 - 180)
        return abs(a["tilt"] - b["tilt"]) <= p.same_tilt and daz <= p.same_azimuth
    if multimodal and all(same(primary, planes[k]) for k in real_planes[1:]):
        multimodal, real_planes = False, [0]

    modes = [dict(tilt=m["tilt"], azimuth=m["azimuth"], share=m["share"]) for m in planes]
    common = dict(n_pixels=n, n_modes=len(planes), primary_share=primary["share"],
                  inlier_frac=float((labels >= 0).mean()), roughness=roughness, modes=modes)
    if multimodal:
        r = _nan_result(MULTIMODAL, inspect=True, offset_suspected=offset_suspected, **common)
    else:
        tilt, az = primary["tilt"], primary["azimuth"]
        status = OK
        if tilt < p.flat_tilt:
            status, az = FLAT, np.nan
        r = dict(status=status, inspect=False, tilt=tilt, azimuth=az, rmse=primary["rmse"],
                 offset_suspected=offset_suspected, **common)
    if return_labels:
        return r, dict(rows=rows, cols=cols, labels=labels, planes=planes,
                       real_planes=real_planes)
    return r

Services

get_service

get_service(spec, **kwargs)

Builds a service from a specification: - a DSMService instance (returned as is) - a name from the catalogue (pypvroof.catalog), e.g. "fr-lidar" (IGNLidarService), "fr-correl" (IGNCorrelService), "nl-ahn", "uk-england", "ch-swisssurface3d"; **kwargs override its settings - a path to a folder -> LocalRasterService(folder, **kwargs)

Source code in pypvroof/dsm.py
def get_service(spec, **kwargs):
    """
    Builds a service from a specification:
      - a DSMService instance (returned as is)
      - a name from the catalogue (`pypvroof.catalog`), e.g. "fr-lidar"
        (IGNLidarService), "fr-correl" (IGNCorrelService), "nl-ahn",
        "uk-england", "ch-swisssurface3d"; `**kwargs` override its settings
      - a path to a folder -> LocalRasterService(folder, **kwargs)
    """
    from . import catalog
    if isinstance(spec, DSMService):
        return spec
    if isinstance(spec, str) and spec.lower() in catalog.SERVICES:
        return catalog.service(spec, **kwargs)
    if isinstance(spec, (str, os.PathLike)) and os.path.isdir(spec):
        return LocalRasterService(spec, **kwargs)
    raise ValueError("unknown DSM service: {!r} (see pypvroof.catalog.SERVICES)".format(spec))

available_services

available_services()

Table of the services of the catalogue (name, region, product, resolution, CRS, licence).

Source code in pypvroof/catalog.py
def available_services():
    """Table of the services of the catalogue (name, region, product, resolution, CRS, licence)."""
    import pandas as pd
    rows = [{"name": k, "region": e["region"], "product": e["product"], "resolution_m": e["resolution"],
             "crs": "EPSG:{}".format(e["crs"]), "licence": e["licence"]} for k, e in SERVICES.items()]
    return pd.DataFrame(rows)

services_at

services_at(lon, lat)

Names of the services whose approximate extent contains (lon, lat), the most specific first (smallest extent; catalogue order on ties, so that "fr-lidar" comes before "fr-correl"). The extents are rough: a service may still answer "no_coverage", in which case the next one can be tried.

Source code in pypvroof/catalog.py
def services_at(lon, lat):
    """
    Names of the services whose approximate extent contains (lon, lat), the
    most specific first (smallest extent; catalogue order on ties, so that
    "fr-lidar" comes before "fr-correl"). The extents are rough: a service may
    still answer "no_coverage", in which case the next one can be tried.
    """
    hits = [(i, k, e["bbox"]) for i, (k, e) in enumerate(SERVICES.items())
            if e["bbox"][0] <= lon <= e["bbox"][2] and e["bbox"][1] <= lat <= e["bbox"][3]]
    area = lambda b: (b[2] - b[0]) * (b[3] - b[1])
    return [k for i, k, b in sorted(hits, key=lambda h: (area(h[2]), h[0]))]

service

service(name, **overrides)

Builds the service name of the catalogue; overrides replace its settings.

Source code in pypvroof/catalog.py
def service(name, **overrides):
    """Builds the service `name` of the catalogue; `overrides` replace its settings."""
    e = SERVICES[name.lower()]
    if e["kind"] == "class":
        return getattr(dsm, e["cls"])(**overrides)
    kw = dict(e["kwargs"], crs=e["crs"], source=name.lower())
    if e["kind"] == "wcs":
        kw["resolution"] = e["resolution"]
        return dsm.WCSService(**dict(kw, **overrides))
    return dsm.STACCogService(**dict(kw, **overrides))

DSMService

Base class of the DSM services.

Subclasses set crs (the CRS of the elevation grids, in which polygons must be passed to fetch) and implement fetch(geometry).

Source code in pypvroof/dsm.py
class DSMService:
    """
    Base class of the DSM services.

    Subclasses set `crs` (the CRS of the elevation grids, in which polygons
    must be passed to `fetch`) and implement `fetch(geometry)`.
    """

    crs = None

    def fetch(self, geometry):
        """
        Returns a FetchResult for a shapely polygon expressed in `self.crs`.
        The grid must cover the polygon's bounding box (plus any margin).
        """
        raise NotImplementedError

fetch

fetch(geometry)

Returns a FetchResult for a shapely polygon expressed in self.crs. The grid must cover the polygon's bounding box (plus any margin).

Source code in pypvroof/dsm.py
def fetch(self, geometry):
    """
    Returns a FetchResult for a shapely polygon expressed in `self.crs`.
    The grid must cover the polygon's bounding box (plus any margin).
    """
    raise NotImplementedError

DSMPatch dataclass

Elevation grid around a polygon.

z : 2D float array of elevations (metres), NaN where there is no data transform : affine transform of the grid (rasterio convention, north up) crs : coordinate reference system of the grid (projected, metres)

Source code in pypvroof/dsm.py
@dataclass
class DSMPatch:
    """
    Elevation grid around a polygon.

    z         : 2D float array of elevations (metres), NaN where there is no data
    transform : affine transform of the grid (rasterio convention, north up)
    crs       : coordinate reference system of the grid (projected, metres)
    """
    z: np.ndarray
    transform: Affine
    crs: CRS

    @property
    def resolution(self):
        return abs(self.transform.a), abs(self.transform.e)

    def pixel_centers(self, rows, cols):
        """Coordinates (x, y) of the centers of the given pixels."""
        x = self.transform.c + (np.asarray(cols) + 0.5) * self.transform.a
        y = self.transform.f + (np.asarray(rows) + 0.5) * self.transform.e
        return x, y

pixel_centers

pixel_centers(rows, cols)

Coordinates (x, y) of the centers of the given pixels.

Source code in pypvroof/dsm.py
def pixel_centers(self, rows, cols):
    """Coordinates (x, y) of the centers of the given pixels."""
    x = self.transform.c + (np.asarray(cols) + 0.5) * self.transform.a
    y = self.transform.f + (np.asarray(rows) + 0.5) * self.transform.e
    return x, y

FetchResult dataclass

Source code in pypvroof/dsm.py
@dataclass
class FetchResult:
    status: str
    patch: Optional[DSMPatch] = None
    meta: dict = field(default_factory=dict)

IGNLidarService

Bases: RemoteDSMService

IGN LiDAR HD elevation models served by the Géoplateforme WMS-R (https://data.geopf.fr/wms-r), as raw float32 GeoTIFFs on any extent.

Parameters:

Name Type Description Default
product "MNS" (digital surface model, default), "MNT" or "MNH"
'MNS'
margin metres added around the polygon bounding box
1.0
resolution pixel size (0.5 m, the native resolution of the product)
0.5
grid_origin offset of the native pixel grid (the IGN tiles' edges are at

x.25 / x.75), so that requested pixels match native ones (no resampling)

0.25
timeout HTTP settings. Retries apply to network errors,

HTTP 429 and 5xx, with exponential backoff and jitter.

30
retries HTTP settings. Retries apply to network errors,

HTTP 429 and 5xx, with exponential backoff and jitter.

30
backoff HTTP settings. Retries apply to network errors,

HTTP 429 and 5xx, with exponential backoff and jitter.

30
fetch_metadata query the LiDAR HD WFS index for the acquisition metadata

of the tile containing the polygon (cached per 1 km tile)

True
user_agent User-Agent header sent to the service
None
Notes

meta keys: source, product, and if fetch_metadata: tile, date_debut_acquisition, date_fin_acquisition, date_edition, code_mission (or metadata_error). On errors: http_status, error.

Source code in pypvroof/dsm.py
class IGNLidarService(RemoteDSMService):
    """
    IGN LiDAR HD elevation models served by the Géoplateforme WMS-R
    (https://data.geopf.fr/wms-r), as raw float32 GeoTIFFs on any extent.

    Parameters
    ----------
    product : "MNS" (digital surface model, default), "MNT" or "MNH"
    margin : metres added around the polygon bounding box
    resolution : pixel size (0.5 m, the native resolution of the product)
    grid_origin : offset of the native pixel grid (the IGN tiles' edges are at
        x.25 / x.75), so that requested pixels match native ones (no resampling)
    timeout, retries, backoff : HTTP settings. Retries apply to network errors,
        HTTP 429 and 5xx, with exponential backoff and jitter.
    fetch_metadata : query the LiDAR HD WFS index for the acquisition metadata
        of the tile containing the polygon (cached per 1 km tile)
    user_agent : User-Agent header sent to the service

    Notes
    -----
    `meta` keys: source, product, and if fetch_metadata: tile,
    date_debut_acquisition, date_fin_acquisition, date_edition, code_mission
    (or metadata_error). On errors: http_status, error.
    """

    WMS_URL = "https://data.geopf.fr/wms-r"
    WFS_URL = "https://data.geopf.fr/wfs/ows"
    WFS_LAYER = "IGNF_LIDAR-HD_METADONNEE:metadata"
    MAX_PIXELS = 5000  # WMS-R accepts up to 5010 x 5010
    METADATA_KEYS = ("date_debut_acquisition", "date_fin_acquisition", "date_edition",
                     "code_mission", "coordonnees_nw")

    crs = CRS.from_epsg(2154)
    source = "ign-lidar-hd"
    attribution = "© IGN, LiDAR HD"

    def __init__(self, product="MNS", margin=1.0, resolution=0.5, grid_origin=0.25,
                 timeout=30, retries=3, backoff=1.0, fetch_metadata=True,
                 user_agent=None):
        product = product.upper()
        if product not in ("MNS", "MNT", "MNH"):
            raise ValueError("product must be MNS, MNT or MNH")
        self.product = product
        self.layer = "IGNF_LIDAR-HD_{}_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93".format(product)
        self.margin = margin
        self.resolution = resolution
        self.grid_origin = grid_origin
        self.fetch_metadata = fetch_metadata
        self._init_http(timeout, retries, backoff, user_agent)
        self._metadata_cache = {}
        self._metadata_lock = threading.Lock()

    # -- metadata -------------------------------------------------------------

    def _tile_metadata(self, x, y):
        key = (int(np.floor(x / 1000)), int(np.floor(y / 1000)))
        with self._metadata_lock:
            if key in self._metadata_cache:
                return self._metadata_cache[key]
        params = {
            "SERVICE": "WFS", "VERSION": "2.0.0", "REQUEST": "GetFeature",
            "TYPENAMES": self.WFS_LAYER, "OUTPUTFORMAT": "application/json",
            "PROPERTYNAME": ",".join(self.METADATA_KEYS),
            "BBOX": "{},{},{},{},urn:ogc:def:crs:EPSG::2154".format(x - 0.5, y - 0.5, x + 0.5, y + 0.5),
        }
        code, _, body = self._get(self.WFS_URL + "?" + urllib.parse.urlencode(params))
        if code != 200:
            return {"metadata_error": "WFS HTTP {}".format(code)}  # not cached: may be transient
        import json
        try:
            features = json.loads(body).get("features", [])
        except ValueError:
            return {"metadata_error": "invalid WFS response"}
        meta = {}
        if features:
            # several editions may exist: keep the latest
            props = max((f["properties"] for f in features), key=lambda p: p.get("date_edition") or "")
            for k in self.METADATA_KEYS:
                v = props.get(k)
                if isinstance(v, str) and k.startswith("date") and v.endswith("Z"):
                    v = v[:-1]
                meta["tile" if k == "coordonnees_nw" else k] = v
        with self._metadata_lock:
            self._metadata_cache[key] = meta
        return meta

    # -- fetch ------------------------------------------------------------------

    def fetch(self, geometry):
        meta = {"source": self.source, "product": self.product}
        (minx, miny, maxx, maxy), width, height = self._extent(geometry)
        res = self.resolution
        if width > self.MAX_PIXELS or height > self.MAX_PIXELS:
            return FetchResult(TOO_LARGE, None, meta)

        params = {
            "SERVICE": "WMS", "VERSION": "1.3.0", "REQUEST": "GetMap", "LAYERS": self.layer,
            "FORMAT": "image/geotiff", "STYLES": "", "CRS": "EPSG:2154",
            "BBOX": "{},{},{},{}".format(minx, miny, maxx, maxy),
            "WIDTH": width, "HEIGHT": height,
        }
        code, ctype, body = self._get(self.WMS_URL + "?" + urllib.parse.urlencode(params))
        if code != 200 or "tiff" not in ctype:
            return self._error(meta, code, body)

        with rasterio.MemoryFile(body) as mem, mem.open() as ds:
            z = _clean(ds.read(1), ds.nodata)
        # the CRS of the response is written as a degraded WKT: use the
        # requested one and rebuild the transform from the requested bbox
        transform = Affine(res, 0, minx, 0, -res, maxy)
        patch = DSMPatch(z, transform, self.crs)

        if self.fetch_metadata:
            c = geometry.centroid
            meta.update(self._tile_metadata(c.x, c.y))
        if not np.isfinite(z).any():
            return FetchResult(NO_COVERAGE, None, meta)
        return FetchResult(OK, patch, meta)

IGNCorrelService

Bases: IGNLidarService

IGN "MNS Correl" surface model (50 cm), served by the Géoplateforme WMS-R.

It is computed by correlation of the aerial images of the BD ORTHO, i.e. from the same images as the orthophotos: it is consistent in time and geometry with detections made on the BD ORTHO, and covers areas without LiDAR HD. Correlation is less precise than LiDAR, especially on low-texture surfaces (dark panels, uniform roofs) and near roof edges.

Same parameters as IGNLidarService, without product; there is no acquisition metadata index (fetch_metadata is ignored). meta keys: source ("ign-mns-correl"), product.

Source code in pypvroof/dsm.py
class IGNCorrelService(IGNLidarService):
    """
    IGN "MNS Correl" surface model (50 cm), served by the Géoplateforme WMS-R.

    It is computed by correlation of the aerial images of the BD ORTHO, i.e.
    from the same images as the orthophotos: it is consistent in time and
    geometry with detections made on the BD ORTHO, and covers areas without
    LiDAR HD. Correlation is less precise than LiDAR, especially on low-texture
    surfaces (dark panels, uniform roofs) and near roof edges.

    Same parameters as IGNLidarService, without `product`; there is no
    acquisition metadata index (`fetch_metadata` is ignored).
    `meta` keys: source ("ign-mns-correl"), product.
    """

    source = "ign-mns-correl"
    attribution = "© IGN, MNS Correl"

    def __init__(self, margin=1.0, resolution=0.5, grid_origin=0.25, timeout=30,
                 retries=3, backoff=1.0, fetch_metadata=False, user_agent=None):
        super().__init__("MNS", margin=margin, resolution=resolution, grid_origin=grid_origin,
                         timeout=timeout, retries=retries, backoff=backoff,
                         fetch_metadata=False, user_agent=user_agent)
        self.product = "MNS-CORREL"
        self.layer = "ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES.MNS"

LocalRasterService

Bases: DSMService

Elevation rasters stored locally.

Expected format: single-band GeoTIFFs whose pixel values are elevations (in metres), georeferenced in a projected CRS (Lambert-93 / EPSG:2154 for IGN products, e.g. LiDAR HD MNS tiles or a thumbnail exported from the WMS-R). Any file name is accepted; the folder is indexed by extent when the service is created. All rasters must share the same CRS. A polygon spanning several rasters is handled (the rasters are mosaicked).

Parameters:

Name Type Description Default
folder directory containing the rasters
required
pattern glob pattern of the raster files (searched recursively)
'*.tif'
margin metres added around the polygon bounding box
1.0
crs CRS to assume for rasters without one
None
Notes

meta keys: source ("local"), files (names of the rasters used), and tags (the GeoTIFF tags of the first raster, if any).

Source code in pypvroof/dsm.py
class LocalRasterService(DSMService):
    """
    Elevation rasters stored locally.

    Expected format: single-band GeoTIFFs whose pixel values are elevations
    (in metres), georeferenced in a projected CRS (Lambert-93 / EPSG:2154 for
    IGN products, e.g. LiDAR HD MNS tiles or a thumbnail exported from the
    WMS-R). Any file name is accepted; the folder is indexed by extent when
    the service is created. All rasters must share the same CRS. A polygon
    spanning several rasters is handled (the rasters are mosaicked).

    Parameters
    ----------
    folder : directory containing the rasters
    pattern : glob pattern of the raster files (searched recursively)
    margin : metres added around the polygon bounding box
    crs : CRS to assume for rasters without one

    Notes
    -----
    `meta` keys: source ("local"), files (names of the rasters used), and
    tags (the GeoTIFF tags of the first raster, if any).
    """

    def __init__(self, folder, pattern="*.tif", margin=1.0, crs=None):
        self.folder = folder
        self.margin = margin
        paths = sorted(glob.glob(os.path.join(folder, "**", pattern), recursive=True))
        if not paths:
            raise ValueError("no raster matching {!r} in {}".format(pattern, folder))
        self.paths, boxes, crss = [], [], set()
        self._info = []
        for p in paths:
            with rasterio.open(p) as ds:
                crs_ = ds.crs or (CRS.from_user_input(crs) if crs else None)
                if crs_ is None:
                    raise ValueError("{} has no CRS; pass `crs`".format(p))
                crss.add(crs_.to_wkt())
                self.paths.append(p)
                boxes.append(box(*ds.bounds))
                self._info.append((ds.transform, ds.res, ds.nodata))
        if len(crss) > 1:
            raise ValueError("all rasters must share the same CRS")
        self.crs = CRS.from_wkt(crss.pop())
        self._boxes = boxes
        self._tree = STRtree(boxes)

    def fetch(self, geometry):
        meta = {"source": "local"}
        minx, miny, maxx, maxy = geometry.bounds
        query = box(minx - self.margin, miny - self.margin, maxx + self.margin, maxy + self.margin)
        idx = sorted(self._tree.query(query, predicate="intersects"))
        if not idx:
            return FetchResult(NO_COVERAGE, None, meta)

        transform, (xres, yres), nodata = self._info[idx[0]]
        minx, maxx = _snap(query.bounds[0], query.bounds[2], xres, transform.c)
        miny, maxy = _snap(query.bounds[1], query.bounds[3], yres, transform.f)
        datasets = [rasterio.open(self.paths[i]) for i in idx]
        try:
            fill = -99999.0
            arr, out_transform = rasterio.merge.merge(
                datasets, bounds=(minx, miny, maxx, maxy), res=(xres, yres),
                nodata=fill, dtype="float64")
            z = _clean(arr[0], fill)
            if nodata is not None:
                z[arr[0] == nodata] = np.nan
            tags = datasets[0].tags()
        finally:
            for ds in datasets:
                ds.close()
        meta["files"] = [os.path.basename(self.paths[i]) for i in idx]
        if tags:
            meta["tags"] = tags
        if not np.isfinite(z).any():
            return FetchResult(NO_COVERAGE, None, meta)
        return FetchResult(OK, DSMPatch(z, out_transform, self.crs), meta)

WCSService

Bases: RemoteDSMService

Elevation model served by an OGC Web Coverage Service (WCS 2.0.1 or 1.0.0) returning GeoTIFFs. Most national LiDAR surface models in Europe are published this way; see pypvroof.catalog for ready-made presets.

Parameters:

Name Type Description Default
url endpoint of the WCS (without query string)
required
coverage coverage identifier (CoverageId in 2.0.1, coverage in 1.0.0)
required
crs CRS of the coverage (EPSG code or any pyproj input); polygons are

reprojected to it

required
resolution native pixel size (metres)
required
grid_origin offset of the native pixel grid (0 for grids aligned on

whole metres)

0.0
version "2.0.1" (subsets in native pixels) or "1.0.0" (bbox + size)
'2.0.1'
axis_labels labels of the (easting, northing) axes for 2.0.1 subsets,

as given by DescribeCoverage (e.g. ("x", "y"), ("E", "N"))

('x', 'y')
format output format requested
'image/tiff'
source name reported in `meta["source"]`
None
attribution licence / attribution string reported in `meta`
None
margin as for IGNLidarService
1.0
timeout as for IGNLidarService
1.0
retries as for IGNLidarService
1.0
backoff as for IGNLidarService
1.0
user_agent as for IGNLidarService
1.0
Notes

meta keys: source, coverage, attribution. On errors: http_status, error.

Source code in pypvroof/dsm.py
class WCSService(RemoteDSMService):
    """
    Elevation model served by an OGC Web Coverage Service (WCS 2.0.1 or
    1.0.0) returning GeoTIFFs. Most national LiDAR surface models in Europe
    are published this way; see `pypvroof.catalog` for ready-made presets.

    Parameters
    ----------
    url : endpoint of the WCS (without query string)
    coverage : coverage identifier (CoverageId in 2.0.1, coverage in 1.0.0)
    crs : CRS of the coverage (EPSG code or any pyproj input); polygons are
        reprojected to it
    resolution : native pixel size (metres)
    grid_origin : offset of the native pixel grid (0 for grids aligned on
        whole metres)
    version : "2.0.1" (subsets in native pixels) or "1.0.0" (bbox + size)
    axis_labels : labels of the (easting, northing) axes for 2.0.1 subsets,
        as given by DescribeCoverage (e.g. ("x", "y"), ("E", "N"))
    format : output format requested
    source : name reported in `meta["source"]`
    attribution : licence / attribution string reported in `meta`
    margin, timeout, retries, backoff, user_agent : as for IGNLidarService

    Notes
    -----
    `meta` keys: source, coverage, attribution. On errors: http_status, error.
    """

    def __init__(self, url, coverage, crs, resolution, grid_origin=0.0, version="2.0.1",
                 axis_labels=("x", "y"), format="image/tiff", source=None, attribution=None,
                 extra_params=None, margin=1.0, timeout=30, retries=3, backoff=1.0,
                 user_agent=None):
        if version not in ("2.0.1", "1.0.0"):
            raise ValueError("version must be 2.0.1 or 1.0.0")
        self.url, self.coverage, self.version = url, coverage, version
        self.crs = CRS.from_user_input(crs)
        self.resolution, self.grid_origin, self.margin = resolution, grid_origin, margin
        self.axis_labels, self.format = axis_labels, format
        self.source = source or "wcs:{}".format(coverage)
        self.attribution = attribution
        self.extra_params = dict(extra_params or {})
        self._init_http(timeout, retries, backoff, user_agent)

    def _url(self, minx, miny, maxx, maxy, width, height):
        if self.version == "1.0.0":
            q = [("SERVICE", "WCS"), ("VERSION", "1.0.0"), ("REQUEST", "GetCoverage"),
                 ("COVERAGE", self.coverage), ("CRS", "EPSG:{}".format(self.crs.to_epsg())),
                 ("BBOX", "{},{},{},{}".format(minx, miny, maxx, maxy)),
                 ("WIDTH", width), ("HEIGHT", height), ("FORMAT", self.format)]
        else:
            ex, ny = self.axis_labels
            q = [("SERVICE", "WCS"), ("VERSION", "2.0.1"), ("REQUEST", "GetCoverage"),
                 ("COVERAGEID", self.coverage), ("FORMAT", self.format),
                 ("SUBSET", "{}({},{})".format(ex, minx, maxx)),
                 ("SUBSET", "{}({},{})".format(ny, miny, maxy))]
        q += list(self.extra_params.items())
        return self.url + "?" + urllib.parse.urlencode(q)

    def fetch(self, geometry):
        meta = {"source": self.source, "coverage": self.coverage}
        if self.attribution:
            meta["attribution"] = self.attribution
        (minx, miny, maxx, maxy), width, height = self._extent(geometry)
        if width > self.MAX_PIXELS or height > self.MAX_PIXELS:
            return FetchResult(TOO_LARGE, None, meta)
        code, ctype, body = self._get(self._url(minx, miny, maxx, maxy, width, height))
        data = self._tiff_bytes(ctype, body) if code == 200 else None
        if data is None:
            return self._error(meta, code, body)
        with rasterio.MemoryFile(data) as mem, mem.open() as ds:
            z = _clean(ds.read(1), ds.nodata)
            transform = ds.transform
            if transform.is_identity or transform.e > 0:  # no / south-up georeferencing
                transform = Affine((maxx - minx) / z.shape[1], 0, minx, 0, -(maxy - miny) / z.shape[0], maxy)
        if not np.isfinite(z).any():
            return FetchResult(NO_COVERAGE, None, meta)
        return FetchResult(OK, DSMPatch(z, transform, self.crs), meta)

STACCogService

Bases: RemoteDSMService

Elevation model published as Cloud-Optimized GeoTIFF tiles indexed by a STAC API (e.g. swisstopo swissSURFACE3D Raster). For each polygon, the tiles intersecting it are found with a STAC search (cached per tile footprint) and only the needed window is read (HTTP range requests).

Parameters:

Name Type Description Default
stac_url STAC API root (e.g. https://data.geo.admin.ch/api/stac/v0.9)
required
collection collection id
required
crs CRS of the tiles
required
asset_filter function (asset_key, asset_dict) -> bool selecting the

GeoTIFF asset of an item

required
tile_size size (metres) of the tiles, used to cache the searches
1000.0
latest when several items cover a tile (several acquisitions), keep

the most recent one

True
source as

for WCSService

None
attribution as

for WCSService

None
margin as

for WCSService

None
timeout as

for WCSService

None
retries as

for WCSService

None
backoff as

for WCSService

None
user_agent as

for WCSService

None
Notes

meta keys: source, attribution, items (ids of the items used), datetime (acquisition date of the items, if given).

Source code in pypvroof/dsm.py
class STACCogService(RemoteDSMService):
    """
    Elevation model published as Cloud-Optimized GeoTIFF tiles indexed by a
    STAC API (e.g. swisstopo swissSURFACE3D Raster). For each polygon, the
    tiles intersecting it are found with a STAC search (cached per tile
    footprint) and only the needed window is read (HTTP range requests).

    Parameters
    ----------
    stac_url : STAC API root (e.g. https://data.geo.admin.ch/api/stac/v0.9)
    collection : collection id
    crs : CRS of the tiles
    asset_filter : function (asset_key, asset_dict) -> bool selecting the
        GeoTIFF asset of an item
    tile_size : size (metres) of the tiles, used to cache the searches
    latest : when several items cover a tile (several acquisitions), keep
        the most recent one
    source, attribution, margin, timeout, retries, backoff, user_agent : as
        for WCSService

    Notes
    -----
    `meta` keys: source, attribution, items (ids of the items used),
    datetime (acquisition date of the items, if given).
    """

    def __init__(self, stac_url, collection, crs, asset_filter, tile_size=1000.0, latest=True,
                 source=None, attribution=None, margin=1.0, timeout=30, retries=3, backoff=1.0,
                 user_agent=None):
        from pyproj import Transformer
        self.stac_url, self.collection = stac_url.rstrip("/"), collection
        self.crs = CRS.from_user_input(crs)
        self.asset_filter, self.tile_size, self.latest = asset_filter, tile_size, latest
        self.source = source or "stac:{}".format(collection)
        self.attribution = attribution
        self.margin = margin
        self._to_lonlat = Transformer.from_crs(self.crs, "EPSG:4326", always_xy=True)
        self._cache, self._lock = {}, threading.Lock()
        self._init_http(timeout, retries, backoff, user_agent)

    def _items(self, tx, ty):
        """Items covering the tile (tx, ty), from the STAC API (cached)."""
        key = (tx, ty)
        with self._lock:
            if key in self._cache:
                return self._cache[key]
        import json
        s = self.tile_size
        # a point well inside the tile, to avoid neighbours touching its edges
        lon, lat = self._to_lonlat.transform((tx + 0.5) * s, (ty + 0.5) * s)
        q = {"bbox": "{},{},{},{}".format(lon, lat, lon, lat), "limit": 50}
        url = "{}/collections/{}/items?{}".format(self.stac_url, self.collection, urllib.parse.urlencode(q))
        code, _, body = self._get(url)
        if code != 200:
            return None  # not cached: may be transient
        items = []
        for f in json.loads(body).get("features", []):
            href = next((a["href"] for k, a in f.get("assets", {}).items() if self.asset_filter(k, a)), None)
            if href:
                items.append((f["properties"].get("datetime") or "", f["id"], href))
        if self.latest and items:
            items = [max(items)]
        with self._lock:
            self._cache[key] = items
        return items

    def fetch(self, geometry):
        meta = {"source": self.source}
        if self.attribution:
            meta["attribution"] = self.attribution
        minx, miny, maxx, maxy = geometry.buffer(self.margin).bounds
        s = self.tile_size
        found = []
        for tx in range(int(np.floor(minx / s)), int(np.floor(maxx / s)) + 1):
            for ty in range(int(np.floor(miny / s)), int(np.floor(maxy / s)) + 1):
                items = self._items(tx, ty)
                if items is None:
                    meta["error"] = "STAC search failed"
                    return FetchResult(SERVICE_ERROR, None, meta)
                found += items
        if not found:
            return FetchResult(NO_COVERAGE, None, meta)
        meta["items"] = [i for _, i, _ in found]
        dates = sorted({d[:10] for d, _, _ in found if d})
        if dates:
            meta["datetime"] = dates[-1] if len(dates) == 1 else dates
        env = rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", GDAL_HTTP_MAX_RETRY=str(self.retries),
                           GDAL_HTTP_RETRY_DELAY=str(self.backoff), GDAL_HTTP_USERAGENT=self.user_agent)
        try:
            with env:
                datasets = [rasterio.open("/vsicurl/" + h) for _, _, h in found]
                try:
                    t = datasets[0].transform
                    xres, yres = datasets[0].res
                    bx = _snap(minx, maxx, xres, t.c)
                    by = _snap(miny, maxy, yres, t.f)
                    fill = -99999.0
                    arr, out_transform = rasterio.merge.merge(
                        datasets, bounds=(bx[0], by[0], bx[1], by[1]), res=(xres, yres),
                        nodata=fill, dtype="float64")
                    nodata = datasets[0].nodata
                finally:
                    for ds in datasets:
                        ds.close()
        except rasterio.errors.RasterioIOError as e:
            meta["error"] = str(e)[:300]
            return FetchResult(SERVICE_ERROR, None, meta)
        z = _clean(arr[0], fill)
        if nodata is not None:
            z[arr[0] == nodata] = np.nan
        if not np.isfinite(z).any():
            return FetchResult(NO_COVERAGE, None, meta)
        return FetchResult(OK, DSMPatch(z, out_transform, self.crs), meta)

Visualization

plot_polygon

plot_polygon(polygon, services=('fr-lidar', 'fr-correl'), crs=None, margin=6.0, params=None, ortho=None, figsize_per_panel=(5.0, 4.2))

Figure with the orthophoto (if ortho) and, below, the elevation grid of each service around the polygon, with the estimated tilt / azimuth.

polygon : a GeoJSON feature / geometry, a shapely polygon, or a one-row GeoDataFrame (CRS from crs, default EPSG:4326) services : services or specifications ("fr-lidar", "fr-correl", "nl-ahn", a folder...) ortho : show the IGN orthophoto (France only); by default, when the first service is an IGN one

Source code in pypvroof/viz.py
def plot_polygon(polygon, services=("fr-lidar", "fr-correl"), crs=None, margin=6.0, params=None,
                 ortho=None, figsize_per_panel=(5.0, 4.2)):
    """
    Figure with the orthophoto (if `ortho`) and, below, the elevation grid of
    each service around the polygon, with the estimated tilt / azimuth.

    polygon  : a GeoJSON feature / geometry, a shapely polygon, or a one-row
               GeoDataFrame (CRS from `crs`, default EPSG:4326)
    services : services or specifications ("fr-lidar", "fr-correl", "nl-ahn", a folder...)
    ortho    : show the IGN orthophoto (France only); by default, when the
               first service is an IGN one
    """
    import matplotlib.pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap

    gdf = to_geodataframe(polygon if not hasattr(polygon, "iloc") else polygon.iloc[:1], crs=crs)
    services = [dsm.get_service(s) for s in services]
    # the panels share the extent of the first service's grid (IGN: Lambert-93)
    target = services[0].crs
    if ortho is None:
        ortho = getattr(services[0], "source", "").startswith("ign")
    geom = _polygonal(reproject(gdf.geometry.iloc[0], gdf.crs, target))

    panels = []
    for svc in services:
        g = reproject(geom, target, svc.crs)
        fr = svc.fetch(g.buffer(margin))  # bigger window for context
        [(_, r, _)] = characterize_polygon(g, svc, params)
        panels.append((svc, fr, r))

    ref = next((fr.patch for _, fr, _ in panels if fr.patch is not None), None)
    if ref is None:
        minx, miny, maxx, maxy = geom.buffer(margin).bounds
    else:
        t, (h, w) = ref.transform, ref.z.shape
        minx, maxx, miny, maxy = t.c, t.c + w * t.a, t.f + h * t.e, t.f
    extent = (minx, maxx, miny, maxy)

    zs = [fr.patch.z for _, fr, _ in panels if fr.patch is not None]
    vals = np.concatenate([z[np.isfinite(z)] for z in zs]) if zs else np.array([0.0, 1.0])
    vmin, vmax = np.percentile(vals, [2, 98]) if vals.size else (0, 1)

    n = len(panels) + (1 if ortho else 0)
    fig, axes = plt.subplots(n, 1, figsize=(figsize_per_panel[0], figsize_per_panel[1] * n),
                             constrained_layout=True, squeeze=False)
    axes = axes[:, 0]
    cmap = LinearSegmentedColormap.from_list("elevation", ELEVATION_RAMP)
    xs, ys = geom.exterior.xy if geom.geom_type == "Polygon" else max(geom.geoms, key=lambda p: p.area).exterior.xy

    def outline(ax):
        ax.plot(xs, ys, color="#ffffff", lw=2.2)
        ax.plot(xs, ys, color=TEXT, lw=1.0)
        ax.set_xlim(minx, maxx)
        ax.set_ylim(miny, maxy)
        ax.set_xticks([])
        ax.set_yticks([])
        for s in ax.spines.values():
            s.set_visible(False)

    i = 0
    if ortho:
        ax = axes[0]
        try:
            ax.imshow(fetch_ortho((minx, miny, maxx, maxy)), extent=extent)
        except Exception as e:  # orthophoto is a nice-to-have
            ax.text(0.5, 0.5, "orthophoto indisponible\n{}".format(type(e).__name__),
                    ha="center", va="center", transform=ax.transAxes, color=TEXT2)
        ax.set_title("Orthophoto (BD ORTHO) — surface projetée {:.0f} m²".format(geom.area),
                     loc="left", color=TEXT, fontsize=10)
        x0, y0 = minx + 1, miny + 1
        ax.plot([x0, x0 + 5], [y0, y0], color="#ffffff", lw=4, solid_capstyle="butt")
        ax.text(x0 + 2.5, y0 + 0.6, "5 m", color="#ffffff", ha="center", fontsize=9, weight="bold")
        outline(ax)
        i = 1

    for svc, fr, r in panels:
        ax = axes[i]
        i += 1
        title = "{} — {}".format(_label(svc), _fmt(r))
        acq = fr.meta.get("date_fin_acquisition")
        if acq:
            title += "\nacquisition LiDAR {}".format(str(acq)[:10])
        if fr.patch is not None:
            t, (h, w) = fr.patch.transform, fr.patch.z.shape
            im = ax.imshow(fr.patch.z, extent=(t.c, t.c + w * t.a, t.f + h * t.e, t.f), cmap=cmap,
                           vmin=vmin, vmax=vmax, interpolation="nearest")
            cb = fig.colorbar(im, ax=ax, shrink=0.8, pad=0.02)
            cb.set_label("Altitude (m)", color=TEXT2)
            cb.outline.set_visible(False)
        else:
            ax.text(0.5, 0.5, fr.status, ha="center", va="center", transform=ax.transAxes, color=TEXT2)
        ax.set_title(title, loc="left", color=TEXT, fontsize=10)
        outline(ax)
    return fig