Phil Package API

Phil package.

class phil.CovarianceMatrix(*, matrix: list[list[float]], variables: list[str] = <factory>, citations: list[str])[source]

Bases: BaseModel

citations: list[str]
matrix: list[list[float]]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

variables: list[str]
class phil.CovariateDistributionImputer(n_neighbors: int = 5, missing_values=nan, random_state=None, threshold: float = 1.0, covariance_matrix=None)[source]

Bases: BaseEstimator

Imputer that samples from the conditional distribution P(x_j | x_{-j}) approximated via k-nearest neighbors in the observed covariate space.

fit(X, y) → CovariateDistributionImputer[source]
predict(X) → ndarray[source]
class phil.CovariateSubset(*, predictors: list[str], citations: list[str], estimators: list[str] | None = None, sample_posterior: bool | None = None)[source]

Bases: BaseModel

citations: list[str]
estimators: list[str] | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

predictors: list[str]
sample_posterior: bool | None
class phil.DistributionImputer(missing_values=nan, random_state=None, threshold=1.0)[source]

Bases: BaseEstimator

Imputer that samples from empirical observed values.

fit(X, y)[source]
predict(X)[source]
class phil.DomainKnowledge(*, covariate_subsets: dict[str, CovariateSubset] | None = None, covariance_matrix: CovarianceMatrix | None = None, variable_bounds: dict[str, VariableBounds] | None = None)[source]

Bases: BaseModel

covariance_matrix: CovarianceMatrix | None
covariate_subsets: dict[str, CovariateSubset] | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

variable_bounds: dict[str, VariableBounds] | None
class phil.ECT(config: ECTConfig)[source]

Bases: Magic

configure(**kwargs)[source]
generate(X: list[ndarray]) → list[ndarray][source]
class phil.ECTCollapseResult(strategy: 'str', collapsed_df: 'pd.DataFrame', selected_index: 'int', weights: 'list[float]', effective_ensemble_size: 'float', ect_distance_to_median: 'float | None', medoid_ect_distance_to_median: 'float', manifold_convexity_ratio: 'float | None', non_convex_manifold_warning: 'bool', distribution_summary: 'dict[str, Any]', column_variability: 'dict[str, dict[str, Any]]', strategy_comparison: 'list[dict[str, Any]]' = <factory>)[source]

Bases: object

collapsed_df: DataFrame
column_variability: dict[str, dict[str, Any]]
distribution_summary: dict[str, Any]
ect_distance_to_median: float | None
effective_ensemble_size: float
manifold_convexity_ratio: float | None
medoid_ect_distance_to_median: float
non_convex_manifold_warning: bool
selected_index: int
strategy: str
strategy_comparison: list[dict[str, Any]]
to_dict() → dict[str, Any][source]
to_report_dict() → dict[str, Any][source]
weights: list[float]
class phil.ECTConfig(*, num_thetas: int, radius: float, resolution: int, scale: int, normalize: bool = True, seed: int = 0)[source]

Bases: BaseModel

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

normalize: bool
num_thetas: int
radius: float
resolution: int
scale: int
seed: int
class phil.GridGallery[source]

Bases: object

Collection of imputation grids optimized for specific domains.

Citations: - Sampling/Multiverse: Wayland et al. (2025) - https://www.nature.com/articles/s41560-025-01871-0 - Finance: Gu, Kelly, & Xiu (2020) on ML for asset pricing and robust ML portfolios. - Healthcare: Stekhoven & Bühlmann (2011) on MissForest and Chen et al. (2023) on clinical imputation. - Marketing: Anand & Mamidi (2020) / Zhang et al. (2025) on ML for consumer analytics. - Engineering: Thomas & Rajabi (2021) and Idri et al. (2016) on systematic reviews of engineering data.

classmethod get(name: str) → ImputationConfig[source]
class phil.ImputationConfig(*, methods: list[str], modules: list[str], grids: list[ParameterGrid], domain_knowledge: DomainKnowledge | None = None)[source]

Bases: BaseModel

Configuration for imputation methods and parameter grids.

domain_knowledge: DomainKnowledge | None
grids: list[ParameterGrid]
methods: list[str]
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

modules: list[str]
class phil.MaskedIterativeImputer(estimator=None, *, missing_values=nan, sample_posterior=False, max_iter=10, tol=0.001, n_nearest_features=None, initial_strategy='mean', fill_value=None, imputation_order='ascending', skip_complete=False, min_value=-inf, max_value=inf, verbose=0, random_state=None, add_indicator=False, keep_empty_features=False, covariate_subsets=None, feature_names=None)[source]

Bases: IterativeImputer

Extension of IterativeImputer that respects a covariate_subsets mapping, per-feature estimator overrides, and per-feature bounds.

This class allows users to restrict which predictors and estimators are used to impute specific target variables based on domain knowledge.

fit(X, y=None)[source]

Fit the imputer on X and return self.

fit_transform(X, y=None)[source]

Fit the imputer on X and return the transformed array.

class phil.Phil(samples: int = 30, param_grid: str = 'default', magic: str = 'ECT', config=None, random_state=None, collapse_strategy: str = 'euclidean_medoid', temperature: float | None = 1.0, trim_quantile: float = 0.2)[source]

Bases: object

collapse(strategy: str = 'auto', *, temperature: float | None = 1.0, trim_quantile: float = 0.2, cluster_id: int | None = None, compare_all: bool = False) → ECTCollapseResult[source]

Agentically navigate and collapse the fitted ECT signature distribution without re-fitting the imputation ensemble.

fit(df: DataFrame, max_iter: int = 5) → DataFrame[source]
generate_descriptors() → list[ndarray][source]
impute(df: DataFrame, max_iter: int = 10) → list[ndarray][source]
plot_mds(**kwargs)[source]

Visualize the ECT descriptor space via MDS after fit().

transform(df: DataFrame, max_iter: int = 5) → DataFrame[source]
class phil.PhilTransformer(samples: int = 30, param_grid: str | ImputationConfig = 'default', magic: str = 'ECT', config: dict | None = None, random_state: int | None = None, max_iter: int = 5)[source]

Bases: BaseEstimator, TransformerMixin

fit(X: DataFrame, y: Any = None) → PhilTransformer[source]
transform(X: DataFrame) → DataFrame[source]
class phil.PreprocessingConfig(*, method: str, module: str = 'sklearn.preprocessing', params: dict[str, ~typing.Any] = <factory>)[source]

Bases: BaseModel

Configuration for data preprocessing steps.

method: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

module: str
params: dict[str, Any]
class phil.VariableBounds(*, min_value: float | None = None, max_value: float | None = None, distribution_family: str | None = None, citations: list[str] = <factory>)[source]

Bases: BaseModel

citations: list[str]
distribution_family: str | None
max_value: float | None
min_value: float | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

phil.analyze_ect_distribution(descriptors: list[ndarray], candidate_metadata: list[dict[str, Any]] | None = None, candidate_methods: list[str] | None = None) → dict[str, Any][source]

Analyze the empirical distribution of ECT signatures {Psi_1, …, Psi_M} to guide agentic selection of the collapse strategy.

phil.build_research_worksheet(df_or_profile: DataFrame | dict[str, Any], profile: dict[str, Any] | None = None, *, grid: str = 'default', run_name: str = 'phil_sweep', data_path: str = '', domain_context: str = '', study_context: str = '', random_state: int = 42) → dict[str, Any][source]

Build a structured Research Worksheet & YAML Config Template from empirical predictability profiles.

Zero domain knowledge is hardcoded in Phil. Instead, this returns:
  1. feature_research_cards: Per-column empirical findings paired with structured literature questions for the frontier agent to investigate.

  2. config_template_yaml: A Phil YAML scaffold with pre-structured domain_knowledge slots (covariate_subsets, variable_bounds, covariance_matrix, and required citations placeholders) ready for the agent to populate after literature review.

phil.collapse_ect_ensemble(candidates: list[DataFrame], descriptors: list[ndarray], *, strategy: str = 'auto', temperature: float = 1.0, trim_quantile: float = 0.2, cluster_id: int | None = None, compare_all: bool = False, original_df: DataFrame | None = None, standardized_candidates: list[ndarray] | None = None, candidate_metadata: list[dict[str, Any]] | None = None, magic_estimator: Any = None, preprocessor: Any = None, variable_bounds: dict[str, Any] | None = None) → ECTCollapseResult[source]

Collapse an ensemble of candidate imputations {X^(1), …, X^(M)} using their ECT signatures {Psi_1, …, Psi_M} and return the collapsed DataFrame plus topological fidelity and Rubin representational variability diagnostics.

Pooling fidelity requires the fitted preprocessor and magic_estimator; distances and ratios are None when unavailable. standardized_candidates is retained for compatibility but is not averaged to approximate returned data.

phil.compute_weiszfeld_median(vectors: ndarray, max_iter: int = 100, tol: float = 1e-06) → ndarray[source]

Compute the L1 geometric median of row vectors via Weiszfeld’s algorithm.

phil.plot_mds(descriptors: list[np.ndarray], selected_index: int, ax=None, figsize: tuple[int, int] = (8, 6), random_state: int | None = None) → tuple[Figure, np.ndarray][source]

Visualize the ECT descriptor space via Multi-Dimensional Scaling (MDS).

phil.profile_predictability(df: DataFrame, target_columns: list[str] | None = None, random_state: int = 42) → dict[str, Any][source]

Empirically profile predictability, predictor rankings, MAR missingness drivers, and observed distributions for incomplete columns in df.

Contains zero hardcoded domain facts.

class phil.phil.Phil(samples: int = 30, param_grid: str = 'default', magic: str = 'ECT', config=None, random_state=None, collapse_strategy: str = 'euclidean_medoid', temperature: float | None = 1.0, trim_quantile: float = 0.2)[source]

Bases: object

collapse(strategy: str = 'auto', *, temperature: float | None = 1.0, trim_quantile: float = 0.2, cluster_id: int | None = None, compare_all: bool = False) → ECTCollapseResult[source]

Agentically navigate and collapse the fitted ECT signature distribution without re-fitting the imputation ensemble.

fit(df: DataFrame, max_iter: int = 5) → DataFrame[source]
generate_descriptors() → list[ndarray][source]
impute(df: DataFrame, max_iter: int = 10) → list[ndarray][source]
plot_mds(**kwargs)[source]

Visualize the ECT descriptor space via MDS after fit().

transform(df: DataFrame, max_iter: int = 5) → DataFrame[source]

Empirical predictability profiling and guided research worksheet generation for Phil.

Contains zero hardcoded domain facts. Instead, this module empirically profiles missingness patterns, linear vs. nonlinear predictability, and observed feature distributions, then emits a structured Research Worksheet & YAML Config Template for frontier models to populate from scientific literature.

phil.diagnostics.build_research_worksheet(df_or_profile: DataFrame | dict[str, Any], profile: dict[str, Any] | None = None, *, grid: str = 'default', run_name: str = 'phil_sweep', data_path: str = '', domain_context: str = '', study_context: str = '', random_state: int = 42) → dict[str, Any][source]

Build a structured Research Worksheet & YAML Config Template from empirical predictability profiles.

Zero domain knowledge is hardcoded in Phil. Instead, this returns:
  1. feature_research_cards: Per-column empirical findings paired with structured literature questions for the frontier agent to investigate.

  2. config_template_yaml: A Phil YAML scaffold with pre-structured domain_knowledge slots (covariate_subsets, variable_bounds, covariance_matrix, and required citations placeholders) ready for the agent to populate after literature review.

phil.diagnostics.profile_predictability(df: DataFrame, target_columns: list[str] | None = None, random_state: int = 42) → dict[str, Any][source]

Empirically profile predictability, predictor rankings, MAR missingness drivers, and observed distributions for incomplete columns in df.

Contains zero hardcoded domain facts.

Scikit-learn compatible transformers for Phil.

class phil.transformers.PhilTransformer(samples: int = 30, param_grid: str | ImputationConfig = 'default', magic: str = 'ECT', config: dict | None = None, random_state: int | None = None, max_iter: int = 5)[source]

Bases: BaseEstimator, TransformerMixin

fit(X: DataFrame, y: Any = None) → PhilTransformer[source]
transform(X: DataFrame) → DataFrame[source]