Skip to content

Database

SQLite persistence for bus types, branch types and entire networks. gi.Database(path) is a database object: it owns its SQLAlchemy engine and session factory and offers the persistence operations as methods. The module-level helpers (gi.start_dbsession, gi.save_network_to_db, ...) work as before and delegate to a default Database. The ORM mirror classes live next to the Pydantic models in groundinsight.models.database_models and expose from_pydantic / to_pydantic converters. For a single network in a file of its own, see the JSON project file.

Physical / modelling context

The persistence layer is a side-channel to the in-memory Pydantic model. Every Pydantic class has an ORM counterpart with suffix DB (BusDB, BranchDB, NetworkDB, ...). Many-to-many relationships (e.g. a BranchType shared by several Network instances, or a Path composed of many Branch segments) are modelled through association tables (network_buses, path_segments, ...). Two design choices are worth noting:

  • Frequency lists are stored as a JSON array. They are conceptually atomic — a network has one frequency list, never shared, never queried element-wise — so a child table is not justified. Up to 0.6.0 the column was a PickleType, which meant that reading a database file executed whatever the blob contained, before any Pydantic validator saw it. A .db file is a shared artefact — it gets mailed around and checked into repositories — so that is the same trust problem the formula guard in utils.validations exists for. Existing files are converted by gi.migrate_database(...) with an unpickler that resolves nothing but list, float and int; anything else aborts the migration and leaves the file untouched.
  • Impedance dicts \(Z(f) \in \mathbb{C}\) are stored as JSON with stringified frequency keys, because SQLite has no native complex type. The ComplexNumber Pydantic helper guarantees symmetric round-trips on read-back.

The database object

# fragment: assumes a bus type `bus_type` and a network `net` named "demo"
import groundinsight as gi

with gi.Database("library.db") as db:
    # 1. Persist a re-usable BusType
    db.save_bustype(bus_type, overwrite=True)

    # 2. Persist an entire fault-ready network
    db.save_network(net, overwrite=True)

    # 3. Read back, list, delete
    recovered_types = db.load_bustypes()          # dict[name -> BusType]
    recovered_net = db.load_network("demo")
    db.list_networks()                            # ['demo', ...]
    db.delete_network("old variant")              # its types stay
Method Purpose
save_bustype(t, overwrite=False), load_bustypes(), delete_bustype(name) bus-type catalogue
save_branchtype(t, overwrite=False), load_branchtypes(), delete_branchtype(name) branch-type catalogue
save_network(net, overwrite=False, overwrite_types=False), load_network(name) networks with all elements and their stored results
list_networks(), delete_network(name) stored network names; delete a network and its elements
needs_migration(), migrate(backup=True) schema check / conversion of a file opened with migrate=False
session() context manager yielding a short-lived SQLAlchemy Session for direct ORM work
close(), closed, path, engine lifetime and introspection; the object is also a context manager

A type that a stored network still uses cannot be deleted; the error names the networks. gi.Database(path, migrate=True) converts a file written by an earlier release before opening it (keeping a .bak copy); with migrate=False the file stays untouched and the first read or write of a legacy file raises an error that names migrate(). gi.Database(":memory:") gives a private in-memory database, handy for tests.

Several files, several threads

Every method runs in its own short-lived session, so no SQLAlchemy Session is ever shared between threads. Two Database objects on two files are independent and can be used from two threads at the same time — a GUI with two open projects, or a server that serves two users. One Database can be used from several threads as well: operations on the same file are serialised by a lock that every Database object of the process shares for that file, because SQLite allows one writer at a time and two unserialised writers race on shared rows (a second insert of the same bus type) or fail with database is locked. Operations on different files never wait for each other. Separate processes on one file rely on SQLite's own locking.

The module-level helpers

# fragment: assumes a network `net` named "demo"
db = gi.start_dbsession("library.db")   # returns the default Database
gi.save_network_to_db(network=net, overwrite=True)
recovered_net = gi.load_network_from_db(name="demo")
db.list_networks()                       # the same object, all methods
gi.close_dbsession()

gi.start_dbsession(path) opens the default database, and gi.save_bustype_to_db, gi.load_bustypes_from_db, gi.save_branchtype_to_db, gi.load_branchtypes_from_db, gi.save_network_to_db and gi.load_network_from_db use it. Names, arguments, messages and errors are those of 0.6.0: without a started session they raise RuntimeError, and a second start_dbsession for another file raises unless force=True. Since the default is a Database, the call now returns it. The lower-level CRUD functions in groundinsight.database.crud take an explicit SQLAlchemy Session argument; use them with with db.session() as session:.

Deprecated: gi.session and gi.db_session

Up to 0.6.0 the session lived in module globals: gi.session, its alias gi.db_session, gi.engine and gi.SessionLocal. They still resolve — to the default database's thread-local scoped session (the same object for both names), its engine and its session factory, or None without a started session — but every access raises a DeprecationWarning. They will be removed no earlier than two releases and six months after the release that deprecated them. session and db_session are no longer in __all__, so a star import does not trigger the warning.

Before Now
crud.save_network(net, gi.session) db.save_network(net), or with db.session() as s: crud.save_network(net, s)
gi.session() (a thread-local Session) with db.session() as s: ... (a short-lived Session)
gi.engine db.engine
gi.SessionLocal() with db.session() as s: ...

db is a gi.Database(path), or the object returned by gi.start_dbsession(path).

Cross-repo version helper: gi.show_versions()

Returns a dictionary with the installed versions of groundinsight, the active Python and platform, and — if importable — the peer packages groundfield and groundmeas. The companion packages offer the same helper, so a bug report can include the full earthing-platform stack with a single call:

>>> import groundinsight as gi
>>> gi.show_versions()
{'groundinsight': '<installed version>',
 'python': '<running interpreter>',
 'platform': 'Linux-...-x86_64-...'}

Database object and module-level helpers

store

The SQLite store as an object: :class:Database.

Persistence through module globals -- an engine, a SessionLocal and one scoped session -- would allow exactly one database per process, and every caller would share one thread-local session registry. A desktop application with two open projects, a server that serves two users, or a study that writes results while the GUI reads the type catalogue cannot work like that. The module-level names survive only as deprecated aliases of the default instance (groundinsight.session, groundinsight.engine, ...).

:class:Database owns its engine and its session factory. Every method opens a short-lived session, does one operation and closes it again, so no SQLAlchemy Session -- which is not thread-safe -- is ever shared between threads. Two Database objects on two files are fully independent and can be used from two threads at the same time.

One file, several threads

SQLite allows one writer at a time. Two threads that write the same file through separate connections race: the second INSERT of a shared bus type fails with an IntegrityError, or a write waits for the busy timeout and fails with database is locked. Operations on the same file are therefore serialised with a re-entrant lock that is shared by every Database object of this process on that file (keyed by the resolved path), not only by one object. Operations on different files never wait for each other. Separate processes on one file rely on SQLite's own locking, as before.

The default instance

The module-level functions -- :func:start_dbsession, :func:close_dbsession, :func:save_bustype_to_db, :func:load_bustypes_from_db, :func:save_branchtype_to_db, :func:load_branchtypes_from_db, :func:save_network_to_db, :func:load_network_from_db -- delegate to a default Database that :func:start_dbsession creates for the configured path and returns; without one they raise RuntimeError rather than silently creating grounding.db in the working directory.

The globals groundinsight.session, db_session, engine and SessionLocal are deprecated aliases resolved through the package's module-level __getattr__ (PEP 562); see :func:deprecated_attribute.

Database

Database(path: _PathLike, *, migrate: bool = True)

A SQLite database of bus types, branch types and networks.

The object owns its SQLAlchemy engine and session factory; each method runs in its own short-lived session. Several Database objects -- on the same or on different files -- can be open at the same time, and one object can be used from several threads.

Parameters:

Name Type Description Default
path str or PathLike

The SQLite file; created if it does not exist. ":memory:" gives a private in-memory database that lives as long as the object.

required
migrate (bool, optional, keyword - only)

If True (the default), a file written by an earlier release is converted to the current schema before the engine is bound, after the unmodified file has been copied to <path>.bak (see :func:groundinsight.migrate_database). If False, the file is left untouched and the first read or write of a legacy file raises a RuntimeError that names :meth:migrate.

True

Raises:

Type Description
ValueError

If the automatic migration refuses the file (for example a pickled frequency list that is not a list of numbers).

RuntimeError

If the automatic migration cannot convert the file.

DatabaseError

If the file is not a SQLite database.

Notes

Bus and branch types are a global catalogue inside one database: every stored network references its types by name. Saving a network whose type formulas differ from the stored ones, while another stored network uses that type, is refused unless overwrite_types=True.

Operations on the same file are serialised by a lock that every Database object of the process shares for that file; operations on different files run in parallel. Use the object as a context manager, or call :meth:close, to release the file.

Examples:

>>> import groundinsight as gi
>>> with gi.Database("library.db") as db:
...     db.save_network(net)
...     db.list_networks()
['demo']
>>> with gi.Database(":memory:") as db:
...     db.list_networks()
[]
Source code in src/groundinsight/database/store.py
def __init__(self, path: _PathLike, *, migrate: bool = True) -> None:
    self._path = os.fspath(path)
    self._in_memory = self._path in _IN_MEMORY
    self._lock = (
        threading.RLock() if self._in_memory else _file_lock(self._path)
    )
    self._closed = False
    self._scoped: Optional[scoped_session] = None
    with self._lock:
        if self._in_memory:
            # One shared connection: an in-memory database exists once per
            # connection, and the lock above serialises its use.
            engine = create_engine(
                "sqlite://",
                poolclass=StaticPool,
                connect_args={"check_same_thread": False},
            )
        else:
            if migrate:
                # Convert a file with an earlier schema *before*
                # binding to it: ``create_all`` only ever creates missing
                # tables and would leave a legacy file looking fine until
                # the first query hit a missing column.
                migrate_database(self._path)
            # ``URL.create`` instead of an f-string: a path containing
            # ``?`` or ``#`` would otherwise be parsed as URL syntax.
            engine = create_engine(URL.create("sqlite", database=self._path))
        try:
            Base.metadata.create_all(engine)
        except Exception:
            engine.dispose()
            raise
    self._engine: Engine = engine
    self._session_factory = sessionmaker(bind=engine)
    logger.debug("Opened database '%s'.", self._path)

closed property

closed: bool

Whether :meth:close has run (bool).

Returns:

Type Description
bool

True after :meth:close.

engine property

engine: Engine

The SQLAlchemy engine this database owns.

For direct SQL access. Prefer :meth:session for ORM work; do not dispose the engine yourself -- :meth:close does that.

Returns:

Type Description
Engine

The engine of the SQLite file.

path property

path: str

The database file as given to the constructor (str).

Returns:

Type Description
str

The path of the SQLite file.

__enter__

__enter__() -> Database

Return the database itself; :meth:close runs on exit.

Source code in src/groundinsight/database/store.py
def __enter__(self) -> "Database":
    """Return the database itself; :meth:`close` runs on exit."""
    return self

__exit__

__exit__(exc_type, exc_value, traceback) -> None

Close the database; exceptions from the block propagate.

Source code in src/groundinsight/database/store.py
def __exit__(self, exc_type, exc_value, traceback) -> None:
    """Close the database; exceptions from the block propagate."""
    self.close()

__repr__

__repr__() -> str

Show the path, and whether the database is closed.

Source code in src/groundinsight/database/store.py
def __repr__(self) -> str:
    """Show the path, and whether the database is closed."""
    state = ", closed" if self._closed else ""
    return f"Database({self._path!r}{state})"

close

close() -> None

Release the database: drop the connections and dispose the engine.

Idempotent and never raises; problems while tearing down are logged at WARNING. Every later operation raises RuntimeError.

Source code in src/groundinsight/database/store.py
def close(self) -> None:
    """
    Release the database: drop the connections and dispose the engine.

    Idempotent and never raises; problems while tearing down are logged at
    ``WARNING``. Every later operation raises ``RuntimeError``.
    """
    with self._lock:
        if self._closed:
            return
        self._closed = True
        if self._scoped is not None:
            try:
                self._scoped.remove()
            except Exception as exc:  # pragma: no cover - defensive
                logger.warning("Error while removing scoped session: %s", exc)
            self._scoped = None
        try:
            self._engine.dispose()
        except Exception as exc:  # pragma: no cover - defensive
            logger.warning("Error while disposing engine: %s", exc)
    logger.debug("Closed database '%s'.", self._path)

delete_branchtype

delete_branchtype(name: str) -> None

Delete a stored BranchType that no stored network uses.

Parameters:

Name Type Description Default
name str

Name of the type.

required

Raises:

Type Description
ValueError

If the type is not stored, or a stored network still uses it.

RuntimeError

If the database is closed, or still uses the legacy schema.

Source code in src/groundinsight/database/store.py
def delete_branchtype(self, name: str) -> None:
    """
    Delete a stored BranchType that no stored network uses.

    Parameters
    ----------
    name : str
        Name of the type.

    Raises
    ------
    ValueError
        If the type is not stored, or a stored network still uses it.
    RuntimeError
        If the database is closed, or still uses the legacy schema.
    """
    with self.session() as session:
        crud.delete_branchtype(name, session)

delete_bustype

delete_bustype(name: str) -> None

Delete a stored BusType that no stored network uses.

Parameters:

Name Type Description Default
name str

Name of the type.

required

Raises:

Type Description
ValueError

If the type is not stored, or a stored network still uses it.

RuntimeError

If the database is closed, or still uses the legacy schema.

Source code in src/groundinsight/database/store.py
def delete_bustype(self, name: str) -> None:
    """
    Delete a stored BusType that no stored network uses.

    Parameters
    ----------
    name : str
        Name of the type.

    Raises
    ------
    ValueError
        If the type is not stored, or a stored network still uses it.
    RuntimeError
        If the database is closed, or still uses the legacy schema.
    """
    with self.session() as session:
        crud.delete_bustype(name, session)

delete_network

delete_network(name: str) -> None

Delete a stored network and all of its elements; types stay.

Parameters:

Name Type Description Default
name str

Name of the network.

required

Raises:

Type Description
ValueError

If no network of that name is stored.

RuntimeError

If the database is closed, or still uses the legacy schema.

Source code in src/groundinsight/database/store.py
def delete_network(self, name: str) -> None:
    """
    Delete a stored network and all of its elements; types stay.

    Parameters
    ----------
    name : str
        Name of the network.

    Raises
    ------
    ValueError
        If no network of that name is stored.
    RuntimeError
        If the database is closed, or still uses the legacy schema.
    """
    with self.session() as session:
        crud.delete_network(name, session)

list_networks

list_networks() -> List[str]

Names of the stored networks.

Returns:

Type Description
list of str

Sorted names.

Raises:

Type Description
RuntimeError

If the database is closed, or still uses the legacy schema.

Source code in src/groundinsight/database/store.py
def list_networks(self) -> List[str]:
    """
    Names of the stored networks.

    Returns
    -------
    list of str
        Sorted names.

    Raises
    ------
    RuntimeError
        If the database is closed, or still uses the legacy schema.
    """
    with self.session() as session:
        return crud.list_networks(session)

load_branchtypes

load_branchtypes() -> Dict[str, BranchType]

Load every stored BranchType.

Returns:

Type Description
dict of str to BranchType

The types, keyed by name.

Raises:

Type Description
RuntimeError

If the database is closed.

Source code in src/groundinsight/database/store.py
def load_branchtypes(self) -> Dict[str, BranchType]:
    """
    Load every stored BranchType.

    Returns
    -------
    dict of str to BranchType
        The types, keyed by name.

    Raises
    ------
    RuntimeError
        If the database is closed.
    """
    with self.session() as session:
        return crud.load_branchtypes(session)

load_bustypes

load_bustypes() -> Dict[str, BusType]

Load every stored BusType.

Returns:

Type Description
dict of str to BusType

The types, keyed by name.

Raises:

Type Description
RuntimeError

If the database is closed.

Source code in src/groundinsight/database/store.py
def load_bustypes(self) -> Dict[str, BusType]:
    """
    Load every stored BusType.

    Returns
    -------
    dict of str to BusType
        The types, keyed by name.

    Raises
    ------
    RuntimeError
        If the database is closed.
    """
    with self.session() as session:
        return crud.load_bustypes(session)

load_network

load_network(name: str) -> Network

Load a stored network by name.

Parameters:

Name Type Description Default
name str

Name of the network.

required

Returns:

Type Description
Network

The network, with the results stored with it.

Raises:

Type Description
ValueError

If no network of that name is stored.

RuntimeError

If the database is closed, or still uses the legacy schema.

Source code in src/groundinsight/database/store.py
def load_network(self, name: str) -> Network:
    """
    Load a stored network by name.

    Parameters
    ----------
    name : str
        Name of the network.

    Returns
    -------
    Network
        The network, with the results stored with it.

    Raises
    ------
    ValueError
        If no network of that name is stored.
    RuntimeError
        If the database is closed, or still uses the legacy schema.
    """
    with self.session() as session:
        return crud.load_network(name, session)

migrate

migrate(backup: bool = True) -> MigrationReport

Convert the file to the current schema (for migrate=False).

The engine's pooled connections are released first, because the conversion may replace the file.

Parameters:

Name Type Description Default
backup bool

Copy the unmodified file to <path>.bak first. Defaults to True.

True

Returns:

Type Description
MigrationReport

What was done, and what could not be recovered.

Raises:

Type Description
RuntimeError

If the database is closed, or the file cannot be converted.

ValueError

If the file carries a payload the migration refuses.

Source code in src/groundinsight/database/store.py
def migrate(self, backup: bool = True) -> MigrationReport:
    """
    Convert the file to the current schema (for ``migrate=False``).

    The engine's pooled connections are released first, because the
    conversion may replace the file.

    Parameters
    ----------
    backup : bool, optional
        Copy the unmodified file to ``<path>.bak`` first. Defaults to
        ``True``.

    Returns
    -------
    MigrationReport
        What was done, and what could not be recovered.

    Raises
    ------
    RuntimeError
        If the database is closed, or the file cannot be converted.
    ValueError
        If the file carries a payload the migration refuses.
    """
    with self._lock:
        self._require_open()
        if self._in_memory:
            return MigrationReport(path=self._path)
        self._engine.dispose()
        report = migrate_database(self._path, backup=backup)
        Base.metadata.create_all(self._engine)
        return report

needs_migration

needs_migration() -> str

Classify the file against the current schema.

Returns:

Type Description
str

"none", "legacy_scoped", "add_columns" or "pickle_frequencies"; see :func:groundinsight.needs_migration.

Source code in src/groundinsight/database/store.py
def needs_migration(self) -> str:
    """
    Classify the file against the current schema.

    Returns
    -------
    str
        ``"none"``, ``"legacy_scoped"``, ``"add_columns"`` or
        ``"pickle_frequencies"``; see
        :func:`groundinsight.needs_migration`.
    """
    if self._in_memory:
        return "none"
    with self._lock:
        return needs_migration(self._path)

save_branchtype

save_branchtype(
    branch_type: BranchType, overwrite: bool = False
) -> None

Save a BranchType to the catalogue.

Parameters:

Name Type Description Default
branch_type BranchType

The type to save.

required
overwrite bool

Replace a stored type of the same name. Defaults to False.

False

Raises:

Type Description
ValueError

If the type exists and overwrite is False.

RuntimeError

If the database is closed.

Source code in src/groundinsight/database/store.py
def save_branchtype(self, branch_type: BranchType, overwrite: bool = False) -> None:
    """
    Save a BranchType to the catalogue.

    Parameters
    ----------
    branch_type : BranchType
        The type to save.
    overwrite : bool, optional
        Replace a stored type of the same name. Defaults to ``False``.

    Raises
    ------
    ValueError
        If the type exists and ``overwrite`` is ``False``.
    RuntimeError
        If the database is closed.
    """
    with self.session() as session:
        if (
            session.get(BranchTypeDB, branch_type.name) is not None
            and not overwrite
        ):
            raise ValueError(
                f"BranchType '{branch_type.name}' already exists. Use "
                "overwrite=True to overwrite."
            )
        crud.save_branchtype(branch_type, session)

save_bustype

save_bustype(
    bus_type: BusType, overwrite: bool = False
) -> None

Save a BusType to the catalogue.

Parameters:

Name Type Description Default
bus_type BusType

The type to save.

required
overwrite bool

Replace a stored type of the same name. Defaults to False.

False

Raises:

Type Description
ValueError

If the type exists and overwrite is False.

RuntimeError

If the database is closed.

Source code in src/groundinsight/database/store.py
def save_bustype(self, bus_type: BusType, overwrite: bool = False) -> None:
    """
    Save a BusType to the catalogue.

    Parameters
    ----------
    bus_type : BusType
        The type to save.
    overwrite : bool, optional
        Replace a stored type of the same name. Defaults to ``False``.

    Raises
    ------
    ValueError
        If the type exists and ``overwrite`` is ``False``.
    RuntimeError
        If the database is closed.
    """
    with self.session() as session:
        if session.get(BusTypeDB, bus_type.name) is not None and not overwrite:
            raise ValueError(
                f"BusType '{bus_type.name}' already exists. Use "
                "overwrite=True to overwrite."
            )
        crud.save_bustype(bus_type, session)

save_network

save_network(
    network: Network,
    overwrite: bool = False,
    overwrite_types: bool = False,
) -> None

Save a network with all of its elements and results, in one transaction.

Parameters:

Name Type Description Default
network Network

The network to save. Its stored results (network.results) are saved with it, as a JSON column of the network row.

required
overwrite bool

Replace a stored network of the same name. Defaults to False.

False
overwrite_types bool

Allow this save to rewrite the formulas of bus/branch types that other stored networks also use. Defaults to False.

False

Raises:

Type Description
ValueError

If the network exists and overwrite is False, if a path references a branch that is not in the network, or if a shared type would be rewritten without overwrite_types=True.

RuntimeError

If the database is closed, or still uses the legacy schema.

See Also

groundinsight.database.crud.save_network : The transaction itself.

Source code in src/groundinsight/database/store.py
def save_network(
    self,
    network: Network,
    overwrite: bool = False,
    overwrite_types: bool = False,
) -> None:
    """
    Save a network with all of its elements and results, in one transaction.

    Parameters
    ----------
    network : Network
        The network to save. Its stored results (``network.results``) are
        saved with it, as a JSON column of the network row.
    overwrite : bool, optional
        Replace a stored network of the same name. Defaults to ``False``.
    overwrite_types : bool, optional
        Allow this save to rewrite the formulas of bus/branch types that
        other stored networks also use. Defaults to ``False``.

    Raises
    ------
    ValueError
        If the network exists and ``overwrite`` is ``False``, if a path
        references a branch that is not in the network, or if a shared
        type would be rewritten without ``overwrite_types=True``.
    RuntimeError
        If the database is closed, or still uses the legacy schema.

    See Also
    --------
    groundinsight.database.crud.save_network : The transaction itself.
    """
    with self.session() as session:
        if session.get(NetworkDB, network.name) is not None and not overwrite:
            raise ValueError(
                f"Network '{network.name}' already exists. Use "
                "overwrite=True to overwrite."
            )
        crud.save_network(
            network, session, overwrite=overwrite, overwrite_types=overwrite_types
        )

session

session() -> Iterator[Session]

A short-lived SQLAlchemy session for direct ORM access.

The session is closed -- not committed -- when the block ends; commit explicitly if you write. Operations on this file wait until the block has finished.

Yields:

Type Description
Session

A new session bound to this database.

Raises:

Type Description
RuntimeError

If the database is closed.

Examples:

>>> from groundinsight.database.crud import load_network
>>> with db.session() as session:
...     net = load_network("demo", session)
Source code in src/groundinsight/database/store.py
@contextlib.contextmanager
def session(self) -> Iterator[Session]:
    """
    A short-lived SQLAlchemy session for direct ORM access.

    The session is closed -- not committed -- when the block ends; commit
    explicitly if you write. Operations on this file wait until the block
    has finished.

    Yields
    ------
    sqlalchemy.orm.Session
        A new session bound to this database.

    Raises
    ------
    RuntimeError
        If the database is closed.

    Examples
    --------
    >>> from groundinsight.database.crud import load_network
    >>> with db.session() as session:  # doctest: +SKIP
    ...     net = load_network("demo", session)
    """
    with self._lock:
        self._require_open()
        session = self._session_factory()
        try:
            yield session
        finally:
            session.close()

close_dbsession

close_dbsession() -> None

Close the default database opened by :func:start_dbsession.

Never raises. Logs at WARNING if no session is active and at INFO when one was closed. :class:Database objects created directly are not affected.

Examples:

>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> gi.close_dbsession()
Source code in src/groundinsight/database/store.py
def close_dbsession() -> None:
    """
    Close the default database opened by :func:`start_dbsession`.

    Never raises. Logs at ``WARNING`` if no session is active and at ``INFO``
    when one was closed. :class:`Database` objects created directly are not
    affected.

    Examples
    --------
    >>> import groundinsight as gi
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> gi.close_dbsession()  # doctest: +SKIP
    """
    global _default
    with _default_guard:
        current, _default = _default, None
    if current is None:
        logger.warning("No database session to close.")
        return
    try:
        current.close()
    except Exception as exc:  # pragma: no cover - Database.close never raises
        logger.warning("Error while closing database '%s': %s", current.path, exc)
    logger.info("Database session closed.")

default_database

default_database() -> Optional[Database]

The database the module-level functions use, if one is open.

Returns:

Type Description
Database or None

The object :func:start_dbsession created, or None when no session is started (or the object was closed directly).

Source code in src/groundinsight/database/store.py
def default_database() -> Optional[Database]:
    """
    The database the module-level functions use, if one is open.

    Returns
    -------
    Database or None
        The object :func:`start_dbsession` created, or ``None`` when no
        session is started (or the object was closed directly).
    """
    database = _default
    if database is None or database.closed:
        return None
    return database

deprecated_attribute

deprecated_attribute(name: str)

The value behind a deprecated package global.

Parameters:

Name Type Description Default
name str

One of :data:DEPRECATED_ATTRIBUTES.

required

Returns:

Type Description
object or None

None while no default database is open (as the globals were); otherwise the default database's thread-local scoped session for session / db_session (the same object for both), its engine for engine and its session factory for SessionLocal.

Raises:

Type Description
AttributeError

If name is not a deprecated attribute.

Source code in src/groundinsight/database/store.py
def deprecated_attribute(name: str):
    """
    The value behind a deprecated package global.

    Parameters
    ----------
    name : str
        One of :data:`DEPRECATED_ATTRIBUTES`.

    Returns
    -------
    object or None
        ``None`` while no default database is open (as the globals were);
        otherwise the default database's thread-local scoped session for
        ``session`` / ``db_session`` (the same object for both), its engine
        for ``engine`` and its session factory for ``SessionLocal``.

    Raises
    ------
    AttributeError
        If ``name`` is not a deprecated attribute.
    """
    if name not in DEPRECATED_ATTRIBUTES:
        raise AttributeError(name)
    database = default_database()
    if database is None:
        return None
    if name in ("session", "db_session"):
        return database._legacy_scoped_session()
    if name == "engine":
        return database.engine
    return database._session_factory

deprecation_message

deprecation_message(name: str) -> str

The DeprecationWarning text for a former package global.

Parameters:

Name Type Description Default
name str

One of :data:DEPRECATED_ATTRIBUTES.

required

Returns:

Type Description
str

Message naming the replacement and the removal policy.

Source code in src/groundinsight/database/store.py
def deprecation_message(name: str) -> str:
    """
    The ``DeprecationWarning`` text for a former package global.

    Parameters
    ----------
    name : str
        One of :data:`DEPRECATED_ATTRIBUTES`.

    Returns
    -------
    str
        Message naming the replacement and the removal policy.
    """
    return (
        f"groundinsight.{name} is deprecated and will be removed no earlier "
        "than two releases and six months after the release that deprecated "
        f"it. Use {_REPLACEMENTS[name]} instead: db = gi.Database(path), or "
        "the object returned by gi.start_dbsession(path)."
    )

load_branchtypes_from_db

load_branchtypes_from_db() -> Dict[str, BranchType]

Load all BranchTypes from the default database.

Returns:

Type Description
dict of str to BranchType

A dictionary of BranchType instances keyed by their names.

Raises:

Type Description
RuntimeError

If the database session is not started.

Examples:

>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> sorted(gi.load_branchtypes_from_db())
['cable']
Source code in src/groundinsight/database/store.py
def load_branchtypes_from_db() -> Dict[str, BranchType]:
    """
    Load all BranchTypes from the default database.

    Returns
    -------
    dict of str to BranchType
        A dictionary of BranchType instances keyed by their names.

    Raises
    ------
    RuntimeError
        If the database session is not started.

    Examples
    --------
    >>> import groundinsight as gi
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> sorted(gi.load_branchtypes_from_db())  # doctest: +SKIP
    ['cable']
    """
    return _require_default().load_branchtypes()

load_bustypes_from_db

load_bustypes_from_db() -> Dict[str, BusType]

Load all BusTypes from the default database.

Returns:

Type Description
dict of str to BusType

A dictionary of BusType instances keyed by their names.

Raises:

Type Description
RuntimeError

If the database session is not started.

Examples:

>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> sorted(gi.load_bustypes_from_db())
['station']
Source code in src/groundinsight/database/store.py
def load_bustypes_from_db() -> Dict[str, BusType]:
    """
    Load all BusTypes from the default database.

    Returns
    -------
    dict of str to BusType
        A dictionary of BusType instances keyed by their names.

    Raises
    ------
    RuntimeError
        If the database session is not started.

    Examples
    --------
    >>> import groundinsight as gi
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> sorted(gi.load_bustypes_from_db())  # doctest: +SKIP
    ['station']
    """
    return _require_default().load_bustypes()

load_network_from_db

load_network_from_db(name: str) -> Network

Load a Network from the default database by name.

Parameters:

Name Type Description Default
name str

The name of the Network to load.

required

Returns:

Type Description
Network

The loaded Network instance.

Raises:

Type Description
RuntimeError

If the database session is not started.

ValueError

If the Network with the specified name does not exist.

Examples:

>>> import groundinsight as gi
>>> gi.start_dbsession("grid.db")
>>> net = gi.load_network_from_db("SmokeTest")
>>> sorted(net.buses)
['bus1', 'bus2', 'bus3']
Source code in src/groundinsight/database/store.py
def load_network_from_db(name: str) -> Network:
    """
    Load a Network from the default database by name.

    Parameters
    ----------
    name : str
        The name of the Network to load.

    Returns
    -------
    Network
        The loaded Network instance.

    Raises
    ------
    RuntimeError
        If the database session is not started.
    ValueError
        If the Network with the specified name does not exist.

    Examples
    --------
    >>> import groundinsight as gi
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> net = gi.load_network_from_db("SmokeTest")  # doctest: +SKIP
    >>> sorted(net.buses)  # doctest: +SKIP
    ['bus1', 'bus2', 'bus3']
    """
    return _require_default().load_network(name)

save_branchtype_to_db

save_branchtype_to_db(
    branch_type: BranchType, overwrite: bool = False
) -> None

Save a BranchType to the default database.

Parameters:

Name Type Description Default
branch_type BranchType

The BranchType instance to save.

required
overwrite bool

Whether to overwrite an existing BranchType with the same name. Defaults to False.

False

Raises:

Type Description
RuntimeError

If the database session is not started.

ValueError

If the BranchType already exists and overwrite is False.

Examples:

>>> import groundinsight as gi
>>> cable = gi.BranchType(name="cable", grounding_conductor=True,
...                       self_impedance_formula="(0.25 + j * f * 0.012) * l",
...                       mutual_impedance_formula="j * f * 0.012 * l")
>>> gi.start_dbsession("grid.db")
>>> gi.save_branchtype_to_db(cable)
Source code in src/groundinsight/database/store.py
def save_branchtype_to_db(branch_type: BranchType, overwrite: bool = False) -> None:
    """
    Save a BranchType to the default database.

    Parameters
    ----------
    branch_type : BranchType
        The BranchType instance to save.
    overwrite : bool, optional
        Whether to overwrite an existing BranchType with the same name.
        Defaults to ``False``.

    Raises
    ------
    RuntimeError
        If the database session is not started.
    ValueError
        If the BranchType already exists and ``overwrite`` is ``False``.

    Examples
    --------
    >>> import groundinsight as gi
    >>> cable = gi.BranchType(name="cable", grounding_conductor=True,
    ...                       self_impedance_formula="(0.25 + j * f * 0.012) * l",
    ...                       mutual_impedance_formula="j * f * 0.012 * l")
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> gi.save_branchtype_to_db(cable)  # doctest: +SKIP
    """
    _require_default().save_branchtype(branch_type, overwrite=overwrite)

save_bustype_to_db

save_bustype_to_db(
    bus_type: BusType, overwrite: bool = False
) -> None

Save a BusType to the default database.

Parameters:

Name Type Description Default
bus_type BusType

The BusType instance to save.

required
overwrite bool

Whether to overwrite an existing BusType with the same name. Defaults to False.

False

Raises:

Type Description
RuntimeError

If the database session is not started.

ValueError

If the BusType already exists and overwrite is False.

Examples:

>>> import groundinsight as gi
>>> station = gi.BusType(name="station", system_type="Substation",
...                      voltage_level=20.0, impedance_formula="rho * 0.01")
>>> gi.start_dbsession("grid.db")
>>> gi.save_bustype_to_db(station)
Source code in src/groundinsight/database/store.py
def save_bustype_to_db(bus_type: BusType, overwrite: bool = False) -> None:
    """
    Save a BusType to the default database.

    Parameters
    ----------
    bus_type : BusType
        The BusType instance to save.
    overwrite : bool, optional
        Whether to overwrite an existing BusType with the same name.
        Defaults to ``False``.

    Raises
    ------
    RuntimeError
        If the database session is not started.
    ValueError
        If the BusType already exists and ``overwrite`` is ``False``.

    Examples
    --------
    >>> import groundinsight as gi
    >>> station = gi.BusType(name="station", system_type="Substation",
    ...                      voltage_level=20.0, impedance_formula="rho * 0.01")
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> gi.save_bustype_to_db(station)  # doctest: +SKIP
    """
    _require_default().save_bustype(bus_type, overwrite=overwrite)

save_network_to_db

save_network_to_db(
    network: Network,
    overwrite: bool = False,
    overwrite_types: bool = False,
) -> None

Save a Network to the default database.

Parameters:

Name Type Description Default
network Network

The Network instance to save.

required
overwrite bool

Whether to overwrite an existing Network with the same name. Defaults to False.

False
overwrite_types bool

Whether this save may rewrite the formulas of bus/branch types that other stored networks also reference. Bus and branch types are a global catalogue keyed by name, so such a change reaches those networks as well. Defaults to False, which raises instead.

False

Raises:

Type Description
RuntimeError

If the database session is not started.

ValueError

If the Network already exists and overwrite is False, or if a shared type definition would be rewritten and overwrite_types is False.

Examples:

>>> import groundinsight as gi
>>> from groundinsight.api.examples import build_minimal
>>> net = build_minimal()
>>> gi.start_dbsession("grid.db")
>>> gi.save_network_to_db(net, overwrite=True)
Source code in src/groundinsight/database/store.py
def save_network_to_db(
    network: Network, overwrite: bool = False, overwrite_types: bool = False
) -> None:
    """
    Save a Network to the default database.

    Parameters
    ----------
    network : Network
        The Network instance to save.
    overwrite : bool, optional
        Whether to overwrite an existing Network with the same name.
        Defaults to ``False``.
    overwrite_types : bool, optional
        Whether this save may rewrite the formulas of bus/branch types that
        other stored networks also reference. Bus and branch types are a
        *global* catalogue keyed by name, so such a change reaches those
        networks as well. Defaults to ``False``, which raises instead.

    Raises
    ------
    RuntimeError
        If the database session is not started.
    ValueError
        If the Network already exists and ``overwrite`` is ``False``, or if a
        shared type definition would be rewritten and ``overwrite_types`` is
        ``False``.

    Examples
    --------
    >>> import groundinsight as gi
    >>> from groundinsight.api.examples import build_minimal
    >>> net = build_minimal()
    >>> gi.start_dbsession("grid.db")  # doctest: +SKIP
    >>> gi.save_network_to_db(net, overwrite=True)  # doctest: +SKIP
    """
    _require_default().save_network(
        network, overwrite=overwrite, overwrite_types=overwrite_types
    )

start_dbsession

start_dbsession(
    sqlite_path: str = "grounding.db",
    force: bool = False,
    migrate: bool = True,
) -> Database

Open the default database used by the module-level persistence functions.

Idempotent in the safe direction: if a session is already active for the same sqlite_path, it is kept and a WARNING is logged. Binding to a different file raises RuntimeError unless force=True, in which case the previous database is closed first. To work with several files at once, use :class:Database objects instead.

A file written by an earlier release is migrated to the current schema before it is opened, after the unmodified file has been copied to <sqlite_path>.bak; see :func:groundinsight.database.migration.migrate_database.

Parameters:

Name Type Description Default
sqlite_path str

The SQLite file. Defaults to "grounding.db".

'grounding.db'
force bool

Close an active default database for another file and rebind. Defaults to False.

False
migrate bool

Convert a database written by an earlier release (the default). Set to False to leave the file untouched and get an explanatory RuntimeError from the first read or write instead.

True

Returns:

Type Description
Database

The default database. Its methods (list_networks, delete_network, session ...) are available directly; the module-level functions use the same object.

Raises:

Type Description
RuntimeError

If a session is already active for a different sqlite_path and force is not set.

Examples:

>>> import groundinsight as gi
>>> db = gi.start_dbsession("library.db")
>>> gi.save_network_to_db(net)
>>> db.list_networks()
['demo']
>>> gi.close_dbsession()
Source code in src/groundinsight/database/store.py
def start_dbsession(
    sqlite_path: str = "grounding.db",
    force: bool = False,
    migrate: bool = True,
) -> Database:
    """
    Open the default database used by the module-level persistence functions.

    Idempotent in the safe direction: if a session is already active for the
    *same* ``sqlite_path``, it is kept and a ``WARNING`` is logged. Binding to
    a *different* file raises ``RuntimeError`` unless ``force=True``, in which
    case the previous database is closed first. To work with several files at
    once, use :class:`Database` objects instead.

    A file written by an earlier release is migrated to the current schema
    before it is opened, after the unmodified file has been copied to
    ``<sqlite_path>.bak``; see
    :func:`groundinsight.database.migration.migrate_database`.

    Parameters
    ----------
    sqlite_path : str, optional
        The SQLite file. Defaults to ``"grounding.db"``.
    force : bool, optional
        Close an active default database for another file and rebind.
        Defaults to ``False``.
    migrate : bool, optional
        Convert a database written by an earlier release (the default). Set
        to ``False`` to leave the file untouched and get an explanatory
        ``RuntimeError`` from the first read or write instead.

    Returns
    -------
    Database
        The default database. Its methods (``list_networks``,
        ``delete_network``, ``session`` ...) are available directly; the
        module-level functions use the same object.

    Raises
    ------
    RuntimeError
        If a session is already active for a different ``sqlite_path`` and
        ``force`` is not set.

    Examples
    --------
    >>> import groundinsight as gi
    >>> db = gi.start_dbsession("library.db")  # doctest: +SKIP
    >>> gi.save_network_to_db(net)  # doctest: +SKIP
    >>> db.list_networks()  # doctest: +SKIP
    ['demo']
    >>> gi.close_dbsession()  # doctest: +SKIP
    """
    global _default
    with _default_guard:
        current = default_database()
        if current is not None:
            requested = os.fspath(sqlite_path)
            if current.path == requested and not force:
                logger.warning(
                    "Database session already started for '%s' — re-using "
                    "existing engine.",
                    sqlite_path,
                )
                return current
            current_url = f"sqlite:///{current.path}"
            if not force:
                raise RuntimeError(
                    "A database session is already active for "
                    f"'{current_url}'. Call gi.close_dbsession() before "
                    f"binding to '{sqlite_path}', or pass force=True to "
                    "dispose the existing engine and rebind."
                )
            logger.warning(
                "Forcing re-bind of database session from '%s' to '%s'.",
                current_url,
                f"sqlite:///{requested}",
            )
            close_dbsession()
        _default = Database(sqlite_path, migrate=migrate)
        logger.info("Database session started with '%s'.", sqlite_path)
        return _default

Migration of older files

gi.needs_migration(path) classifies a file, gi.migrate_database(path, backup=True) converts it in place after keeping a .bak copy and returns a gi.MigrationReport; gi.Database(path) does both when it opens a file. Save, load and migrate walks through a migration.

migration

Schema migration for existing SQLite databases.

The legacy schema -- files written by groundinsight 0.4.0 and earlier -- keys buses, branches, faults, sources and paths by element name alone and links them to their network through the association tables network_buses, network_branches, network_faults, network_sources and network_paths. Two networks that contain an element of the same name therefore share one physical row, so saving one network silently rewrites the other. The current schema keys the element tables by (network_name, name).

Base.metadata.create_all only ever creates missing tables — it never adds a column to an existing one — so an old database file opens without complaint and then fails deep inside a query with a bare OperationalError: no such column: buses.network_name. This module converts such a file instead, so an existing user keeps working:

  • :func:needs_migration reports what, if anything, has to change.
  • :func:migrate_database performs the conversion, after copying the file to a .bak sibling.

:func:groundinsight.start_dbsession calls :func:migrate_database automatically; pass migrate=False to get the diagnostic error instead.

Two properties of the legacy schema cannot be recovered and are reported rather than guessed:

Shared elements A bus that two networks both referenced existed once. Splitting the row per network can only duplicate the one surviving definition into each of them. If the networks meant different things by that name, the older definition is already gone — it was overwritten on the last save, before this migration ever ran. Every such name is listed in :attr:MigrationReport.shared_elements and logged at WARNING.

Path segment order The legacy path_segments table had no position column; a path was an unordered set of (path_name, branch_name) rows. Order is therefore reconstructed from SQLite's rowid, which reflects insertion order and hence the original segment sequence. The result is verified by walking each path bus-by-bus; paths whose segments do not form a chain are listed in :attr:MigrationReport.broken_paths and must be rebuilt with :func:groundinsight.create_paths.

Pickled frequency lists In a legacy file networks.frequencies is a SQLAlchemy PickleType. Loading such a file through the ORM would execute it: pickle.loads runs before any Pydantic validator sees the value, so a .db received from someone else would be arbitrary code execution. The current column is a JSON list, and the legacy blobs are converted here with a restrictive unpickler that only ever resolves builtins.list / float / int. Anything else aborts the migration with a :class:ValueError and leaves the file untouched; the payload is then a hostile file, not a frequency list.

MigrationReport

Bases: BaseModel

What :func:migrate_database did, and what a user has to check afterwards.

Attributes:

Name Type Description
migrated bool

True if the file was rewritten. False means it already used the current schema and was left untouched.

path str

The database file the report refers to.

backup_path Optional[str]

Where the pre-migration file was copied to, or None if no backup was taken (backup=False, or nothing needed migrating).

kind str

"none", "legacy_scoped" for the full rebuild from the name-keyed schema, or "add_columns" when only new nullable columns were missing.

networks List[str]

Networks found in the file.

rows Dict[str, int]

Rows written per table.

shared_elements Dict[str, List[str]]

"table:name" -> the networks that shared that one row. Non-empty means the migration had to duplicate a definition; see the module docstring.

orphaned Dict[str, List[str]]

table -> element names that no network referenced. They are not carried over — the new schema has nowhere to put them.

missing_rows Dict[str, List[str]]

table -> element names a network referenced but which had no row in the element table. Skipped.

broken_paths List[str]

"network:path" for paths whose reconstructed segment order does not form a connected chain.

defaulted_cells Dict[str, int]

"table.column" -> how many NULL\ s were replaced by the column's own declared default (see :func:_declared_defaults). A non-empty dict means values were filled in, so it counts towards :attr:needs_attention.

added_columns Dict[str, List[str]]

table -> columns added in place by the "add_columns" path.

converted_frequencies List[str]

Networks whose pickled frequencies blob was rewritten as a JSON list. A lossless conversion, so it does not count towards :attr:needs_attention.

unloadable Dict[str, str]

network -> the error :func:groundinsight.load_network_from_db raised for it on the converted file. A network listed here was written successfully but cannot be turned back into a :class:~groundinsight.models.core_models.Network, almost always because a column the database allows to be NULL is mandatory in the Pydantic model. The other networks in the file are unaffected.

Examples:

>>> from groundinsight import MigrationReport
>>> report = MigrationReport(migrated=True, path="grid.db", kind="legacy",
...                          networks=["netA"])
>>> report.needs_attention
False

needs_attention property

needs_attention: bool

True if the migration had to guess or drop something.

Returns:

Type Description
bool

Whether the report lists shared, dropped or unloadable elements.

needs_migration

needs_migration(sqlite_path: str) -> str

Classify an existing database file against the current schema.

Parameters:

Name Type Description Default
sqlite_path str

Path to the SQLite file. A path that does not exist, or an empty file, counts as "none" — create_all will lay out the current schema.

required

Returns:

Type Description
str

"none" if the file is already current, "legacy_scoped" if the element tables are still keyed by name alone and need the full rebuild, "add_columns" if the keys are current but columns added by a later release are missing, or "pickle_frequencies" if the only thing left is the pickled networks.frequencies column. "add_columns" also covers a file that needs both -- the in-place path performs both steps.

Examples:

>>> needs_migration("grounding.db")
'legacy_scoped'
Source code in src/groundinsight/database/migration.py
def needs_migration(sqlite_path: str) -> str:
    """
    Classify an existing database file against the current schema.

    Parameters
    ----------
    sqlite_path : str
        Path to the SQLite file. A path that does not exist, or an empty
        file, counts as ``"none"`` — ``create_all`` will lay out the current
        schema.

    Returns
    -------
    str
        ``"none"`` if the file is already current, ``"legacy_scoped"`` if the
        element tables are still keyed by name alone and need the full
        rebuild, ``"add_columns"`` if the keys are current but columns added
        by a later release are missing, or ``"pickle_frequencies"`` if the
        only thing left is the pickled ``networks.frequencies`` column.
        ``"add_columns"`` also covers a file that needs both -- the in-place
        path performs both steps.

    Examples
    --------
    >>> needs_migration("grounding.db")  # doctest: +SKIP
    'legacy_scoped'
    """
    if not os.path.exists(sqlite_path) or os.path.getsize(sqlite_path) == 0:
        return "none"

    conn = sqlite3.connect(sqlite_path)
    try:
        tables = _table_names(conn)
        if "buses" not in tables:
            # Not a groundinsight database yet, or an empty one.
            return "none"
        if "network_name" not in _column_names(conn, "buses"):
            return "legacy_scoped"

        metadata = _current_metadata()
        for table in metadata.sorted_tables:
            if table.name not in tables:
                # ``create_all`` will add a whole missing table by itself.
                continue
            present = set(_column_names(conn, table.name))
            for column in table.columns:
                if column.name not in present:
                    return "add_columns"
        if _pickled_frequency_networks(conn):
            return "pickle_frequencies"
        return "none"
    finally:
        conn.close()

migrate_database

migrate_database(
    sqlite_path: str, backup: bool = True
) -> MigrationReport

Bring an existing database file up to the current schema.

Safe to call on a file that is already current: it then does nothing, takes no backup, and returns a report with migrated=False.

The legacy conversion is written to a temporary sibling file and moved over the original with :func:os.replace, so an interruption leaves either the old file or the new one — never a half-converted database.

Parameters:

Name Type Description Default
sqlite_path str

Path to the SQLite file.

required
backup bool

Copy the file to <path>.bak before touching it. An existing backup is never overwritten; .bak.1, .bak.2 … are used instead. Defaults to True.

True

Returns:

Type Description
MigrationReport

What was done, and what could not be recovered. Check :attr:MigrationReport.needs_attention.

Raises:

Type Description
RuntimeError

If a NOT NULL column without a declared default is missing from an otherwise current file, which cannot be added in place; or if a legacy row has no value for a column the current schema requires and cannot default (see :func:_declared_defaults). In both cases the file on disk is left exactly as it was.

ValueError

If the legacy pickled networks.frequencies blob names anything but list / float / int, or does not decode to a list of numbers. Nothing is written in that case; the file is untrusted.

Examples:

>>> report = migrate_database("grounding.db")
>>> report.shared_elements
{'buses': ['A']}
Source code in src/groundinsight/database/migration.py
def migrate_database(sqlite_path: str, backup: bool = True) -> MigrationReport:
    """
    Bring an existing database file up to the current schema.

    Safe to call on a file that is already current: it then does nothing, takes
    no backup, and returns a report with ``migrated=False``.

    The legacy conversion is written to a temporary sibling file and moved over
    the original with :func:`os.replace`, so an interruption leaves either the
    old file or the new one — never a half-converted database.

    Parameters
    ----------
    sqlite_path : str
        Path to the SQLite file.
    backup : bool, optional
        Copy the file to ``<path>.bak`` before touching it. An existing
        backup is never overwritten; ``.bak.1``, ``.bak.2`` … are used
        instead. Defaults to ``True``.

    Returns
    -------
    MigrationReport
        What was done, and what could not be recovered. Check
        :attr:`MigrationReport.needs_attention`.

    Raises
    ------
    RuntimeError
        If a ``NOT NULL`` column without a declared default is missing from an
        otherwise current file, which cannot be added in place; or if a legacy
        row has no value for a column the current schema requires and cannot
        default (see :func:`_declared_defaults`). In both cases the file on
        disk is left exactly as it was.
    ValueError
        If the legacy pickled ``networks.frequencies`` blob names anything but
        ``list`` / ``float`` / ``int``, or does not decode to a list of
        numbers. Nothing is written in that case; the file is untrusted.

    Examples
    --------
    >>> report = migrate_database("grounding.db")  # doctest: +SKIP
    >>> report.shared_elements  # doctest: +SKIP
    {'buses': ['A']}
    """
    report = MigrationReport(path=sqlite_path)
    kind = needs_migration(sqlite_path)
    report.kind = kind
    if kind == "none":
        logger.debug("'%s' already uses the current schema.", sqlite_path)
        return report

    if backup:
        report.backup_path = _backup(sqlite_path)
        logger.warning(
            "Migrating the groundinsight database '%s' (%s). A copy of the "
            "unmodified file was written to '%s'.",
            sqlite_path,
            kind,
            report.backup_path,
        )
    else:
        logger.warning(
            "Migrating the groundinsight database '%s' (%s) without a backup.",
            sqlite_path,
            kind,
        )

    if kind in ("add_columns", "pickle_frequencies"):
        # Both steps are no-ops when there is nothing to do, so they can run
        # unconditionally for either kind -- a file can need both. The
        # frequency conversion goes first: it is the one that can refuse a
        # hostile payload, and refusing before any DDL has been executed keeps
        # the file exactly as it was.
        _convert_pickled_frequencies(sqlite_path, report)
        _add_missing_columns(sqlite_path, report)
        report.migrated = True
        if report.added_columns:
            logger.warning(
                "Added columns introduced by a later release: %s",
                report.added_columns,
            )
        return report

    target_path = f"{sqlite_path}.migrating"
    if os.path.exists(target_path):
        os.remove(target_path)
    try:
        _rebuild_from_legacy(sqlite_path, target_path, report)
        os.replace(target_path, sqlite_path)
    except Exception:
        if os.path.exists(target_path):
            os.remove(target_path)
        raise
    report.migrated = True

    _log_report(report)
    return report

CRUD functions

crud

CRUD Operations Module.

This module provides functions for creating, reading, updating, and deleting (CRUD) entities in the GroundInsight database using SQLAlchemy sessions. It facilitates the management of core electrical network components such as BusTypes, BranchTypes, Networks, Buses, Branches, Faults, Sources, and Paths. The functions convert between Pydantic models and SQLAlchemy database models to ensure seamless data manipulation and persistence.

delete_branchtype

delete_branchtype(name: str, session: Session)

Delete a stored BranchType that no stored network uses.

Parameters:

Name Type Description Default
name str

The name of the BranchType.

required
session Session

The SQLAlchemy session used for database operations.

required

Raises:

Type Description
ValueError

If no BranchType of that name is stored, or if a stored network still has a branch of that type (the message names the networks).

RuntimeError

If the database still uses the legacy, globally-keyed element tables.

Source code in src/groundinsight/database/crud.py
def delete_branchtype(name: str, session: Session):
    """
    Delete a stored BranchType that no stored network uses.

    Parameters
    ----------
    name : str
        The name of the BranchType.
    session : Session
        The SQLAlchemy session used for database operations.

    Raises
    ------
    ValueError
        If no BranchType of that name is stored, or if a stored network still
        has a branch of that type (the message names the networks).
    RuntimeError
        If the database still uses the legacy, globally-keyed element tables.
    """
    _delete_type(session, BranchTypeDB, BranchDB, name, "BranchType")

delete_bustype

delete_bustype(name: str, session: Session)

Delete a stored BusType that no stored network uses.

Parameters:

Name Type Description Default
name str

The name of the BusType.

required
session Session

The SQLAlchemy session used for database operations.

required

Raises:

Type Description
ValueError

If no BusType of that name is stored, or if a stored network still has a bus of that type (the message names the networks).

RuntimeError

If the database still uses the legacy, globally-keyed element tables.

Source code in src/groundinsight/database/crud.py
def delete_bustype(name: str, session: Session):
    """
    Delete a stored BusType that no stored network uses.

    Parameters
    ----------
    name : str
        The name of the BusType.
    session : Session
        The SQLAlchemy session used for database operations.

    Raises
    ------
    ValueError
        If no BusType of that name is stored, or if a stored network still
        has a bus of that type (the message names the networks).
    RuntimeError
        If the database still uses the legacy, globally-keyed element tables.
    """
    _delete_type(session, BusTypeDB, BusDB, name, "BusType")

delete_network

delete_network(name: str, session: Session)

Delete a stored network together with all of its elements.

Buses, branches, faults, sources and paths are scoped to their network and go with it (the relationships cascade). Bus and branch types are a global catalogue and stay; delete them with :func:delete_bustype / :func:delete_branchtype once no network uses them any more.

Parameters:

Name Type Description Default
name str

The name of the network to delete.

required
session Session

The SQLAlchemy session used for database operations.

required

Raises:

Type Description
ValueError

If no network of that name is stored.

RuntimeError

If the database still uses the legacy, globally-keyed element tables.

Exception

If the commit fails; the transaction is rolled back first.

Source code in src/groundinsight/database/crud.py
def delete_network(name: str, session: Session):
    """
    Delete a stored network together with all of its elements.

    Buses, branches, faults, sources and paths are scoped to their network
    and go with it (the relationships cascade). Bus and branch types are a
    global catalogue and stay; delete them with :func:`delete_bustype` /
    :func:`delete_branchtype` once no network uses them any more.

    Parameters
    ----------
    name : str
        The name of the network to delete.
    session : Session
        The SQLAlchemy session used for database operations.

    Raises
    ------
    ValueError
        If no network of that name is stored.
    RuntimeError
        If the database still uses the legacy, globally-keyed element tables.
    Exception
        If the commit fails; the transaction is rolled back first.
    """
    ensure_current_schema(session)
    network_db = session.get(NetworkDB, name)
    if network_db is None:
        raise ValueError(f"Network '{name}' not found.")
    try:
        session.delete(network_db)
        session.commit()
    except Exception:
        session.rollback()
        raise

ensure_current_schema

ensure_current_schema(session: Session)

Reject databases written by the pre-network-scoped schema.

buses, branches, faults, sources and paths are keyed by (network_name, name). A file of the association-table schema keys them by element name alone and links them to their network through network_buses & co.; two networks containing an element of the same name share one row there, so saving one network would silently rewrite the other.

Base.metadata.create_all only ever creates missing tables -- it never adds a column to an existing one -- so an old database file opens without complaint and only fails deep inside a query with a bare OperationalError: no such column: buses.network_name. This helper turns that into an actionable message before any row is read or written.

This is the last line of defence, not the normal path: :func:groundinsight.start_dbsession converts such a file automatically (keeping a .bak copy) before the engine is bound. The error is reached when the caller passed migrate=False, or built its own engine and session without going through start_dbsession.

Parameters:

Name Type Description Default
session Session

The SQLAlchemy session whose bind is inspected.

required

Raises:

Type Description
RuntimeError

If the connected database still uses the legacy, globally-keyed element tables. The message names :func:groundinsight.migrate_database.

See Also

groundinsight.database.migration.migrate_database : performs the conversion this function refuses to do implicitly.

Source code in src/groundinsight/database/crud.py
def ensure_current_schema(session: Session):
    """
    Reject databases written by the pre-network-scoped schema.

    ``buses``, ``branches``, ``faults``, ``sources`` and ``paths`` are keyed
    by ``(network_name, name)``. A file of the association-table schema keys
    them by element name alone and links them to their network through
    ``network_buses`` & co.; two networks containing an element of the same
    name share one row there, so saving one network would silently rewrite
    the other.

    ``Base.metadata.create_all`` only ever creates *missing* tables -- it never
    adds a column to an existing one -- so an old database file opens without
    complaint and only fails deep inside a query with a bare
    ``OperationalError: no such column: buses.network_name``. This helper turns
    that into an actionable message before any row is read or written.

    This is the *last* line of defence, not the normal path:
    :func:`groundinsight.start_dbsession` converts such a file automatically
    (keeping a ``.bak`` copy) before the engine is bound. The error is reached
    when the caller passed ``migrate=False``, or built its own engine and
    session without going through ``start_dbsession``.

    Parameters
    ----------
    session : Session
        The SQLAlchemy session whose bind is inspected.

    Raises
    ------
    RuntimeError
        If the connected database still uses the legacy, globally-keyed
        element tables. The message names
        :func:`groundinsight.migrate_database`.

    See Also
    --------
    groundinsight.database.migration.migrate_database : performs the
        conversion this function refuses to do implicitly.
    """
    inspector = inspect(session.connection())
    table_names = set(inspector.get_table_names())
    if "buses" not in table_names:
        # Nothing written yet; ``create_all`` will lay out the current schema.
        return
    if any(column["name"] == "network_name" for column in inspector.get_columns("buses")):
        return

    legacy_tables = [name for name in _LEGACY_ASSOCIATION_TABLES if name in table_names]
    database = getattr(session.get_bind().url, "database", None) or "<your file>.db"
    raise RuntimeError(
        "This database uses the legacy groundinsight schema, in which buses, "
        "branches, faults, sources and paths were keyed by name alone and "
        "shared between networks"
        + (f" (found: {', '.join(legacy_tables)})" if legacy_tables else "")
        + ". Element tables are now keyed by (network_name, name). Convert the "
        f"file with gi.migrate_database('{database}') -- it copies the "
        "unmodified file to a .bak sibling first and reports anything it could "
        "not recover -- or let gi.start_dbsession() do it for you, which is "
        "the default."
    )

list_networks

list_networks(session: Session) -> List[str]

List the names of all networks stored in the database.

Parameters:

Name Type Description Default
session Session

The SQLAlchemy session used for database operations.

required

Returns:

Type Description
List[str]

Network names, sorted.

Raises:

Type Description
RuntimeError

If the database still uses the legacy, globally-keyed element tables.

Source code in src/groundinsight/database/crud.py
def list_networks(session: Session) -> List[str]:
    """
    List the names of all networks stored in the database.

    Parameters
    ----------
    session : Session
        The SQLAlchemy session used for database operations.

    Returns
    -------
    List[str]
        Network names, sorted.

    Raises
    ------
    RuntimeError
        If the database still uses the legacy, globally-keyed element tables.
    """
    ensure_current_schema(session)
    return sorted(row[0] for row in session.query(NetworkDB.name).all())

load_branchtypes

load_branchtypes(session: Session) -> Dict[str, BranchType]

Load all BranchTypes from the database.

This function retrieves all BranchType entries from the database and converts them into a dictionary mapping BranchType names to their corresponding Pydantic models.

Parameters:

Name Type Description Default
session Session

The SQLAlchemy session used for database operations.

required

Returns:

Type Description
Dict[str, BranchType]

A dictionary where keys are BranchType names and values are BranchType instances.

Source code in src/groundinsight/database/crud.py
def load_branchtypes(session: Session) -> Dict[str, BranchType]:
    """
    Load all BranchTypes from the database.

    This function retrieves all BranchType entries from the database and converts them
    into a dictionary mapping BranchType names to their corresponding Pydantic models.

    Parameters
    ----------
    session : Session
        The SQLAlchemy session used for database operations.

    Returns
    -------
    Dict[str, BranchType]
        A dictionary where keys are BranchType names and values are BranchType instances.
    """
    branch_types = session.query(BranchTypeDB).all()
    return {bt.name: bt.to_pydantic() for bt in branch_types}

load_bustypes

load_bustypes(session: Session) -> Dict[str, BusType]

Load all BusTypes from the database.

This function retrieves all BusType entries from the database and converts them into a dictionary mapping BusType names to their corresponding Pydantic models.

Parameters:

Name Type Description Default
session Session

The SQLAlchemy session used for database operations.

required

Returns:

Type Description
Dict[str, BusType]

A dictionary where keys are BusType names and values are BusType instances.

Source code in src/groundinsight/database/crud.py
def load_bustypes(session: Session) -> Dict[str, BusType]:
    """
    Load all BusTypes from the database.

    This function retrieves all BusType entries from the database and converts them
    into a dictionary mapping BusType names to their corresponding Pydantic models.

    Parameters
    ----------
    session : Session
        The SQLAlchemy session used for database operations.

    Returns
    -------
    Dict[str, BusType]
        A dictionary where keys are BusType names and values are BusType instances.
    """
    bus_types = session.query(BusTypeDB).all()
    return {bt.name: bt.to_pydantic() for bt in bus_types}

load_network

load_network(name: str, session: Session) -> Network

Load a Network from the database.

This function retrieves a Network instance by its name from the database and converts it into a Pydantic Network model. It ensures that all related entities such as Buses, Branches, Faults, Sources, and Paths are properly associated.

Parameters:

Name Type Description Default
name str

The name of the network to load.

required
session Session

The SQLAlchemy session used for database operations.

required

Returns:

Type Description
Network

The loaded Network instance.

Raises:

Type Description
ValueError

If the specified network does not exist in the database.

RuntimeError

If the database still uses the legacy, globally-keyed element tables.

Source code in src/groundinsight/database/crud.py
def load_network(name: str, session: Session) -> Network:
    """
    Load a Network from the database.

    This function retrieves a `Network` instance by its name from the database and converts it
    into a Pydantic `Network` model. It ensures that all related entities such as Buses, Branches,
    Faults, Sources, and Paths are properly associated.

    Parameters
    ----------
    name : str
        The name of the network to load.
    session : Session
        The SQLAlchemy session used for database operations.

    Returns
    -------
    Network
        The loaded `Network` instance.

    Raises
    ------
    ValueError
        If the specified network does not exist in the database.
    RuntimeError
        If the database still uses the legacy, globally-keyed element tables.
    """
    ensure_current_schema(session)
    network_db = session.get(NetworkDB, name)
    if not network_db:
        raise ValueError(f"Network '{name}' not found.")
    network = network_db.to_pydantic()
    return network

save_branchtype

save_branchtype(branch_type: BranchType, session: Session)

Save a BranchType to the database.

This function converts a Pydantic BranchType model to its corresponding SQLAlchemy BranchTypeDB model and saves it to the database. If a BranchType with the same name already exists, it will be updated.

Parameters:

Name Type Description Default
branch_type BranchType

The BranchType instance to be saved.

required
session Session

The SQLAlchemy session used for database operations.

required

Raises:

Type Description
Exception

If there is an error during the database commit.

Source code in src/groundinsight/database/crud.py
def save_branchtype(branch_type: BranchType, session: Session):
    """
    Save a BranchType to the database.

    This function converts a Pydantic `BranchType` model to its corresponding SQLAlchemy
    `BranchTypeDB` model and saves it to the database. If a BranchType with the same name
    already exists, it will be updated.

    Parameters
    ----------
    branch_type : BranchType
        The BranchType instance to be saved.
    session : Session
        The SQLAlchemy session used for database operations.

    Raises
    ------
    Exception
        If there is an error during the database commit.
    """
    branch_type_db = BranchTypeDB.from_pydantic(branch_type)
    session.merge(branch_type_db)
    session.commit()

save_bustype

save_bustype(bus_type: BusType, session: Session)

Save a BusType to the database.

This function converts a Pydantic BusType model to its corresponding SQLAlchemy BusTypeDB model and saves it to the database. If a BusType with the same name already exists, it will be updated.

Parameters:

Name Type Description Default
bus_type BusType

The BusType instance to be saved.

required
session Session

The SQLAlchemy session used for database operations.

required

Raises:

Type Description
Exception

If there is an error during the database commit.

Source code in src/groundinsight/database/crud.py
def save_bustype(bus_type: BusType, session: Session):
    """
    Save a BusType to the database.

    This function converts a Pydantic `BusType` model to its corresponding SQLAlchemy
    `BusTypeDB` model and saves it to the database. If a BusType with the same name
    already exists, it will be updated.

    Parameters
    ----------
    bus_type : BusType
        The BusType instance to be saved.
    session : Session
        The SQLAlchemy session used for database operations.

    Raises
    ------
    Exception
        If there is an error during the database commit.

    """
    bus_type_db = BusTypeDB.from_pydantic(bus_type)
    session.merge(bus_type_db)
    session.commit()

save_network

save_network(
    network: Network,
    session: Session,
    overwrite: bool = False,
    overwrite_types: bool = False,
)

Save a Network to the database.

This function saves a comprehensive Network instance to the database, including all associated BusTypes, BranchTypes, Buses, Branches, Faults, Sources, and Paths. It handles the creation or updating of related entities and ensures referential integrity. If overwrite is set to True, an existing network with the same name will be deleted and replaced.

BusTypes and BranchTypes are a global catalogue: they are merged, exactly as :func:save_bustype and :func:save_branchtype do, so re-saving a network with an edited type definition updates the stored type instead of silently keeping the old one. Because the catalogue is shared, a type whose formulas changed and which another network also references is refused unless overwrite_types=True -- see :func:_check_type_merge. Every other element is scoped to this network and is written under the composite key (network.name, element.name), so saving one network can never rewrite another's buses, branches, faults, sources or paths.

The whole operation runs in a single transaction. On overwrite, the delete of the previous revision is flushed but not committed before the replacement rows are written, so a failure anywhere in the save rolls the delete back as well and leaves the stored network untouched.

Parameters:

Name Type Description Default
network Network

The Network instance to be saved.

required
session Session

The SQLAlchemy session used for database operations.

required
overwrite bool

If True, existing network data with the same name will be overwritten. Defaults to False.

False
overwrite_types bool

If True, allow this save to rewrite the formulas of bus/branch types that other networks also reference; the change is logged at WARNING. Defaults to False, which refuses that case.

False

Raises:

Type Description
ValueError

If the network already exists and overwrite is set to False, if a path references a branch that is not part of network.branches, or if a shared type definition would be rewritten without overwrite_types=True.

RuntimeError

If the database still uses the legacy, globally-keyed element tables.

Exception

If there is an error during the database commit. The transaction is rolled back before the exception is re-raised.

Source code in src/groundinsight/database/crud.py
def save_network(
    network: Network,
    session: Session,
    overwrite: bool = False,
    overwrite_types: bool = False,
):
    """
    Save a Network to the database.

    This function saves a comprehensive `Network` instance to the database, including all
    associated BusTypes, BranchTypes, Buses, Branches, Faults, Sources, and Paths. It handles
    the creation or updating of related entities and ensures referential integrity. If `overwrite`
    is set to `True`, an existing network with the same name will be deleted and replaced.

    BusTypes and BranchTypes are a *global catalogue*: they are merged, exactly
    as :func:`save_bustype` and :func:`save_branchtype` do, so re-saving a
    network with an edited type definition updates the stored type instead of
    silently keeping the old one. Because the catalogue is shared, a type whose
    *formulas* changed and which **another** network also references is refused
    unless ``overwrite_types=True`` -- see :func:`_check_type_merge`. Every
    other element is scoped to this network
    and is written under the composite key ``(network.name, element.name)``, so
    saving one network can never rewrite another's buses, branches, faults,
    sources or paths.

    The whole operation runs in a single transaction. On overwrite, the delete
    of the previous revision is *flushed but not committed* before the
    replacement rows are written, so a failure anywhere in the save rolls the
    delete back as well and leaves the stored network untouched.

    Parameters
    ----------
    network : Network
        The Network instance to be saved.
    session : Session
        The SQLAlchemy session used for database operations.
    overwrite : bool, optional
        If `True`, existing network data with the same name will be overwritten.
        Defaults to `False`.
    overwrite_types : bool, optional
        If `True`, allow this save to rewrite the formulas of bus/branch types
        that other networks also reference; the change is logged at
        ``WARNING``. Defaults to `False`, which refuses that case.

    Raises
    ------
    ValueError
        If the network already exists and `overwrite` is set to `False`, if a
        path references a branch that is not part of ``network.branches``, or
        if a shared type definition would be rewritten without
        ``overwrite_types=True``.
    RuntimeError
        If the database still uses the legacy, globally-keyed element tables.
    Exception
        If there is an error during the database commit. The transaction is
        rolled back before the exception is re-raised.
    """
    ensure_current_schema(session)

    # Check for existing network
    existing_network = session.get(NetworkDB, network.name)
    if existing_network and not overwrite:
        raise ValueError(
            f"Network '{network.name}' already exists. Use overwrite=True to overwrite."
        )

    # Fail before touching the database rather than half-way through the write.
    _validate_path_segments(network)
    _check_type_merge(network, session, overwrite_types)

    try:
        # Save BusTypes / BranchTypes -- merge, so an edited type definition
        # replaces the stored one instead of being ignored when the name exists.
        for bus in network.buses.values():
            session.merge(BusTypeDB.from_pydantic(bus.type))
        for branch in network.branches.values():
            session.merge(BranchTypeDB.from_pydantic(branch.type))

        if existing_network is not None:
            # Drop the previous revision including its child rows (the
            # relationships cascade), then flush so the primary keys are free
            # for the replacement rows. This stays inside the transaction
            # opened above -- no commit happens until the new rows are written.
            session.delete(existing_network)
            session.flush()

        network_db = NetworkDB.from_pydantic(network)
        network_db.active_fault_name = network.active_fault

        # ``Network`` element dictionaries are keyed by element name (see
        # ``Network.add_bus`` & co.), and ``to_pydantic`` rebuilds them from
        # the stored names, so the values -- not the dictionary keys -- are the
        # source of truth here. The enumeration index preserves the dictionary
        # order across the round-trip.
        network_db.buses = [
            BusDB.from_pydantic(bus, network.name, position)
            for position, bus in enumerate(network.buses.values())
        ]
        network_db.branches = [
            BranchDB.from_pydantic(branch, network.name, position)
            for position, branch in enumerate(network.branches.values())
        ]
        network_db.faults = [
            FaultDB.from_pydantic(fault, network.name, position)
            for position, fault in enumerate(network.faults.values())
        ]
        network_db.sources = [
            SourceDB.from_pydantic(source, network.name, position)
            for position, source in enumerate(network.sources.values())
        ]

        path_dbs = []
        for position, path in enumerate(network.paths.values()):
            path_db = PathDB.from_pydantic(path, network.name, position)
            # Segment order is semantically meaningful, so it is stored
            # explicitly instead of being left to the database.
            path_db.segments = [
                PathSegmentDB(
                    network_name=network.name,
                    path_name=path.name,
                    position=segment_position,
                    branch_name=segment.name,
                )
                for segment_position, segment in enumerate(path.segments)
            ]
            path_dbs.append(path_db)
        network_db.paths = path_dbs

        session.add(network_db)
        session.flush()

        # Commit the session only once every replacement row is on disk.
        session.commit()
    except Exception:
        # Roll the delete and the partial write back as one unit so a failed
        # overwrite cannot destroy the stored network.
        session.rollback()
        raise

ORM models

database_models

Database Models Module.

This module defines the SQLAlchemy ORM (Object-Relational Mapping) models corresponding to the core electrical network components in the GroundInsight package. Each database model facilitates the storage, retrieval, and manipulation of data related to BusTypes, BranchTypes, Buses, Branches, Faults, Sources, Paths, and Networks. The models include methods to convert between Pydantic models and SQLAlchemy database models, ensuring seamless data integration and persistence.

Ownership model

BusTypeDB and BranchTypeDB form a global catalogue: a type is identified by its name alone and is deliberately shared between networks, so re-saving an edited type updates every network that references it.

Every other element -- BusDB, BranchDB, FaultDB, SourceDB, PathDB and the PathSegmentDB rows -- belongs to exactly one network. This mirrors the Pydantic :class:~groundinsight.models.core_models.Network, whose element dictionaries only require uniqueness within a network. The primary key of those tables is therefore the composite (network_name, name); the relationships from NetworkDB are plain one-to-many collections with delete-orphan cascade, so dropping a network (or shrinking one on overwrite) removes its child rows instead of leaving them behind.

Earlier revisions keyed the child tables by name alone and linked them to their network through network_buses / network_branches / network_faults / network_sources / network_paths association tables. Two networks that happened to contain an element of the same name -- the default case for create_paths, which names every path path_1, path_2, ... -- then shared a single row, so saving one network silently rewrote the other. Databases written by those revisions are not readable by this schema; they are detected and rejected with an actionable error by :func:groundinsight.database.crud.ensure_current_schema.

Collection order is preserved explicitly through position columns rather than being left to the database. PathDB.segments in particular is order-sensitive: the solver walks the segments from the source bus onwards and fails if consecutive segments do not connect.

BranchDB

Bases: Base

BranchDB Model.

Represents a Branch in the database, including its properties, type, connected buses, the frequency-domain impedance dicts and -- when the type defines them -- the lumped RLCM dicts used by the transient solvers.

A branch belongs to exactly one network; the primary key is the composite (network_name, name). from_bus_name / to_bus_name reference buses of the same network, hence the composite foreign keys.

from_pydantic classmethod

from_pydantic(
    branch: Branch,
    network_name: Optional[str] = None,
    position: int = 0,
)

Build a BranchDB row from a Pydantic :class:Branch.

Parameters:

Name Type Description Default
branch Branch

The branch to convert.

required
network_name str

Name of the owning network. Part of the composite primary key.

None
position int

Zero-based index of the branch inside Network.branches, used to restore the dictionary order on load. Defaults to 0.

0

Returns:

Type Description
BranchDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, branch: Branch, network_name: Optional[str] = None, position: int = 0):
    """Build a ``BranchDB`` row from a Pydantic :class:`Branch`.

    Parameters
    ----------
    branch : Branch
        The branch to convert.
    network_name : str, optional
        Name of the owning network. Part of the composite primary key.
    position : int, optional
        Zero-based index of the branch inside ``Network.branches``, used
        to restore the dictionary order on load. Defaults to ``0``.

    Returns
    -------
    BranchDB
        The unattached database row.
    """
    # Convert impedance to JSON serializable format
    self_impedance = (
        {
            str(freq): {
                "real": json_safe_float(imp.real),
                "imag": json_safe_float(imp.imag),
            }
            for freq, imp in branch.self_impedance.items()
        }
        if branch.self_impedance
        else {}
    )

    mutual_impedance = (
        {
            str(freq): {
                "real": json_safe_float(imp.real),
                "imag": json_safe_float(imp.imag),
            }
            for freq, imp in branch.mutual_impedance.items()
        }
        if branch.mutual_impedance
        else {}
    )

    phase_impedance = (
        {
            str(freq): {
                "real": json_safe_float(imp.real),
                "imag": json_safe_float(imp.imag),
            }
            for freq, imp in branch.phase_impedance.items()
        }
        if branch.phase_impedance
        else None
    )

    return cls(
        network_name=network_name,
        position=position,
        name=branch.name,
        description=branch.description,
        type_name=branch.type.name,
        length=branch.length,
        from_bus_name=branch.from_bus,
        to_bus_name=branch.to_bus,
        self_impedance=self_impedance,
        mutual_impedance=mutual_impedance,
        phase_impedance=phase_impedance,
        specific_earth_resistance=branch.specific_earth_resistance,
        parallel_coefficient=branch.parallel_coefficient,
        active=branch.active,
        R_self=_real_dict_to_json(branch.R_self),
        L_self=_real_dict_to_json(branch.L_self),
        C_self=_real_dict_to_json(branch.C_self),
        R_mutual=_real_dict_to_json(branch.R_mutual),
        M_mutual=_real_dict_to_json(branch.M_mutual),
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:Branch.

Returns:

Type Description
Branch

The reconstructed branch.

Raises:

Type Description
ValueError

If type_name does not resolve to a stored BranchTypeDB. See :meth:BusDB.to_pydantic for the rationale.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """Convert the row back into a Pydantic :class:`Branch`.

    Returns
    -------
    Branch
        The reconstructed branch.

    Raises
    ------
    ValueError
        If ``type_name`` does not resolve to a stored
        ``BranchTypeDB``. See :meth:`BusDB.to_pydantic` for the
        rationale.
    """
    if self.type is None:
        raise ValueError(
            f"Branch '{self.name}' of network '{self.network_name}' "
            f"references branch type '{self.type_name}', which is not "
            "stored in the database. The database is inconsistent -- "
            "re-save that branch type or point the branch at an existing "
            "one."
        )

    # Convert impedance JSON to Dict[float, ComplexNumber]
    self_impedance = (
        {
            float(freq): ComplexNumber(**value)
            for freq, value in self.self_impedance.items()
        }
        if self.self_impedance
        else {}
    )

    mutual_impedance = (
        {
            float(freq): ComplexNumber(**value)
            for freq, value in self.mutual_impedance.items()
        }
        if self.mutual_impedance
        else {}
    )

    phase_impedance = (
        {
            float(freq): ComplexNumber(**value)
            for freq, value in self.phase_impedance.items()
        }
        if self.phase_impedance
        else None
    )

    return Branch(
        name=self.name,
        description=self.description,
        type=self.type.to_pydantic(),
        length=self.length,
        from_bus=self.from_bus_name,
        to_bus=self.to_bus_name,
        self_impedance=self_impedance,
        mutual_impedance=mutual_impedance,
        phase_impedance=phase_impedance,
        specific_earth_resistance=self.specific_earth_resistance,
        parallel_coefficient=self.parallel_coefficient,
        active=True if self.active is None else bool(self.active),
        R_self=_real_dict_from_json(self.R_self),
        L_self=_real_dict_from_json(self.L_self),
        C_self=_real_dict_from_json(self.C_self),
        R_mutual=_real_dict_from_json(self.R_mutual),
        M_mutual=_real_dict_from_json(self.M_mutual),
    )

BranchTypeDB

Bases: Base

BranchTypeDB Model.

Represents a BranchType in the database, including the mandatory self_impedance_formula / mutual_impedance_formula and the optional lumped RLCM formulas for the transient solvers (R_self_formula, L_self_formula, C_self_formula, R_mutual_formula, M_mutual_formula).

from_pydantic classmethod

from_pydantic(branch_type: BranchType)

Build a BranchTypeDB row from a Pydantic :class:BranchType.

Parameters:

Name Type Description Default
branch_type BranchType

The model to convert.

required

Returns:

Type Description
BranchTypeDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, branch_type: BranchType):
    """
    Build a ``BranchTypeDB`` row from a Pydantic :class:`BranchType`.

    Parameters
    ----------
    branch_type : BranchType
        The model to convert.

    Returns
    -------
    BranchTypeDB
        The unattached database row.
    """
    return cls(
        name=branch_type.name,
        description=branch_type.description,
        grounding_conductor=branch_type.grounding_conductor,
        self_impedance_formula=branch_type.self_impedance_formula,
        mutual_impedance_formula=branch_type.mutual_impedance_formula,
        phase_impedance_formula=branch_type.phase_impedance_formula,
        R_self_formula=branch_type.R_self_formula,
        L_self_formula=branch_type.L_self_formula,
        C_self_formula=branch_type.C_self_formula,
        R_mutual_formula=branch_type.R_mutual_formula,
        M_mutual_formula=branch_type.M_mutual_formula,
        conductor_material=branch_type.conductor_material,
        cross_section_mm2=branch_type.cross_section_mm2,
        theta_initial_C=branch_type.theta_initial_C,
        theta_final_C=branch_type.theta_final_C,
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:BranchType.

Returns:

Type Description
BranchType

A fresh model object.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """
    Convert the row back into a Pydantic :class:`BranchType`.

    Returns
    -------
    BranchType
        A fresh model object.
    """
    return BranchType(
        name=self.name,
        description=self.description,
        grounding_conductor=self.grounding_conductor,
        self_impedance_formula=self.self_impedance_formula,
        mutual_impedance_formula=self.mutual_impedance_formula,
        phase_impedance_formula=self.phase_impedance_formula,
        R_self_formula=self.R_self_formula,
        L_self_formula=self.L_self_formula,
        C_self_formula=self.C_self_formula,
        R_mutual_formula=self.R_mutual_formula,
        M_mutual_formula=self.M_mutual_formula,
        conductor_material=self.conductor_material,
        cross_section_mm2=self.cross_section_mm2,
        theta_initial_C=(self.theta_initial_C if self.theta_initial_C is not None else 20.0),
        theta_final_C=self.theta_final_C,
    )

BusDB

Bases: Base

BusDB Model.

Represents a Bus in the database. Carries the frequency-domain impedance dict and -- when the type defines them -- the lumped R, L and C dicts used by the transient solvers.

A bus belongs to exactly one network; the primary key is the composite (network_name, name) so two networks may each own a bus of the same name. position records the insertion order of Network.buses so a round-trip through the database returns the dictionary in the order it was written.

from_pydantic classmethod

from_pydantic(
    bus: Bus,
    network_name: Optional[str] = None,
    position: int = 0,
)

Build a BusDB row from a Pydantic :class:Bus.

Parameters:

Name Type Description Default
bus Bus

The bus to convert.

required
network_name str

Name of the owning network. Part of the composite primary key; may be left out when the row is appended to NetworkDB.buses, in which case SQLAlchemy fills it in.

None
position int

Zero-based index of the bus inside Network.buses, used to restore the dictionary order on load. Defaults to 0.

0

Returns:

Type Description
BusDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, bus: Bus, network_name: Optional[str] = None, position: int = 0):
    """Build a ``BusDB`` row from a Pydantic :class:`Bus`.

    Parameters
    ----------
    bus : Bus
        The bus to convert.
    network_name : str, optional
        Name of the owning network. Part of the composite primary key;
        may be left out when the row is appended to
        ``NetworkDB.buses``, in which case SQLAlchemy fills it in.
    position : int, optional
        Zero-based index of the bus inside ``Network.buses``, used to
        restore the dictionary order on load. Defaults to ``0``.

    Returns
    -------
    BusDB
        The unattached database row.
    """
    # Convert impedance to JSON serializable format
    impedance = (
        {
            str(freq): {
                "real": json_safe_float(imp.real),
                "imag": json_safe_float(imp.imag),
            }
            for freq, imp in bus.impedance.items()
        }
        if bus.impedance
        else {}
    )

    return cls(
        network_name=network_name,
        position=position,
        name=bus.name,
        description=bus.description,
        type_name=bus.type.name,
        specific_earth_resistance=bus.specific_earth_resistance,
        impedance=impedance,
        active=bus.active,
        R=_real_dict_to_json(bus.R),
        L=_real_dict_to_json(bus.L),
        C=_real_dict_to_json(bus.C),
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:Bus.

Returns:

Type Description
Bus

The reconstructed bus.

Raises:

Type Description
ValueError

If type_name does not resolve to a stored BusTypeDB -- a bus type deleted from a shared database, or a hand-edited row. Without the check the unresolved relationship surfaced as AttributeError: 'NoneType' object has no attribute 'to_pydantic', which names neither the bus nor the type.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """Convert the row back into a Pydantic :class:`Bus`.

    Returns
    -------
    Bus
        The reconstructed bus.

    Raises
    ------
    ValueError
        If ``type_name`` does not resolve to a stored ``BusTypeDB`` --
        a bus type deleted from a shared database, or a hand-edited
        row. Without the check the unresolved relationship surfaced as
        ``AttributeError: 'NoneType' object has no attribute
        'to_pydantic'``, which names neither the bus nor the type.
    """
    if self.type is None:
        raise ValueError(
            f"Bus '{self.name}' of network '{self.network_name}' references "
            f"bus type '{self.type_name}', which is not stored in the "
            "database. The database is inconsistent -- re-save that bus "
            "type or point the bus at an existing one."
        )

    # Convert impedance JSON to Dict[float, ComplexNumber]
    impedance = (
        {
            float(freq): ComplexNumber(**value)
            for freq, value in self.impedance.items()
        }
        if self.impedance
        else {}
    )

    return Bus(
        name=self.name,
        description=self.description,
        type=self.type.to_pydantic(),
        impedance=impedance,
        specific_earth_resistance=self.specific_earth_resistance,
        active=True if self.active is None else bool(self.active),
        R=_real_dict_from_json(self.R),
        L=_real_dict_from_json(self.L),
        C=_real_dict_from_json(self.C),
    )

BusTypeDB

Bases: Base

BusTypeDB Model.

Represents a BusType in the database, including its properties, the mandatory frequency-domain impedance_formula, the optional lumped RLC formulas for the transient solvers (R_formula, L_formula, C_formula) and the optional thermal-limit data of the earthing conductor and the earth electrode (EN 50522 / IEC 60949), consumed by :func:groundinsight.check_node_limits.

from_pydantic classmethod

from_pydantic(bus_type: BusType)

Build a BusTypeDB row from a Pydantic :class:BusType.

Parameters:

Name Type Description Default
bus_type BusType

The model to convert.

required

Returns:

Type Description
BusTypeDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, bus_type: BusType):
    """
    Build a ``BusTypeDB`` row from a Pydantic :class:`BusType`.

    Parameters
    ----------
    bus_type : BusType
        The model to convert.

    Returns
    -------
    BusTypeDB
        The unattached database row.
    """
    return cls(
        name=bus_type.name,
        description=bus_type.description,
        system_type=bus_type.system_type,
        voltage_level=bus_type.voltage_level,
        impedance_formula=bus_type.impedance_formula,
        R_formula=bus_type.R_formula,
        L_formula=bus_type.L_formula,
        C_formula=bus_type.C_formula,
        earthing_conductor_material=bus_type.earthing_conductor_material,
        earthing_conductor_cross_section_mm2=bus_type.earthing_conductor_cross_section_mm2,
        earthing_conductor_theta_initial_C=bus_type.earthing_conductor_theta_initial_C,
        earthing_conductor_theta_final_C=bus_type.earthing_conductor_theta_final_C,
        earthing_conductor_current_split=bus_type.earthing_conductor_current_split,
        electrode_material=bus_type.electrode_material,
        electrode_cross_section_mm2=bus_type.electrode_cross_section_mm2,
        electrode_theta_initial_C=bus_type.electrode_theta_initial_C,
        electrode_theta_final_C=bus_type.electrode_theta_final_C,
        electrode_current_split=bus_type.electrode_current_split,
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:BusType.

Returns:

Type Description
BusType

A fresh model object.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """
    Convert the row back into a Pydantic :class:`BusType`.

    Returns
    -------
    BusType
        A fresh model object.
    """
    # The scalar-with-default columns are stored nullable so that rows
    # written before these fields existed still load; ``None`` therefore
    # has to be mapped back onto the pydantic default rather than passed
    # through, which would fail validation.
    return BusType(
        name=self.name,
        description=self.description,
        system_type=self.system_type,
        voltage_level=self.voltage_level,
        impedance_formula=self.impedance_formula,
        R_formula=self.R_formula,
        L_formula=self.L_formula,
        C_formula=self.C_formula,
        earthing_conductor_material=self.earthing_conductor_material,
        earthing_conductor_cross_section_mm2=self.earthing_conductor_cross_section_mm2,
        earthing_conductor_theta_initial_C=(
            self.earthing_conductor_theta_initial_C
            if self.earthing_conductor_theta_initial_C is not None
            else 20.0
        ),
        earthing_conductor_theta_final_C=self.earthing_conductor_theta_final_C,
        earthing_conductor_current_split=(
            self.earthing_conductor_current_split
            if self.earthing_conductor_current_split is not None
            else 1.0
        ),
        electrode_material=self.electrode_material,
        electrode_cross_section_mm2=self.electrode_cross_section_mm2,
        electrode_theta_initial_C=(
            self.electrode_theta_initial_C
            if self.electrode_theta_initial_C is not None
            else 20.0
        ),
        electrode_theta_final_C=self.electrode_theta_final_C,
        electrode_current_split=(
            self.electrode_current_split
            if self.electrode_current_split is not None
            else 1.0
        ),
    )

ComplexNumberDB

Bases: Base

ComplexNumberDB Model.

Represents a complex number with real and imaginary parts for storage in the database.

from_pydantic classmethod

from_pydantic(complex_number: ComplexNumber)

Build a ComplexNumberDB row from a Pydantic :class:ComplexNumber.

Parameters:

Name Type Description Default
complex_number ComplexNumber

The model to convert.

required

Returns:

Type Description
ComplexNumberDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, complex_number: ComplexNumber):
    """
    Build a ``ComplexNumberDB`` row from a Pydantic :class:`ComplexNumber`.

    Parameters
    ----------
    complex_number : ComplexNumber
        The model to convert.

    Returns
    -------
    ComplexNumberDB
        The unattached database row.
    """
    return cls(
        value={
            "real": json_safe_float(complex_number.real),
            "imag": json_safe_float(complex_number.imag),
        }
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:ComplexNumber.

Returns:

Type Description
ComplexNumber

A fresh model object.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """
    Convert the row back into a Pydantic :class:`ComplexNumber`.

    Returns
    -------
    ComplexNumber
        A fresh model object.
    """
    return ComplexNumber(**self.value)

FaultDB

Bases: Base

FaultDB Model.

Represents a Fault in the database, including its properties and associated bus.

A fault belongs to exactly one network; the primary key is the composite (network_name, name) and bus_name references a bus of the same network.

from_pydantic classmethod

from_pydantic(
    fault: Fault,
    network_name: Optional[str] = None,
    position: int = 0,
)

Build a FaultDB row from a Pydantic :class:Fault.

Parameters:

Name Type Description Default
fault Fault

The fault to convert.

required
network_name str

Name of the owning network. Part of the composite primary key.

None
position int

Zero-based index of the fault inside Network.faults, used to restore the dictionary order on load. Defaults to 0.

0

Returns:

Type Description
FaultDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, fault: Fault, network_name: Optional[str] = None, position: int = 0):
    """Build a ``FaultDB`` row from a Pydantic :class:`Fault`.

    Parameters
    ----------
    fault : Fault
        The fault to convert.
    network_name : str, optional
        Name of the owning network. Part of the composite primary key.
    position : int, optional
        Zero-based index of the fault inside ``Network.faults``, used to
        restore the dictionary order on load. Defaults to ``0``.

    Returns
    -------
    FaultDB
        The unattached database row.
    """
    scalings = {str(freq): scale for freq, scale in fault.scalings.items()}
    return cls(
        network_name=network_name,
        position=position,
        name=fault.name,
        description=fault.description,
        bus_name=fault.bus,
        scalings=scalings,
        active=fault.active,
        t_k_s=fault.t_k_s,
        n_factor=fault.n_factor,
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:Fault.

Returns:

Type Description
Fault

A fresh model object.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """
    Convert the row back into a Pydantic :class:`Fault`.

    Returns
    -------
    Fault
        A fresh model object.
    """
    # Convert scalings JSON to Dict[float, float]
    scalings = {float(freq): scale for freq, scale in self.scalings.items()}

    fault = Fault(
        name=self.name,
        description=self.description,
        bus=self.bus_name,
        scalings=scalings,
        t_k_s=self.t_k_s,
        # Legacy rows written before the 60909 columns existed store
        # NULL here; fall back to the far-from-generator default
        # instead of failing validation on None.
        n_factor=1.0 if self.n_factor is None else self.n_factor,
    )
    fault.mark_active(self.active)
    return fault

NetworkDB

Bases: Base

NetworkDB Model.

Represents a Network in the database, including its properties and associated components such as buses, branches, faults, sources, and paths. It also tracks the active fault within the network.

The element collections are one-to-many with delete-orphan cascade: a bus, branch, fault, source or path row is owned by exactly one network, so deleting a network -- or replacing a collection on overwrite -- removes the rows it no longer contains instead of orphaning them in a global table. Each collection is ordered by the element's position column so the Pydantic dictionaries come back in insertion order.

from_pydantic classmethod

from_pydantic(network: Network)

Build a NetworkDB row from a Pydantic :class:Network.

Parameters:

Name Type Description Default
network Network

The model to convert.

required

Returns:

Type Description
NetworkDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, network: Network):
    """
    Build a ``NetworkDB`` row from a Pydantic :class:`Network`.

    Parameters
    ----------
    network : Network
        The model to convert.

    Returns
    -------
    NetworkDB
        The unattached database row.
    """
    return cls(
        name=network.name,
        description=network.description,
        frequencies=network.frequencies,
        results=_results_to_json(network.results),
        active_fault_name=network.active_fault,
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:Network.

Buses, branches, faults, sources, paths and stored results are converted with it.

Returns:

Type Description
Network

A fresh model object.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """
    Convert the row back into a Pydantic :class:`Network`.

    Buses, branches, faults, sources, paths and stored results are
    converted with it.

    Returns
    -------
    Network
        A fresh model object.
    """
    return Network(
        name=self.name,
        description=self.description,
        frequencies=self.frequencies,
        buses={bus.name: bus.to_pydantic() for bus in self.buses},
        branches={branch.name: branch.to_pydantic() for branch in self.branches},
        faults={fault.name: fault.to_pydantic() for fault in self.faults},
        sources={source.name: source.to_pydantic() for source in self.sources},
        paths={path.name: path.to_pydantic() for path in self.paths},
        active_fault=self.active_fault_name,
        results=_results_from_json(self.results),
    )

PathDB

Bases: Base

PathDB Model.

Represents a Path in the database, including its properties, associated source and fault, and connected branches (segments).

A path belongs to exactly one network; the primary key is the composite (network_name, name). This matters in practice because :func:groundinsight.create_paths names every path path_1, path_2, ..., so path-name collisions between two saved networks are the rule rather than the exception.

from_pydantic classmethod

from_pydantic(
    path: Path,
    network_name: Optional[str] = None,
    position: int = 0,
)

Build a PathDB row from a Pydantic :class:Path.

Parameters:

Name Type Description Default
path Path

The path to convert.

required
network_name str

Name of the owning network. Part of the composite primary key.

None
position int

Zero-based index of the path inside Network.paths, used to restore the dictionary order on load. Defaults to 0.

0

Returns:

Type Description
PathDB

The unattached database row. segments is left empty; the caller fills it once the branches of the network are known.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, path: Path, network_name: Optional[str] = None, position: int = 0):
    """Build a ``PathDB`` row from a Pydantic :class:`Path`.

    Parameters
    ----------
    path : Path
        The path to convert.
    network_name : str, optional
        Name of the owning network. Part of the composite primary key.
    position : int, optional
        Zero-based index of the path inside ``Network.paths``, used to
        restore the dictionary order on load. Defaults to ``0``.

    Returns
    -------
    PathDB
        The unattached database row. ``segments`` is left empty; the
        caller fills it once the branches of the network are known.
    """
    return cls(
        network_name=network_name,
        position=position,
        name=path.name,
        description=path.description,
        source_name=path.source,
        fault_name=path.fault,
        # Segments will be added separately after the branches are saved
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:Path.

Returns:

Type Description
Path

The reconstructed path, with segments in stored order.

Raises:

Type Description
ValueError

If a stored segment references a branch that is not present in the owning network -- a corrupt or hand-edited database.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """Convert the row back into a Pydantic :class:`Path`.

    Returns
    -------
    Path
        The reconstructed path, with ``segments`` in stored order.

    Raises
    ------
    ValueError
        If a stored segment references a branch that is not present in
        the owning network -- a corrupt or hand-edited database.
    """
    segments = []
    for segment in self.segments:
        if segment.branch is None:
            raise ValueError(
                f"Path '{self.name}' of network '{self.network_name}' references "
                f"branch '{segment.branch_name}', which is not stored in that "
                "network. The database is inconsistent."
            )
        segments.append(segment.branch.to_pydantic())

    return Path(
        name=self.name,
        description=self.description,
        source=self.source_name,
        fault=self.fault_name,
        segments=segments,
    )

PathSegmentDB

Bases: Base

PathSegmentDB Model.

One ordered segment of a :class:PathDB, pointing at a branch of the same network. Segment order is semantically meaningful -- the solver walks the segments from the source bus onwards and raises if a segment does not connect to the current bus -- hence the explicit position column, which is part of the primary key and drives PathDB.segments' order_by. A plain association table would return Path.segments in an unspecified order.

SourceDB

Bases: Base

SourceDB Model.

Represents a Source in the database. Both the current-source mode and the Thevenin (voltage-source) mode are persisted in the same row. The source_type column selects which of values and the pair (voltage, source_impedance) carries the actual data; the other fields are stored as NULL.

A source belongs to exactly one network; the primary key is the composite (network_name, name) and bus_name references a bus of the same network.

from_pydantic classmethod

from_pydantic(
    source: Source,
    network_name: Optional[str] = None,
    position: int = 0,
)

Build a SourceDB row from a Pydantic :class:Source.

Parameters:

Name Type Description Default
source Source

The source to convert.

required
network_name str

Name of the owning network. Part of the composite primary key.

None
position int

Zero-based index of the source inside Network.sources, used to restore the dictionary order on load. Defaults to 0.

0

Returns:

Type Description
SourceDB

The unattached database row.

Source code in src/groundinsight/models/database_models.py
@classmethod
def from_pydantic(cls, source: Source, network_name: Optional[str] = None, position: int = 0):
    """Build a ``SourceDB`` row from a Pydantic :class:`Source`.

    Parameters
    ----------
    source : Source
        The source to convert.
    network_name : str, optional
        Name of the owning network. Part of the composite primary key.
    position : int, optional
        Zero-based index of the source inside ``Network.sources``, used
        to restore the dictionary order on load. Defaults to ``0``.

    Returns
    -------
    SourceDB
        The unattached database row.
    """
    return cls(
        network_name=network_name,
        position=position,
        name=source.name,
        description=source.description,
        bus_name=source.bus,
        source_type=source.source_type,
        values=cls._freq_dict_to_json(source.values),
        voltage=cls._freq_dict_to_json(source.voltage),
        source_impedance=cls._freq_dict_to_json(source.source_impedance),
        i_k_a=source.i_k_a,
        r_to_x=source.r_to_x,
        kappa=source.kappa,
    )

to_pydantic

to_pydantic()

Convert the row back into a Pydantic :class:Source.

Returns:

Type Description
Source

A fresh model object.

Source code in src/groundinsight/models/database_models.py
def to_pydantic(self):
    """
    Convert the row back into a Pydantic :class:`Source`.

    Returns
    -------
    Source
        A fresh model object.
    """
    source_type = self.source_type or "current"
    return Source(
        name=self.name,
        description=self.description,
        bus=self.bus_name,
        source_type=source_type,
        values=self._freq_dict_to_pydantic(self.values),
        voltage=self._freq_dict_to_pydantic(self.voltage),
        source_impedance=self._freq_dict_to_pydantic(self.source_impedance),
        i_k_a=self.i_k_a,
        r_to_x=self.r_to_x,
        kappa=self.kappa,
    )