Source code for windkit.io.wasp.lib

"""Read and write WAsP .lib files.

The .lib format stores generalized wind climate data as Weibull
parameters (A, k) and wind direction frequencies for a single point
across multiple generalized roughness classes and heights.

Data contract: wdfreq values are stored as percentages (0-100) in the
file but returned/expected as normalized fractions (0-1) by these
functions. Conversion happens automatically. A and k are raw Weibull
parameters (no conversion).
"""

import re

import numpy as np

from windkit._errors import WindkitFileFormatError
from windkit.io.wasp._common import detect_encoding


def _floats(fields, filepath, what):
    """Convert whitespace-split fields to floats, reporting where they came from."""
    try:
        return [float(x) for x in fields]
    except ValueError:
        raise WindkitFileFormatError(
            f"{filepath}: {what} holds a value that is not a number: "
            f"{' '.join(fields)!r}"
        ) from None


def _read_floats(f, n, filepath):
    """Read a row of *n* floats from *f*, accumulating across wrapped lines."""
    values = []
    while len(values) < n:
        line = f.readline()
        if not line:
            raise WindkitFileFormatError(
                f"{filepath}: unexpected end of file, expected {n} values, "
                f"got {len(values)}"
            )
        values.extend(_floats(line.split(), filepath, "row"))
    if len(values) != n:
        raise WindkitFileFormatError(
            f"{filepath}: row has {len(values)} values, expected {n}"
        )
    return values


[docs] def read_lib(filepath, encoding="infer"): """Read a WAsP .lib file and return parsed data. Parameters ---------- filepath : str or Path Path to the ``.lib`` file. encoding : str, optional File encoding. If ``"infer"`` (default), the encoding is detected automatically. Returns ------- dict Dictionary with keys: - ``"A"`` : ndarray, shape (n_sectors, n_heights, n_roughnesses) - ``"k"`` : ndarray, same shape as *A* - ``"wdfreq"`` : ndarray, shape (n_sectors, n_roughnesses), normalized values (0-1) - ``"gen_roughness"`` : ndarray, shape (n_roughnesses,) - ``"gen_height"`` : ndarray, shape (n_heights,) - ``"coords"`` : dict with ``"west_east"``, ``"south_north"``, ``"height"`` (values are *None* when the file has no ``<coordinates>`` tag) - ``"metadata"`` : dict with ``"description"`` Raises ------ WindkitFileFormatError If the encoding cannot be detected; if the header line does not hold three integers; if a roughness, height, row or ``<coordinates>`` value is not a number; if the file ends before a row is complete; if a row holds more values than the header declares; or if the first generalized roughness is not 0.0. """ if encoding == "infer": encoding = detect_encoding(filepath) with open(filepath, encoding=encoding) as f: desc = f.readline().strip() header = f.readline().split() if len(header) != 3: raise WindkitFileFormatError( f"{filepath}: header line must hold 3 counts (roughnesses, " f"heights, sectors), got {len(header)}" ) try: n_roughnesses, n_heights, n_sectors = (int(x) for x in header) except ValueError: raise WindkitFileFormatError( f"{filepath}: header line holds a value that is not an integer: " f"{' '.join(header)!r}" ) from None gen_roughness = np.array( _floats(f.readline().split(), filepath, "roughness line"), dtype=np.float64, ) gen_height = np.array( _floats(f.readline().split(), filepath, "height line"), dtype=np.float64, ) wdfreq = np.zeros((n_sectors, n_roughnesses), dtype=np.float64) A = np.zeros((n_sectors, n_heights, n_roughnesses), dtype=np.float64) k = np.zeros((n_sectors, n_heights, n_roughnesses), dtype=np.float64) for i in range(n_roughnesses): wdfreq[:, i] = _read_floats(f, n_sectors, filepath) for j in range(n_heights): A[:, j, i] = _read_floats(f, n_sectors, filepath) k[:, j, i] = _read_floats(f, n_sectors, filepath) coords = {"west_east": None, "south_north": None, "height": None} match = re.search(r"<coordinates>(.*?)</coordinates>", desc) if match: fields = match.group(1).split(",") if len(fields) != 3: raise WindkitFileFormatError( f"{filepath}: <coordinates> must hold 3 comma-separated values, " f"got {match.group(1)!r}" ) we, sn, h = _floats(fields, filepath, "<coordinates> tag") coords = {"west_east": we, "south_north": sn, "height": h} if gen_roughness[0] != 0.0: raise WindkitFileFormatError( f"The first generalized roughness must be 0.0, got {gen_roughness[0]}" ) # Normalize wdfreq from percent (0-100) to fraction (0-1) wdfreq_sum = wdfreq.sum(axis=0, keepdims=True) wdfreq_sum[wdfreq_sum == 0] = 1.0 # avoid division by zero wdfreq = wdfreq / wdfreq_sum return { "A": A, "k": k, "wdfreq": wdfreq, "gen_roughness": gen_roughness, "gen_height": gen_height, "coords": coords, "metadata": {"description": desc}, }
[docs] def format_lib(A, k, wdfreq, gen_roughness, gen_height, coords, metadata=None): """Format Weibull parameters as a .lib file content string. Parameters ---------- A : array_like, shape (n_sectors, n_heights, n_roughnesses) Weibull A parameters. k : array_like, shape (n_sectors, n_heights, n_roughnesses) Weibull k parameters. wdfreq : array_like, shape (n_sectors, n_roughnesses) Normalized wind direction frequencies (0-1). gen_roughness : array_like, shape (n_roughnesses,) Generalized roughness classes. gen_height : array_like, shape (n_heights,) Generalized heights. coords : dict Dictionary with ``"west_east"``, ``"south_north"``, ``"height"``. metadata : dict, optional Dictionary with ``"description"`` key. Returns ------- str File content string (with ``\\n`` line endings). """ A = np.asarray(A) k = np.asarray(k) wdfreq = np.asarray(wdfreq) * 100.0 # Convert from fraction (0-1) to percent gen_roughness = np.asarray(gen_roughness) gen_height = np.asarray(gen_height) if gen_roughness[0] != 0.0: raise ValueError( f"The first generalized roughness must be 0.0, got {gen_roughness[0]}" ) n_roughnesses = len(gen_roughness) n_heights = len(gen_height) n_sectors = A.shape[0] lines = [] # Description line with coordinate tag description = metadata.get("description", "") if metadata else "" description = re.sub(r"<coordinates>.*?</coordinates>", "", description) coord_tag = "" if coords and coords.get("west_east") is not None: coord_tag = ( f"<coordinates>" f"{coords['west_east']},{coords['south_north']},{coords['height']}" f"</coordinates>" ) lines.append(description + coord_tag) # Dimensions: n_roughnesses, n_heights, n_sectors lines.append(f"{n_roughnesses} {n_heights} {n_sectors}") # Roughness classes lines.append(" ".join(f"{v:9.3f}" for v in gen_roughness)) # Heights lines.append(" ".join(f"{v:9.1f}" for v in gen_height)) # Data arrays for i in range(n_roughnesses): lines.append("".join(f"{v:9.2f}" for v in wdfreq[:, i])) for j in range(n_heights): lines.append("".join(f"{v:9.2f}" for v in A[:, j, i])) lines.append("".join(f"{v:9.3f}" for v in k[:, j, i])) return "\n".join(lines) + "\n"
[docs] def write_lib(filepath, A, k, wdfreq, gen_roughness, gen_height, coords, metadata=None): """Write Weibull parameters to a WAsP .lib file. Parameters ---------- filepath : str or Path Output file path. A : array_like, shape (n_sectors, n_heights, n_roughnesses) Weibull A parameters. k : array_like, shape (n_sectors, n_heights, n_roughnesses) Weibull k parameters. wdfreq : array_like, shape (n_sectors, n_roughnesses) Normalized wind direction frequencies (0-1). gen_roughness : array_like, shape (n_roughnesses,) Generalized roughness classes. gen_height : array_like, shape (n_heights,) Generalized heights. coords : dict Dictionary with ``"west_east"``, ``"south_north"``, ``"height"``. metadata : dict, optional Dictionary with ``"description"`` key. """ content = format_lib(A, k, wdfreq, gen_roughness, gen_height, coords, metadata) with open(filepath, "w", newline="\r\n") as f: f.write(content)