Skip to content

refactor(core): re-arange core, move set_default_event and friends ou…#224

Merged
smlloyd merged 1 commit intomasterfrom
rearrange-core
Mar 5, 2026
Merged

refactor(core): re-arange core, move set_default_event and friends ou…#224
smlloyd merged 1 commit intomasterfrom
rearrange-core

Conversation

@smlloyd
Copy link
Copy Markdown
Member

@smlloyd smlloyd commented Mar 5, 2026

…t of core.


📚 Documentation preview 📚: https://aimbat--224.org.readthedocs.build/en/224/

Copilot AI review requested due to automatic review settings March 5, 2026 10:56
Comment thread src/aimbat/core/_event.py
def get_event_parameter(session: Session, name: EventParameterBool) -> bool: ...
def get_event_parameter(
session: Session, event: AimbatEvent, name: EventParameterBool
) -> bool: ...
Comment thread src/aimbat/core/_event.py
def get_event_parameter(session: Session, name: EventParameterFloat) -> float: ...
def get_event_parameter(
session: Session, event: AimbatEvent, name: EventParameterFloat
) -> float: ...
def plot_all_seismograms(session: Session, return_fig: Literal[False]) -> None: ...
def plot_all_seismograms(
session: Session, event: AimbatEvent, return_fig: Literal[False]
) -> None: ...
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 5, 2026

Codecov Report

❌ Patch coverage is 69.36937% with 136 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.33%. Comparing base (7c4c0bc) to head (ffad792).
⚠️ Report is 2 commits behind head on master.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/aimbat/_tui/app.py 5.71% 66 Missing ⚠️
src/aimbat/core/_iccs.py 52.94% 16 Missing ⚠️
src/aimbat/_cli/pick.py 0.00% 9 Missing ⚠️
src/aimbat/_cli/plot.py 0.00% 9 Missing ⚠️
src/aimbat/_cli/align.py 0.00% 7 Missing ⚠️
src/aimbat/_cli/project.py 86.95% 6 Missing ⚠️
src/aimbat/_cli/station.py 79.31% 6 Missing ⚠️
src/aimbat/_cli/data.py 84.84% 5 Missing ⚠️
src/aimbat/_cli/seismogram.py 90.19% 5 Missing ⚠️
src/aimbat/core/_seismogram.py 83.33% 3 Missing ⚠️
... and 3 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #224      +/-   ##
==========================================
- Coverage   72.29%   70.33%   -1.97%     
==========================================
  Files          50       50              
  Lines        2805     2869      +64     
==========================================
- Hits         2028     2018      -10     
- Misses        777      851      +74     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refactors aimbat.core to reduce implicit “active event” coupling by requiring explicit event arguments for many operations, while moving table-printing responsibilities into CLI commands and extending the TUI to detect/handle ICCS staleness via an event.last_modified timestamp.

Changes:

  • Update core APIs (snapshots/events/seismograms/stations/data/ICCS) to accept an explicit AimbatEvent (or event=) instead of always resolving the active event internally.
  • Add AimbatEvent.last_modified plus SQLite triggers to update it when parameters change; introduce BoundICCS and staleness checks in the TUI.
  • Refresh CLI implementations and documentation/navigation to reflect the new interface structure (CLI/TUI/GUI/API/Shell).

Reviewed changes

Copilot reviewed 46 out of 48 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
zensical.toml Reorganises docs navigation (CLI/Shell/TUI/GUI/API/Defaults).
uv.lock Locks new dependency additions (prompt-toolkit + wcwidth).
pyproject.toml Adds prompt-toolkit dependency.
.gitignore Ignores scratch/ directory.
tests/integration/models/test_operations.py Updates snapshot calls to pass explicit event.
tests/integration/models/test_models.py Updates snapshot creation to use explicit active event.
tests/integration/core/test_station.py Updates station APIs; removes printing tests.
tests/integration/core/test_snapshots.py Updates snapshot APIs; removes printing tests.
tests/integration/core/test_seismogram.py Updates seismogram APIs; removes printing tests.
tests/integration/core/test_project.py Removes print_project_info tests; adjusts delete behaviour.
tests/integration/core/test_event.py Updates event parameter APIs; removes printing tests.
tests/integration/core/test_data.py Updates data APIs; removes printing tests.
src/aimbat/utils/_style.py Handles NaT timestamps in table formatting.
src/aimbat/models/_readers.py Adds last_modified to event read model.
src/aimbat/models/_parameters.py Import ordering only (no functional change).
src/aimbat/models/_models.py Adds AimbatEvent.last_modified column.
src/aimbat/models/init.py Re-exports parameter base classes.
src/aimbat/core/_station.py Renames/refactors station queries; adds JSON dump with counts.
src/aimbat/core/_snapshot.py Requires explicit event for snapshot creation and filtering.
src/aimbat/core/_seismogram.py Requires explicit event for selection/parameter dumping and plotting.
src/aimbat/core/_project.py Adds SQLite triggers to update last_modified; removes print helper.
src/aimbat/core/_iccs.py Introduces BoundICCS; makes ICCS ops event-explicit.
src/aimbat/core/_event.py Makes event parameter APIs event-explicit; trims printing helpers.
src/aimbat/core/_data.py Makes data queries event-explicit; removes printing helper.
src/aimbat/core/_active_event.py Import reordering to avoid circular imports.
src/aimbat/_types/_seismogram.py Updates doc links to new module paths.
src/aimbat/_types/_event.py Updates doc links to new module paths.
src/aimbat/_tui/app.py Uses BoundICCS + periodic staleness detection; shows modified time.
src/aimbat/_cli/utils/sampledata.py Aligns global parameter handling with other CLI commands.
src/aimbat/_cli/station.py Rebuilds station list output using core JSON/dump helpers.
src/aimbat/_cli/snapshot.py Rebuilds snapshot list/details output using JSON dump helpers.
src/aimbat/_cli/seismogram.py Rebuilds seismogram list/parameter list around updated core APIs.
src/aimbat/_cli/project.py Inlines former project info printing into CLI command.
src/aimbat/_cli/plot.py Adapts plotting commands to pass explicit event/ICCS instance.
src/aimbat/_cli/pick.py Adapts pick tools to explicit event/ICCS instance.
src/aimbat/_cli/event.py Rebuilds event list/parameter list around JSON table output.
src/aimbat/_cli/data.py Rebuilds data list output in CLI (moved from core).
src/aimbat/_cli/align.py Adapts ICCS/MCCC run commands to explicit event/ICCS instance.
docs/usage/tui.md Adds TUI usage page stub.
docs/usage/shell.md Adds shell usage page stub.
docs/usage/index.md Updates usage overview and interface descriptions.
docs/usage/gui.md Updates GUI heading.
docs/usage/defaults.md Updates defaults heading.
docs/usage/cli.md Replaces CLI page with new overview + validation note.
docs/usage/api.md Adds Python API overview page.
docs/first-steps/workflow.md Rewrites workflow content; adds proper citations and guidance.
docs/first-steps/installation.md Rewrites installation instructions (uv/pipx links, examples).
docs/first-steps/data.md Rewrites data model explanation and improves formatting.

Comment on lines +68 to 71
## Installing locally

After successfully test driving AIMBAT you may want to actually install it.
This is very simple with `uv`:
Permanent installation of is just as easy. Just run `uv tool install`:

Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sentence “Permanent installation of is just as easy.” is missing the object (e.g. “Permanent installation of AIMBAT…”). This reads as a typo in the rendered docs.

Copilot uses AI. Check for mistakes.
Comment thread src/aimbat/_cli/station.py Outdated
Comment on lines +50 to +54
with Session(engine) as session:
print_json(dump_station_table_to_json(session))

if __name__ == "__main__":
app()
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if __name__ == "__main__": app() is currently indented inside cli_station_dump(), which means it only runs when that command executes and the module has no top-level entrypoint when run as a script. Move the main guard back to module scope (bottom of file) and remove it from inside the command function.

Copilot uses AI. Check for mistakes.
Comment thread src/aimbat/core/_station.py Outdated
Comment on lines +98 to +155
# @overload
# def get_stations_with_event_seismogram_count(
# session: Session, as_json: Literal[False]
# ) -> Sequence[tuple[AimbatStation, int, int]]: ...
#
#
# @overload
# def get_stations_with_event_seismogram_count(
# session: Session, as_json: Literal[True]
# ) -> list[dict[str, Any]]: ...
#
#
# def get_stations_with_event_seismogram_count(
# session: Session, as_json: bool
# ) -> Sequence[tuple[AimbatStation, int, int]] | list[dict[str, Any]]:
# """Get stations along with the count of seismograms and events they are associated with.
#
# Args:
# session: Database session.
# as_json: Whether to return the result as JSON.
#
# Returns: A sequence of tuples containing the station, count of seismograms
# and count of events, or a JSON string if as_json is True.
# """
# logger.info("Getting stations with associated seismogram and event counts.")
#
# statement = (
# select(
# AimbatStation,
# func.count(col(AimbatSeismogram.id)),
# func.count(func.distinct(col(AimbatEvent.id))),
# )
# .select_from(AimbatStation)
# .join(AimbatSeismogram, isouter=True)
# .join(AimbatEvent, isouter=True)
# .group_by(col(AimbatStation.id))
# )
#
# logger.debug(f"Executing query: {statement}")
# results = session.exec(statement).all()
#
# if not as_json:
# return results
#
# formatted_results = []
#
# for row in results:
# # 1. Dump the station to a dict. mode="json" safely converts UUIDs/Datetimes to strings!
# station_dict = row[0].model_dump(mode="json")
#
# # 2. Add the counts directly to the dictionary
# station_dict["seismogram_count"] = row[1]
# station_dict["event_count"] = row[2]
#
# # 3. Add to our final list
# formatted_results.append(station_dict)
#
# return formatted_results
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Large blocks of dead code have been left commented-out (the old get_stations_with_event_seismogram_count implementation). This makes the module harder to maintain and review, and risks diverging behaviour if it’s later partially re-enabled. Delete the commented-out implementation (it’s preserved in git history) and keep only the current API.

Copilot uses AI. Check for mistakes.
Comment on lines +81 to +102
# Trigger 3: Track last modification time when event parameters change
connection.execute(text("""
CREATE TRIGGER IF NOT EXISTS event_modified_on_params_update
AFTER UPDATE ON aimbateventparameters
BEGIN
UPDATE aimbatevent SET last_modified = datetime('now')
WHERE id = NEW.event_id;
END;
"""))

# Trigger 4: Track last modification time when seismogram parameters change
connection.execute(text("""
CREATE TRIGGER IF NOT EXISTS event_modified_on_seis_params_update
AFTER UPDATE ON aimbatseismogramparameters
BEGIN
UPDATE aimbatevent SET last_modified = datetime('now')
WHERE id = (
SELECT event_id FROM aimbatseismogram
WHERE id = NEW.seismogram_id
);
END;
"""))
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

last_modified is set via SQLite datetime('now'), which only has 1-second resolution. Since BoundICCS.created_at is a high-resolution pandas Timestamp, updates occurring within the same second as ICCS creation may not be detected as stale (last_modified may not compare greater than created_at). Consider storing sub-second precision in the trigger (e.g. using strftime with %f) or normalising created_at to the same resolution.

Copilot uses AI. Check for mistakes.
Comment thread docs/usage/index.md Outdated

Once [installed](../first-steps/installation.md), AIMBAT can be used in several ways:
Once [installed](../first-steps/installation.md), AIMBAT can be used in several
ways, each of which have unique strengths depending on the task at hand:
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grammar: “each of which have unique strengths” should be “each of which has unique strengths” (singular ‘each’).

Suggested change
ways, each of which have unique strengths depending on the task at hand:
ways, each of which has unique strengths depending on the task at hand:

Copilot uses AI. Check for mistakes.
@smlloyd smlloyd force-pushed the rearrange-core branch 2 times, most recently from d491777 to c41e64d Compare March 5, 2026 11:22
@smlloyd smlloyd merged commit fbada03 into master Mar 5, 2026
22 of 24 checks passed
@smlloyd smlloyd deleted the rearrange-core branch March 5, 2026 11:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants