Skip to content

polychron.models.Model Module

Model dataclass

MVP Model representing a polychron model.

Note

Optional[foo] must be used rather than from __future__ import annotations and foo | None in python 3.9 due to use of get_type_hints

name instance-attribute

name: str

The name of the model within the project (unique)

path instance-attribute

path: Path

The path to the directory representing this model on disk

stratigraphic_graphviz_file class-attribute instance-attribute

stratigraphic_graphviz_file: Optional[Path] = field(default=None)

Stratigraphic path for .dot/.gv input

Formerly StartPage.FILE_INPUT

stratigraphic_df class-attribute instance-attribute

stratigraphic_df: Optional[DataFrame] = field(default=None)

The stratigraphic file from CSV, if loaded.

Formerly StartPage.stratfile

stratigraphic_dag class-attribute instance-attribute

stratigraphic_dag: Optional[DiGraph] = field(default=None)

Stratigraphic Directed Acyclic Graph, initially produced from the stratigraphic dataframe or graphviz file before being mutated.

Formerly StartPage.graph

stratigraphic_image class-attribute instance-attribute

stratigraphic_image: Optional[Image] = field(default=None)

Rendered version of the stratigraphic graph as an image, for whicle a handle must be kept for persistence.

radiocarbon_df class-attribute instance-attribute

radiocarbon_df: Optional[DataFrame] = field(default=None)

Dataframe containing radiocarbon dating information, loaded from disk

Formerly StartPage.datefile

context_no_unordered class-attribute instance-attribute

context_no_unordered: Optional[List[str]] = field(default=None)

A list of stratigraphic graph nodes, initially populated within open_scientific_dating_file before being used elsewhere.

This list is in the order from the input file, rather than a topological order.

group_df class-attribute instance-attribute

group_df: Optional[DataFrame] = field(default=None)

Dataframe of context grouping information loaded from disk.

Expected columns ["context", "Group"]

Formerly StartPage.phasefile

group_relationship_df class-attribute instance-attribute

group_relationship_df: Optional[DataFrame] = field(default=None)

Dataframe containing group relationship information loaded from disk

Required columns ["above", "below"], optional columns ["relationship"]

Formerly phase_rel_df in StartPage.open_file5

context_equality_df class-attribute instance-attribute

context_equality_df: Optional[DataFrame] = field(default=None)

Dataframe containing context equality relationship information loaded from disk

Formerly equal_rel_df in StartPage.open_file6

load_check class-attribute instance-attribute

load_check: bool = False

If the chronological graph has been rendered for the current state of the model

Formerly global load_check, where "loaded" is now True and "not_loaded" is False.

chronological_dag class-attribute instance-attribute

chronological_dag: Optional[DiGraph] = field(default=None)

Chronological directed graph, produced by rendering the chronological graph

Formerly StartPage.chrono_dag

chronological_image class-attribute instance-attribute

chronological_image: Optional[Image] = field(default=None)

Rendered version of the Chronological graph as an image, for which a handle must be kept for persistence and to avoid regenerating when not required.

When load_check is True, this image is valid for the current state of the Model.

Formerly StartPage.image2

mcmc_check class-attribute instance-attribute

mcmc_check: bool = False

If the model has been calibrated

Formerly global mcmc_check, where "mcmc_loaded" is now True and "mcmc_notloaded" is False.

deleted_nodes class-attribute instance-attribute

deleted_nodes: List[Tuple[str, str]] = field(default_factory=list)

List of deleted nodes and the reason they were deleted.

This may include the same node multiple times (as nodes can be deleted, then added again)

Formerly StartPage.delnodes and StartPage.delnodes_meta

deleted_edges class-attribute instance-attribute

deleted_edges: List[Tuple[str, str, str]] = field(default_factory=list)

List of deleted edges and the reason they were deleted

Each entry is the (a_node, b_node, reason).

This may include the same edges multiple times (as edges can be deleted, then added again)

Formerly StartPage.edges_del and StartPage.deledges_meta

resid_or_intru_dag class-attribute instance-attribute

resid_or_intru_dag: Optional[DiGraph] = field(default=None)

Copy of stratigraphic_dag for the residual or intrusive workflow

This is mutated to show which nodes have been marked as residual or intrusive.

This does not need saving.

Formerly PageTwo.graphcopy

resid_or_intru_image class-attribute instance-attribute

resid_or_intru_image: Optional[Image] = field(default=None)

Image handle for the rendered png of the stratigraphic graph with residual or intrusive node highlighting.

A handle to this needs to be maintained to avoid garbage collection

Formerly PageTwo.image

intrusive_contexts class-attribute instance-attribute

intrusive_contexts: List[str] = field(default_factory=list)

List of intrusive contexts/nodes.

Formerly PageTwo.intru_list

residual_contexts class-attribute instance-attribute

residual_contexts: List[str] = field(default_factory=list)

List of residual contexts/nodes.

Formerly PageTwo.resid_list

intrusive_context_types class-attribute instance-attribute

intrusive_context_types: Dict[str, str] = field(default_factory=dict)

Dict of selected drop down choice for intrusive context/nodes.

residual_context_types class-attribute instance-attribute

residual_context_types: Dict[str, str] = field(default_factory=dict)

Dict of selected drop down choice for intrusive context/nodes.

grouped_rendering class-attribute instance-attribute

grouped_rendering: bool = False

Flag indicating that the graphs should be rendered in grouped rendering mode

Previously global phase_true

context_types class-attribute instance-attribute

context_types: List[Literal['normal', 'residual', 'intrusive']] = field(default_factory=list)

The type of each context, in the same order as as context_no_unordered.

Used for calibration (MCMC)

Formerly StartPage.CONT_TYPE

prev_group class-attribute instance-attribute

prev_group: List[str] = field(default_factory=list)

List of previous phases, with "start" as the 0th value.

Initialised in ManageGroupRelationshipsPresenter.full_chronograph_func

Formerly StartPage.prev_phase and popupWindow3.prev_phase

post_group class-attribute instance-attribute

post_group: List[str] = field(default_factory=list)

List of post phases, with "end" as the final value.

Initialised in ManageGroupRelationshipsPresenter.full_chronograph_func

Formerly StartPage.post_phase and popupWindow3.post_phase

phi_ref class-attribute instance-attribute

phi_ref: List[str] = field(default_factory=list)

Ordered list of groups, from oldest to youngest.

Formerly StartPage.phi_ref

removed_nodes_tracker class-attribute instance-attribute

removed_nodes_tracker: List[str] = field(default_factory=list)

List of nodes (contexts) for which there was insufficient node or group information, and so been removed during group relationship management.

This is separate from nodes which were deleted by the user.

Formerly StartPage.node_del_tracker, PageTwo.node_del_tracker and popupWindow3.node_del_tracker

mcmc_data class-attribute instance-attribute

mcmc_data: MCMCData = field(default_factory=MCMCData)

MCMC data for this model. Includes values used as inputs and outputs for the MCMC data pase

If mcmc_check is true, it is implied that this has been saved to disk

stratigraphic_node_coords class-attribute instance-attribute

stratigraphic_node_coords: Optional[tuple[dict[str, list[float]], list[FloatingPointError]]] = field(default=None)

A tuple containing node coordinates and within the svg representation of the stratigraphic graph, and the dimensions of the svg.

This is updated when the stratigraphic_dag is re-rendered.

Formerly (part of) global node_df

Todo
  • ensure this is correct when reopening from disk? and there is no other places where this needs re-generating, for all 3 versions.

chronological_node_coords class-attribute instance-attribute

chronological_node_coords: Optional[tuple[dict[str, list[float]], list[FloatingPointError]]] = field(default=None)

A tuple containing node coordinates and within the svg representation of the chronological graph, and the dimensions of the svg.

This is updated when the chronological_dag is re-rendered.

Formerly (part of) global node_df

resid_or_intru_node_coords class-attribute instance-attribute

resid_or_intru_node_coords: Optional[Tuple[DataFrame, List[float]]] = field(default=None)

A tuple containing node coordinates and within the svg representation of the resid_or_intru graph, and the dimensions of the svg.

This is updated when the resid_or_intru_dag is re-rendered.

Formerly (part of) global node_df

__calibration class-attribute instance-attribute

__calibration: Optional[InterpolatedRCDCalibrationCurve] = field(default=None, init=False, repr=False)

Interpolated RCD calibration curve object, which is stored in a member variable so it is loaded once and only once

get_working_directory

get_working_directory() -> pathlib.Path

Get the working directory to be used for dynamically created files

This allows the "saved" version of the model to different from the version currently being worked on. I.e. the rendered chronological graph used in the UI as changes are made can be different to the version from when save the model was last saved.

get_chronological_graph_directory

get_chronological_graph_directory() -> pathlib.Path

Get the path to the chronological_graph directory for this model

Returns:

Type Description
Path

The path to the chronological_graph directory for this model

get_stratigraphic_graph_directory

get_stratigraphic_graph_directory() -> pathlib.Path

Get the path to the stratigraphic_graph directory for this model

Returns:

Type Description
Path

The path to the stratigraphic_graph directory for this model

get_mcmc_results_directory

get_mcmc_results_directory() -> pathlib.Path

Get the path to the mcmc_results directory for this model

Returns:

Type Description
Path

The path to the mcmc_results directory for this model

get_python_only_directory

get_python_only_directory() -> pathlib.Path

Get the path to the python_only directory for this model

Returns:

Type Description
Path

The path to the python_only directory for this model

to_json

to_json(pretty: bool = False)

Serialise this object to JSON, excluding ephemeral members

save

save() -> None

Save the current state of this model to disk at self.path

Raises:

Type Description
RuntimeError

raised when any error occurred during saving, with a message to present to the user

load_from_disk classmethod

load_from_disk(path: Path) -> 'Model'

Get an instance of the model from serialised json on disk.

Parameters:

Name Type Description Default
path Path

Path to a model directory (not the json file)

required

Raises:

Type Description
RuntimeWarning

when the model could not be loaded, but in a recoverable way. I.e. the directory exits but no files are contained (so allow the model to be "loaded")

RuntimeError

when the model could not be loaded, and the error cannot be recovered from within PolyChron. I.e. the json file is invalid/corrupt

create_dirs

create_dirs() -> None

Create the expected directories for this model, including working directories.

Formerly part of load_Window.create_file, popupWindow9.make_directories & popupWindow10.make_directories

Raises:

Type Description
OSError

Propagated from pathlib.Path.mkdir if an OSError occurred during directory creation

NotADirectoryError

Propagated from pathlib.Path.mkdir if any ancestors within the path are not a directory

save_deleted_contexts

save_deleted_contexts() -> None

Save the delete contexts metadata to disk

Formerly StartPage.tree2, in save_state_1

Raises:

Type Description
OSError

if any OS errors occur during csv writing (e.g. if the disk is full)

set_stratigraphic_graphviz_file

set_stratigraphic_graphviz_file(file_input: str | Path) -> None

provided a .dot/.gv file path, set the model input.

set_stratigraphic_df

set_stratigraphic_df(df: DataFrame) -> None

Provided a dataframe for stratigraphic relationships, set the values locally and post-process it to produce the stratigraphic graph

Nodes are added to the graph in row-major order, rather than using a set to avoid duplicates to ensure deterministic graph production.

I.e.

a, b
c, d

Will have nodes created in the order a, b, c, d

Parameters:

Name Type Description Default
df DataFrame

A dataframe containing 2 columns of context labels.

required

set_radiocarbon_df

set_radiocarbon_df(df: DataFrame) -> None

Provided a dataframe containing radiocarbon dating information for contexts, store a copy of the dataframe and mutate the stratigraphic dag

Parameters:

Name Type Description Default
df Dataframe

dataframe containing radiocarbon dating information. Expected columns ["context", "date", "error"]

required

set_group_df

set_group_df(df: DataFrame) -> None

Provided a dataframe for context grouping information, set the values locally and perform post processing

set_group_relationship_df

set_group_relationship_df(df: DataFrame) -> None

Provided a dataframe for group relationships information, set the values locally and post-process

Parameters:

Name Type Description Default
df DataFrame

The dataframe containing group relationship information, with required columns ["above", "below"] and optional column "relationship".

required

group_relationships_list

group_relationships_list() -> list[tuple[str, str]]

Get a list of group relationships for the model, based on the group_relationship_df.

Returns:

Type Description
list[tuple[str, str]]

A list of the group relationships, as tuples of (above, below)

group_relationships_dict

group_relationships_dict() -> dict[tuple[str, str], Optional[str]]

Get a dict of group relationships for the model including the type of relationship if known, based on the group_relationship_df.

Returns:

Type Description
dict[tuple[str, str], Optional[str]]

A list of the group relationships, as tuples of (above, below)

get_unique_groups

get_unique_groups() -> list[str]

Get a list of unique group labels

Returns:

Type Description
list[str]

List of group labels in a stable order.

set_context_equality_df

set_context_equality_df(df: DataFrame) -> None

Provided a dataframe for context equality information, set the values locally and post-process

Columns names are not currently expected/used, but there must be atleast 2 columns.

Parameters:

Name Type Description Default
df DataFrame

A dataframe containing context equality data.

required

render_strat_graph

render_strat_graph() -> None

Render the stratigraphic graph as a png and svg, with or without phasing depending on model state. Also updates the location of each node via the svg

render_resid_or_intru_dag

render_resid_or_intru_dag() -> None

Render the residual or intrusive sratigraphic graph as a png and svg, with or without phasing depending on model state. Also updates the locatison of each node

This graph will have different presentation information to highlight which contexts have been marked as residual or intrusive.

__render_strat_graph

__render_strat_graph() -> None

Render the stratigraphic graph mutating the Model state

Formerly imgrender

__render_strat_graph_phase

__render_strat_graph_phase() -> None

Render the stratigraphic graph, with phasing mutating the Model state

Formerly imgrender_phase

Todo
  • Consistently use graphviz.render or write_png|dot if possible throughout Model

__render_resid_or_intru_dag

__render_resid_or_intru_dag() -> None

Render the stratigraphic graph mutating the Model state

Formerly imgrender

__render_resid_or_intru_dag_phase

__render_resid_or_intru_dag_phase() -> None

Render the stratigraphic graph, with phasing mutating the Model state

Formerly imgrender_phase

render_chrono_graph

render_chrono_graph() -> None

Render the chronological graph as a PNG and an SVG, mutating the Model state

Formerly imgrender2

Todo
  • This should not require fi_new_chrono to exist on disk, but instead should create it from the chronological_dag if it exists?

reopen_stratigraphic_image

reopen_stratigraphic_image() -> None

Re-open the stratigraphic image from disk

Used when the window is reiszed as the in memory copy may have been resized

Formerly part of StartPage.resize

reopen_chronological_image

reopen_chronological_image() -> None

Re-open the chrono image from disk

Used when the window is reiszed as the in memory copy may have been resized

Formerly part of StartPage.resize2

record_deleted_node

record_deleted_node(context: str, reason: Optional[str] = None) -> None

Method to add a node to the list of deleted nodes

Parameters:

Name Type Description Default
context str

the context / node which was removed

required
reason Optional[str]

the reason the node was deleted, if provided.

None

record_deleted_edge

record_deleted_edge(context_a: str, context_b: str, reason: Optional[str] = None) -> None

Method to add an edge to the list of deleted edges

Parameters:

Name Type Description Default
context_a str

one context from the edge

required
context_a str

the other context from the edge

required
reason Optional[str]

the reason the node was deleted, if provided.

None

is_ready_for_mcmc

is_ready_for_mcmc() -> bool

Indicate if the model is ready for mcmc calibration or not.

Returns:

Type Description
bool

bool indicating if the model is ready for calibration

MCMC_func

MCMC_func(progress_io: Optional[Writable]) -> Tuple[List[str], List[List[float]], List[List[float]], List[str], int, int, List[List[float]], List[List[float]], Dict[str[List[float]]], Dict[str[List[float]]]]

run the mcmc calibration on the current model, returning output values without (significantly) mutating state

gathers all the inputs for the mcmc module and then runs it and returns resuslts dictionaries

Parameters:

Name Type Description Default
progress_io Optional[Writable]

An object which implements write(str) for the progress percentage. Could be stdout, MCMCProgressView or similar.

required

Returns:

Type Description
Tuple[List[str], List[List[float]], List[List[float]], List[str], int, int, List[List[float]], List[List[float]], Dict[str[List[float]]], Dict[str[List[float]]]]

a tuple of calibration results

Formerly StartPage.MCMC_func