### Install mofdsribe with all extras Source: https://mofdscribe.readthedocs.io/en/latest/installation.html To include all optional utilities, append `[all]` to the pip install command. ```bash pip install -e ".[all]" ``` -------------------------------- ### Install mofdsribe from GitHub Source: https://mofdscribe.readthedocs.io/en/latest/installation.html Install the latest code and data directly from GitHub. Use the `-e` flag for an editable installation. ```bash git clone git+https://github.com/kjappelbaum/mofdscribe.git cd mofdscribe pip install -e . ``` -------------------------------- ### Initialize BUFeaturizer with RDKitAdaptor Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_featurizer.html Example of initializing BUFeaturizer with RDKitAdaptor and specifying aggregation methods. This setup is useful for calculating features like asphericity on MOF BUs. ```python from mofdscribe.bu import BUFeaturizer, MOFBBs from mofdscribe.bu.rdkitadaptor import RDKitAdaptor from rdkit.Chem.Descriptors3D import Asphericity from pymatgen.core import Molecule from pymatgen.io.babel import BabelMolAdaptor base_featurizer = RDKitAdaptor(featurizer=Asphericity, feature_labels=["asphericity"]) bu_featurizer = BUFeaturizer(featurizer=base_featurizer, aggregations=("mean", "std", "min", "max")) bu_featurizer.featurize( mofbbs=MOFBBs(nodes=[BabelMolAdaptor.from_string( "[CH-]1C=CC=C1.[CH-]1C=CC=C1.[Fe+2]", "smi").pymatgen_mol], linkers=[BabelMolAdaptor.from_string("CCCC", "smi").pymatgen_mol])) ``` -------------------------------- ### BUFeaturizer Example Source: https://mofdscribe.readthedocs.io/en/latest/api/featurizers.html Demonstrates how to use BUFeaturizer with RDKitAdaptor to compute and aggregate features like asphericity for MOF building blocks. ```python >>> from mofdscribe.bu import BUFeaturizer, MOFBBs >>> from mofdscribe.bu.rdkitadaptor import RDKitAdaptor >>> from rdkit.Chem.Descriptors3D import Asphericity >>> from pymatgen.core import Molecule >> from pymatgen.io.babel import BabelMolAdaptor >>> base_featurizer = RDKitAdaptor(featurizer=Asphericity, feature_labels=["asphericity"]) >>> bu_featurizer = BUFeaturizer(featurizer=base_featurizer, aggregations=("mean", "std", "min", "max")) >>> bu_featurizer.featurize( mofbbs=MOFBBs(nodes=[BabelMolAdaptor.from_string( "[CH-]1C=CC=C1.[CH-]1C=CC=C1.[Fe+2]", "smi").pymatgen_mol], linkers=[BabelMolAdaptor.from_string("CCCC", "smi").pymatgen_mol])) ``` -------------------------------- ### Example Custom Model for MOFBench Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/bench/mofbench.html This example demonstrates how to implement a custom model class that can be used with MOFBench. It includes methods for featurization, fitting, and prediction using scikit-learn pipelines. ```python class MyDummyModel: def __init__(self): self.model = Pipeline( [("scaler", StandardScaler()), ("lr", LinearRegression(**(lr_kwargs or {})))] ) def featurize(self, s: Structure): return s.density def fit(self, idx, structures, y): x = np.array([self.featurize(s) for s in structures]).reshape(-1, 1) self.model.fit(x, y) def predict(self, idx, structures): x = np.array([self.featurize(s) for s in structures]).reshape(-1, 1) return self.model.predict(x) ``` -------------------------------- ### Initialize and Featurize with APRDF Source: https://mofdscribe.readthedocs.io/en/latest/api/featurizers.html Demonstrates how to initialize the APRDF featurizer and use it to compute features for a given structure. Ensure pymatgen and mofdscribe are installed. ```python from mofdscribe.chemistry.aprdf import APRDF from pymatgen.core.structure import Structure s = Structure.from_file("tests/test_files/LiTiO3.cif") aprdf = APRDF() features = aprdf.featurize(s) ``` -------------------------------- ### PHVect Initialization with Default Settings Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/ph_vect.html Demonstrates the initialization of the PHVect featurizer using its default parameters. This is useful for a quick start or when default behavior is desired. ```python PHVect() ``` -------------------------------- ### Install RASPA and Zeo++ dependencies Source: https://mofdscribe.readthedocs.io/en/latest/installation.html Install RASPA and Zeo++ using conda for energy grid/Henry coefficient and pore descriptor calculations. ```bash # RASPA and Zeo++ (if you want to use energy grid/Henry coefficient and pore descriptors) conda install -c conda-forge raspa2 zeopp-lsmo ``` -------------------------------- ### Instantiate a MOF-Dscribe Dummy Model for Benchmarking Source: https://mofdscribe.readthedocs.io/en/latest/getting_started.html Use a pre-implemented dummy model from MOF-Dscribe for testing or as a reference. This example uses `DensityRegressor` for a linear regression task. ```python from mofdscribe.bench.dummy_models import DensityRegressor from mofdscribe.bench.logKHCO2 import LogkHCO2IDBench logkHCO2_interpolation_density = LogkHCO2IDBench( DensityRegressor(), version="v0.0.1", name="linear density", features="density", model_type="linear regression /w polynomial features", implementation="mofdscribe", reference="mofdscribe", ) ``` -------------------------------- ### Install Open Babel dependency Source: https://mofdscribe.readthedocs.io/en/latest/installation.html Install Open Babel using conda for SBU-centered features with moffragmentor. ```bash # openbabel dependency for moffragmentor (if you want to use SBU-centered features) conda install -c conda-forge openbabel ``` -------------------------------- ### QMOF Dataset Initialization Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/datasets/qmof_dataset.html Demonstrates how to initialize the QMOF dataset with various options. ```APIDOC ## QMOF Dataset Initialization ### Description This section describes how to instantiate the QMOF dataset object, allowing users to specify version, flavor, and data filtering options. ### Method ```python QMOF(version: str = "v0.0.1", flavor: str = "all", drop_basename_duplicates: bool = True, drop_graph_duplicates: bool = True, subset: Optional[Collection[int]] = None, drop_nan: bool = False) ``` ### Parameters #### Arguments - **version** (str): The version of the dataset to use. Defaults to "v0.0.1". - **flavor** (str): The flavor of the dataset. Accepted values are "all", "csd", "gcmc", and "csd-gcmc". Defaults to "all". - **drop_basename_duplicates** (bool): If True, removes duplicate structures based on CSD basename. Defaults to True. - **drop_graph_duplicates** (bool): If True, removes duplicate structures based on graph hash. Defaults to True. - **subset** (Optional[Collection[int]]): A collection of indices to load a subset of the dataset. Defaults to None. - **drop_nan** (bool): If True, rows with NaN values in features or hashes are dropped. Defaults to False. ### Raises - **ValueError**: If an unavailable version is specified. ``` -------------------------------- ### Install CGAL and Dionysus dependencies Source: https://mofdscribe.readthedocs.io/en/latest/installation.html Install CGAL and Dionysus using conda for persistent-homology based features. May require system-level package manager installation on some systems. ```bash # cgal dependency for moltda (if you want to use persistent-homology based features) # on some systems, you might need to replace this with sudo apt-get install libcgal-dev or brew install cgal conda install -c conda-forge cgal dionysus ``` -------------------------------- ### LSOP Featurizer Initialization and Usage Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/lsop_featurizer.html This snippet demonstrates how to initialize and use the LSOP featurizer. It covers the constructor arguments and the featurization process. ```APIDOC ## LSOP Class ### Description Compute shape parameters for a fragment. The fragments can be a molecule or a molecule that only contains important part (e.g. binding sites) of a molecule. The shape parameters are then supposed to quantify the shape of the fragment. For instance, a triangular molecule will have a `tri_plan` parameter close to 1. While there is a site-based LSOP featurizer in matminer there is none that uses LSOP to quantify the shape of some fragment. This featurizers just does that. It does so by placing a dummy site at the center of mass of the fragment and then computes the LSOP considering all other sites as neighbors. ### Methods #### `__init__(self, types: Tuple[str] = _default_types, parameters: Optional[List[dict]] = None)` Initialize the featurizer. Args: types (Tuple[str]): The types of LSOP to compute. For the full list of types see: :py:attr:`pymatgen.analysis.local_env.LocalStructOrderParams.__supported_types`. Defaults to: ["tet", "oct", "bcc", "sq_pyr", "sq_pyr_legacy", "tri_bipyr", "sq_bipyr", "oct_legacy", "tri_plan", "sq_plan", "pent_plan", "tri_pyr", "pent_pyr", "hex_pyr", "pent_bipyr", "hex_bipyr", "T", "cuboct", "oct_max", "tet_max", "tri_plan_max", "sq_plan_max", "pent_plan_max", "cuboct_max", "bent", "see_saw_rect", "hex_plan_max", "sq_face_cap_trig_pris"] parameters(List[dict], optional): The parameters to pass to the LocalStructOrderParams object. #### `feature_labels(self) -> List[str]` Returns the feature labels for the computed LSOP types. #### `featurize(self, s: Union[Structure, IStructure, Molecule, IMolecule]) -> np.ndarray` Computes the LSOP values for the given structure or molecule. Args: s (Union[Structure, IStructure, Molecule, IMolecule]): The input structure or molecule. Returns: np.ndarray: An array of computed LSOP values. #### `implementors(self) -> List[str]` Returns the list of implementors for this featurizer. #### `citations(self) -> List[str]` Returns the list of citations relevant to this featurizer. ``` -------------------------------- ### get_regression_metrics Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/metrics/regression.html Get regression metrics. ```APIDOC ## get_regression_metrics ### Description Get regression metrics. ### Parameters #### Arguments - **predictions** (ArrayLike) - predictions for one objective - **labels** (ArrayLike) - true labels for one objective ### Returns - **RegressionMetrics**: regression metrics ### Example ```python predictions = [0.1, 0.2, 0.3, 0.4, 0.5] labels = [0.1, 0.2, 0.3, 0.4, 0.5] get_regression_metrics(predictions, labels) ``` ``` -------------------------------- ### Get Implementors of PartialChargeHistogram Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/partialchargehistogram.html List the individuals who implemented the PartialChargeHistogram featurizer. ```python from mofdscribe.featurizers.chemistry import PartialChargeHistogram featurizer = PartialChargeHistogram() implementors = featurizer.implementors() print(implementors) ``` -------------------------------- ### Initialize EnergyGrid Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/energygrid.html Initializes the EnergyGrid featurizer with various parameters controlling the energy grid computation and RASPA simulation settings. Ensure RASPA_DIR is set or provided. ```python from mofscribe.featurizers.chemistry import EnergyGrid featurizer = EnergyGrid( raspa_dir="/path/to/raspa", grid_spacing=0.1, bin_size_vdw=0.05, min_energy_vdw=-10.0, max_energy_vdw=10.0, cutoff=12.0, mof_ff="cpg", mol_ff="TraPPE", mol_name="CO2", sites=("C_co2",), tail_corrections=True, mixing_rule="Lorentz-Berthelot", shifted=False, separate_interactions=True, run_eqeq=True, primitive=True, ) ``` -------------------------------- ### Get Implementors Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/compositionstats_featurizer.html Returns a list of the developers who implemented the CompositionStats featurizer. ```python CompositionStats().implementors() ``` -------------------------------- ### Get Implementors List Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/pore/geometric_properties.html Returns a list of the names of the individuals who implemented the featurizer. ```python def implementors(self) -> List[str]: return ["Kevin Maik Jablonka", "Maciej Haranczyk and Zeo++ authors"] ``` -------------------------------- ### AtomCenteredPHSite Initialization and Featurization Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/atom_centered_ph.html Demonstrates how to initialize the AtomCenteredPHSite featurizer with custom parameters and how to use its featurize method to extract features from a structure. ```APIDOC ## AtomCenteredPHSite ### Description Site featurizer for atom-centered statistics of persistence diagrams. This featurizer computes the persistence diagrams for the neighborhood of every site and then aggregates the diagrams by computing certain statistics. ### Class Signature ```python AtomCenteredPHSite( aggregation_functions: Tuple[str] = ("min", "max", "mean", "std"), cutoff: float = 12, dimensions: Tuple[int] = (1, 2), alpha_weight: Optional[str] = None ) ``` ### Parameters * **aggregation_functions** (Tuple[str]): Aggregations to compute on the persistence diagrams (over birth/death time and persistence). Defaults to ("min", "max", "mean", "std"). * **cutoff** (float): Consider neighbors of site within this radius (in Angstrom). Defaults to 12. * **dimensions** (Tuple[int]): Betti numbers to consider. 0 describes isolated components, 1 cycles and 2 cavities. Defaults to (1, 2). * **alpha_weight** (Optional[str]): If specified, use weighted alpha shapes, i.e., replacing the points with balls of varying radii. For instance `atomic_radius_calculated` or `van_der_waals_radius`. ### Methods #### `featurize(self, s: Union[Structure, IStructure], idx: int) -> np.ndarray` Computes the persistence diagrams for the neighborhood of a given site and aggregates them. * **Parameters**: * **s** (Union[Structure, IStructure]): The input structure. * **idx** (int): The index of the site to featurize. * **Returns**: * np.ndarray: An array of computed features. ### Example Usage ```python from matminer.featurizers.structure import SiteStatsFingerprint from mofdscribe.topology.atom_centered_ph import AtomCenteredPHSite # Initialize the featurizer featurizer = SiteStatsFingerprint(AtomCenteredPHSite(dimensions=(0, 1), cutoff=10.0)) # Assuming 'structure' is a pymatgen Structure object # features = featurizer.featurize(structure) # print(features) ``` ### Feature Labels ```python # Example of how to get feature labels # atom_centered_ph_site = AtomCenteredPHSite(dimensions=(0, 1)) # print(atom_centered_ph_site.feature_labels()) # Output might look like: ['dim0_birth_min', 'dim0_birth_max', ...] ``` ### Implementors * Kevin Maik Jablonka ### Citations * @article{Jiang2021, doi = {10.1038/s41524-021-00493-w}, url = {https://doi.org/10.1038/s41524-021-00493-w}, year = {2021}, month = feb, publisher = {Springer Science and Business Media {LLC}}, volume = {7}, number = {1}, author = {Yi Jiang and Dong Chen and Xin Chen and Tangyi Li and Guo-Wei Wei and Feng Pan}, title = {Topological representations of crystalline compounds for the machine-learning prediction of materials properties}, journal = {npj Computational Materials}} * @article{doi:10.1021/acs.jpcc.0c01167, author = {Krishnapriyan, Aditi S. and Haranczyk, Maciej and Morozov, Dmitriy}, title = {Topological Descriptors Help Predict Guest Adsorption in Nanoporous Materials}, journal = {The Journal of Physical Chemistry C}, volume = {124}, number = {17}, pages = {9360-9368}, year = {2020}, doi = {10.1021/acs.jpcc.0c01167} ``` -------------------------------- ### Get BU Featurizer Implementors Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_featurizer.html Retrieves a list of implementors for the underlying featurizer. ```python def implementors(self) -> List[str]: return self._featurizer.implementors() ``` -------------------------------- ### QMOF Dataset Initialization Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/datasets/qmof_dataset.html Initializes the QMOF dataset with specified version, flavor, and duplicate handling options. Raises ValueError if an invalid version is provided. ```python from mofds.datasets import QMOF # Initialize with default settings dataset = QMOF() # Initialize with specific flavor and drop NaNs dataset_gcmc_no_nan = QMOF(flavor="gcmc", drop_nan=True) # Initialize with a specific version dataset_v001 = QMOF(version="v0.0.1") ``` -------------------------------- ### _PBEBandGapIDBench Source: https://mofdscribe.readthedocs.io/en/latest/api/bench.html Benchmarking models for the PBE bandgap under in-distribution conditions. This class initializes the PBE bandgap benchmark. ```APIDOC ## _PBEBandGapIDBench ### Description Benchmarking models for the PBE bandgap under in-distribution conditions. In-distribution implies that we use a cluster stratified splitter that ensures that the ratios of different clusters in the training and test set are the same. Initialize the PBE bandgap benchmark. ### Parameters * **model** (_object_) – The model to be benchmarked. Must implement the fit and predict methods. * **name** (_str_) – The name of the modeling approach. * **version** (_str_, optional) – Version of the dataset to use. Defaults to “v0.0.1”. * **features** (_str_, optional) – Description of the features used in the model. Defaults to None. * **model_type** (_str_, optional) – Model type (e.g. Conv-Net, BERT, XGBoost). Defaults to None. * **reference** (_str_, optional) – Reference with more details about modeling approach. Defaults to None. * **implementation** (_str_, optional) – Link to implementation. Defaults to None. * **debug** (_bool_) – If True, use a small dataset (1% of full dataset) for debugging. Defaults to False. * **patch_in_ds** (_bool_) – If True, the dataset will be patched into the model class under the ds attribute. ``` -------------------------------- ### Get Groups for HashSplitter Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/splitters/splitters.html Returns the groups for splitting, which are derived from the hashes of the dataset structures. ```python def _get_groups(self) -> Collection[int]: return self._get_hashes() ``` -------------------------------- ### Initialize Model Configuration Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/bench/logkHCO2.html This snippet shows how to initialize a model configuration object with various parameters. It is used when setting up a new model instance. ```python features=features, name=name, model_type=model_type, reference=reference, implementation=implementation, debug=debug, patch_in_ds=patch_in_ds, ) ``` -------------------------------- ### Get BU Featurizer Citations Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_featurizer.html Retrieves a list of citations associated with the underlying featurizer. ```python def citations(self) -> List[str]: return self._featurizer.citations() ``` -------------------------------- ### enable_logging Source: https://mofdscribe.readthedocs.io/en/latest/api/helpers.html Set up the mofdscribe logging with sane defaults. ```APIDOC ## enable_logging() ### Description Set up the mofdscribe logging with sane defaults. ### Return Type `List`[`int`] ``` -------------------------------- ### Get Citation Information Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/ph_image.html Provides a list of bibliographic citations relevant to the Persistence Images method. ```bibtex @article{doi:10.1021/acs.jpcc.0c01167, author = {Krishnapriyan, Aditi S. and Haranczyk, Maciej and Morozov, Dmitriy}, title = {Topological Descriptors Help Predict Guest Adsorption in Nanoporous Materials}, journal = {The Journal of Physical Chemistry C}, volume = {124}, number = {17}, pages = {9360-9368}, year = {2020}, doi = {10.1021/acs.jpcc.0c01167}, } ``` ```bibtex @article{krishnapriyan_machine_2021, title={Machine learning with persistent homology and chemical word embeddings improves prediction accuracy and interpretability in metal-organic frameworks}, author={Krishnapriyan, Aditi S and Montoya, Joseph and Haranczyk, Maciej and Hummelsh{\o}j, Jens and Morozov, Dmitriy}, journal = {Scientific Reports}, volume = {11}, numer = {1}, issn = {2045-2322}, pages = {8888}, year={2021}, doi = {10.1038/s41598-021-88027-8} } ``` ```bibtex @article{adams2017persistence, title={Persistence images: A stable vector representation of persistent homology}, author={Adams, Henry and Emerson, Tegan and Kirby, Michael and Neville, Rachel and Peterson, Chris and Shipman, Patrick and Chepushtanova, Sofya and Hanson, Eric and Motta, Francis and Ziegelmeier, Lori}, } ``` -------------------------------- ### Initialize and Use BUMatch Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/api/featurizers.html Instantiate the BUMatch featurizer with specified topologies and aggregation functions, then apply it to a MOF structure. Note that edge match values are generally less meaningful than vertex match values. ```python from mofdscribe.bu import BUMatch from pymatgen.core import Structure s = Structure.from_file("tests/test_files/bu_test_1.cif") bu_match = BUMatch(topos=["tbo", "pcu"], aggregations=["mean", "min"]) bu_match.featurize(s) ``` -------------------------------- ### Get Implementors Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_matches.html Returns a list of the implementors of this featurizer. Currently lists Kevin Maik Jablonka. ```python def implementors(self): return ["Kevin Maik Jablonka"] ``` -------------------------------- ### Initialize HostGuestFeaturizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/hostguest/host_guest_featurizer.html Instantiate the HostGuestFeaturizer with a base featurizer and desired aggregation methods. Ensure the base featurizer is compatible and not a MultipleFeaturizer. ```python from mofdscribe.featurizers.hostguest import HostGuestFeaturizer from matminer.featurizers.structure.sites import SiteStatsFingerprint from pymatgen.core import Structure structure = Structure.from_file("tests/data/structures/Co2O3.cif") featurizer = HostGuestFeaturizer(featurizer=SiteStatsFingerprint.from_preset("SOAP_formation_energy"), aggregations=("mean", "std", "min", "max")) ``` -------------------------------- ### Get Citations Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_matches.html Returns a list of citations associated with this featurizer. Currently lists a placeholder citation. ```python def citations(self): return ["Kevin Maik Jablonka and Berend Smit, TBA."] ``` -------------------------------- ### Retrieving Labels Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/datasets/arcmof_dataset.html Method to get specific label values for a given set of indices and label names. ```APIDOC ## Method ### `get_labels(idx: Collection[int], labelnames: Collection[str] = None) -> np.ndarray` ### Description Retrieves the label values for the specified indices. If `labelnames` is not provided, it defaults to all available label names. ### Parameters - **idx** (`Collection[int]`) - Required - A collection of integer indices for which to retrieve labels. - **labelnames** (`Collection[str]`, optional) - The specific label names to retrieve. Defaults to all available label names if not provided. ### Returns - **np.ndarray**: A NumPy array containing the requested label values. ``` -------------------------------- ### Initialize PHVect Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/ph_vect.html Instantiate the PHVect featurizer with various configuration options. Customize atom types, dimensions, UMAP settings, and periodicity. ```python PHVect( atom_types=( "C-H-N-O", "F-Cl-Br-I", "Cu-Mn-Ni-Mo-Fe-Pt-Zn-Ca-Er-Au-Cd-Co-Gd-Na-Sm-Eu-Tb-V-Ag-Nd-U-Ba-Ce-K-Ga- Cr-Al-Li-Sc-Ru-In-Mg-Zr-Dy-W-Yb-Y-Ho-Re-Be-Rb-La-Sn-Cs-Pb-Pr-Bi-Tm-Sr-Ti- Hf-Ir-Nb-Pd-Hg-Th-Np-Lu-Rh-Pu", ), compute_for_all_elements=True, dimensions=(1, 2), min_size=20, n_components=20, apply_umap=False, umap_n_components=2, umap_metric="hellinger", p=1, random_state=None, periodic=False, no_supercell=False, primitive=False, alpha_weight=None, ) ``` -------------------------------- ### Directly use RDKitAdaptor Source: https://mofdscribe.readthedocs.io/en/latest/featurizers/bu_centered/rdkit_derived.html Demonstrates how to directly instantiate RDKitAdaptor with an RDKit descriptor and a list of output feature names, avoiding the need for subclassing. ```python from mofdscribe.bu.rdkitadaptor import RDKitAdaptor from rdkit.Chem.Descriptors3D import InertialShapeFactor my_featurizer = RDKitAdaptor(InertialShapeFactor, ["inertial_shape_factor"]) ``` -------------------------------- ### Get Citations Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/compositionstats_featurizer.html Returns a list of citations relevant to the CompositionStats featurizer. Currently returns an empty list. ```python CompositionStats().citations() ``` -------------------------------- ### Get SphereLikeness Citations Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/shape_featurizer.html Retrieve the citation information for the Sphere Likeness descriptor. This includes the relevant publication details. ```python sphere_likeness.citations() ``` -------------------------------- ### Initialize VoxelGrid Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/pore/voxelgrid.html Instantiate the VoxelGrid featurizer with custom parameters for grid dimensions, aggregation methods, and property calculations. Defaults are provided for common use cases. ```python VoxelGrid( min_size=30, n_x=25, n_y=25, n_z=25, geometry_aggregations=("binary",), properties=("X", "electron_affinity"), flatten=True, regular_bounding_box=True, primitive=False, ) ``` -------------------------------- ### Initialize BUMatch Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_matches.html Instantiates the BUMatch featurizer, which quantifies the mismatch between MOF building blocks and topological prototypes. Configure parameters like scaling, mismatch fill value, and aggregation methods. ```python from mofdscribe.bu import BUMatch from pymatgen.core import Structure # Example usage: s = Structure.from_file("tests/test_files/bu_test_1.cif") bu_match = BUMatch(topos=["tbo", "pcu"], aggregations=["mean", "min"]) # Featurize a structure: features = bu_match.featurize(s) print(features) ``` -------------------------------- ### Instantiate a Reference Dataset Source: https://mofdscribe.readthedocs.io/en/latest/getting_started.html Load a de-duplicated structure dataset, such as QMOF, for use in machine learning studies. Datasets are downloaded to `~/.data/mofdscribe` on first use. ```python from mofdscribe.datasets import CoRE, QMOF qmof = QMOF() # will use no labels and the latest version of the dataset ``` -------------------------------- ### Get Stratification Column Values Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/splitters/splitters.html Retrieves the stratification column from the dataset's DataFrame or returns a pre-defined array-like object. ```python def _get_stratification_col(self) -> Collection[Union[int, float]]: if isinstance(self._stratification_col, str): return self._ds._df[self._stratification_col].values else: return self._stratification_col ``` -------------------------------- ### Get Feature Labels Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/racs.html Retrieves the labels for the computed RACS features, indicating the specific combination of parameters used for each feature. ```APIDOC ## Get Feature Labels ### Description Retrieves the labels for the computed RACS features, indicating the specific combination of parameters used for each feature. ### Method `feature_labels()` ### Returns - List[str]: A sorted list of feature labels. ``` -------------------------------- ### Initialize PHHist Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/ph_hist.html Initialize the PHHist featurizer with custom parameters for atom types, dimensions, histogram resolution, and periodicity. ```python from mofdscribe.featurizers.topology.ph_hist import PHHist featurizer = PHHist( atom_types=("C-H-N-O", "F-Cl-Br-I"), dimensions=(1, 2), min_size=20, nx=10, ny=10, periodic=False, normed=True, primitive=False, alpha_weight="van_der_waals_radius" ) ``` -------------------------------- ### Get Feature Labels for LSOP Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/lsop_featurizer.html Returns a list of feature labels for the computed LSOP types. Each label is prefixed with 'lsop_'. ```python def feature_labels(self) -> List[str]: return [f"lsop_{val}" for val in self.types] ``` -------------------------------- ### AccessibleVolume Source: https://mofdscribe.readthedocs.io/en/latest/api/featurizers.html Featurizer for calculating accessible volume. Provides methods to get feature labels, citations, implementors, and set fit requests. ```APIDOC ## AccessibleVolume ### Description Calculates the accessible volume of a material. ### Methods - `feature_labels()`: Returns the labels for the features generated by this featurizer. - `citations()`: Returns the citations associated with this featurizer. - `implementors()`: Returns the implementors of this featurizer. - `set_fit_request()`: Sets the request for fitting the featurizer. ``` -------------------------------- ### Initialize LSOP Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/lsop_featurizer.html Initializes the LSOP featurizer with specified types and parameters. Supports molecules and structures. ```python # -*- coding: utf-8 -*- """Compute local structure order parameters for a fragment.""" from typing import List, Optional, Tuple, Union import numpy as np from matminer.featurizers.base import BaseFeaturizer from pymatgen.analysis.local_env import LocalStructOrderParams from pymatgen.core import IMolecule, IStructure, Molecule, Structure from pymatgen.core.periodic_table import DummySpecies from mofdscribe.featurizers.utils.extend import ( operates_on_imolecule, operates_on_istructure, operates_on_molecule, operates_on_structure, ) _default_types = ( "cn", "tet", "oct", "bcc", "sq_pyr", "sq_pyr_legacy", "tri_bipyr", "sq_bipyr", "oct_legacy", "tri_plan", "sq_plan", "pent_plan", "tri_pyr", "pent_pyr", "hex_pyr", "pent_bipyr", "hex_bipyr", "T", "cuboct", "oct_max", "tet_max", "tri_plan_max", "sq_plan_max", "pent_plan_max", "cuboct_max", "bent", "see_saw_rect", "hex_plan_max", "sq_face_cap_trig_pris", ) @operates_on_structure @operates_on_istructure @operates_on_molecule @operates_on_imolecule class LSOP(BaseFeaturizer): """Compute shape parameters for a fragment. The fragments can be a molecule or a molecule that only contains important part (e.g. binding sites) of a molecule. The shape parameters are then supposed to quantify the shape of the fragment. For instance, a triangular molecule will have a `tri_plan` parameter close to 1. While there is a site-based LSOP featurizer in matminer there is none that uses LSOP to quantify the shape of some fragment. This featurizers just does that. It does so by placing a dummy site at the center of mass of the fragment and then computes the LSOP considering all other sites as neighbors. """ def __init__( self, types: Tuple[str] = _default_types, parameters: Optional[List[dict]] = None, ) -> None: """Initialize the featurizer. Args: types (Tuple[str]): The types of LSOP to compute. For the full list of types see: :py:attr:`pymatgen.analysis.local_env.LocalStructOrderParams. __supported_types`. Defaults to: ["tet", "oct", "bcc", "sq_pyr", "sq_pyr_legacy", "tri_bipyr", "sq_bipyr", "oct_legacy", "tri_plan", "sq_plan", "pent_plan", "tri_pyr", "pent_pyr", "hex_pyr", "pent_bipyr", "hex_bipyr", "T", "cuboct", "oct_max", "tet_max", "tri_plan_max", "sq_plan_max", "pent_plan_max", "cuboct_max", "bent", "see_saw_rect", "hex_plan_max", "sq_face_cap_trig_pris"] parameters(List[dict], optional): The parameters to pass to the LocalStructOrderParams object. """ self._lsop = LocalStructOrderParams(types, parameters) self.types = types ``` -------------------------------- ### Initialize AMD Featurizer Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/amd.html Initializes the AMD featurizer with custom parameters for nearest neighbors, atom types, aggregation methods, and primitive cell computation. ```python from mofdscribe.featurizers.chemistry import AMD # Initialize with default parameters featurizer_default = AMD() # Initialize with custom parameters featurizer_custom = AMD( k=50, atom_types=("C", "O"), compute_for_all_elements=False, aggregations=("mean", "std"), primitive=False ) ``` -------------------------------- ### Get Feature Labels for PHVect Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/ph_vect.html Retrieves the labels for the computed features from a fitted PHVect object. This is useful for understanding the output of the featurizer. ```python self._get_feature_labels() ``` -------------------------------- ### PHImage Featurizer Initialization Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/ph_image.html Initializes the PHImage featurizer with various parameters to control the topological analysis. ```APIDOC ## PHImage ### Description Computes the persistence homology image of a crystal structure. ### Parameters - **atom_types** (Optional[List[str]]): List of atom types to consider. If None, all atom types are considered. - **compute_for_all_elements** (bool): Whether to compute features for all elements. Defaults to False. - **min_size** (float): Minimum size for alpha shapes. Defaults to 1.0. - **image_size** (Tuple[int, int]): The size of the persistence image (number of bins). - **spread** (float): Spread parameter for the persistence image. Defaults to 0.1. - **dimensions** (List[int]): List of topological dimensions to consider (e.g., [0, 1, 2]). - **weight** (Optional[str]): Weighting scheme for alpha shapes. Defaults to None. - **max_b** (Union[float, List[float]]): Maximum birth value for persistence diagrams. Can be a single float or a list matching the number of dimensions. - **max_p** (Union[float, List[float]]): Maximum persistence value for persistence diagrams. Can be a single float or a list matching the number of dimensions. - **max_fit_tolerence** (float): Tolerance for fitting persistence diagrams. Defaults to 0.01. - **periodic** (bool): Whether to consider periodic boundary conditions. Defaults to True. - **no_supercell** (bool): Whether to avoid creating supercells. Defaults to False. - **alpha_weight** (Optional[str]): If specified, uses weighted alpha shapes based on atomic radii (e.g., 'atomic_radius_calculated' or 'van_der_waals_radius'). ### Raises - **AssertionError**: If the length of `max_b` or `max_p` does not match the number of dimensions. ``` -------------------------------- ### Get Implementors of Atom-Centered Features Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/atom_centered_ph.html Returns a list of names for the individuals who implemented the atom-centered features. This is for attribution and understanding the origin of the code. ```python return ["Kevin Maik Jablonka", "Aditi Krishnapriyan"] ``` -------------------------------- ### Enable Logging with Default Configuration Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/helpers.html Call this function to set up the mofdscribe logging system with predefined handlers and formats for INFO and WARNING levels. It returns a list of handler IDs. ```python # -*- coding: utf-8 -*- """Convenience functions for mofdscribe.""" import sys from typing import List from loguru import logger __all__ = ["enable_logging"] def enable_logging() -> List[int]: """Set up the mofdscribe logging with sane defaults.""" logger.enable("mofdscribe") config = dict( handlers=[ dict( sink=sys.stderr, format="{time:YYYY-MM-DD HH:mm:ss.SSS Z UTC}" " | {level} | {name}:{function}:{line}" " | {message}", level="INFO", ), dict( sink=sys.stderr, format="{time:YYYY-MM-DD HH:mm:ss.SSS Z UTC} | {level} | {name}:{function}:{line} | {message}", level="WARNING", ), ] ) return logger.configure(**config) ``` -------------------------------- ### Get Atom-Centered Feature Labels Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/topology/atom_centered_ph.html Retrieves the labels for atom-centered topological features. This is useful for understanding the naming convention of generated features. ```python names = [] for atom_type in self.atom_types: for aggregation in self.species_aggregation_functions: for fl in self.site_featurizer.feature_labels(): names.append(f"{atom_type}_{aggregation}_{fl}") return names ``` -------------------------------- ### Initialize BU Matcher Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/bu/bu_matches.html Initializes the BU matcher with various configuration options. Set `return_only_best` to False and provide `aggregations` if you need detailed statistics beyond the minimum RMSD. ```python def __init__(self, allow_rescale=True, mismatch_fill_value=1000.0, return_only_best=True, aggregations=("max", "min", "mean", "std"), topos=ALL_AVAILABLE_TOPOS, match="auto", skip_non_fitting_if_possible=True): self.allow_rescale = allow_rescale self.mismatch_fill_value = mismatch_fill_value self.topos = topos self.return_only_best = return_only_best if not return_only_best and aggregations is None: logger.error("If return_only_best is False, aggregations must be set.") self.aggregations = aggregations if self.return_only_best: self.aggregations = ("min",) self.match = match self.skip_non_fitting_if_possible = skip_non_fitting_if_possible ``` -------------------------------- ### Get Feature Importance Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/metrics/adverserial.html Determine the importance of each feature in distinguishing between the two datasets using the trained classifier's feature importances. ```python validator.get_feature_importance() ``` -------------------------------- ### EnergyGrid Featurizer Initialization Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/energygrid.html Initializes the EnergyGrid featurizer with various parameters to control the energy grid computation. ```APIDOC ## EnergyGrid(raspa_dir: Optional[str] = None, grid_spacing: float = 0.1, bin_size_vdw: float = 0.05, min_energy_vdw: float = -1.0, max_energy_vdw: float = 1.0, cutoff: float = 12.0, mof_ff: str = 'UFF', mol_ff: str = 'UFF', mol_name: str = 'CO2', sites: Tuple[str] = ('C_co2',), tail_corrections: bool = True, mixing_rule: str = 'Lorentz-Berthelot', shifted: bool = False, separate_interactions: bool = True, run_eqeq: bool = True, primitive: bool = True) ### Description Initializes the EnergyGrid featurizer. This class computes energy diagrams for specified Van-der-Waals sites within a MOF structure. ### Parameters - **raspa_dir** (Optional[str]) - Path to the RASPA directory. Defaults to the RASPA_DIR environment variable or auto-detection. - **grid_spacing** (float) - Spacing for the grid points in the energy diagram. Defaults to 0.1. - **bin_size_vdw** (float) - Bin size for the Van der Waals energy histogram. Defaults to 0.05. - **min_energy_vdw** (float) - Minimum energy value for the Van der Waals histogram. Defaults to -1.0. - **max_energy_vdw** (float) - Maximum energy value for the Van der Waals histogram. Defaults to 1.0. - **cutoff** (float) - Cutoff distance for interactions. Defaults to 12.0. - **mof_ff** (str) - Force field for the MOF framework. Defaults to 'UFF'. - **mol_ff** (str) - Force field for the guest molecule. Defaults to 'UFF'. - **mol_name** (str) - Name of the guest molecule. Defaults to 'CO2'. - **sites** (Tuple[str]) - Names of the Van-der-Waals sites for which energy diagrams are computed. Defaults to ('C_co2',). - **tail_corrections** (bool) - Whether to use analytical tail-correction for interactions beyond the cutoff. Defaults to True. - **mixing_rule** (str) - Mixing rule for framework and guest molecule force fields. Available options: `Jorgenson`, `Lorentz-Berthelot`. Defaults to "Lorentz-Berthelot". - **shifted** (bool) - Whether to shift the potential to be zero at the cutoff. Defaults to False. - **separate_interactions** (bool) - Whether to use the framework's force field for framework-molecule interactions. Defaults to True. - **run_eqeq** (bool) - Whether to run EqEq to compute charges. Defaults to True. - **primitive** (bool) - Whether to reduce the structure to its primitive form before computation. Defaults to True. ### Raises - **ValueError**: If `raspa_dir` is not a valid directory and cannot be detected. ``` -------------------------------- ### Get Feature Labels for PartialChargeHistogram Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/partialchargehistogram.html Retrieve the descriptive labels for each bin in the partial charge histogram. These labels correspond to the charge ranges. ```python from mofdscribe.featurizers.chemistry import PartialChargeHistogram featurizer = PartialChargeHistogram() labels = featurizer.feature_labels() print(labels) ``` -------------------------------- ### Initialize PBEBandGapIDBench Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/bench/pbegap.html Initializes the PBEBandGapIDBench for benchmarking PBE bandgap prediction models. It configures the dataset splitting strategy to ensure similar cluster ratios in training and testing sets for in-distribution evaluation. The `debug` flag allows for using a smaller dataset subset for faster testing. ```python # -*- coding: utf-8 -*- """In-dataset predictions for PBE bandgaps.""" from typing import Optional from mofdscribe.bench.mofbench import MOFBenchRegression from mofdscribe.datasets import QMOFDataset from mofdscribe.splitters.splitters import HashSplitter __all__ = ("PBEBandGapIDBench",) class PBEBandGapIDBench(MOFBenchRegression): """Benchmarking models for the PBE bandgap under in-distribution conditions. In-distribution implies that we use a cluster stratified splitter that ensures that the ratios of different clusters in the training and test set are the same. """ def __init__( self, model, name: str, version: Optional[str] = "v0.0.1", features: Optional[str] = None, model_type: Optional[str] = None, reference: Optional[str] = None, implementation: Optional[str] = None, debug: bool = False, patch_in_ds: bool = False, ): """Initialize the PBE bandgap benchmark. Args: model (object): The model to be benchmarked. Must implement the `fit` and `predict` methods. name (str): The name of the modeling approach. version (str, optional): Version of the dataset to use. Defaults to "v0.0.1". features (str, optional): Description of the features used in the model. Defaults to None. model_type (str, optional): Model type (e.g. Conv-Net, BERT, XGBoost). Defaults to None. reference (str, optional): Reference with more details about modeling approach. Defaults to None. implementation (str, optional): Link to implementation. Defaults to None. debug (bool): If True, use a small dataset (1% of full dataset) for debugging. Defaults to False. patch_in_ds (bool): If True, the dataset will be patched into the model class under the `ds` attribute. """ super().__init__( model, ds=QMOFDataset(version), splitter=HashSplitter( QMOFDataset(version, flavor="all"), stratification_col="outputs.pbe.bandgap", sample_frac=0.01 if debug else 1.0, ), target=["outputs.pbe.bandgap"], task="pbe_bandgap_id", k=5, version=version, features=features, name=name, model_type=model_type, reference=reference, implementation=implementation, debug=debug, patch_in_ds=patch_in_ds, ) ``` -------------------------------- ### Get Feature Labels for PartialChargeStats Source: https://mofdscribe.readthedocs.io/en/latest/_modules/mofdscribe/featurizers/chemistry/partialchargestats.html Retrieves the descriptive labels for the features generated by the PartialChargeStats featurizer. These labels correspond to the aggregations used. ```python featurizer.feature_labels() ```