Adapters¶
This page documents the adapter interface and the concrete adapter implementations currently shipped with causaliq-discovery.
PackageAdapter¶
PackageAdapter
¶
Interface every structure learning package must implement.
Each concrete subclass wraps a single external package (e.g. bnlearn, Tetrad, causal-learn). Adding a new package requires implementing this interface and registering the adapter and its AlgorithmSpec entries with AlgorithmRegistry.
The three-method design keeps the concerns separate: - convert_input handles all data preparation for the package. - run invokes the algorithm with package-specific arguments. - convert_output normalises the result to a common SDG.
Methods:
-
build_trace–Convert raw output to a JSON-serialisable score_steps trace.
-
convert_input–Convert input data to the package-specific format.
-
convert_output–Convert the raw package output to an SDG.
-
run–Run the structure learning algorithm.
build_trace
abstractmethod
¶
build_trace(raw_output: Any) -> Optional[List[Dict[str, Any]]]
Convert raw output to a JSON-serialisable score_steps trace.
Called only when trace=True was passed to run(). The returned list is stored directly in DiscoveryResult.trace. Return None if no trace data is available in raw_output.
Parameters:
-
(raw_output¶Any) –Raw output from run().
Returns:
-
Optional[List[Dict[str, Any]]]–Score-steps trace as a list of dicts, or None.
convert_input
abstractmethod
¶
convert_input(
data: Union[DataFrame, Data],
variable_types: Optional[Dict[str, VariableType]],
sample_size: Optional[int],
randomise: Optional[list],
seed: Optional[int],
) -> Any
Convert input data to the package-specific format.
Parameters:
-
(data¶Union[DataFrame, Data]) –Input data as a pandas DataFrame or a CausalIQ Data object. File path strings are resolved to a DataFrame by
learn_graphbefore this is called. -
(variable_types¶Optional[Dict[str, VariableType]]) –Mapping of variable name to VariableType, or None to use imputed types.
-
(sample_size¶Optional[int]) –Number of rows to use, or None for all rows.
-
(randomise¶Optional[list]) –List of randomisation options to apply, or None.
-
(seed¶Optional[int]) –Randomisation seed, or None.
Returns:
-
Any–Package-specific data representation.
convert_output
abstractmethod
¶
convert_output(raw_output: Any) -> SDG
Convert the raw package output to an SDG.
Parameters:
-
(raw_output¶Any) –Raw output from run().
Returns:
-
SDG–Learnt graph as an SDG object.
run
abstractmethod
¶
run(
converted_data: Any,
algorithm: str,
mapped_hyperparameters: Dict[str, Any],
trace: bool = False,
) -> Any
Run the structure learning algorithm.
Parameters:
-
(converted_data¶Any) –Package-specific data from convert_input.
-
(algorithm¶str) –Algorithm name in the package's own terminology.
-
(mapped_hyperparameters¶Dict[str, Any]) –Hyperparameters with names and values already translated to package-specific form by AlgorithmRegistry.
-
(trace¶bool, default:False) –If True, the raw output must include trace data that build_trace() can convert.
Returns:
-
Any–Raw package output (format is package-specific).
BnlearnAdapter¶
BnlearnAdapter
¶
PackageAdapter wrapping the bnlearn R package.
Translates between the common causaliq-discovery interface and bnlearn's R API via the causaliq-core subprocess R session. Supports seven algorithms: hc, tabu, pc-stable, gs, iiamb, h2pc, and mmhc.
Methods:
-
build_trace–Parse bnlearn debug output into score_steps format.
-
convert_input–Convert Data to an R data.frame code string.
-
convert_output–Parse arcs from R stdout and return an SDG.
-
run–Build and execute the bnlearn R script.
build_trace
¶
build_trace(raw_output: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]
Parse bnlearn debug output into score_steps format.
Extracts arc changes and score deltas from the verbose
debug=TRUE output produced by HC-family algorithms.
Constraint-based algorithms (pc-stable, gs, iiamb) produce
no parseable trace and return None.
Parameters:
-
(raw_output¶Dict[str, Any]) –Dict returned by run.
Returns:
-
Optional[List[Dict[str, Any]]]–List of score_step dicts for score-based algorithms,
-
Optional[List[Dict[str, Any]]]–or
Nonefor constraint-based algorithms. Each dict -
contains(Optional[List[Dict[str, Any]]]) – -
Optional[List[Dict[str, Any]]]–time:None— bnlearn provides no per-step timing. -
Optional[List[Dict[str, Any]]]–arc_change: Arc changed as[from, to]list. -
Optional[List[Dict[str, Any]]]–score_increase: Score delta for the chosen change.
convert_input
¶
convert_input(
data: Union[DataFrame, Data],
variable_types: Optional[Dict[str, VariableType]],
sample_size: Optional[int],
randomise: Optional[list],
seed: Optional[int],
) -> Dict[str, Any]
Convert Data to an R data.frame code string.
Generates R source code that creates a data.frame using
causaliq_core.r.data_to_r_dataframe. Categorical
columns become R factors; continuous columns become numeric
vectors. Normalisation and sampling are applied by
learn_graph before this method is called.
Parameters:
-
(data¶Union[DataFrame, Data]) –Input data as a CausalIQ NumPy Data object.
-
(variable_types¶Optional[Dict[str, VariableType]]) –Resolved variable types, or None if all variables are assumed continuous.
-
(sample_size¶Optional[int]) –Already applied by learn_graph; ignored.
-
(randomise¶Optional[list]) –Already applied by learn_graph; ignored.
-
(seed¶Optional[int]) –Already applied by learn_graph; ignored.
Returns:
-
Dict[str, Any]–Dict with keys:
-
Dict[str, Any]–r_data_code: R source that creates the data.frame. -
Dict[str, Any]–dstype: Dataset type,"continuous"or -
Dict[str, Any]–"categorical". -
Dict[str, Any]–nodes: Ordered list of node names. -
Dict[str, Any]–n_rows: Number of rows in the dataset.
convert_output
¶
convert_output(raw_output: Dict[str, Any]) -> SDG
Parse arcs from R stdout and return an SDG.
Splits stdout on the arcs sentinel to isolate the arc table,
then uses r_arcs_to_edges to collapse bidirectional pairs
(which bnlearn uses for undirected edges) into single
undirected edge tuples.
Parameters:
-
(raw_output¶Dict[str, Any]) –Dict returned by run.
Returns:
-
SDG–DAG for score-based algorithms (hc, tabu, h2pc, mmhc);
-
SDG–PDAG for constraint-based algorithms (pc-stable, gs,
-
SDG–iiamb).
run
¶
run(
converted_data: Dict[str, Any],
algorithm: str,
mapped_hyperparameters: Dict[str, Any],
trace: bool = False,
) -> Dict[str, Any]
Build and execute the bnlearn R script.
Adjusts score and CI-test names for Gaussian continuous data,
applies the BIC penalty-weight transformation for discrete
data, then calls run_r_script with the assembled R code.
The max_elapsed hyperparameter is silently ignored because
bnlearn has no built-in timeout.
When trace=True, bnlearn's debug=TRUE output is
captured in stdout before the arcs sentinel, allowing
build_trace to parse the score steps.
Parameters:
-
(converted_data¶Dict[str, Any]) –Dict returned by convert_input.
-
(algorithm¶str) –Common algorithm name, e.g.
"hc". -
(mapped_hyperparameters¶Dict[str, Any]) –Hyperparameters with names already translated via
AlgorithmSpec.hyperparameter_name_map. -
(trace¶bool, default:False) –If True, enable bnlearn debug output.
Returns:
-
Dict[str, Any]–Dict with keys:
-
Dict[str, Any]–stdout: Raw stdout captured from R. -
Dict[str, Any]–algorithm: The common algorithm name. -
Dict[str, Any]–nodes: Ordered node names from convert_input.
Raises:
-
RNotAvailableError–If R is not installed or not on PATH.
-
RRuntimeError–If the R script raises a runtime error.
TetradAdapter¶
TetradAdapter
¶
PackageAdapter wrapping Tetrad causal-cmd algorithms.
This initial implementation supports fges only and calls the
pinned Java causal-cmd executable via causaliq_core.java.
Methods:
-
build_trace–Build a minimal trace with init and stop records.
-
convert_input–Convert input to a DataFrame consumable by causal-cmd.
-
convert_output–Return the parsed graph from run output.
-
run–Run causal-cmd and parse the output graph file.
build_trace
¶
Build a minimal trace with init and stop records.
Tetrad does not expose step-by-step arc operations in causal-cmd output, so this adapter emits a two-row trace containing start score and final score with elapsed time.
convert_input
¶
convert_input(
data: Union[DataFrame, Data],
variable_types: Optional[Dict[str, VariableType]],
sample_size: Optional[int],
randomise: Optional[list],
seed: Optional[int],
) -> Dict[str, Any]
Convert input to a DataFrame consumable by causal-cmd.
Parameters:
-
(data¶Union[DataFrame, Data]) –Input data as DataFrame or CausalIQ Data object.
-
(variable_types¶Optional[Dict[str, VariableType]]) –Already resolved variable types; unused.
-
(sample_size¶Optional[int]) –Already applied by learn_graph; ignored.
-
(randomise¶Optional[list]) –Already applied by learn_graph; ignored.
-
(seed¶Optional[int]) –Already applied by learn_graph; ignored.
Returns:
-
Dict[str, Any]–Dict containing the DataFrame and dataset type.
convert_output
¶
Return the parsed graph from run output.
run
¶
run(
converted_data: Dict[str, Any],
algorithm: str,
mapped_hyperparameters: Dict[str, Any],
trace: bool = False,
) -> TetradRunOutput
Run causal-cmd and parse the output graph file.
Parameters:
-
(converted_data¶Dict[str, Any]) –Dict returned by convert_input.
-
(algorithm¶str) –Algorithm name, currently
fgesonly. -
(mapped_hyperparameters¶Dict[str, Any]) –Mapped package-specific parameters.
-
(trace¶bool, default:False) –Trace output is not currently supported.
Returns:
-
TetradRunOutput–Dict containing parsed graph and runtime metadata.
Raises:
-
ValueError–If unsupported algorithm or parameter values.
-
RuntimeError–If output file cannot be parsed.