Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/jmrplens/phonometry. Standards-conformant acoustics library for Python: measurement and metrology, docs.jmrp.io/phonometry
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607# Copyright (c) 2026. Jose Manuel Requena Plens"""The gate on results that keep the caller's array instead of a copy.
``scripts/check_array_aliasing.py`` follows every parameter of every functionof the package to the places an array is kept. Its own run only says the treeis clean today; these tests fix what it must catch, on small packages writtenfor the purpose. The defects are here in the shapes the tree held them in:the ISO 3743 helper that read the band frequencies with ``np.asarray``, thevalidation helper whose return is the caller's array, the coupler record thatcleared the writeable flag on the caller's own columns, and the copy of acaller's record made with ``dataclasses.replace``. So are the shapes it mustleave alone, because a gate that refuses ``levels[levels > 0]`` or``levels - 10.0`` would be switched off within a week."""
from __future__ import annotations
import pathlibimport sysimport textwrap
import pytest
_SCRIPTS = str(pathlib.Path(__file__).resolve().parent.parent / "scripts")if _SCRIPTS not in sys.path: sys.path.insert(0, _SCRIPTS)
import ast_scanimport check_array_aliasing as caa
#: The helpers every package below imports, as the real one spells them._FROZEN = """import numpy as np
def read_only(array): array.flags.writeable = False return array
def read_only_copy(array, dtype=None): if array is None: return None return read_only(np.array(array, dtype=dtype))
class OwnsArrays: def __post_init__(self): pass
def handed_over(array): return array"""
#: A validation helper of the kind ``_internal/validation.py`` holds: its#: return is the caller's array whenever that is already ``float64``._VALIDATION = """import numpy as np
def require_finite_array(x, name): arr = np.atleast_1d(np.asarray(x, dtype=np.float64)) if not np.all(np.isfinite(arr)): raise ValueError(name) return arr"""
_RESULT = """from dataclasses import dataclass
import numpy as npfrom numpy.typing import NDArray
@dataclass(frozen=True)class BandResult: frequencies: NDArray[np.float64] levels: NDArray[np.float64] | None label: str = """""
def _findings(tmp_path: pathlib.Path, **modules: str) -> set[tuple[str, str, str]]: """``(function, sink, parameters)`` for a package of the modules given.
The package is ``pkg`` with the two private helpers above beside the modules, so ``from ._internal.frozen import read_only_copy`` reads as it does in the tree. """ root = _package(tmp_path, modules) found = caa.findings_in(sorted(root.rglob("*.py")), root) return {(f.function, f.sink, ", ".join(f.parameters)) for f in found}
def _unequipped(tmp_path: pathlib.Path, **modules: str) -> set[str]: """The public records of the package that can hold an array and do not inherit ``OwnsArrays``, by qualified class name. """ root = _package(tmp_path, modules) found = caa.records_without_mechanism(sorted(root.rglob("*.py")), root) return {f.function for f in found}
def _package(tmp_path: pathlib.Path, modules: dict[str, str]) -> pathlib.Path: """Write ``pkg`` with the helpers above and *modules*, and return it.""" root = tmp_path / "pkg" files = { "__init__.py": "", "_internal/__init__.py": "", "_internal/frozen.py": _FROZEN, "_internal/validation.py": _VALIDATION, "results.py": _RESULT, **{f"{name}.py": source for name, source in modules.items()}, } for name, source in files.items(): path = root / name path.parent.mkdir(parents=True, exist_ok=True) path.write_text(textwrap.dedent(source), encoding="utf-8") return root
# ---------------------------------------------------------------------------# The defects, as the tree held them# ---------------------------------------------------------------------------
def test_the_iso_3743_helper_before_its_fix_is_refused(tmp_path: pathlib.Path) -> None: """``_octave_frequencies`` read the bands with ``np.asarray`` (#915).""" found = _findings( tmp_path, power=""" import numpy as np
from .results import BandResult
def _octave_frequencies(frequencies, n_bands): freqs = np.asarray(frequencies, dtype=np.float64) if freqs.shape != (n_bands,): raise ValueError("frequencies") return freqs
def sound_power(levels, frequencies): freqs = _octave_frequencies(frequencies, len(levels)) return BandResult(frequencies=freqs, levels=np.asarray(levels) + 3.0) """, ) assert found == {("sound_power", "BandResult.frequencies", "frequencies")}
def test_a_validation_helper_carries_the_caller_s_array(tmp_path: pathlib.Path) -> None: """The helper's return is summarised once, and every caller inherits it.""" found = _findings( tmp_path, rating=""" from ._internal.validation import require_finite_array from .results import BandResult
def rating(frequencies, levels): f = require_finite_array(frequencies, "frequencies") return BandResult(frequencies=f, levels=f * 0.0) """, ) assert found == {("rating", "BandResult.frequencies", "frequencies")}
def test_a_record_that_freezes_the_caller_s_column_is_refused( tmp_path: pathlib.Path,) -> None: """``read_only`` on a normalised field clears the flag on the caller's own array: the coupler record of IEC 61094-2 did it to three columns. """ found = _findings( tmp_path, coupler=""" from dataclasses import dataclass
import numpy as np from numpy.typing import NDArray
from ._internal.frozen import read_only
@dataclass(frozen=True) class Coupler: impedance: NDArray[np.complex128]
def __post_init__(self): column = np.asarray(self.impedance, dtype=np.complex128).reshape(-1) object.__setattr__(self, "impedance", read_only(column)) """, ) assert found == { ("Coupler.__post_init__", "Coupler.impedance", "self.impedance"), ("Coupler.__post_init__", "read_only(...)", "self.impedance"), }
def test_a_record_copied_with_replace_keeps_the_caller_s_axes( tmp_path: pathlib.Path,) -> None: """``dataclasses.replace`` carries over every field it is not given.""" found = _findings( tmp_path, curves=""" import dataclasses
from .results import BandResult
def revise(curves: BandResult, levels): return dataclasses.replace(curves, levels=levels * 1.0) """, ) assert found == { ("revise", "BandResult.frequencies (kept by replace)", "curves"), }
# ---------------------------------------------------------------------------# The fixes pass# ---------------------------------------------------------------------------
def test_the_fixes_pass(tmp_path: pathlib.Path) -> None: """A copy of its own, made read only, ends every trail above.""" found = _findings( tmp_path, fixed=""" import dataclasses from dataclasses import dataclass
import numpy as np from numpy.typing import NDArray
from ._internal.frozen import read_only, read_only_copy from ._internal.validation import require_finite_array from .results import BandResult
def rating(frequencies, levels): f = require_finite_array(frequencies, "frequencies") return BandResult(frequencies=read_only_copy(f), levels=f * 0.0)
def revise(curves: BandResult, levels): return dataclasses.replace( curves, frequencies=read_only_copy(curves.frequencies), levels=levels * 1.0, )
@dataclass(frozen=True) class Coupler: impedance: NDArray[np.complex128]
def __post_init__(self): column = np.asarray(self.impedance, dtype=np.complex128).reshape(-1) object.__setattr__(self, "impedance", read_only(column.copy()))
def coupler(impedance): return Coupler(impedance=np.asarray(impedance)) """, ) assert found == set()
# ---------------------------------------------------------------------------# The rule, case by case# ---------------------------------------------------------------------------
@pytest.mark.parametrize( "kept", [ "levels", "np.asarray(levels)", "np.atleast_2d(levels)[:, 0]", "levels.T", "levels.reshape(-1)", "np.ravel(levels)", "levels[1:]", "levels if levels.ndim else None", ],)def test_the_caller_s_array_or_a_view_of_it_is_refused( tmp_path: pathlib.Path, kept: str) -> None: found = _findings( tmp_path, views=f""" import numpy as np
from .results import BandResult
def views(levels): return BandResult(frequencies=np.arange(3.0), levels={kept}) """, ) assert found == {("views", "BandResult.levels", "levels")}
@pytest.mark.parametrize( "kept", [ "levels - 10.0", "np.array(levels)", "levels.copy()", "levels.astype(float)", "levels[levels > 0.0]", "np.asarray([levels, levels])", "None", ],)def test_a_new_array_passes(tmp_path: pathlib.Path, kept: str) -> None: """Arithmetic, a copy, a mask or a stack is an array of the result's own.""" found = _findings( tmp_path, fresh=f""" import numpy as np
from .results import BandResult
def fresh(levels): return BandResult(frequencies=np.arange(3.0), levels={kept}) """, ) assert found == set()
def test_a_scalar_field_is_not_an_array(tmp_path: pathlib.Path) -> None: """Only a field that can hold an array is a place an array is kept.""" found = _findings( tmp_path, named=""" import numpy as np
from .results import BandResult
def named(levels, label): return BandResult(np.arange(3.0), None, label) """, ) assert found == set()
def test_a_private_record_carries_what_it_was_given(tmp_path: pathlib.Path) -> None: """A private record is plumbing, but what it carries reaches the result.""" found = _findings( tmp_path, plumbing=""" from dataclasses import dataclass
import numpy as np
from .results import BandResult
@dataclass(frozen=True) class _Setup: frequencies: np.ndarray scale: float
def _setup(frequencies): return _Setup(frequencies=np.asarray(frequencies), scale=2.0)
def predict(frequencies): setup = _setup(frequencies) return BandResult(frequencies=setup.frequencies, levels=None) """, ) assert found == {("predict", "BandResult.frequencies", "frequencies")}
def test_a_record_parameter_s_text_fields_are_not_arrays( tmp_path: pathlib.Path,) -> None: """A parameter annotated with a record is read field by field.""" found = _findings( tmp_path, combine=""" from dataclasses import dataclass
import numpy as np from numpy.typing import NDArray
from .results import BandResult
@dataclass(frozen=True) class Contributions: parts: tuple[tuple[str, NDArray[np.float64]], ...]
def combine(paths: list[BandResult]): labels = Contributions(parts=tuple((p.label, p.levels * 1.0) for p in paths)) kept = Contributions(parts=tuple((p.label, p.levels) for p in paths)) return labels, kept """, ) assert found == {("combine", "Contributions.parts", "paths")}
def test_a_field_the_record_copies_itself_needs_no_copy_at_the_factory( tmp_path: pathlib.Path,) -> None: """A record whose ``__post_init__`` copies a field owns it, whoever builds it.""" found = _findings( tmp_path, owned=""" from dataclasses import dataclass
import numpy as np
from ._internal.frozen import read_only_copy
@dataclass(frozen=True) class Owned: data: np.ndarray other: np.ndarray
def __post_init__(self): object.__setattr__(self, "data", read_only_copy(self.data))
def build(data, other): return Owned(data=data, other=other) """, ) assert found == {("build", "Owned.other", "other")}
def test_a_record_s_writeable_copy_is_still_the_caller_s_to_edit( tmp_path: pathlib.Path,) -> None: """A record that copies a field but leaves it writeable hands a later result an array its caller can still edit, through the record; one that seals its copy read-only does not. """ found = _findings( tmp_path, traverse=""" from dataclasses import dataclass
import numpy as np
from ._internal.frozen import read_only_copy from .results import BandResult
@dataclass(frozen=True) class Traverse: positions: np.ndarray levels: np.ndarray
def __post_init__(self): object.__setattr__(self, "positions", np.array(self.positions)) object.__setattr__(self, "levels", read_only_copy(self.levels))
def deviations(traverse: Traverse): return BandResult(frequencies=traverse.positions, levels=traverse.levels) """, ) assert found == {("deviations", "BandResult.frequencies", "traverse")}
def test_read_only_on_an_argument_is_refused_anywhere(tmp_path: pathlib.Path) -> None: """It would clear the flag on the caller's own array.""" found = _findings( tmp_path, freeze=""" import numpy as np
from ._internal.frozen import read_only
def freeze(levels): return read_only(np.asarray(levels, dtype=np.float64)) """, ) assert found == {("freeze", "read_only(...)", "levels")}
def test_a_nested_function_sees_the_arrays_of_its_closure( tmp_path: pathlib.Path,) -> None: found = _findings( tmp_path, closure=""" import numpy as np
from .results import BandResult
def outer(levels): aligned = np.asarray(levels)
def build(label): return BandResult(frequencies=np.arange(3.0), levels=aligned, label=label)
return build("x") """, ) assert found == {("outer.build", "BandResult.levels", "levels")}
def test_a_plain_class_keeps_an_annotated_attribute(tmp_path: pathlib.Path) -> None: found = _findings( tmp_path, bank=""" import numpy as np
class Bank: sos: np.ndarray fs: float
def __init__(self, sos, fs): self.sos = np.asarray(sos) self.fs = fs """, ) assert found == {("Bank.__init__", "self.sos", "sos")}
@pytest.mark.parametrize( ("init", "attribute"), [ ("self.sos = np.asarray(sos)", "self.sos"), ("self._sos = sos", "self._sos"), ("self._sos: np.ndarray = np.atleast_2d(sos)", "self._sos"), ("self._sections = [sos]", "self._sections"), ],)def test_a_plain_class_keeps_an_unannotated_attribute( tmp_path: pathlib.Path, init: str, attribute: str) -> None: """No class-level annotation is needed: the parameter's own decides.
``SilencerChain`` kept the caller's frequency grid as ``self._frequencies`` behind a ``frequencies`` property, and nothing in its class body said the attribute was an array. """ found = _findings( tmp_path, bank=f""" import numpy as np
class Bank: def __init__(self, sos, fs: float): {init} self.fs = fs
@property def sos(self): return self._sos """, ) assert found == {("Bank.__init__", attribute, "sos")}
def test_a_plain_class_reads_its_parameter_s_annotation( tmp_path: pathlib.Path,) -> None: """A float parameter is not an array; one typed through an alias is.
``FDTD2D`` takes ``c: float | Field2D``, where ``Field2D`` is a module alias of ``NDArray[np.float64]``. """ found = _findings( tmp_path, grid=""" import numpy as np from numpy.typing import NDArray
Field2D = NDArray[np.float64]
class Grid: def __init__(self, c: float | Field2D, dx: float, label: str): self.c = np.asarray(c, dtype=np.float64) self.dx = dx self.label = label """, ) assert found == {("Grid.__init__", "self.c", "c")}
def test_a_database_that_hands_out_its_constructor_s_arrays_is_refused( tmp_path: pathlib.Path,) -> None: """``ANPDatabase`` kept the caller's distances and gave them to its curves.
The record is built in a method, from ``self``; the array is caught where the constructor kept it. """ found = _findings( tmp_path, database=""" import numpy as np
from .results import BandResult
class Database: def __init__(self, curves, distances): self._curves = dict(curves) self._distances = distances
def curve(self, key): return BandResult(frequencies=self._distances, levels=self._curves[key]) """, ) assert found == { ("Database.__init__", "self._curves", "curves"), ("Database.__init__", "self._distances", "distances"), }
def test_a_plain_class_that_files_the_caller_s_array_is_refused( tmp_path: pathlib.Path,) -> None: """``self.items.append(x)`` keeps x as surely as ``self.x = x`` does.
A record that holds no array, like an FDTD source, is not one. """ found = _findings( tmp_path, chain=""" from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True) class Element: label: str length: float
class Chain: def __init__(self): self._layers: list[np.ndarray] = [] self._elements: list[Element] = [] self._named: dict[str, np.ndarray] = {}
def layer(self, levels): self._layers.append(np.asarray(levels))
def element(self, element: Element): self._elements.append(element)
def name(self, key: str, levels): self._named[key] = levels """, ) assert found == { ("Chain.layer", "self._layers.append(...)", "levels"), ("Chain.name", "self._named[...]", "levels"), }
def _indexed_by_helper( tmp_path: pathlib.Path, helper: str) -> set[tuple[str, str, str]]: """The findings of a factory that indexes its argument with a helper.""" return _findings( tmp_path, head=f""" import numpy as np
from .results import BandResult
def _head(n): {helper}
def head(frequencies): return BandResult(frequencies=frequencies[_head(3)], levels=None) """, )
def test_a_helper_that_returns_a_slice_selects_a_view(tmp_path: pathlib.Path) -> None: """A private helper used as an index is read, not trusted to copy.""" found = _indexed_by_helper(tmp_path, "return slice(0, n)") assert found == {("head", "BandResult.frequencies", "frequencies")}
@pytest.mark.parametrize( "helper", [ "return np.arange(n)", "return np.asarray([i for i in range(n)], dtype=np.intp)", "return np.arange(5) < n", ],)def test_a_helper_that_returns_positions_selects_a_copy( tmp_path: pathlib.Path, helper: str) -> None: assert _indexed_by_helper(tmp_path, helper) == set()
@pytest.mark.parametrize( "body", [ "kept = dict(bands).copy()['a']", "kept = np.diag(bands)", "kept = np.trim_zeros(bands)", ],)def test_a_shallow_copy_or_a_numpy_view_is_refused( tmp_path: pathlib.Path, body: str) -> None: """A mapping's ``copy`` keeps its arrays; ``np.diag`` of a matrix is a view.""" found = _findings( tmp_path, shallow=f""" import numpy as np
from .results import BandResult
def shallow(bands): {body} return BandResult(frequencies=kept, levels=None) """, ) assert found == {("shallow", "BandResult.frequencies", "bands")}
def test_a_mapping_parameter_s_copy_keeps_its_arrays(tmp_path: pathlib.Path) -> None: found = _findings( tmp_path, mapping=""" from collections.abc import Mapping
import numpy as np
from .results import BandResult
def mapping(bands: Mapping[str, np.ndarray], levels: np.ndarray): own = levels.copy() mine = bands.copy() return BandResult(frequencies=mine["a"], levels=own) """, ) assert found == {("mapping", "BandResult.frequencies", "bands")}
def test_a_field_patched_in_a_factory_is_refused(tmp_path: pathlib.Path) -> None: """``object.__setattr__`` on a record just built keeps what it is given.""" found = _findings( tmp_path, patched=""" import numpy as np
from .results import BandResult
def patched(levels): result = BandResult(frequencies=np.arange(3.0), levels=None) object.__setattr__(result, "levels", levels) object.__setattr__(result, "label", "patched") return result """, ) assert found == {("patched", "BandResult.levels", "levels")}
# ---------------------------------------------------------------------------# Records that copy what they are handed# ---------------------------------------------------------------------------
#: A public record that copies every array it is built with._OWNING = """from dataclasses import dataclass
import numpy as npfrom numpy.typing import NDArray
from ._internal.frozen import OwnsArrays
@dataclass(frozen=True)class Spectrum(OwnsArrays): frequencies: NDArray[np.float64] levels: NDArray[np.float64] | None columns: dict[str, np.ndarray] label: str = """""
def test_a_public_record_that_can_hold_an_array_must_copy_it( tmp_path: pathlib.Path,) -> None: """``BandResult``, written by hand, would keep the caller's array.
No function of the package stands between a caller who builds the record and the record, so no trail reaches it: the class itself is refused. """ assert _unequipped(tmp_path) == {"BandResult"}
def test_a_record_that_inherits_the_copy_passes(tmp_path: pathlib.Path) -> None: """Directly, or through a record it extends; and a record of numbers, or one only a private module holds, needs nothing. """ found = _unequipped( tmp_path, results=""" from dataclasses import dataclass
import numpy as np
from ._internal.frozen import OwnsArrays
@dataclass(frozen=True) class BandResult(OwnsArrays): frequencies: np.ndarray
@dataclass(frozen=True) class Rated(BandResult): rating_db: np.ndarray
@dataclass(frozen=True) class Single: level: float label: str """, _plumbing=""" from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True) class Grid: nodes: np.ndarray """, ) assert found == set()
def test_a_listed_record_and_a_named_tuple_are_held_to_it( tmp_path: pathlib.Path,) -> None: """A record of a private module that a public ``__all__`` lists reaches callers; a named tuple cannot inherit the copy and is refused all the same. """ found = _unequipped( tmp_path, _impl=""" from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True) class Listed: nodes: np.ndarray """, api=""" from typing import NamedTuple
import numpy as np
from ._impl import Listed
__all__ = ["Listed", "Pair"]
class Pair(NamedTuple): frequencies: np.ndarray weight: float """, ) assert found == {"BandResult", "Listed", "Pair"}
def test_a_record_that_copies_takes_the_caller_s_array_as_it_is( tmp_path: pathlib.Path,) -> None: """Every field is the record's own, so a factory hands the array over as it is, and what the record's own ``__post_init__`` reads back from ``self`` is its copy: sealing it there touches nobody else's array. """ found = _findings( tmp_path, owning=_OWNING, spectra=""" import dataclasses from dataclasses import dataclass
import numpy as np from numpy.typing import NDArray
from ._internal.frozen import OwnsArrays, read_only from ._internal.validation import require_finite_array from .owning import Spectrum
@dataclass(frozen=True) class Coupler(OwnsArrays): impedance: NDArray[np.complex128]
def __post_init__(self): column = np.asarray(self.impedance, dtype=np.complex128).reshape(-1) object.__setattr__(self, "impedance", read_only(column))
def spectrum(frequencies, levels): f = require_finite_array(frequencies, "frequencies") return Spectrum(frequencies=f, levels=levels[:, 0], columns={"a": f})
def revise(spectrum: Spectrum, levels): return dataclasses.replace(spectrum, levels=levels)
def coupler(impedance): return Coupler(impedance=impedance) """, ) assert found == set()
@pytest.mark.parametrize( "argument", [ "read_only_copy(f)", "read_only_copy(f, np.float64)", "f.copy()", "np.copy(f)", "read_only(f.copy())", "read_only(np.array(f))", "None if f is None else read_only_copy(f)", "f.astype(np.float64)", "read_only(f.astype(np.float64))", ],)def test_a_copy_handed_to_a_record_that_copies_is_refused( tmp_path: pathlib.Path, argument: str) -> None: """The record copies the array again: the first copy is wasted.""" found = _findings( tmp_path, owning=_OWNING, spectra=f""" import numpy as np
from ._internal.frozen import read_only, read_only_copy from .owning import Spectrum
def spectrum(f): return Spectrum(frequencies={argument}, levels=None, columns={{}}) """, ) assert found == {("spectrum", "Spectrum.frequencies (copied twice)", "")}
@pytest.mark.parametrize( ("field", "argument"), [ ("frequencies", "np.asarray(f, dtype=np.float64)"), ("frequencies", "np.array([1.0, 2.0])"), ("frequencies", "f"), ("frequencies", "f.astype(np.float64, copy=False)"), ("columns", "table.copy()"), ],)def test_a_conversion_or_a_container_s_copy_is_not_a_second_copy( tmp_path: pathlib.Path, field: str, argument: str) -> None: """``np.array`` of a list builds the array; a mapping's ``copy`` copies the mapping, which the record does not. """ given = {"frequencies": "np.zeros(2)", "levels": "None", "columns": "{}"} given[field] = argument call = ", ".join(f"{name}={value}" for name, value in given.items()) found = _findings( tmp_path, owning=_OWNING, spectra=f""" import numpy as np
from .owning import Spectrum
def spectrum(f, table): return Spectrum({call}) """, ) assert found == set()
#: A helper that only reads what it is handed, and two that write into it:#: one through a subscript, one through an augmented assignment to the name._HELPERS = """import numpy as np
def check_positive(values, name): if np.any(values <= 0.0): raise ValueError(f"{name} must be positive: {values}")
def fill_gaps(values): values[np.isnan(values)] = 0.0
def shift_in_place(values): values += 1.0 return float(values.sum())"""
@pytest.mark.parametrize( ("bound", "used"), [ ("read_only_copy(x)", "Spectrum(frequencies=f, levels=None, columns={})"), ( "x.copy()", "Spectrum(frequencies=read_only(f), levels=f * 2.0, columns={})", ), ( "np.copy(x)", "Spectrum(frequencies=f, levels=np.log10(f[1:]), columns={})", ), ( "x.astype(np.float64)", "Spectrum(frequencies=read_only(f), levels=None, columns={})", ), ],)def test_a_copy_bound_to_a_name_and_handed_over_is_refused( tmp_path: pathlib.Path, bound: str, used: str) -> None: """The copy is read, checked and handed to a record that copies it again.
The shape the tree held after the copies at the call were dropped: ``f = require_positive_array(...).copy()`` early in the function and ``frequencies=read_only(f)`` at the end, with only reads between. """ found = _findings( tmp_path, owning=_OWNING, helpers=_HELPERS, spectra=f""" import numpy as np
from ._internal.frozen import read_only, read_only_copy from .helpers import check_positive from .owning import Spectrum
def spectrum(x): f = {bound} check_positive(f, "x") if f.size < 2 or f[0] > f[-1]: raise ValueError(f"x must ascend: {{f}}") return {used} """, ) assert found == {("spectrum", "Spectrum.frequencies (copied twice, as f)", "")}
@pytest.mark.parametrize( "middle", [ "f[0] = 1.0", "f += 1.0", "f.sort()", "np.copyto(f, x)", "np.add.at(f, 0, 1.0)", "np.multiply(f, 2.0, out=f)", "fill_gaps(f)", "shift_in_place(f)", "view = f[1:]", "kept = [f]", "f = x if x.size > 3 else f", ],)def test_a_copy_the_function_needs_is_not_a_second_copy( tmp_path: pathlib.Path, middle: str) -> None: """A copy that something writes into, keeps a view of, or binds again is what keeps the caller's array whole: the rule never asks for it to be dropped. A helper of the package that writes into its parameter counts as writing. """ found = _findings( tmp_path, owning=_OWNING, helpers=_HELPERS, spectra=f""" import numpy as np
from .helpers import fill_gaps, shift_in_place from .owning import Spectrum
def spectrum(x): f = x.copy() {middle} return Spectrum(frequencies=f, levels=None, columns={{}}) """, ) assert found == set()
def test_a_parameter_copied_into_itself_is_not_read_as_a_second_copy( tmp_path: pathlib.Path,) -> None: """``x = x.copy()`` binds a parameter: the reading does not vouch for it.""" found = _findings( tmp_path, owning=_OWNING, spectra=""" from .owning import Spectrum
def spectrum(x): x = x.copy() return Spectrum(frequencies=x, levels=None, columns={}) """, ) assert found == set()
# ---------------------------------------------------------------------------# An array handed over to the record without a copy# ---------------------------------------------------------------------------
#: A record that copies, a record that does not, and helpers that write into#: their array, keep it or hand it on._RUN = """from dataclasses import dataclass
import numpy as npfrom numpy.typing import NDArray
from ._internal.frozen import OwnsArrays
@dataclass(frozen=True)class Run(OwnsArrays): frames: NDArray[np.float64] | None times: NDArray[np.float64]
@dataclass(frozen=True)class _Plain: frames: NDArray[np.float64] | None times: NDArray[np.float64]
def write(frames, n): if frames is not None: frames[0] = 1.0 for i in range(n): frames[i, 0] += 2.0
def write_on(n, *, frames): write(frames, n)
def keep(store, frames): store.append(frames)
def fill_and_return(frames): frames[0] = 1.0 return frames
def rebind(frames): frames = frames[::2] frames[0] = 1.0
def write_later(frames): frames[0] = 1.0 yield
def write_deep_1(frames): write_deep_2(frames)
def write_deep_2(frames): write_deep_3(frames)
def write_deep_3(frames): write_deep_4(frames)
def write_deep_4(frames): frames[0] = 1.0
_SEEN = []
def remember(function): def wrapper(*args): _SEEN.append(args) return function(*args) return wrapper
@rememberdef write_remembered(frames): frames[0] = 1.0"""
def _handovers(tmp_path: pathlib.Path, body: str) -> set[tuple[str, str]]: """``(function, sink)`` of every handover the check refuses in *body*, a module ``sim`` that imports the helpers above. """ source = ( "import numpy as np\n\n" "from ._internal.frozen import handed_over\n" "from .run import (\n" " Run, _Plain, fill_and_return, keep, rebind, write, write_deep_1,\n" " write_deep_2, write_later, write_on, write_remembered,\n" ")\n" + textwrap.dedent(body) ) root = _package(tmp_path, {"run": _RUN, "sim": source}) found = caa.handovers_in(sorted(root.rglob("*.py")), root) return {(f.function, f.sink) for f in found}
@pytest.mark.parametrize( "body", [ # Allocated, written in place, handed to the record returned. """ def run(n): frames = np.zeros((n, 3)) for i in range(n): frames[i] = i frames[i, 0] += 1.0 return Run(frames=handed_over(frames), times=np.arange(n)) """, # An optional array, tested against None, written by a helper of the # package (by position and by keyword), handed over by position. """ def run(n, every=None): frames: np.ndarray | None = ( None if every is None else np.empty((n, 3), dtype=np.float64) ) if frames is not None: frames[0] = 0.0 write(frames, n) write_on(n, frames=frames) return Run(handed_over(frames), np.arange(n)) """, # Down three helpers, each only passing it on or writing into it. """ def run(n): frames = np.ones((n, 3)) write_deep_2(frames) return Run(frames=handed_over(frames), times=np.arange(n)) """, ], ids=["written-in-place", "optional-written-by-helpers", "three-helpers-deep"],)def test_an_array_nothing_else_can_reach_may_be_handed_over( tmp_path: pathlib.Path, body: str) -> None: """The shape of the simulation factories: one allocation, writes into it there or in a helper, and the record that keeps it as the return. """ assert _handovers(tmp_path, body) == set()
@pytest.mark.parametrize( ("body", "reason"), [ ( """ def run(frames): return Run(frames=handed_over(frames), times=np.arange(3)) """, "frames is a parameter", ), ( """ from . import _internal
def run(frames): return Run( frames=_internal.frozen.handed_over(frames), times=np.arange(3) ) """, "frames is a parameter", ), ( """ import pkg._internal.frozen
def run(frames): return Run( frames=pkg._internal.frozen.handed_over(frames), times=np.arange(3), ) """, "frames is a parameter", ), ( """ def run(x): frames = np.asarray(x) return Run(frames=handed_over(frames), times=np.arange(3)) """, "frames is not bound once", ), ( """ def run(x): frames = np.zeros(3) frames = np.zeros(4) return Run(frames=handed_over(frames), times=np.arange(3)) """, "frames is not bound once", ), ( """ def run(x): kept = frames = np.zeros(3) return Run(frames=handed_over(frames), times=kept) """, "frames is not bound once", ), ( """ def run(x): for frames in (np.zeros(3),): pass return Run(frames=handed_over(frames), times=np.arange(3)) """, "frames is not bound once", ), ( """ def run(x): def build(): frames = np.zeros(3) return frames return Run(frames=handed_over(frames), times=build()) """, "frames is not bound once", ), ( """ def run(n): frames = np.zeros((n, 3)) first = frames[0] return Run(frames=handed_over(frames), times=first) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) return Run(frames=handed_over(frames), times=frames.T) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) frames[0][1] = 2.0 return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n, store): frames = np.zeros((n, 3)) keep(store, frames) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) times = fill_and_return(frames) return Run(frames=handed_over(frames), times=times) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) rebind(frames) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) list(write_later(frames)) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) write_deep_1(frames) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) write_remembered(frames) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) return Run(frames=handed_over(frames), times=handed_over(frames)) """, "frames is read where it may be kept", ), ( """ def run(n, hooks): frames = np.zeros((n, 3)) def peek(): frames[0] = 1.0 hooks.append(peek) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n, hooks): frames = np.zeros((n, 3)) hooks.append(lambda: frames) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) rows = [frames[i] for i in range(n)] return Run(frames=handed_over(frames), times=np.asarray(rows)) """, "frames is read where it may be kept", ), ( """ def run(n, cache): frames = np.zeros((n, 3)) cache.update(locals()) return Run(frames=handed_over(frames), times=np.arange(n)) """, "the function can reach its own frame", ), ( """ def run(n): frames = np.zeros((n, 3)) yield n return Run(frames=handed_over(frames), times=np.arange(n)) """, "the function can reach its own frame", ), ( """ def run(n, seen): frames = np.zeros((n, 3)) if frames in seen: raise ValueError(n) return Run(frames=handed_over(frames), times=np.arange(n)) """, "frames is read where it may be kept", ), ( """ def run(n): frames = np.zeros((n, 3)) result = Run(frames=handed_over(frames), times=np.arange(n)) return result """, "the record is not built in the return statement", ), ( """ def run(n): frames = np.zeros((n, 3)) return _Plain(frames=handed_over(frames), times=np.arange(n)) """, "it is not an argument of a record that inherits OwnsArrays", ), ( """ def run(n): frames = handed_over(np.zeros((n, 3))) return Run(frames=frames, times=np.arange(n)) """, "it is not an argument of a record", ), ( """ def run(n): return Run(frames=handed_over(np.zeros((n, 3))), times=np.arange(n)) """, "its argument is not a name", ), ], ids=[ "parameter", "dotted-path", "absolute-dotted-path", "not-allocated", "bound-twice", "second-name", "loop-target", "bound-in-nested-scope", "view-kept", "transpose-kept", "view-written", "helper-keeps", "helper-returns", "helper-rebinds", "helper-generator", "four-helpers-deep", "decorated-helper", "handed-twice", "closure", "lambda", "comprehension", "locals", "generator", "membership-test", "record-not-returned", "record-without-mechanism", "outside-record", "not-a-name", ],)def test_an_array_something_else_may_reach_is_refused( tmp_path: pathlib.Path, body: str, reason: str) -> None: """A parameter, a view, a second name, a helper that keeps or returns it or binds it again, a helper behind a decorator, a closure, a frame the function hands out, and a record that is not what the function returns: in each the record would not be the only one to hold the array it keeps without a copy. The function is found however it is spelt, a dotted path to its module included. """ found = _handovers(tmp_path, body) assert len(found) == 1, found ((function, sink),) = found assert function == "run" assert sink.startswith("handed_over(...): " + reason), sink
@pytest.mark.parametrize( ("body", "reason"), [ ("KEPT = handed_over(np.zeros(3))\n", "it is not called in a function"), ("hand = handed_over\n", "the function is named where it is not called"), ( "def run(n):\n" " make = lambda frames: Run(frames=handed_over(frames), times=frames)\n" " return make(np.zeros(n))\n", "it is not called in a function", ), ( "from ._internal import frozen\n\n" "def run(frames):\n" " hand = getattr(frozen, 'handed_over')\n" " return Run(frames=hand(frames), times=np.arange(3))\n", "the function is named where it is not called", ), ], ids=["module-level", "named-not-called", "in-a-lambda", "named-in-a-string"],)def test_the_handover_named_outside_a_function_is_refused( tmp_path: pathlib.Path, body: str, reason: str) -> None: """At module level, in a lambda, or the function passed around under another name or fetched by its name as a string, nothing can be proved of what it is handed. """ found = _handovers(tmp_path, body) assert {sink for _, sink in found} == {"handed_over(...): " + reason}
def test_a_record_exemption_silences_its_class_and_goes_stale_without_it( tmp_path: pathlib.Path,) -> None: root = _package(tmp_path, {}) found = caa.records_without_mechanism(sorted(root.rglob("*.py")), root) key = (found[0].path, "BandResult") left, stale = ast_scan.exempted(found, {key: "reason"}) assert (left, stale) == ([], []) left, stale = ast_scan.exempted([], {key: "reason"}) assert stale == [key]
def test_an_exemption_silences_its_function_and_goes_stale_without_it( tmp_path: pathlib.Path,) -> None: root = tmp_path / "pkg" root.mkdir() path = root / "keep.py" path.write_text( textwrap.dedent( """ from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True) class Kept: data: np.ndarray
def keep(data): return Kept(data=data) """ ), encoding="utf-8", ) found = caa.findings_in([path], root) key = (found[0].path, "keep") left, stale = ast_scan.exempted(found, {key: "reason"}) assert (left, stale) == ([], []) left, stale = ast_scan.exempted([], {key: "reason"}) assert stale == [key]
def test_the_tree_passes(capsys: pytest.CaptureFixture[str]) -> None: status = caa.main([]) assert status == 0, capsys.readouterr().out