Skip to content

new_simulator

Scaffold a new simulator backend (stub, export, and test).

SimulatorNames dataclass

Derived names for a scaffolded simulator.

Source code in shadowsim/cli/new_simulator.py
@dataclass(frozen=True)
class SimulatorNames:
    """Derived names for a scaffolded simulator."""

    base_name: str
    class_name: str
    snake_name: str
    module_name: str
    simulator_id: str

    @property
    def stub_filename(self) -> str:
        """Return the stub module filename."""
        return f"{self.module_name}.py"

    @property
    def test_filename(self) -> str:
        """Return the scaffolded test filename."""
        return f"test_{self.module_name}.py"

stub_filename property

stub_filename: str

Return the stub module filename.

test_filename property

test_filename: str

Return the scaffolded test filename.

ScaffoldError

Bases: Exception

Raised when simulator scaffolding cannot proceed.

Source code in shadowsim/cli/new_simulator.py
class ScaffoldError(Exception):
    """Raised when simulator scaffolding cannot proceed."""

pascal_to_snake

pascal_to_snake(name: str) -> str

Convert a PascalCase name to snake_case.

Source code in shadowsim/cli/new_simulator.py
def pascal_to_snake(name: str) -> str:
    """Convert a PascalCase name to snake_case."""
    return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()

normalize_base_name

normalize_base_name(raw: str) -> str

Validate PascalCase input and strip a trailing Simulator suffix.

Source code in shadowsim/cli/new_simulator.py
def normalize_base_name(raw: str) -> str:
    """Validate PascalCase input and strip a trailing ``Simulator`` suffix."""
    name = raw.strip()
    if not name:
        raise ScaffoldError("Name must not be empty")
    if any(ch.isspace() for ch in name):
        raise ScaffoldError("Name must not contain spaces")
    if "_" in name or "-" in name:
        raise ScaffoldError("Name must be PascalCase with no underscores or hyphens")
    if not _PASCAL_RE.fullmatch(name):
        raise ScaffoldError("Name must be PascalCase (start with an uppercase letter; letters and digits only)")
    if name.endswith("Simulator") and name != "Simulator":
        name = name[: -len("Simulator")]
        # Defensive: unreachable after _PASCAL_RE, kept for clear errors if the regex changes.
        if not name or not _PASCAL_RE.fullmatch(name):  # pragma: no cover
            raise ScaffoldError("Name must include a PascalCase prefix before 'Simulator'")
    if name == "Simulator":
        raise ScaffoldError("Name 'Simulator' is reserved for the base class")
    return name

normalize_kind

normalize_kind(raw: str) -> Kind

Validate a simulator kind.

classical records observables and takes no circuit backend, the same shape as QuTiP. circuit keeps a backend-shaped stub.

Source code in shadowsim/cli/new_simulator.py
def normalize_kind(raw: str) -> Kind:
    """Validate a simulator kind.

    ``classical`` records observables and takes no circuit backend, the same
    shape as QuTiP. ``circuit`` keeps a backend-shaped stub.
    """
    kind = raw.strip().lower()
    if kind == "classical":
        return "classical"
    if kind == "circuit":
        return "circuit"
    raise ScaffoldError("Kind must be 'classical' or 'circuit'")

normalize_lindblads

normalize_lindblads(raw: str) -> bool

Return whether a classical simulator accepts Lindblad operators.

Source code in shadowsim/cli/new_simulator.py
def normalize_lindblads(raw: str) -> bool:
    """Return whether a classical simulator accepts Lindblad operators."""
    answer = raw.strip().lower()
    if answer in _YES:
        return True
    if answer in _NO:
        return False
    raise ScaffoldError("Answer must be 'yes' or 'no'")

derive_names

derive_names(raw: str) -> SimulatorNames

Derive class, module, and id names from a user-provided PascalCase name.

Source code in shadowsim/cli/new_simulator.py
def derive_names(raw: str) -> SimulatorNames:
    """Derive class, module, and id names from a user-provided PascalCase name."""
    base = normalize_base_name(raw)
    snake = pascal_to_snake(base)
    module = f"{snake}_simulator"
    return SimulatorNames(
        base_name=base,
        class_name=f"{base}Simulator",
        snake_name=snake,
        module_name=module,
        simulator_id=module,
    )

default_repo_root

default_repo_root() -> Path

Resolve the repository root from the working directory or package location.

Source code in shadowsim/cli/new_simulator.py
def default_repo_root() -> Path:
    """Resolve the repository root from the working directory or package location."""
    cwd = Path.cwd()
    if (cwd / "shadowsim" / "simulators").is_dir():
        return cwd
    package_root = Path(__file__).resolve().parents[1]
    repo_root = package_root.parent
    if (repo_root / "shadowsim" / "simulators").is_dir():
        return repo_root
    raise ScaffoldError("Could not find the ShadowSim.py repository root. Run this command from the cloned repository.")

stub_path

stub_path(repo_root: Path, names: SimulatorNames) -> Path

Return the path for the new simulator module.

Source code in shadowsim/cli/new_simulator.py
def stub_path(repo_root: Path, names: SimulatorNames) -> Path:
    """Return the path for the new simulator module."""
    return repo_root / "shadowsim" / "simulators" / names.stub_filename

test_path

test_path(repo_root: Path, names: SimulatorNames) -> Path

Return the path for the scaffolded simulator test.

Source code in shadowsim/cli/new_simulator.py
def test_path(repo_root: Path, names: SimulatorNames) -> Path:
    """Return the path for the scaffolded simulator test."""
    return repo_root / "test" / "simulators" / names.test_filename

init_path

init_path(repo_root: Path) -> Path

Return the simulators package __init__.py path.

Source code in shadowsim/cli/new_simulator.py
def init_path(repo_root: Path) -> Path:
    """Return the simulators package ``__init__.py`` path."""
    return repo_root / "shadowsim" / "simulators" / "__init__.py"

check_collisions

check_collisions(
    repo_root: Path, names: SimulatorNames
) -> None

Raise if stub, test, or export already exist for this name.

Source code in shadowsim/cli/new_simulator.py
def check_collisions(repo_root: Path, names: SimulatorNames) -> None:
    """Raise if stub, test, or export already exist for this name."""
    stub = stub_path(repo_root, names)
    test = test_path(repo_root, names)
    init = init_path(repo_root)
    problems: list[str] = []

    if stub.exists():
        problems.append(f"simulator module already exists: {stub}")
    if test.exists():
        problems.append(f"test file already exists: {test}")
    if not init.exists():
        problems.append(f"simulators package init is missing: {init}")
    else:
        init_text = init.read_text(encoding="utf-8")
        conflict = _registration_conflict(init_text, init, names)
        if conflict is not None:
            problems.append(conflict)

    if problems:
        raise ScaffoldError("Name already exists:\n- " + "\n- ".join(problems))

render_stub

render_stub(
    names: SimulatorNames,
    *,
    kind: str = "circuit",
    closed_system: bool = False,
) -> str

Return the source for a new simulator stub module.

Source code in shadowsim/cli/new_simulator.py
def render_stub(names: SimulatorNames, *, kind: str = "circuit", closed_system: bool = False) -> str:
    """Return the source for a new simulator stub module."""
    resolved = _resolve_kind(kind, closed_system=closed_system)
    if resolved == "classical":
        return _render_classical_stub(names, closed_system=closed_system)
    return _render_circuit_stub(names)

render_test

render_test(
    names: SimulatorNames,
    *,
    kind: str = "circuit",
    closed_system: bool = False,
) -> str

Return the source for a minimal simulator test scaffold.

Source code in shadowsim/cli/new_simulator.py
def render_test(names: SimulatorNames, *, kind: str = "circuit", closed_system: bool = False) -> str:
    """Return the source for a minimal simulator test scaffold."""
    resolved = _resolve_kind(kind, closed_system=closed_system)
    if resolved == "classical":
        return _render_classical_test(names, closed_system=closed_system)
    return _render_circuit_test(names)

patch_init_file

patch_init_file(path: Path, names: SimulatorNames) -> None

Register the new simulator in _EXPORTS with no optional extra.

Source code in shadowsim/cli/new_simulator.py
def patch_init_file(path: Path, names: SimulatorNames) -> None:
    """Register the new simulator in ``_EXPORTS`` with no optional extra."""
    content = path.read_text(encoding="utf-8")
    conflict = _registration_conflict(content, path, names)
    if conflict is not None:
        raise ScaffoldError(conflict)
    body_start, body_end = _exports_span(content, path)
    updated = _insert_export_line(content[body_start:body_end], names)
    path.write_text(content[:body_start] + updated + content[body_end:], encoding="utf-8")

create_simulator

create_simulator(
    raw_name: str,
    *,
    repo_root: Path | None = None,
    kind: str = "circuit",
    closed_system: bool = False,
) -> SimulatorNames

Validate, check collisions, and write stub + export + test scaffold.

kind="classical" writes a QuTiP-shaped constructor that takes observables. closed_system is set on that class from the Lindblad answer. A circuit scaffold leaves both at the backend-shaped default.

Source code in shadowsim/cli/new_simulator.py
def create_simulator(
    raw_name: str,
    *,
    repo_root: Path | None = None,
    kind: str = "circuit",
    closed_system: bool = False,
) -> SimulatorNames:
    """Validate, check collisions, and write stub + export + test scaffold.

    ``kind="classical"`` writes a QuTiP-shaped constructor that takes
    ``observables``. ``closed_system`` is set on that class from the Lindblad
    answer. A circuit scaffold leaves both at the backend-shaped default.
    """
    names = derive_names(raw_name)
    resolved = _resolve_kind(kind, closed_system=closed_system)
    root = repo_root if repo_root is not None else default_repo_root()
    check_collisions(root, names)

    stub = stub_path(root, names)
    test = test_path(root, names)
    init = init_path(root)

    test.parent.mkdir(parents=True, exist_ok=True)
    init_before = init.read_text(encoding="utf-8")
    stub.write_text(render_stub(names, kind=resolved, closed_system=closed_system), encoding="utf-8")
    try:
        patch_init_file(init, names)
        test.write_text(render_test(names, kind=resolved, closed_system=closed_system), encoding="utf-8")
    except Exception:
        if stub.exists():
            stub.unlink()
        if init.read_text(encoding="utf-8") != init_before:
            init.write_text(init_before, encoding="utf-8")
        if test.exists():
            test.unlink()
        raise

    return names

build_parser

build_parser() -> ArgumentParser

Build the CLI argument parser.

Source code in shadowsim/cli/new_simulator.py
def build_parser() -> argparse.ArgumentParser:
    """Build the CLI argument parser."""
    parser = argparse.ArgumentParser(
        prog="new-simulator",
        description="Scaffold a new ShadowSim simulator backend.",
    )
    parser.add_argument(
        "--name",
        help="PascalCase simulator name (e.g. WaveMatrix). Prompted if omitted.",
    )
    parser.add_argument(
        "--kind",
        choices=["classical", "circuit"],
        help=(
            "classical records observables and takes no circuit backend; circuit uses a backend. Prompted if omitted."
        ),
    )
    parser.add_argument(
        "--lindblads",
        choices=["yes", "no"],
        help=("Whether a classical simulator accepts Lindblad operators. Prompted for classical when omitted."),
    )
    return parser

main

main(argv: list[str] | None = None) -> int

Run the new-simulator scaffolding CLI.

Source code in shadowsim/cli/new_simulator.py
def main(argv: list[str] | None = None) -> int:
    """Run the new-simulator scaffolding CLI."""
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        raw_name, kind, closed_system = _scaffold_choices(args)
        names = create_simulator(raw_name, kind=kind, closed_system=closed_system)
    except ScaffoldError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    print(f"Created {names.class_name}")
    print(f"  kind:   {kind}")
    if kind == "classical":
        print(f"  lindblads: {'no' if closed_system else 'yes'}")
    print(f"  module: shadowsim/simulators/{names.stub_filename}")
    print("  export: shadowsim/simulators/__init__.py")
    print(f"  test:   test/simulators/{names.test_filename}")
    print("Next: implement simulate() (look for TODO).")
    return 0