pymatgen.analysis namespace
Subpackages
- pymatgen.analysis.chemenv package
- Subpackages
- pymatgen.analysis.chemenv.connectivity package
- Submodules
- pymatgen.analysis.chemenv.connectivity.connected_components module
ConnectedComponentConnectedComponent.as_dict()ConnectedComponent.compute_periodicity()ConnectedComponent.compute_periodicity_all_simple_paths_algorithm()ConnectedComponent.compute_periodicity_cycle_basis()ConnectedComponent.coordination_sequence()ConnectedComponent.description()ConnectedComponent.elastic_centered_graph()ConnectedComponent.from_dict()ConnectedComponent.from_graph()ConnectedComponent.graphConnectedComponent.is_0dConnectedComponent.is_1dConnectedComponent.is_2dConnectedComponent.is_3dConnectedComponent.is_periodicConnectedComponent.make_supergraph()ConnectedComponent.periodicityConnectedComponent.periodicity_vectorsConnectedComponent.show_graph()
draw_network()make_supergraph()
- pymatgen.analysis.chemenv.connectivity.connectivity_finder module
- pymatgen.analysis.chemenv.connectivity.environment_nodes module
AbstractEnvironmentNodeAbstractEnvironmentNode.ATOMAbstractEnvironmentNode.CE_NNBCES_NBCES_LIGANDSAbstractEnvironmentNode.COORDINATION_ENVIRONMENTAbstractEnvironmentNode.DEFAULT_EXTENSIONSAbstractEnvironmentNode.LIGANDS_ARRANGEMENTAbstractEnvironmentNode.NEIGHBORING_CESAbstractEnvironmentNode.NEIGHBORING_COORDINATION_ENVIRONMENTSAbstractEnvironmentNode.NEIGHBORS_LIGANDS_ARRANGEMENTAbstractEnvironmentNode.NUMBER_OF_LIGANDS_FOR_EACH_NEIGHBORING_CEAbstractEnvironmentNode.NUMBER_OF_LIGANDS_FOR_EACH_NEIGHBORING_COORDINATION_ENVIRONMENTAbstractEnvironmentNode.NUMBER_OF_NEIGHBORING_CESAbstractEnvironmentNode.NUMBER_OF_NEIGHBORING_COORDINATION_ENVIRONMENTSAbstractEnvironmentNode.atom_symbolAbstractEnvironmentNode.ceAbstractEnvironmentNode.ce_symbolAbstractEnvironmentNode.coordination_environmentAbstractEnvironmentNode.everything_equal()AbstractEnvironmentNode.isiteAbstractEnvironmentNode.mp_symbol
EnvironmentNodeget_environment_node()
- pymatgen.analysis.chemenv.connectivity.structure_connectivity module
StructureConnectivityStructureConnectivity.add_bonds()StructureConnectivity.add_sites()StructureConnectivity.as_dict()StructureConnectivity.environment_subgraph()StructureConnectivity.from_dict()StructureConnectivity.get_connected_components()StructureConnectivity.print_links()StructureConnectivity.setup_atom_environment_subgraph()StructureConnectivity.setup_atom_environments_subgraph()StructureConnectivity.setup_connectivity_description()StructureConnectivity.setup_environment_subgraph()StructureConnectivity.setup_environments_subgraph()
get_delta_image()
- pymatgen.analysis.chemenv.coordination_environments package
- Subpackages
- Submodules
- pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies module
AbstractChemenvStrategyAbstractChemenvStrategy.ACAbstractChemenvStrategy.DEFAULT_SYMMETRY_MEASURE_TYPEAbstractChemenvStrategy.STRATEGY_DESCRIPTIONAbstractChemenvStrategy.STRATEGY_INFO_FIELDSAbstractChemenvStrategy.STRATEGY_OPTIONSAbstractChemenvStrategy.as_dict()AbstractChemenvStrategy.equivalent_site_index_and_transform()AbstractChemenvStrategy.from_dict()AbstractChemenvStrategy.get_site_ce_fractions_and_neighbors()AbstractChemenvStrategy.get_site_coordination_environment()AbstractChemenvStrategy.get_site_coordination_environments()AbstractChemenvStrategy.get_site_coordination_environments_fractions()AbstractChemenvStrategy.get_site_neighbors()AbstractChemenvStrategy.prepare_symmetries()AbstractChemenvStrategy.set_option()AbstractChemenvStrategy.set_structure_environments()AbstractChemenvStrategy.setup_options()AbstractChemenvStrategy.symmetry_measure_typeAbstractChemenvStrategy.uniquely_determines_coordination_environments
AdditionalConditionIntAngleCutoffFloatAngleNbSetWeightAnglePlateauNbSetWeightCNBiasNbSetWeightCSMFloatDeltaCSMNbSetWeightDeltaCSMNbSetWeight.DEFAULT_EFFECTIVE_CSM_ESTIMATORDeltaCSMNbSetWeight.DEFAULT_SYMMETRY_MEASURE_TYPEDeltaCSMNbSetWeight.DEFAULT_WEIGHT_ESTIMATORDeltaCSMNbSetWeight.SHORT_NAMEDeltaCSMNbSetWeight.as_dict()DeltaCSMNbSetWeight.delta_cn_specifics()DeltaCSMNbSetWeight.from_dict()DeltaCSMNbSetWeight.weight()
DeltaDistanceNbSetWeightDistanceAngleAreaNbSetWeightDistanceAngleAreaNbSetWeight.ACDistanceAngleAreaNbSetWeight.DEFAULT_SURFACE_DEFINITIONDistanceAngleAreaNbSetWeight.SHORT_NAMEDistanceAngleAreaNbSetWeight.as_dict()DistanceAngleAreaNbSetWeight.from_dict()DistanceAngleAreaNbSetWeight.rectangle_crosses_area()DistanceAngleAreaNbSetWeight.w_area_has_intersection()DistanceAngleAreaNbSetWeight.w_area_intersection_nbsfh_fbs_onb0()DistanceAngleAreaNbSetWeight.weight()
DistanceCutoffFloatDistanceNbSetWeightDistancePlateauNbSetWeightMultiWeightsChemenvStrategyMultiWeightsChemenvStrategy.DEFAULT_CE_ESTIMATORMultiWeightsChemenvStrategy.STRATEGY_DESCRIPTIONMultiWeightsChemenvStrategy.as_dict()MultiWeightsChemenvStrategy.from_dict()MultiWeightsChemenvStrategy.stats_article_weights_parameters()MultiWeightsChemenvStrategy.uniquely_determines_coordination_environments
NbSetWeightNormalizedAngleDistanceNbSetWeightNormalizedAngleDistanceNbSetWeight.SHORT_NAMENormalizedAngleDistanceNbSetWeight.ang()NormalizedAngleDistanceNbSetWeight.anginvdist()NormalizedAngleDistanceNbSetWeight.anginvndist()NormalizedAngleDistanceNbSetWeight.angn()NormalizedAngleDistanceNbSetWeight.angninvdist()NormalizedAngleDistanceNbSetWeight.angninvndist()NormalizedAngleDistanceNbSetWeight.as_dict()NormalizedAngleDistanceNbSetWeight.aweight()NormalizedAngleDistanceNbSetWeight.from_dict()NormalizedAngleDistanceNbSetWeight.gweight()NormalizedAngleDistanceNbSetWeight.invdist()NormalizedAngleDistanceNbSetWeight.invndist()NormalizedAngleDistanceNbSetWeight.weight()
SelfCSMNbSetWeightSimpleAbundanceChemenvStrategySimpleAbundanceChemenvStrategy.DEFAULT_ADDITIONAL_CONDITIONSimpleAbundanceChemenvStrategy.DEFAULT_MAX_DISTSimpleAbundanceChemenvStrategy.STRATEGY_DESCRIPTIONSimpleAbundanceChemenvStrategy.STRATEGY_OPTIONSSimpleAbundanceChemenvStrategy.as_dict()SimpleAbundanceChemenvStrategy.from_dict()SimpleAbundanceChemenvStrategy.get_site_coordination_environment()SimpleAbundanceChemenvStrategy.get_site_coordination_environments()SimpleAbundanceChemenvStrategy.get_site_neighbors()SimpleAbundanceChemenvStrategy.uniquely_determines_coordination_environments
SimplestChemenvStrategySimplestChemenvStrategy.DEFAULT_ADDITIONAL_CONDITIONSimplestChemenvStrategy.DEFAULT_ANGLE_CUTOFFSimplestChemenvStrategy.DEFAULT_CONTINUOUS_SYMMETRY_MEASURE_CUTOFFSimplestChemenvStrategy.DEFAULT_DISTANCE_CUTOFFSimplestChemenvStrategy.STRATEGY_DESCRIPTIONSimplestChemenvStrategy.STRATEGY_OPTIONSSimplestChemenvStrategy.add_strategy_visualization_to_subplot()SimplestChemenvStrategy.additional_conditionSimplestChemenvStrategy.angle_cutoffSimplestChemenvStrategy.as_dict()SimplestChemenvStrategy.continuous_symmetry_measure_cutoffSimplestChemenvStrategy.distance_cutoffSimplestChemenvStrategy.from_dict()SimplestChemenvStrategy.get_site_coordination_environment()SimplestChemenvStrategy.get_site_coordination_environments()SimplestChemenvStrategy.get_site_coordination_environments_fractions()SimplestChemenvStrategy.get_site_neighbors()SimplestChemenvStrategy.uniquely_determines_coordination_environments
StrategyOptionTargetedPenaltiedAbundanceChemenvStrategyTargetedPenaltiedAbundanceChemenvStrategy.DEFAULT_TARGET_ENVIRONMENTSTargetedPenaltiedAbundanceChemenvStrategy.as_dict()TargetedPenaltiedAbundanceChemenvStrategy.from_dict()TargetedPenaltiedAbundanceChemenvStrategy.get_site_coordination_environment()TargetedPenaltiedAbundanceChemenvStrategy.uniquely_determines_coordination_environments
WeightedNbSetChemenvStrategyWeightedNbSetChemenvStrategy.DEFAULT_CE_ESTIMATORWeightedNbSetChemenvStrategy.STRATEGY_DESCRIPTIONWeightedNbSetChemenvStrategy.as_dict()WeightedNbSetChemenvStrategy.from_dict()WeightedNbSetChemenvStrategy.get_site_coordination_environment()WeightedNbSetChemenvStrategy.get_site_coordination_environments()WeightedNbSetChemenvStrategy.get_site_coordination_environments_fractions()WeightedNbSetChemenvStrategy.get_site_neighbors()WeightedNbSetChemenvStrategy.uniquely_determines_coordination_environments
get_effective_csm()set_info()
- pymatgen.analysis.chemenv.coordination_environments.coordination_geometries module
AbstractChemenvAlgorithmAllCoordinationGeometriesAllCoordinationGeometries.get_geometries()AllCoordinationGeometries.get_geometry_from_IUCr_symbol()AllCoordinationGeometries.get_geometry_from_IUPAC_symbol()AllCoordinationGeometries.get_geometry_from_mp_symbol()AllCoordinationGeometries.get_geometry_from_name()AllCoordinationGeometries.get_implemented_geometries()AllCoordinationGeometries.get_not_implemented_geometries()AllCoordinationGeometries.get_symbol_cn_mapping()AllCoordinationGeometries.get_symbol_name_mapping()AllCoordinationGeometries.is_a_valid_coordination_geometry()AllCoordinationGeometries.pretty_print()
CoordinationGeometryCoordinationGeometry.CSM_SKIP_SEPARATION_PLANE_ALGOCoordinationGeometry.IUCr_symbolCoordinationGeometry.IUCr_symbol_strCoordinationGeometry.IUPAC_symbolCoordinationGeometry.IUPAC_symbol_strCoordinationGeometry.NeighborsSetsHintsCoordinationGeometry.NeighborsSetsHints.ALLOWED_HINTS_TYPESCoordinationGeometry.NeighborsSetsHints.as_dict()CoordinationGeometry.NeighborsSetsHints.double_cap_hints()CoordinationGeometry.NeighborsSetsHints.from_dict()CoordinationGeometry.NeighborsSetsHints.hints()CoordinationGeometry.NeighborsSetsHints.single_cap_hints()CoordinationGeometry.NeighborsSetsHints.triple_cap_hints()
CoordinationGeometry.algorithmsCoordinationGeometry.as_dict()CoordinationGeometry.ce_symbolCoordinationGeometry.coordination_numberCoordinationGeometry.distfactor_maxCoordinationGeometry.edges()CoordinationGeometry.faces()CoordinationGeometry.from_dict()CoordinationGeometry.get_central_site()CoordinationGeometry.get_coordination_number()CoordinationGeometry.get_name()CoordinationGeometry.get_pmeshes()CoordinationGeometry.is_implemented()CoordinationGeometry.mp_symbolCoordinationGeometry.number_of_permutationsCoordinationGeometry.pauling_stability_ratioCoordinationGeometry.ref_permutation()CoordinationGeometry.solid_angles()
ExplicitPermutationsAlgorithmSeparationPlane
- pymatgen.analysis.chemenv.coordination_environments.coordination_geometry_finder module
AbstractGeometryAbstractGeometry.cnAbstractGeometry.coordination_numberAbstractGeometry.from_cg()AbstractGeometry.points_wcs_csc()AbstractGeometry.points_wcs_ctwcc()AbstractGeometry.points_wcs_ctwocc()AbstractGeometry.points_wocs_csc()AbstractGeometry.points_wocs_ctwcc()AbstractGeometry.points_wocs_ctwocc()
LocalGeometryFinderLocalGeometryFinder.BVA_DISTANCE_SCALE_FACTORSLocalGeometryFinder.DEFAULT_BVA_DISTANCE_SCALE_FACTORLocalGeometryFinder.DEFAULT_SPG_ANALYZER_OPTIONSLocalGeometryFinder.DEFAULT_STRATEGYLocalGeometryFinder.PRESETSLocalGeometryFinder.STRUCTURE_REFINEMENT_NONELocalGeometryFinder.STRUCTURE_REFINEMENT_REFINEDLocalGeometryFinder.STRUCTURE_REFINEMENT_SYMMETRIZEDLocalGeometryFinder.compute_coordination_environments()LocalGeometryFinder.compute_structure_environments()LocalGeometryFinder.coordination_geometry_symmetry_measures()LocalGeometryFinder.coordination_geometry_symmetry_measures_fallback_random()LocalGeometryFinder.coordination_geometry_symmetry_measures_separation_plane()LocalGeometryFinder.coordination_geometry_symmetry_measures_separation_plane_optim()LocalGeometryFinder.coordination_geometry_symmetry_measures_sepplane_optim()LocalGeometryFinder.coordination_geometry_symmetry_measures_standard()LocalGeometryFinder.get_coordination_symmetry_measures()LocalGeometryFinder.get_coordination_symmetry_measures_optim()LocalGeometryFinder.get_structure()LocalGeometryFinder.set_structure()LocalGeometryFinder.setup_explicit_indices_local_geometry()LocalGeometryFinder.setup_local_geometry()LocalGeometryFinder.setup_ordered_indices_local_geometry()LocalGeometryFinder.setup_parameter()LocalGeometryFinder.setup_parameters()LocalGeometryFinder.setup_random_indices_local_geometry()LocalGeometryFinder.setup_random_structure()LocalGeometryFinder.setup_structure()LocalGeometryFinder.setup_test_perfect_environment()LocalGeometryFinder.update_nb_set_environments()
find_rotation()find_scaling_factor()symmetry_measure()
- pymatgen.analysis.chemenv.coordination_environments.structure_environments module
ChemicalEnvironmentsLightStructureEnvironmentsLightStructureEnvironments.DEFAULT_STATISTICS_FIELDSLightStructureEnvironments.DELTA_MAX_OXIDATION_STATELightStructureEnvironments.NeighborsSetLightStructureEnvironments.NeighborsSet.as_dict()LightStructureEnvironments.NeighborsSet.from_dict()LightStructureEnvironments.NeighborsSet.neighb_coordsLightStructureEnvironments.NeighborsSet.neighb_indices_and_imagesLightStructureEnvironments.NeighborsSet.neighb_sitesLightStructureEnvironments.NeighborsSet.neighb_sites_and_indices
LightStructureEnvironments.as_dict()LightStructureEnvironments.clear_environments()LightStructureEnvironments.contains_only_one_anion()LightStructureEnvironments.contains_only_one_anion_atom()LightStructureEnvironments.environments_identified()LightStructureEnvironments.from_dict()LightStructureEnvironments.from_structure_environments()LightStructureEnvironments.get_site_info_for_specie_allces()LightStructureEnvironments.get_site_info_for_specie_ce()LightStructureEnvironments.get_statistics()LightStructureEnvironments.setup_statistic_lists()LightStructureEnvironments.site_contains_environment()LightStructureEnvironments.site_has_clear_environment()LightStructureEnvironments.structure_contains_atom_environment()LightStructureEnvironments.structure_has_clear_environments()LightStructureEnvironments.uniquely_determines_coordination_environments
StructureEnvironmentsStructureEnvironments.ACStructureEnvironments.NeighborsSetStructureEnvironments.NeighborsSet.add_source()StructureEnvironments.NeighborsSet.angle_plateau()StructureEnvironments.NeighborsSet.anglesStructureEnvironments.NeighborsSet.as_dict()StructureEnvironments.NeighborsSet.coordsStructureEnvironments.NeighborsSet.detailed_voronoiStructureEnvironments.NeighborsSet.distance_plateau()StructureEnvironments.NeighborsSet.distancesStructureEnvironments.NeighborsSet.from_dict()StructureEnvironments.NeighborsSet.get_neighb_voronoi_indices()StructureEnvironments.NeighborsSet.infoStructureEnvironments.NeighborsSet.isiteStructureEnvironments.NeighborsSet.local_planesStructureEnvironments.NeighborsSet.neighb_coordsStructureEnvironments.NeighborsSet.neighb_coordsOptStructureEnvironments.NeighborsSet.neighb_sitesStructureEnvironments.NeighborsSet.neighb_sites_and_indicesStructureEnvironments.NeighborsSet.normalized_anglesStructureEnvironments.NeighborsSet.normalized_distancesStructureEnvironments.NeighborsSet.separationsStructureEnvironments.NeighborsSet.site_voronoi_indicesStructureEnvironments.NeighborsSet.sourceStructureEnvironments.NeighborsSet.sourcesStructureEnvironments.NeighborsSet.structureStructureEnvironments.NeighborsSet.voronoiStructureEnvironments.NeighborsSet.voronoi_grid_surface_points()
StructureEnvironments.add_neighbors_set()StructureEnvironments.as_dict()StructureEnvironments.differences_wrt()StructureEnvironments.from_dict()StructureEnvironments.get_coordination_environments()StructureEnvironments.get_csm()StructureEnvironments.get_csm_and_maps()StructureEnvironments.get_csms()StructureEnvironments.get_environments_figure()StructureEnvironments.init_neighbors_sets()StructureEnvironments.plot_csm_and_maps()StructureEnvironments.plot_environments()StructureEnvironments.save_environments_figure()StructureEnvironments.update_coordination_environments()StructureEnvironments.update_site_info()
- pymatgen.analysis.chemenv.coordination_environments.voronoi module
DetailedVoronoiContainerDetailedVoronoiContainer.ACDetailedVoronoiContainer.as_dict()DetailedVoronoiContainer.default_normalized_angle_toleranceDetailedVoronoiContainer.default_normalized_distance_toleranceDetailedVoronoiContainer.default_voronoi_cutoffDetailedVoronoiContainer.from_dict()DetailedVoronoiContainer.get_rdf_figure()DetailedVoronoiContainer.get_sadf_figure()DetailedVoronoiContainer.is_close_to()DetailedVoronoiContainer.maps_and_surfaces()DetailedVoronoiContainer.maps_and_surfaces_bounded()DetailedVoronoiContainer.neighbors()DetailedVoronoiContainer.neighbors_surfaces()DetailedVoronoiContainer.neighbors_surfaces_bounded()DetailedVoronoiContainer.setup_neighbors_distances_and_angles()DetailedVoronoiContainer.setup_voronoi_list()DetailedVoronoiContainer.to_bson_voronoi_list2()DetailedVoronoiContainer.voronoi_parameters_bounds_and_limits()
from_bson_voronoi_list2()
- pymatgen.analysis.chemenv.utils package
- Submodules
- pymatgen.analysis.chemenv.utils.chemenv_config module
- pymatgen.analysis.chemenv.utils.chemenv_errors module
- pymatgen.analysis.chemenv.utils.coordination_geometry_utils module
PlanePlane.TEST_2D_POINTSPlane.aPlane.abcdPlane.bPlane.cPlane.coefficientsPlane.crosses_originPlane.dPlane.distance_to_originPlane.distance_to_point()Plane.distances()Plane.distances_indices_groups()Plane.distances_indices_sorted()Plane.fit_error()Plane.fit_least_square_distance_error()Plane.fit_maximum_distance_error()Plane.from_2points_and_origin()Plane.from_3points()Plane.from_coefficients()Plane.from_npoints()Plane.from_npoints_least_square_distance()Plane.from_npoints_maximum_distance()Plane.indices_separate()Plane.init_3points()Plane.is_in_list()Plane.is_in_plane()Plane.is_same_plane_as()Plane.orthonormal_vectors()Plane.perpendicular_bisector()Plane.project_and_to2dim()Plane.project_and_to2dim_ordered_indices()Plane.projectionpoints()
anticlockwise_sort()anticlockwise_sort_indices()changebasis()collinear()diamond_functions()function_comparison()get_lower_and_upper_f()is_anion_cation_bond()matrixTimesVector()quarter_ellipsis_functions()rectangle_surface_intersection()rotateCoords()rotateCoordsOpt()separation_in_list()solid_angle()sort_separation()sort_separation_tuple()spline_functions()vectorsToMatrix()
- pymatgen.analysis.chemenv.utils.defs_utils module
AdditionalConditionsAdditionalConditions.ALLAdditionalConditions.CONDITION_DESCRIPTIONAdditionalConditions.NONEAdditionalConditions.NO_ACAdditionalConditions.NO_ADDITIONAL_CONDITIONAdditionalConditions.NO_E2SEBAdditionalConditions.NO_ELEMENT_TO_SAME_ELEMENT_BONDSAdditionalConditions.ONLY_ACBAdditionalConditions.ONLY_ACB_AND_NO_E2SEBAdditionalConditions.ONLY_ANION_CATION_BONDSAdditionalConditions.ONLY_ANION_CATION_BONDS_AND_NO_ELEMENT_TO_SAME_ELEMENT_BONDSAdditionalConditions.ONLY_E2OBAdditionalConditions.ONLY_ELEMENT_TO_OXYGEN_BONDSAdditionalConditions.check_condition()
- pymatgen.analysis.chemenv.utils.func_utils module
- pymatgen.analysis.chemenv.utils.graph_utils module
- pymatgen.analysis.chemenv.utils.math_utils module
cosinus_step()divisors()get_center_of_arc()get_linearly_independent_vectors()normal_cdf_step()power2_decreasing_exp()power2_inverse_decreasing()power2_inverse_power2_decreasing()power2_inverse_powern_decreasing()power2_tangent_decreasing()power3_step()powern_decreasing()powern_parts_step()prime_factors()scale_and_clamp()smootherstep()smoothstep()
- pymatgen.analysis.chemenv.utils.scripts_utils module
- pymatgen.analysis.chemenv.connectivity package
- Subpackages
- pymatgen.analysis.compatibility package
AnionCorrectionAqueousCorrectionCompatibilityCompatibilityErrorCorrectionCorrectionsListGasCorrectionMITAqueousCompatibilityMITCompatibilityMaterialsProject2020CompatibilityMaterialsProjectAqueousCompatibilityMaterialsProjectCompatibilityPotcarCorrectionSmoothPESCompatibilityUCorrectionneeds_u_correction()- Submodules
- pymatgen.analysis.compatibility.compatibility module
- pymatgen.analysis.compatibility.computed_entries module
- pymatgen.analysis.compatibility.correction_calculator module
CorrectionCalculatorCorrectionCalculator.speciesCorrectionCalculator.exp_compoundsCorrectionCalculator.calc_compoundsCorrectionCalculator.correctionsCorrectionCalculator.corrections_std_errorCorrectionCalculator.corrections_dictCorrectionCalculator.compute_corrections()CorrectionCalculator.compute_from_files()CorrectionCalculator.graph_residual_error()CorrectionCalculator.graph_residual_error_per_species()CorrectionCalculator.make_yaml()
- pymatgen.analysis.compatibility.entry_tools module
- pymatgen.analysis.compatibility.exp_entries module
- pymatgen.analysis.compatibility.mixing_scheme module
- pymatgen.analysis.diffraction package
- Submodules
- pymatgen.analysis.diffraction.core module
AbstractDiffractionPatternCalculatorAbstractDiffractionPatternCalculator.SCALED_INTENSITY_TOLAbstractDiffractionPatternCalculator.TWO_THETA_TOLAbstractDiffractionPatternCalculator.get_pattern()AbstractDiffractionPatternCalculator.get_plot()AbstractDiffractionPatternCalculator.plot_structures()AbstractDiffractionPatternCalculator.show_plot()
DiffractionPatternget_unique_families()
- pymatgen.analysis.diffraction.neutron module
- pymatgen.analysis.diffraction.tem module
TEMCalculatorTEMCalculator.bragg_angles()TEMCalculator.cell_intensity()TEMCalculator.cell_scattering_factors()TEMCalculator.electron_scattering_factors()TEMCalculator.generate_points()TEMCalculator.get_first_point()TEMCalculator.get_interplanar_angle()TEMCalculator.get_interplanar_spacings()TEMCalculator.get_pattern()TEMCalculator.get_plot_2d()TEMCalculator.get_plot_2d_concise()TEMCalculator.get_plot_coeffs()TEMCalculator.get_positions()TEMCalculator.get_s2()TEMCalculator.is_parallel()TEMCalculator.normalized_cell_intensity()TEMCalculator.tem_dots()TEMCalculator.wavelength_rel()TEMCalculator.x_ray_factors()TEMCalculator.zone_axis_filter()
- pymatgen.analysis.diffraction.xrd module
- pymatgen.analysis.elasticity package
- pymatgen.analysis.ferroelectricity package
- Submodules
- pymatgen.analysis.ferroelectricity.polarization module
EnergyTrendPolarizationPolarization.from_outcars_and_structures()Polarization.get_lattice_quanta()Polarization.get_pelecs_and_pions()Polarization.get_polarization_change()Polarization.get_polarization_change_norm()Polarization.get_same_branch_polarization_data()Polarization.max_spline_jumps()Polarization.same_branch_splines()Polarization.smoothness()
calc_ionic()get_nearest_site()get_total_ionic_dipole()zval_dict_from_potcar()
- pymatgen.analysis.interfaces package
- Submodules
- pymatgen.analysis.interfaces.coherent_interfaces module
- pymatgen.analysis.interfaces.substrate_analyzer module
- pymatgen.analysis.interfaces.zsl module
- pymatgen.analysis.magnetism package
- Submodules
- pymatgen.analysis.magnetism.analyzer module
CollinearMagneticStructureAnalyzerCollinearMagneticStructureAnalyzer.get_exchange_group_info()CollinearMagneticStructureAnalyzer.get_ferromagnetic_structure()CollinearMagneticStructureAnalyzer.get_nonmagnetic_structure()CollinearMagneticStructureAnalyzer.get_structure_with_only_magnetic_atoms()CollinearMagneticStructureAnalyzer.get_structure_with_spin()CollinearMagneticStructureAnalyzer.is_magneticCollinearMagneticStructureAnalyzer.magmomsCollinearMagneticStructureAnalyzer.magnetic_species_and_magmomsCollinearMagneticStructureAnalyzer.matches_ordering()CollinearMagneticStructureAnalyzer.number_of_magnetic_sitesCollinearMagneticStructureAnalyzer.number_of_unique_magnetic_sites()CollinearMagneticStructureAnalyzer.orderingCollinearMagneticStructureAnalyzer.types_of_magnetic_specieCollinearMagneticStructureAnalyzer.types_of_magnetic_species
MagneticDeformationMagneticStructureEnumeratorOrderingOverwriteMagmomModemagnetic_deformation()
- pymatgen.analysis.magnetism.heisenberg module
HeisenbergMapperHeisenbergMapper.strategyHeisenbergMapper.sgraphsHeisenbergMapper.unique_site_idsHeisenbergMapper.wyckoff_idsHeisenbergMapper.nn_interactionsHeisenbergMapper.distsHeisenbergMapper.ex_matHeisenbergMapper.ex_paramsHeisenbergMapper.estimate_exchange()HeisenbergMapper.get_exchange()HeisenbergMapper.get_heisenberg_model()HeisenbergMapper.get_interaction_graph()HeisenbergMapper.get_low_energy_orderings()HeisenbergMapper.get_mft_temperature()
HeisenbergModelHeisenbergScreener
- pymatgen.analysis.magnetism.jahnteller module
JahnTellerAnalyzerJahnTellerAnalyzer.get_analysis()JahnTellerAnalyzer.get_analysis_and_structure()JahnTellerAnalyzer.get_magnitude_of_effect_from_species()JahnTellerAnalyzer.get_magnitude_of_effect_from_spin_config()JahnTellerAnalyzer.is_jahn_teller_active()JahnTellerAnalyzer.mu_so()JahnTellerAnalyzer.tag_structure()
- pymatgen.analysis.prototypes package
AflowPrototypeMatchercanonicalize_element_wyckoffs()count_crystal_dof()count_crystal_sites()count_distinct_wyckoff_letters()count_values_for_wyckoff()count_wyckoff_positions()get_anonymous_formula_from_prototype_formula()get_formula_from_protostructure_label()get_protostructure_label()get_protostructure_label_from_aflow()get_protostructure_label_from_moyopy()get_protostructure_label_from_spg_analyzer()get_protostructure_label_from_spglib()get_protostructures_from_aflow_label_and_composition()get_prototype_formula_from_composition()get_prototype_from_protostructure()get_random_structure_for_protostructure()sort_and_score_element_wyckoffs()split_alpha_numeric()
- pymatgen.analysis.solar package
- pymatgen.analysis.structure_prediction package
- pymatgen.analysis.topological package
- pymatgen.analysis.xas package
Submodules
pymatgen.analysis.adsorption module
This module provides classes used to enumerate surface sites and to find adsorption sites on slabs.
pymatgen.analysis.bond_dissociation module
Module for BondDissociationEnergies.
- class BondDissociationEnergies(molecule_entry: dict[str, str | dict[str, str | int]], fragment_entries: list[dict[str, str | dict[str, str | int]]], allow_additional_charge_separation: bool = False, multibreak: bool = False)[source]
Bases:
MSONableStandard constructor for bond dissociation energies. All bonds in the principle molecule are looped through and their dissociation energies are calculated given the energies of the resulting fragments, or, in the case of a ring bond, from the energy of the molecule obtained from breaking the bond and opening the ring. This class should only be called after the energies of the optimized principle molecule and all relevant optimized fragments have been determined, either from quantum chemistry or elsewhere. It was written to provide the analysis after running an atomate fragmentation workflow.
The provided entries must have the following keys: formula_pretty, initial_molecule, final_molecule. If a PCM is present, all entries should also have a pcm_dielectric key.
- Parameters:
molecule_entry (dict) – Entry for the principle molecule. Should have the keys mentioned above.
fragment_entries (list[dict]) – Fragment entries. Each should have the keys mentioned above.
allow_additional_charge_separation (bool) – If True, consider larger than normal charge separation among fragments. Defaults to False. See the definition of self.expected_charges below for more specific information.
multibreak (bool) – If True, additionally attempt to break pairs of bonds. Defaults to False.
- build_new_entry(frags: list, bonds: list) list[source]
Build a new entry for bond dissociation that will be returned to the user.
- Parameters:
frags (list) – Fragments involved in the bond dissociation.
bonds (list) – Bonds broken in the dissociation process.
- Returns:
Formatted bond dissociation entries.
- Return type:
list
- filter_fragment_entries(fragment_entries: list) None[source]
Filter the fragment entries.
- Parameters:
fragment_entries (List) – Fragment entries to be filtered.
- fragment_and_process(bonds)[source]
Fragment and process bonds.
- Parameters:
bonds (list) – bonds to process.
- search_fragment_entries(frag) list[source]
Search all fragment entries for those isomorphic to the given fragment. We distinguish between entries where both initial and final MoleculeGraphs are isomorphic to the given fragment (entries) vs those where only the initial MoleculeGraph is isomorphic to the given fragment (initial_entries) vs those where only the final MoleculeGraph is isomorphic (final_entries).
- Parameters:
frag – Fragment
pymatgen.analysis.bond_valence module
This module implements classes to perform bond valence analyses.
pymatgen.analysis.chempot_diagram module
This module implements the construction and plotting of chemical potential diagrams from a list of entries within a chemical system containing 2 or more elements. The chemical potential diagram is the mathematical dual to the traditional compositional phase diagram.
For more information, please cite/reference the paper below:
Todd, P. K., McDermott, M. J., Rom, C. L., Corrao, A. A., Denney, J. J., Dwaraknath, S. S., Khalifah, P. G., Persson, K. A., & Neilson, J. R. (2021). Selectivity in Yttrium Manganese Oxide Synthesis via Local Chemical Potentials in Hyperdimensional Phase Space. Journal of the American Chemical Society, 143(37), 15185-15194. https://doi.org/10.1021/jacs.1c06229
Please also consider referencing the original 1999 paper by H. Yokokawa, who outlined many of its possible uses:
Yokokawa, H. “Generalized chemical potential diagram and its applications to chemical reactions at interfaces between dissimilar materials.” JPE 20, 258 (1999). https://doi.org/10.1361/105497199770335794
- class ChemicalPotentialDiagram(entries: list[PDEntry], limits: dict[Element, tuple[float, float]] | None = None, default_min_limit: float = -50.0, formal_chempots: bool = True)[source]
Bases:
MSONableThe chemical potential diagram is the mathematical dual to the compositional phase diagram. To create the diagram, convex minimization is performed in energy (E) vs. chemical potential (μ) space by taking the lower convex envelope of hyperplanes. Accordingly, “points” on the compositional phase diagram become N-dimensional convex polytopes (domains) in chemical potential space.
For more information on this specific implementation of the algorithm, please cite/reference the paper below:
Todd, P. K., McDermott, M. J., Rom, C. L., Corrao, A. A., Denney, J. J., Dwaraknath, S. S., Khalifah, P. G., Persson, K. A., & Neilson, J. R. (2021). Selectivity in Yttrium Manganese Oxide Synthesis via Local Chemical Potentials in Hyperdimensional Phase Space. Journal of the American Chemical Society, 143(37), 15185-15194. https://doi.org/10.1021/jacs.1c06229
- Parameters:
entries (list[PDEntry]) – PDEntry-like objects containing a composition and energy. Must contain elemental references and be suitable for typical phase diagram construction. Entries must be within a chemical system of with 2+ elements.
limits (dict[Element, float] | None) – Bounds of elemental chemical potentials (min, max), which are used to construct the border hyperplanes used in the HalfSpaceIntersection algorithm; these constrain the space over which the domains are calculated and also determine the size of the plotted diagram. Any elemental limits not specified are covered in the default_min_limit argument. e.g. {Element(“Li”): [-12.0, 0.0], …}
default_min_limit (float) – Default minimum chemical potential limit (i.e., lower bound) for unspecified elements within the “limits” argument.
formal_chempots (bool) – Whether to plot the formal (‘reference’) chemical potentials (i.e. μ_X - μ_X^0) or the absolute DFT reference energies (i.e. μ_X(DFT)). Default is True (i.e. plot formal chemical potentials).
- property domains: dict[str, ndarray][source]
Mapping of formulas to array of domain boundary points.
- property entry_dict: dict[str, ComputedEntry][source]
Mapping between reduced formula and ComputedEntry.
- get_plot(elements: list[Element | str] | None = None, label_stable: bool | None = True, formulas_to_draw: list[str] | None = None, draw_formula_meshes: bool | None = True, draw_formula_lines: bool | None = True, formula_colors: list[str] = ['rgb(27,158,119)', 'rgb(217,95,2)', 'rgb(117,112,179)', 'rgb(231,41,138)', 'rgb(102,166,30)', 'rgb(230,171,2)', 'rgb(166,118,29)', 'rgb(102,102,102)'], element_padding: float | None = 1.0) Figure[source]
Plot the 2-dimensional or 3-dimensional chemical potential diagram using an interactive Plotly interface.
Elemental axes can be specified; if none provided, will automatically default to first 2-3 elements within the “elements” attribute.
In 3D, this method also allows for plotting of lower-dimensional “slices” of hyperdimensional polytopes (e.g., the LiMnO2 domain within a Y-Mn-O diagram). This allows for visualization of some of the phase boundaries that can only be seen fully in high dimensional space; see the “formulas_to_draw” argument.
- Parameters:
elements – list of elements to use as axes in the diagram. If None, automatically defaults to the first 2 or elements within the object’s “elements” attribute.
label_stable – whether to label stable phases by their reduced formulas. Defaults to True.
formulas_to_draw – for 3-dimensional diagrams, an optional list of formulas to plot on the diagram; if these are from a different chemical system a 3-d polyhedron “slice” will be plotted. Defaults to None.
draw_formula_meshes – whether to draw a colored mesh for the optionally specified formulas_to_draw. Defaults to True.
draw_formula_lines – whether to draw bounding lines for the optionally specified formulas_to_draw. Defaults to True.
formula_colors – a list of colors to use in the plotting of the optionally specified formulas_to-draw. Defaults to the Plotly Dark2 color scheme.
element_padding – if provided, automatically adjusts chemical potential axis limits of the plot such that elemental domains have the specified padding (in eV/atom), helping provide visual clarity. Defaults to 1.0.
- Returns:
plotly.graph_objects.Figure
- get_2d_orthonormal_vector(line_pts: ndarray) ndarray[source]
Calculates a vector that is orthonormal to a line given by a set of points. Used for determining the location of an annotation on a 2-d chemical potential diagram.
- Parameters:
line_pts – a 2x2 array in the form of [[x0, y0], [x1, y1]] giving the coordinates of a line
- Returns:
A length-2 vector that is orthonormal to the line.
- Return type:
np.ndarray
- get_centroid_2d(vertices: ndarray) ndarray[source]
A bare-bones implementation of the formula for calculating the centroid of a 2D polygon. Useful for calculating the location of an annotation on a chemical potential domain within a 3D chemical potential diagram.
NOTE vertices must be ordered circumferentially!
- Parameters:
vertices – array of 2-d coordinates corresponding to a polygon, ordered circumferentially
- Returns:
Giving 2-d centroid coordinates.
- Return type:
np.ndarray
- simple_pca(data: ndarray, k: int = 2) tuple[ndarray, ndarray, ndarray][source]
A bare-bones implementation of principal component analysis (PCA) used in the ChemicalPotentialDiagram class for plotting.
- Parameters:
data – array of observations
k – Number of principal components returned
- Returns:
projected data, eigenvalues, eigenvectors
- Return type:
tuple
pymatgen.analysis.cost module
This module is used to estimate the cost of various compounds. Costs are taken from the a CostDB instance, for example a CSV file via CostDBCSV. For compounds with no cost listed, a Phase Diagram style convex hull optimization is performed to determine a set of compositions that can be mixed to give the desired compound with lowest total cost.
- class CostAnalyzer(costdb: CostDB)[source]
Bases:
objectGiven a CostDB, figures out the minimum cost solutions via convex hull.
- Parameters:
costdb (CostDB) – Cost database to use.
- get_cost_per_kg(comp)[source]
Get best estimate of minimum cost/kg based on known data.
- Parameters:
comp (CompositionLike) – chemical formula
- Returns:
energy cost/kg
- Return type:
float
- class CostDB[source]
Bases:
ABCAbstract class for representing a Cost database. Can be extended, e.g. for file-based or REST-based databases.
- class CostDBCSV(filename)[source]
Bases:
CostDBRead a CSV file to get costs. Format is formula,cost_per_kg,name,BibTeX.
- Parameters:
filename (str) – Filename of cost database.
- class CostEntry(composition, cost, name, reference)[source]
Bases:
PDEntryExtends PDEntry to include a BibTeX reference and include language about cost.
- Parameters:
composition (Composition) – chemical composition of the entry
cost (float) – per mol, NOT per kg of the full Composition
name (str) – Optional parameter to name the entry. Defaults to the reduced chemical formula as in PDEntry.
reference (str) – Reference data as BiBTeX string.
pymatgen.analysis.dimensionality module
This module provides functions to get the dimensionality of a structure.
A number of different algorithms are implemented. These are based on the following publications:
- get_dimensionality_larsen:
P. M. Larsen, M. Pandey, M. Strange, K. W. Jacobsen. Definition of a scoring parameter to identify low-dimensional materials components. Phys. Rev. Materials 3, 034003 (2019).
- get_dimensionality_cheon:
Cheon, G.; Duerloo, K.-A. N.; Sendek, A. D.; Porter, C.; Chen, Y.; Reed, E. J. Data Mining for New Two- and One-Dimensional Weakly Bonded Solids and Lattice-Commensurate Heterostructures. Nano Lett. 2017.
- get_dimensionality_gorai:
Gorai, P., Toberer, E. & Stevanovic, V. Computational Identification of Promising Thermoelectric Materials Among Known Quasi-2D Binary Compounds. J. Mater. Chem. A 2, 4136 (2016).
- calculate_dimensionality_of_site(bonded_structure, site_index, inc_vertices=False)[source]
Calculate the dimensionality of the component containing the given site.
Implements directly the modified breadth-first-search algorithm described in Algorithm 1 of:
P. M. Larsen, M. Pandey, M. Strange, K. W. Jacobsen. Definition of a scoring parameter to identify low-dimensional materials components. Phys. Rev. Materials 3, 034003 (2019).
- Parameters:
bonded_structure (StructureGraph) – A structure with bonds, represented as a pymatgen structure graph. For example, generated using the CrystalNN.get_bonded_structure() method.
site_index (int) – The index of a site in the component of interest.
inc_vertices (bool, optional) – Whether to return the vertices (site images) of the component.
- Returns:
- If inc_vertices is False, the dimensionality of the
component will be returned as an int. If inc_vertices is true, the function will return a tuple of (dimensionality, vertices), where vertices is a list of tuples. E.g. [(0, 0, 0), (1, 1, 1)].
- Return type:
int | tuple
- find_clusters(struct, connected_matrix)[source]
Find bonded clusters of atoms in the structure with periodic boundary conditions.
If there are atoms that are not bonded to anything, returns [0,1,0]. (For faster computation time)
Author: Gowoon Cheon Email: gcheon@stanford.edu
- Parameters:
struct (Structure) – Input structure
connected_matrix – Must be made from the same structure with find_connected_atoms() function.
- Returns:
the size of the largest cluster in the crystal structure min_cluster: the size of the smallest cluster in the crystal structure clusters: list of bonded clusters found here, clusters are formatted as sets of indices of atoms
- Return type:
max_cluster
- find_connected_atoms(struct, tolerance=0.45, ldict=None)[source]
Find bonded atoms and returns a adjacency matrix of bonded atoms.
Author: “Gowoon Cheon” Email: “gcheon@stanford.edu”
- Parameters:
struct (Structure) – Input structure
tolerance – length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + (radius of atom 2) + (tolerance) < (distance between atoms 1 and 2). Default value = 0.45, the value used by JMol and Cheon et al.
ldict – dictionary of bond lengths used in finding bonded atoms. Values from JMol are used as default
- Returns:
- A numpy array of shape (number of atoms, number of atoms);
If any image of atom j is bonded to atom i with periodic boundary conditions, the matrix element [atom i, atom j] is 1.
- Return type:
np.ndarray
- get_dimensionality_cheon(structure_raw, tolerance=0.45, ldict=None, standardize=True, larger_cell=False)[source]
Algorithm for finding the dimensions of connected subunits in a structure. This method finds the dimensionality of the material even when the material is not layered along low-index planes, or does not have flat layers/molecular wires.
Author: “Gowoon Cheon” Email: “gcheon@stanford.edu”
See details at :
Cheon, G.; Duerloo, K.-A. N.; Sendek, A. D.; Porter, C.; Chen, Y.; Reed, E. J. Data Mining for New Two- and One-Dimensional Weakly Bonded Solids and Lattice-Commensurate Heterostructures. Nano Lett. 2017.
- Parameters:
structure_raw (Structure) – A pymatgen Structure object.
tolerance (float) – length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + (radius of atom 2) + (tolerance) < (distance between atoms 1 and 2). Default value = 0.45, the value used by JMol and Cheon et al.
ldict (dict) – dictionary of bond lengths used in finding bonded atoms. Values from JMol are used as default
standardize – works with conventional standard structures if True. It is recommended to keep this as True.
larger_cell –
tests with 3x3x3 supercell instead of 2x2x2. Testing with 2x2x2 supercell is faster but misclassifies rare interpenetrated 3D
structures. Testing with a larger cell circumvents this problem
- Returns:
- dimension of the largest cluster as a string. If there are ions
or molecules it returns ‘intercalated ion/molecule’
- Return type:
str
- get_dimensionality_gorai(structure, max_hkl=2, el_radius_updates=None, min_slab_size=5, min_vacuum_size=5, standardize=True, bonds=None)[source]
This method returns whether a structure is 3D, 2D (layered), or 1D (linear chains or molecules) according to the algorithm published in Gorai, P., Toberer, E. & Stevanovic, V. Computational Identification of Promising Thermoelectric Materials Among Known Quasi-2D Binary Compounds. J. Mater. Chem. A 2, 4136 (2016).
Note that a 1D structure detection might indicate problems in the bonding algorithm, particularly for ionic crystals (e.g., NaCl)
Users can change the behavior of bonds detection by passing either el_radius_updates to update atomic radii for auto-detection of max bond distances, or bonds to explicitly specify max bond distances for atom pairs. Note that if you pass both, el_radius_updates are ignored.
- Parameters:
structure (Structure) – structure to analyze dimensionality for
max_hkl (int) – max index of planes to look for layers
el_radius_updates (dict) – symbol->float to update atomic radii
min_slab_size (float) – internal surface construction parameter
min_vacuum_size (float) – internal surface construction parameter
standardize (bool) – whether to standardize the structure before analysis. Set to False only if you already have the structure in a convention where layers / chains will be along low <hkl> indexes.
bonds (dict[tuple, float]) – bonds are specified as a dict of 2-tuples of Species mapped to floats, the max bonding distance. For example, PO4 groups may be defined as {(“P”, “O”): 3}.
- Returns:
- the dimensionality of the structure - 1 (molecules/chains),
2 (layered), or 3 (3D)
- Return type:
int
- get_dimensionality_larsen(bonded_structure)[source]
Gets the dimensionality of a bonded structure.
The dimensionality of the structure is the highest dimensionality of all structure components. This method is very robust and can handle many tricky structures, regardless of structure type or improper connections due to periodic boundary conditions.
Requires a StructureGraph object as input. This can be generated using one of the NearNeighbor classes. For example, using the CrystalNN class:
bonded_structure = CrystalNN().get_bonded_structure(structure)
Based on the modified breadth-first-search algorithm described in:
P. M. Larsen, M. Pandey, M. Strange, K. W. Jacobsen. Definition of a scoring parameter to identify low-dimensional materials components. Phys. Rev. Materials 3, 034003 (2019).
- Parameters:
bonded_structure (StructureGraph) – A structure with bonds, represented as a pymatgen structure graph. For example, generated using the CrystalNN.get_bonded_structure() method.
- Returns:
The dimensionality of the structure.
- Return type:
int
- get_structure_components(bonded_structure, inc_orientation=False, inc_site_ids=False, inc_molecule_graph=False)[source]
Gets information on the components in a bonded structure.
Correctly determines the dimensionality of all structures, regardless of structure type or improper connections due to periodic boundary conditions.
Requires a StructureGraph object as input. This can be generated using one of the NearNeighbor classes. For example, using the CrystalNN class:
bonded_structure = CrystalNN().get_bonded_structure(structure)
Based on the modified breadth-first-search algorithm described in:
P. M. Larsen, M. Pandey, M. Strange, K. W. Jacobsen. Definition of a scoring parameter to identify low-dimensional materials components. Phys. Rev. Materials 3, 034003 (2019).
- Parameters:
bonded_structure (StructureGraph) – A structure with bonds, represented as a pymatgen structure graph. For example, generated using the CrystalNN.get_bonded_structure() method.
inc_orientation (bool, optional) – Whether to include the orientation of the structure component. For surfaces, the miller index is given, for one-dimensional structures, the direction of the chain is given.
inc_site_ids (bool, optional) – Whether to include the site indices of the sites in the structure component.
inc_molecule_graph (bool, optional) – Whether to include MoleculeGraph objects for zero-dimensional components.
- Returns:
- Information on the components in a structure as a list
of dictionaries with the keys:
- ”structure_graph”: A pymatgen StructureGraph object for the
component.
- ”dimensionality”: The dimensionality of the structure component as an
int.
- ”orientation”: If inc_orientation is True, the orientation of the
component as a tuple. E.g. (1, 1, 1)
- ”site_ids”: If inc_site_ids is True, the site indices of the
sites in the component as a tuple.
- ”molecule_graph”: If inc_molecule_graph is True, the site a
MoleculeGraph object for zero-dimensional components.
- Return type:
list[dict]
- zero_d_graph_to_molecule_graph(bonded_structure, graph)[source]
Converts a zero-dimensional networkx Graph object into a MoleculeGraph.
Implements a similar breadth-first search to that in calculate_dimensionality_of_site().
- Parameters:
bonded_structure (StructureGraph) – A structure with bonds, represented as a pymatgen structure graph. For example, generated using the CrystalNN.get_bonded_structure() method.
graph (nx.Graph) – A networkx Graph object for the component of interest.
- Returns:
A MoleculeGraph object of the component.
- Return type:
pymatgen.analysis.disorder module
This module provides various methods to analyze order/disorder in materials.
- get_warren_cowley_parameters(structure: Structure, r: float, dr: float) dict[tuple, float][source]
Warren-Crowley parameters.
- Parameters:
structure – Pymatgen Structure.
r – Radius
dr – Shell width
- Returns:
-1.0, …}
- Return type:
Warren-Crowley parameters in the form of a dict, e.g. {(Element Mo, Element W)
pymatgen.analysis.energy_models module
This module implements a EnergyModel abstract class and some basic implementations. Basically, an EnergyModel is any model that returns an “energy” for any given structure.
pymatgen.analysis.eos module
This module implements various equation of states.
Note: Most of the code were initially adapted from ASE and deltafactor by @gmatteo but has since undergone major refactoring.
- class Birch(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
EOSBaseBirch EOS.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
- class BirchMurnaghan(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
EOSBaseBirchMurnaghan EOS.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
- class DeltaFactor(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
PolynomialEOSFitting a polynomial EOS using delta factor.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
- class EOS(eos_name: str = 'murnaghan')[source]
Bases:
objectConvenient wrapper. Retained in its original state to ensure backward compatibility.
Fit equation of state for bulk systems.
The following equations are supported:
murnaghan: PRB 28, 5480 (1983)
- birch: Intermetallic compounds: Principles and Practice, Vol I:
Principles. pages 195-210
birch_murnaghan: PRB 70, 224107
pourier_tarantola: PRB 70, 224107
vinet: PRB 70, 224107
deltafactor
numerical_eos: 10.1103/PhysRevB.90.174107.
Usage:
eos = EOS(eos_name=’murnaghan’) eos_fit = eos.fit(volumes, energies) eos_fit.plot()
- Parameters:
eos_name (str) – Type of EOS to fit.
- MODELS: ClassVar[dict[str, Any]] = {'birch': <class 'pymatgen.analysis.eos.Birch'>, 'birch_murnaghan': <class 'pymatgen.analysis.eos.BirchMurnaghan'>, 'deltafactor': <class 'pymatgen.analysis.eos.DeltaFactor'>, 'murnaghan': <class 'pymatgen.analysis.eos.Murnaghan'>, 'numerical_eos': <class 'pymatgen.analysis.eos.NumericalEOS'>, 'pourier_tarantola': <class 'pymatgen.analysis.eos.PourierTarantola'>, 'vinet': <class 'pymatgen.analysis.eos.Vinet'>}[source]
- class EOSBase(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
ABCAbstract class that must be subclassed by all equation of state implementations.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
- property b0_GPa: FloatWithUnit[source]
The bulk modulus in GPa. This assumes the energy and volumes are in eV and Ang^3.
- fit() None[source]
Do the fitting. Does least square fitting. If you want to use custom fitting, must override this.
- func(volume)[source]
The equation of state function with the parameters other than volume set to the ones obtained from fitting.
- Parameters:
volume (float | list[float]) – volumes in Ang^3
- Returns:
numpy.array
- plot(width: float = 8, height: float | None = None, ax: Axes = None, dpi: float | None = None, **kwargs) Axes[source]
Plot the equation of state.
- Parameters:
width (float) – Width of plot in inches. Defaults to 8in.
height (float) – Height of plot in inches. Defaults to width * golden ratio.
ax (plt.Axes) – If supplied, changes will be made to the existing Axes. Otherwise, new Axes will be created.
dpi (float) – DPI.
kwargs (dict) – additional args fed to pyplot.plot. supported keys: style, color, text, label
- Returns:
The matplotlib axes.
- Return type:
plt.Axes
- plot_ax(ax: Axes | None = None, fontsize: float = 12, **kwargs) plt.Figure[source]
Plot the equation of state on axis ax.
- Parameters:
ax – matplotlib Axes or None if a new figure should be created.
fontsize – Legend fontsize.
- Returns:
matplotlib figure.
- Return type:
plt.Figure
Keyword arguments controlling the display of the figure:
kwargs
Meaning
title
Title of the plot (Default: None).
show
True to show the figure (default: True).
savefig
“abc.png” or “abc.eps” to save the figure to a file.
size_kwargs
Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)
tight_layout
True to call fig.tight_layout (default: False)
ax_grid
True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.
ax_annotate
Add labels to subplots e.g. (a), (b). Default: False
fig_close
Close figure. Default: False.
- class Murnaghan(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
EOSBaseMurnaghan EOS.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
- class NumericalEOS(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
PolynomialEOSA numerical EOS.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
- fit(min_ndata_factor: int = 3, max_poly_order_factor: int = 5, min_poly_order: int = 2) None[source]
Fit the input data to the ‘numerical eos’, the equation of state employed in the quasiharmonic Debye model described in the paper: 10.1103/PhysRevB.90.174107.
credits: Cormac Toher
- Parameters:
min_ndata_factor (int) – parameter that controls the minimum number of data points that will be used for fitting. minimum number of data points = total data points-2*min_ndata_factor
max_poly_order_factor (int) – parameter that limits the max order of the polynomial used for fitting. max_poly_order = number of data points used for fitting - max_poly_order_factor
min_poly_order (int) – minimum order of the polynomial to be considered for fitting.
- class PolynomialEOS(volumes: Sequence[float], energies: Sequence[float])[source]
Bases:
EOSBaseDerives from EOSBase. Polynomial based equations of states must subclass this.
- Parameters:
volumes (Sequence[float]) – in Ang^3.
energies (Sequence[float]) – in eV.
pymatgen.analysis.ewald module
This module provides classes for calculating the Ewald sum of a structure.
pymatgen.analysis.excitation module
This module defines an excitation spectrum class.
pymatgen.analysis.fragmenter module
Perform fragmentation of molecules.
- class Fragmenter(molecule: Molecule, edges: list | None = None, depth: int = 1, open_rings: bool = False, use_metal_edge_extender: bool = False, opt_steps: int = 10000, prev_unique_frag_dict: dict | None = None, assume_previous_thoroughness: bool = True)[source]
Bases:
MSONableMolecule fragmenter class.
Standard constructor for molecule fragmentation.
- Parameters:
molecule (Molecule) – The molecule to fragment.
edges (list) – List of index pairs that define graph edges, aka molecule bonds. If not set, edges will be determined with OpenBabel. Defaults to None.
depth (int) – The number of levels of iterative fragmentation to perform, where each level will include fragments obtained by breaking one bond of a fragment one level up. Defaults to 1. However, if set to 0, instead all possible fragments are generated using an alternative, non-iterative scheme.
open_rings (bool) – Whether or not to open any rings encountered during fragmentation. Defaults to False. If true, any bond that fails to yield disconnected graphs when broken is instead removed and the entire structure is optimized with OpenBabel in order to obtain a good initial guess for an opened geometry that can then be put back into QChem to be optimized without the ring just reforming.
use_metal_edge_extender (bool) – Whether or not to attempt to add additional edges from O, N, F, or Cl to any Li or Mg atoms present that OpenBabel may have missed. Defaults to False. Most important for ionic bonding. Note that additional metal edges may yield new “rings” (e.g. -C-O-Li-O- in LiEC) that will not play nicely with ring opening.
opt_steps (int) – Number of optimization steps when opening rings. Defaults to 10000.
prev_unique_frag_dict (dict) – A dictionary of previously identified unique fragments. Defaults to None. Typically only used when trying to find the set of unique fragments that come from multiple molecules.
assume_previous_thoroughness (bool) – Whether or not to assume that a molecule / fragment provided in prev_unique_frag_dict has all of its unique subfragments also provided in prev_unique_frag_dict. Defaults to True. This is an essential optimization when trying to find the set of unique fragments that come from multiple molecules if all of those molecules are being fully iteratively fragmented. However, if you’re passing a prev_unique_frag_dict which includes a molecule and its fragments that were generated at insufficient depth to find all possible subfragments to a fragmentation calculation of a different molecule that you aim to find all possible subfragments of and which has common subfragments with the previous molecule, this optimization will cause you to miss some unique subfragments.
- open_ring(mol_graph: MoleculeGraph, bond: list, opt_steps: int) MoleculeGraph[source]
Open a ring using OpenBabel’s local opt. Given a molecule graph and a bond, convert the molecule graph into an OpenBabel molecule, remove the given bond, perform the local opt with the number of steps determined by self.steps, and then convert the resulting structure back into a molecule graph to be returned.
pymatgen.analysis.functional_groups module
Determine functional groups present in a Molecule.
- class FunctionalGroupExtractor(molecule, optimize=False)[source]
Bases:
objectThis class is used to algorithmically parse a molecule (represented by an instance of pymatgen.analysis.graphs.MoleculeGraph) and determine arbitrary functional groups.
Instantiation method for FunctionalGroupExtractor.
- Parameters:
molecule – Either a filename, a pymatgen.core.structure.Molecule object, or a pymatgen.analysis.graphs.MoleculeGraph object.
optimize – Default False. If True, then the input molecule will be modified, adding Hydrogens, performing a simple conformer search, etc.
- categorize_functional_groups(groups)[source]
Determine classes of functional groups present in a set.
- Parameters:
groups – Set of functional groups.
- Returns:
dict containing representations of the groups, the indices of where the group occurs in the MoleculeGraph, and how many of each type of group there is.
- get_all_functional_groups(elements=None, func_groups=None, catch_basic=True)[source]
Identify all functional groups (or all within a certain subset) in the molecule, combining the methods described above.
- Parameters:
elements – List of elements that will qualify a carbon as special (if only certain functional groups are of interest). Default None.
func_groups – List of strs representing the functional groups of interest. Default to None, meaning that all of the functional groups defined in this function will be sought.
catch_basic – bool. If True, use get_basic_functional_groups and other methods
- Returns:
list of sets of ints, representing groups of connected atoms
- get_basic_functional_groups(func_groups=None)[source]
Identify functional groups that cannot be identified by the Ertl method of get_special_carbon and get_heteroatoms, such as benzene rings, methyl groups, and ethyl groups.
TODO: Think of other functional groups that are important enough to be added (ex: do we need ethyl, butyl, propyl?)
- Parameters:
func_groups – List of strs representing the functional groups of interest. Default to None, meaning that all of the functional groups defined in this function will be sought.
- Returns:
list of sets of ints, representing groups of connected atoms
- get_heteroatoms(elements=None)[source]
Identify non-H, non-C atoms in the MoleculeGraph, returning a list of their node indices.
- Parameters:
elements – List of elements to identify (if only certain
interest). (functional groups are of)
- Returns:
set of ints representing node indices
- get_special_carbon(elements=None)[source]
Identify Carbon atoms in the MoleculeGraph that fit the characteristics defined Ertl (2017), returning a list of their node indices.
- The conditions for marking carbon atoms are (quoted from Ertl):
“- atoms connected by non-aromatic double or triple bond to any heteroatom - atoms in nonaromatic carbon-carbon double or triple bonds - acetal carbons, i.e. sp3 carbons connected to two or more oxygens, nitrogens or sulfurs; these O, N or S atoms must have only single bonds - all atoms in oxirane, aziridine and thiirane rings”
- Parameters:
elements – List of elements that will qualify a carbon as special (if only certain functional groups are of interest). Default None.
- Returns:
set of ints representing node indices
- link_marked_atoms(atoms)[source]
Take a list of marked “interesting” atoms (heteroatoms, special carbons) and attempt to connect them, returning a list of disjoint groups of special atoms (and their connected hydrogens).
- Parameters:
atoms – set of marked “interesting” atoms, presumably identified using other functions in this class.
- Returns:
list of sets of ints, representing groups of connected atoms
pymatgen.analysis.graphs module
Module for graph representations of crystals and molecules.
pymatgen.analysis.hhi module
This module is used to estimate the Herfindahl-Hirschman Index, or HHI, of chemical compounds. The HHI is a measure of how geographically confined or dispersed the elements comprising a compound are. A low HHI is desirable because it means the component elements are geographically dispersed.
Data/strategy from “Data-Driven Review of Thermoelectric Materials: Performance and Resource Considerations” by Gaultois et al., published in Chemistry of Materials (2013).
pymatgen.analysis.interface_reactions module
This module provides a class to predict and analyze interfacial reactions between two solids, with or without an open element (e.g., flowing O2).
- class GrandPotentialInterfacialReactivity(c1: Composition, c2: Composition, grand_pd: GrandPotentialPhaseDiagram, pd_non_grand: PhaseDiagram, include_no_mixing_energy: bool = False, norm: bool = True, use_hull_energy: bool = True)[source]
Bases:
InterfacialReactivityExtends upon InterfacialReactivity to allow for modelling possible reactions at the interface between two solids in the presence of an open element. The thermodynamics of the open system are provided by the user via the GrandPotentialPhaseDiagram class.
- Parameters:
c1 – Reactant 1 composition
c2 – Reactant 2 composition
grand_pd – Grand potential phase diagram object built from all elements in composition c1 and c2.
include_no_mixing_energy – No_mixing_energy for a reactant is the opposite number of its energy above grand potential convex hull. In cases where reactions involve elements reservoir, this param determines whether no_mixing_energy of reactants will be included in the final reaction energy calculation. By definition, if pd is not a GrandPotentialPhaseDiagram object, this param is False.
pd_non_grand – PhaseDiagram object but not GrandPotentialPhaseDiagram object built from elements in c1 and c2.
norm – Whether or not the total number of atoms in composition of reactant will be normalized to 1.
use_hull_energy – Whether or not use the convex hull energy for a given composition for reaction energy calculation. If false, the energy of ground state structure will be used instead. Note that in case when ground state can not be found for a composition, convex hull energy will be used associated with a warning message.
- class InterfacialReactivity(c1: Composition, c2: Composition, pd: PhaseDiagram, norm: bool = True, use_hull_energy: bool = False, **kwargs)[source]
Bases:
MSONableModel an interface between two solids and its possible reactions. The two reactants are provided as Composition objects (c1 and c2), along with the relevant compositional PhaseDiagram object. Possible reactions are calculated by finding all points along a tie-line between c1 and c2 where there is a “kink” in the phase diagram; i.e. a point or facet of the phase diagram.
Please consider citing one or both of the following papers if you use this code in your own work.
References
Richards, W. D., Miara, L. J., Wang, Y., Kim, J. C., & Ceder, G. (2015). Interface stability in solid-state batteries. Chemistry of Materials, 28(1), 266-273. https://doi.org/10.1021/acs.chemmater.5b04082
Xiao, Y., Wang, Y., Bo, S.-H., Kim, J. C., Miara, L. J., & Ceder, G. (2019). Understanding interface stability in solid-state batteries. Nature Reviews Materials, 5(2), 105-126. https://doi.org/10.1038/s41578-019-0157-5
- Parameters:
c1 – Reactant 1 composition
c2 – Reactant 2 composition
pd – Phase diagram object built from all elements in composition c1 and c2.
norm – Whether or not the total number of atoms in composition of reactant will be normalized to 1.
use_hull_energy – Whether or not use the convex hull energy for a given composition for reaction energy calculation. If false, the energy of ground state structure will be used instead. Note that in case when ground state can not be found for a composition, convex hull energy will be used associated with a warning message.
- classmethod get_chempot_correction(element: str, temp: float, pres: float)[source]
Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, T_std = 1 bar). The gas phase is limited to be one of O2, N2, Cl2, F2, H2. Calculation formula can be found in the documentation of Materials Project website.
- Parameters:
element – The string representing the element.
temp – The temperature of the gas phase in Kelvin.
pres – The pressure of the gas phase in Pa. # codespell:ignore pres
- Returns:
The correction of chemical potential in eV/atom of the gas phase at given temperature and pressure.
- get_critical_original_kink_ratio()[source]
Get a list of molar mixing ratio for each kink between ORIGINAL (instead of processed) reactant compositions. This is the same list as mixing ratio obtained from get_kinks method if self.norm = False.
- Returns:
A list of floats representing molar mixing ratios between the original reactant compositions for each kink.
- get_dataframe() DataFrame[source]
Get a pandas DataFrame representation of the data produced by the get_kinks() method.
- get_kinks() list[tuple[int, float, float, Reaction, float]][source]
Find all the kinks in mixing ratio where reaction products changes along the tie-line of composition self.c1 and composition self.c2.
- Returns:
(index, mixing ratio, reaction energy in eV/atom, Reaction object, reaction energy per mol of formula in kJ/mol).
- Return type:
List object of tuples, each of which contains 5 elements
- property labels[source]
A dictionary containing kink information: {index: ‘x= mixing_ratio energy= reaction_energy reaction_equation’}. e.g. {1: ‘x= 0 energy = 0 Mn -> Mn’,
2: ‘x= 0.5 energy = -15 O2 + Mn -> MnO2’, 3: ‘x= 1 energy = 0 O2 -> O2’}.
- property minimum[source]
The minimum reaction energy E_min and corresponding mixing ratio x_min as tuple[float, float]: (x_min, E_min).
- plot(backend: Literal['plotly', 'matplotlib'] = 'plotly') Figure | plt.Figure[source]
Plots reaction energy as a function of mixing ratio x in self.c1 - self.c2 tie line.
- Parameters:
backend ("plotly" | "matplotlib") – Plotting library used to create the plot. Defaults to “plotly” but can also be “matplotlib”.
- Returns:
Plot of reaction energies as a function of mixing ratio
pymatgen.analysis.lobster_env module
This module provides classes to perform analyses of the local environments (e.g., finding near neighbors) of single sites in molecules and structures based on bonding analysis with LOBSTER.
If you use this module, please cite: J. George, G. Petretto, A. Naik, M. Esters, A. J. Jackson, R. Nelson, R. Dronskowski, G.-M. Rignanese, G. Hautier, “Automated Bonding Analysis with Crystal Orbital Hamilton Populations”, ChemPlusChem 2022, e202200123, DOI: 10.1002/cplu.202200123.
- class ICOHPNeighborsInfo(total_icohp: float, list_icohps: list[float], n_bonds: int, labels: list[str], atoms: list[list[str]], central_isites: list[int] | None)[source]
Bases:
NamedTupleTuple to record information on relevant bonds.
- Parameters:
total_icohp (float) – Sum of ICOHP values of neighbors to the selected sites (given by the index in structure).
list_icohps (list) – Summed ICOHP values for all identified interactions with neighbors.
n_bonds (int) – Number of identified bonds to the selected sites.
labels (list[str]) – Labels (from ICOHPLIST) for all identified bonds.
atoms (list[list[str]]) – Lists describing the species present (from ICOHPLIST) in the identified interactions , e.g. [“Ag3”, “O5”].
central_isites (list[int]) – The central site indexes for each identified interaction.
Create new instance of ICOHPNeighborsInfo(total_icohp, list_icohps, n_bonds, labels, atoms, central_isites)
- class LobsterLightStructureEnvironments(strategy, coordination_environments=None, all_nbs_sites=None, neighbors_sets=None, structure=None, valences=None, valences_origin=None)[source]
Bases:
LightStructureEnvironmentsStore LightStructureEnvironments based on LOBSTER outputs.
Constructor for the LightStructureEnvironments object.
- Parameters:
strategy – ChemEnv strategy used to get the environments.
coordination_environments – The coordination environments identified.
all_nbs_sites – All the possible neighbors for each site in the structure.
neighbors_sets – The neighbors sets of each site in the structure.
structure – The structure.
valences – The valences used to get the environments (if needed).
valences_origin – How the valences were obtained (e.g. from the Bond-valence analysis or from the original structure).
- as_dict() dict[str, Any][source]
Bson-serializable dict representation of the object.
- Returns:
Bson-serializable dict representation.
- classmethod from_Lobster(list_ce_symbol: list[str | None], list_csm: list[float | None], list_permutation: list, list_neighsite: list[PeriodicSite], list_neighisite: list[list[int]], structure: Structure | IStructure, valences: list[float] | None = None) Self[source]
Set up a LightStructureEnvironments from LOBSTER.
- Parameters:
list_ce_symbol (list[str]) – Coordination environments symbols.
list_csm (list[float]) – Continuous symmetry measures.
list_permutation (list) – Permutations.
list_neighsite (list[PeriodicSite]) – Neighboring sites.
list_neighisite (list[list[int]]) – Neighboring sites indexes.
structure (Structure) – Structure object.
valences (list[float]) – Valences.
- Returns:
LobsterLightStructureEnvironments
- class LobsterNeighbors(structure: Structure | IStructure, filename_icohp: PathLike | None = 'ICOHPLIST.lobster', obj_icohp: Icohplist | None = None, are_coops: bool = False, are_cobis: bool = False, valences: list[float] | None = None, limits: tuple[float, float] | None = None, additional_condition: Literal[0, 1, 2, 3, 4, 5, 6] = 0, only_bonds_to: list[str] | None = None, perc_strength_icohp: float = 0.15, noise_cutoff: float = 0.1, valences_from_charges: bool = False, filename_charge: PathLike | None = None, obj_charge: Charge | None = None, which_charge: Literal['Mulliken', 'Loewdin'] = 'Mulliken', adapt_extremum_to_add_cond: bool = False, add_additional_data_sg: bool = False, filename_blist_sg1: PathLike | None = None, filename_blist_sg2: PathLike | None = None, id_blist_sg1: Literal['icoop', 'icobi'] = 'icoop', id_blist_sg2: Literal['icoop', 'icobi'] = 'icobi', backward_compatibility: bool = False)[source]
Bases:
NearNeighborsThis class combines capabilities from LocalEnv and ChemEnv to determine coordination environments based on bonding analysis.
- Parameters:
filename_icohp (PathLike) – Path to ICOHPLIST.lobster or ICOOPLIST.lobster or ICOBILIST.lobster.
obj_icohp (Icohplist) – Icohplist object.
structure (Structure) – Typically constructed by Structure.from_file(“POSCAR”).
are_coops (bool) – Whether the file is a ICOOPLIST.lobster (True) or a ICOHPLIST.lobster (False). Only tested for ICOHPLIST.lobster so far.
are_cobis (bool) – Whether the file is a ICOBILIST.lobster (True) or a ICOHPLIST.lobster (False).
valences (list[float]) – Valence/charge for each element.
limits (tuple[float, float]) – Range to decide which ICOHPs (ICOOP or ICOBI) should be considered.
additional_condition (int) –
Additional condition that decides which kind of bonds will be considered:
0 - NO_ADDITIONAL_CONDITION 1 - ONLY_ANION_CATION_BONDS 2 - NO_ELEMENT_TO_SAME_ELEMENT_BONDS 3 - ONLY_ANION_CATION_BONDS_AND_NO_ELEMENT_TO_SAME_ELEMENT_BONDS 4 - ONLY_ELEMENT_TO_OXYGEN_BONDS 5 - DO_NOT_CONSIDER_ANION_CATION_BONDS 6 - ONLY_CATION_CATION_BONDS
only_bonds_to (list[str]) – Only consider bonds to certain elements (e.g. [“O”] for oxygen).
perc_strength_icohp (float) – If no “limits” are given, this will decide which ICOHPs will be considered (relative to the strongest ICOHP/ICOOP/ICOBI).
noise_cutoff (float) – The lower limit of ICOHPs considered.
valences_from_charges (bool) – If True and path to CHARGE.lobster is provided, will use LOBSTER charges (Mulliken) instead of valences.
filename_charge (PathLike) – Path to Charge.lobster.
obj_charge (Charge) – Charge object.
which_charge ("Mulliken" | "Loewdin") – Source of charge.
adapt_extremum_to_add_cond (bool) – Whether to adapt the limits to only focus on the bonds determined by the additional condition.
add_additional_data_sg (bool) – Add the information from filename_add_bondinglist_sg1.
filename_blist_sg1 (PathLike) – Path to additional ICOOP, ICOBI data for structure graphs.
filename_blist_sg2 (PathLike) – Path to additional ICOOP, ICOBI data for structure graphs.
id_blist_sg1 ("icoop" | "icobi") – Identity of data in filename_blist_sg1.
id_blist_sg2 ("icoop" | "icobi") – Identity of data in filename_blist_sg2.
backward_compatibility (bool) – compatibility with neighbor detection prior 2025 (less strict).
- property anion_types: set[Element][source]
The set of anion types in crystal structure.
- Returns:
Anions in the crystal structure.
- Return type:
set[Element]
- classmethod from_files(structure_path: PathLike = 'CONTCAR', icoxxlist_path: PathLike = 'ICOHPLIST.lobster', are_coops: bool = False, are_cobis: bool = False, charge_path: PathLike | None = None, blist_sg1_path: PathLike | None = None, blist_sg2_path: PathLike | None = None, id_blist_sg1: Literal['icoop', 'icobi'] = 'icoop', id_blist_sg2: Literal['icoop', 'icobi'] = 'icobi', **kwargs)[source]
Instanitate LobsterNeighbors using file paths.
- Parameters:
structure_path (PathLike) – Path to structure file, typically CONTCAR
icoxxlist_path (PathLike) – Path to ICOHPLIST.lobster or ICOOPLIST.lobster or ICOBILIST.lobster.
are_coops (bool) – Whether the file is a ICOOPLIST.lobster (True) or a ICOHPLIST.lobster (False). Only tested for ICOHPLIST.lobster so far.
are_cobis (bool) – Whether the file is a ICOBILIST.lobster (True) or a ICOHPLIST.lobster (False).
charge_path (PathLike) – Path to Charge.lobster.
blist_sg1_path (PathLike) – Path to additional ICOOP, ICOBI data for structure graphs.
blist_sg2_path (PathLike) – Path to additional ICOOP, ICOBI data for structure graphs.
id_blist_sg1 ("icoop" | "icobi") – Population type in blist_sg1_path.
id_blist_sg2 ("icoop" | "icobi") – Population type in in blist_sg2_path.
- get_info_cohps_to_neighbors(path_to_cohpcar: PathLike | None = 'COHPCAR.lobster', coxxcar_obj: CompleteCohp | None = None, isites: list[int] | None = None, only_bonds_to: list[str] | None = None, onlycation_isites: bool = True, per_bond: bool = True, summed_spin_channels: bool = False) tuple[str | None, CompleteCohp | None][source]
Get the COHPs (COOPs or COBIs) as a summed Cohp object and a label from all sites mentioned in isites with neighbors.
- Parameters:
path_to_cohpcar (PathLike) – Path to COHPCAR/COOPCAR/COBICAR.
coxxcar_obj (CompleteCohp | None) – CompleteCohp object.
isites (list[int]) – The indexes of the sites.
only_bonds_to (list[str]) – Only show COHPs to selected element, e.g. [“O”].
onlycation_isites (bool) – If isites is None, only cation sites will be returned.
per_bond (bool) – Whether to normalize per bond.
summed_spin_channels (bool) – Whether to sum both spin channels.
- Returns:
Label for COHP. CompleteCohp: Describe all COHPs/COOPs/COBIs of the sites
as given by isites and the other arguments.
- Return type:
str
- get_info_icohps_between_neighbors(isites: list[int] | None = None, onlycation_isites: bool = True) ICOHPNeighborsInfo[source]
Get interactions between neighbors of certain sites.
- Parameters:
isites (list[int]) – Site IDs. If is None, all sites will be used.
onlycation_isites (bool) – Only use cations, if isite is None.
- Returns:
ICOHPNeighborsInfo
- get_info_icohps_to_neighbors(isites: list[int] | None = None, onlycation_isites: bool = True) ICOHPNeighborsInfo[source]
Get information on the ICOHPs of neighbors for certain sites as identified by their site id.
This is useful for plotting the COHPs (ICOOPLIST.lobster/ ICOHPLIST.lobster/ICOBILIST.lobster) of a site in the structure.
- Parameters:
isites (list[int]) – Site IDs. If is None, all isites will be used to add the ICOHPs of the neighbors.
onlycation_isites (bool) – If True and if isite is None, will only analyse the cations sites.
- Returns:
ICOHPNeighborsInfo
- get_light_structure_environment(only_cation_environments: bool = False, only_indices: list[int] | None = None, on_error: Literal['raise', 'warn', 'ignore'] = 'raise') LobsterLightStructureEnvironments[source]
Get a LobsterLightStructureEnvironments object if the structure only contains coordination environments smaller 13.
- Parameters:
only_cation_environments (bool) – Only return data for cations.
only_indices (list[int]) – Only evaluate indexes in this list.
on_error ("raise" | "warn" | "ignore") – Whether to raise an error, warn or ignore if the environment of a site cannot be determined.
- Returns:
LobsterLightStructureEnvironments
- get_nn_info(structure: Structure | IStructure, n: int, use_weights: bool = False) dict[str, Any][source]
Get coordination number (CN) of site by index.
- Parameters:
structure (Structure) – Input structure.
n (int) – Index of site for which to determine CN.
use_weights (bool) – Whether to use weights for computing the CN (True), or each coordinated site has equal weight (False). The former is not implemented yet.
- Raises:
ValueError – If use_weights is True, or if arg “structure” and structure used to initialize LobsterNeighbors have different lengths.
- Returns:
coordination number and a list of nearest neighbors.
- Return type:
dict[str, Any]
- property molecules_allowed: Literal[False][source]
Whether this LobsterNeighbors class can be used with Molecule objects.
- plot_cohps_of_neighbors(path_to_cohpcar: PathLike | None = 'COHPCAR.lobster', coxxcar_obj: CompleteCohp | None = None, isites: list[int] | None = None, onlycation_isites: bool = True, only_bonds_to: list[str] | None = None, per_bond: bool = False, summed_spin_channels: bool = False, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] = (-10, 6), integrated: bool = False) mpl.axes.Axes[source]
Plot summed COHPs or COBIs or COOPs.
Please be careful in the spin polarized case (plots might overlap).
- Parameters:
path_to_cohpcar (PathLike) – Path to COHPCAR or COOPCAR or COBICAR.
coxxcar_obj (CompleteCohp | None) – CompleteCohp object
isites (list[int]) – Site IDs. If empty, all sites will be used to add the ICOHPs of the neighbors.
onlycation_isites (bool) – Only use cations, if isite is empty.
only_bonds_to (list[str]) – Only anions in this list will be considered.
per_bond (bool) – Whether to plot a normalization of the plotted COHP per number of bond (True), or the sum (False).
xlim (tuple[float, float]) – Limits of x values.
ylim (tuple[float, float]) – Limits of y values.
integrated (bool) – Whether to show integrated COHP instead of COHP.
- Returns:
plt of the COHPs or COBIs or COOPs.
pymatgen.analysis.local_env module
This module provides classes to perform analyses of the local environments (e.g., finding near neighbors) of single sites in molecules and structures.
pymatgen.analysis.molecule_matcher module
This module provides classes to perform fitting of molecule with arbitrary atom orders. This module is supposed to perform exact comparisons without the atom order correspondence prerequisite, while molecule_structure_comparator is supposed to do rough comparisons with the atom order correspondence prerequisite.
The implementation is based on an excellent python package called rmsd that you can find at https://github.com/charnley/rmsd.
pymatgen.analysis.molecule_structure_comparator module
This module provides classes to comparison the structures of the two molecule. As long as the two molecule have the same bond connection tables, the molecules are deemed to be same. The atom in the two molecule must be paired accordingly. This module is supposed to perform rough comparisons with the atom order correspondence prerequisite, while molecule_matcher is supposed to do exact comparisons without the atom order correspondence prerequisite.
pymatgen.analysis.nmr module
A module for NMR analysis.
- class ChemicalShielding(cs_matrix, vscale=None)[source]
Bases:
SquareTensorThis class extends the SquareTensor to perform extra analysis unique to NMR Chemical shielding tensors.
Three notations to describe chemical shielding tensor (RK Harris; Magn. Resonance Chem. 2008, 46, 582-598; DOI: 10.1002/mrc.2225) are supported.
Authors: Shyam Dwaraknath, Xiaohui Qu
Create a Chemical Shielding tensor. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays.
- Parameters:
cs_matrix (1x3 or 3x3 array-like) – the 3x3 array-like representing the chemical shielding tensor or a 1x3 array of the primary sigma values corresponding to the principal axis system
vscale (6x1 array-like) – 6x1 array-like scaling the Voigt notation vector with the tensor entries
- class HaeberlenNotation(sigma_iso, delta_sigma_iso, zeta, eta)[source]
Bases:
NamedTupleCreate new instance of HaeberlenNotation(sigma_iso, delta_sigma_iso, zeta, eta)
- class MarylandNotation(sigma_iso, omega, kappa)[source]
Bases:
NamedTupleCreate new instance of MarylandNotation(sigma_iso, omega, kappa)
- class MehringNotation(sigma_iso, sigma_11, sigma_22, sigma_33)[source]
Bases:
NamedTupleCreate new instance of MehringNotation(sigma_iso, sigma_11, sigma_22, sigma_33)
- class ElectricFieldGradient(efg_matrix, vscale=None)[source]
Bases:
SquareTensorThis class extends the SquareTensor to perform extra analysis unique to NMR Electric Field Gradient tensors in units of V/Angstrom^2.
Authors: Shyam Dwaraknath, Xiaohui Qu
Create a Chemical Shielding tensor. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays.
- Parameters:
efg_matrix (1x3 or 3x3 array-like) – the 3x3 array-like representing the electric field tensor or a 1x3 array of the primary values corresponding to the principal axis system
vscale (6x1 array-like) – 6x1 array-like scaling the Voigt notation vector with the tensor entries
- coupling_constant(specie)[source]
Compute the coupling constant C_q as defined in:
Wasylishen R E, Ashbrook S E, Wimperis S. NMR of quadrupolar nuclei in solid materials[M]. John Wiley & Sons, 2012. (Chapter 3.2).
- C_q for a specific atom type for this electric field tensor:
C_q=e*Q*V_zz/h
h: Planck’s constant Q: nuclear electric quadrupole moment in mb (millibarn e: elementary proton charge
- Parameters:
specie – flexible input to specify the species at this site. Can take a isotope or element string, Species object, or Site object
- Returns:
the coupling constant as a FloatWithUnit in MHz
pymatgen.analysis.optics module
Perform optical property calculations.
- class DielectricAnalysis(energies: list[float], eps_real: list[list[float]], eps_imag: list[list[float]])[source]
Bases:
objectClass to compute optical properties of materials based on provided energy levels, real and imaginary components of the dielectric function. The resulting properties include wavelength, refractive index (n), extinction coefficient (k), reflectivity (R), absorptivity (L), and transmittance (T) for up to six configurations.
This class provides capabilities to compute these properties from supplied dielectric data or parsed data from VASP calculation results.
- eps_real[source]
Array of real parts of the dielectric function for different configurations. The structure aligns with the input list provided at initialization.
- Type:
numpy.ndarray
- eps_imag[source]
Array of imaginary parts of the dielectric function matching the structure of eps_real.
- Type:
numpy.ndarray
- wavelengths[source]
Array of wavelengths (in nanometers) corresponding to the energy levels. Computed using Planck’s constant and the speed of light.
- Type:
numpy.ndarray
- n[source]
Array of refractive indices for each energy level and corresponding configuration.
- Type:
numpy.ndarray
- k[source]
Array of extinction coefficients for each energy level and corresponding configuration.
- Type:
numpy.ndarray
- R[source]
Array of reflectivity values for each energy level and corresponding configuration.
- Type:
numpy.ndarray
- L[source]
Array of absorptivity values for each energy level and corresponding configuration.
- Type:
numpy.ndarray
- T[source]
Array of transmittance values for each energy level and corresponding configuration.
- Type:
numpy.ndarray
Class to compute optical properties of materials based on provided energy levels, real and imaginary components of the dielectric function. The resulting properties include wavelength, refractive index (n), extinction coefficient (k), reflectivity (R), absorptivity (L), and transmittance (T).
- Parameters:
energies (list[float]) – List of energy levels in electron volts (eV).
eps_real (list[list[float]]) – 2D list of real parts of the dielectric function for different configurations. The outer list corresponds to different energy levels, and the inner list corresponds to configurations.
eps_imag (list[list[float]]) – 2D list of imaginary parts of the dielectric function matching the structure of eps_real.
- classmethod from_vasprun(vasprun: Vasprun) DielectricAnalysis[source]
Creates an instance of the DielectricAnalysis class using the dielectric data extracted from a VASP calculation parsed by the vasprun object. The dielectric data typically includes the energies, real part of the dielectric tensor, and imaginary part of the dielectric tensor.
- Parameters:
vasprun (Vasprun) – Object containing parsed VASP calculation results, specifically
calculation. (the dielectric data extracted from the)
- Returns:
An instance of the DielectricAnalysis class initialized with the dielectric data (energies, real dielectric tensor, and imaginary dielectric tensor).
- Return type:
pymatgen.analysis.phase_diagram module
This module defines tools to generate and analyze phase diagrams.
- class CompoundPhaseDiagram(entries: Sequence[Entry], terminal_compositions: Sequence[Composition], normalize_terminal_compositions: bool = True)[source]
Bases:
PhaseDiagramGenerates phase diagrams from compounds as terminations instead of elements.
Initialize a CompoundPhaseDiagram.
- Parameters:
entries ([PDEntry]) – Sequence of input entries. For example, if you want a Li2O-P2O5 phase diagram, you might have all Li-P-O entries as an input.
terminal_compositions (list[Composition]) – Terminal compositions of phase space. In the Li2O-P2O5 example, these will be the Li2O and P2O5 compositions.
normalize_terminal_compositions (bool) – Whether to normalize the terminal compositions to a per atom basis. If normalized, the energy above hulls will be consistent for comparison across systems. Non-normalized terminals are more intuitive in terms of compositional breakdowns.
- classmethod from_dict(dct: dict) Self[source]
- Parameters:
dct (dict) – dictionary representation of CompoundPhaseDiagram.
- Returns:
CompoundPhaseDiagram
- static num2str(num)[source]
Convert number to a list of letter(s). First letter must be f.
- Parameters:
int (num) – Number to convert
- Return type:
str
:return Converted string
- transform_entries(entries: Sequence[Entry], terminal_compositions: Sequence[Composition]) tuple[list[TransformedPDEntry], dict[Composition, DummySpecies]][source]
Method to transform all entries to the composition coordinate in the terminal compositions. If the entry does not fall within the space defined by the terminal compositions, they are excluded. For example, Li3PO4 is mapped into a Li2O:1.5, P2O5:0.5 composition. The terminal compositions are represented by DummySpecies.
TODO: update serialization here.
- Parameters:
entries – Sequence of all input entries
terminal_compositions – Terminal compositions of phase space.
- Returns:
Sequence of TransformedPDEntries falling within the phase space.
- class GrandPotPDEntry(entry: PDEntry, chempots: dict[Element, float], name: str | None = None)[source]
Bases:
PDEntryA grand potential pd entry object encompassing all relevant data for phase diagrams. Chemical potentials are given as a element-chemical potential dict.
- Parameters:
entry – A PDEntry-like object.
chempots – Chemical potential specification as {Element: float}.
name – Optional parameter to name the entry. Defaults to the reduced chemical formula of the original entry.
- property chemical_energy: float[source]
The chemical energy term mu*N in the grand potential.
- Returns:
The chemical energy term mu*N in the grand potential
- property composition: Composition[source]
The composition after removing free species.
- Returns:
Composition
- class GrandPotentialPhaseDiagram(entries: Collection[Entry], chempots: dict[Element, float], elements: Collection[Element] | None = None, *, computed_data: dict[str, Any] | None = None)[source]
Bases:
PhaseDiagramA class representing a Grand potential phase diagram. Grand potential phase diagrams are essentially phase diagrams that are open to one or more components. To construct such phase diagrams, the relevant free energy is the grand potential, which can be written as the Legendre transform of the Gibbs free energy as follows.
Grand potential = G - u_X N_X
The algorithm is based on the work in the following papers:
S. P. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807. doi:10.1021/cm702327g
S. P. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first principles calculations. Electrochem. Comm., 2010, 12(3), 427-430. doi:10.1016/j.elecom.2010.01.010
Standard constructor for grand potential phase diagram.
TODO: update serialization here.
- Parameters:
entries (Sequence[Entry]) – A list of Entry objects having an energy, energy_per_atom and composition.
chempots (dict[Element, float]) – Specify the chemical potentials of the open elements.
elements (Sequence[Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the entries themselves.
computed_data (dict[str, Any]) – A dict containing pre-computed data. This allows PhaseDiagram object to be reconstituted without performing the expensive convex hull computation. The dict is the output from the PhaseDiagram._compute() method and is stored in PhaseDiagram.computed_data when generated for the first time.
- class PDEntry(composition: CompositionLike, energy: float, name: str | None = None, attribute: object = None)[source]
Bases:
EntryAn object encompassing all relevant data for phase diagrams.
- name[source]
A name for the entry. This is the string shown in the phase diagrams. By default, this is the reduced formula for the composition, but can be set to some other string for display purposes.
- Type:
str
- attribute[source]
A arbitrary attribute. Can be used to specify that the entry is a newly found compound, or to specify a particular label for the entry, etc. An attribute can be anything but must be MSONable.
- Type:
MSONable
- Parameters:
composition (CompositionLike) – Composition
energy (float) – Energy for composition.
name (str) – Optional parameter to name the entry. Defaults to the reduced chemical formula.
attribute – Optional attribute of the entry. Must be MSONable.
- class PDPlotter(phasediagram: PhaseDiagram, show_unstable: float = 0.2, backend: Literal['plotly', 'matplotlib'] = 'plotly', ternary_style: Literal['2d', '3d'] = '2d', **plotkwargs)[source]
Bases:
objectA plotting class for compositional phase diagrams.
To use, initialize this class with a PhaseDiagram object containing 1-4 components and call get_plot() or show().
- Parameters:
phasediagram (PhaseDiagram) – PhaseDiagram object (must be 1-4 components).
show_unstable (float) – Whether unstable (above the hull) phases will be plotted. If a number > 0 is entered, all phases with e_hull < show_unstable (eV/atom) will be shown.
backend ("plotly" | "matplotlib") – Python package to use for plotting. Defaults to “plotly”.
ternary_style ("2d" | "3d") – Ternary phase diagrams are typically plotted in two-dimensions (2d), but can be plotted in three dimensions (3d) to visualize the depth of the hull. This argument only applies when backend=”plotly”. Defaults to “2d”.
**plotkwargs (dict) –
Keyword args passed to matplotlib.pyplot.plot (only applies when backend=”matplotlib”). Can be used to customize markers etc. If not set, the default is:
- {
“markerfacecolor”: “#4daf4a”, “markersize”: 10, “linewidth”: 3
}.
- get_chempot_range_map_plot(elements: Sequence[Element], referenced: bool = True) plt.Axes[source]
Get a plot of the chemical potential range _map. Currently works only for 3-component PDs.
Note: this functionality is now included in the ChemicalPotentialDiagram class (pymatgen.analysis.chempot_diagram).
- Parameters:
elements – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to uLi and uO, you will supply [Element(“Li”), Element(“O”)]
referenced – if True, gives the results with a reference being the energy of the elemental phase. If False, gives absolute values.
- Returns:
matplotlib axes object.
- Return type:
plt.Axes
- get_contour_pd_plot() Axes[source]
Plot a contour phase diagram plot, where phase triangles are colored according to degree of instability by interpolation. Currently only works for 3-component phase diagrams.
- Returns:
A matplotlib plot object.
- get_plot(label_stable: bool = True, label_unstable: bool = True, ordering: Sequence[Literal['Up', 'Left', 'Right']] | None = None, energy_colormap: str | Colormap | None = None, process_attributes: bool = False, ax: plt.Axes | None = None, label_uncertainties: bool = False, fill: bool = True, highlight_entries: Collection[PDEntry] | None = None) go.Figure | plt.Axes | None[source]
- Parameters:
label_stable – Whether to label stable compounds.
label_unstable – Whether to label unstable compounds.
ordering – Ordering of vertices, given as a list [“Up”, “Left”, “Right”] (matplotlib only).
energy_colormap – Colormap for coloring energy (matplotlib only).
process_attributes – Whether to process the attributes (matplotlib only).
ax – Existing matplotlib Axes object if plotting multiple phase diagrams (matplotlib only).
label_uncertainties – Whether to add error bars to the hull. For binaries, this also shades the hull with the uncertainty window. (plotly only).
fill – Whether to shade the hull. For ternary_2d and quaternary plots, this colors facets arbitrarily for visual clarity. For ternary_3d plots, this shades the hull by formation energy (plotly only).
highlight_entries – Entries to highlight in the plot (plotly only). This will create a new marker trace that is separate from the other entries.
- Returns:
Plotly figure or matplotlib axes object depending on backend.
- Return type:
go.Figure | plt.Axes
- property pd_plot_data: tuple[list, dict, dict][source]
Plotting data for phase diagram. Cached for repetitive calls.
2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangles
- Returns:
lines: a list of list of coordinates for lines in the PD.
- stable_entries: a dict of {coordinates: entry} for each stable node
in the phase diagram. (Each coordinate can only have one stable phase)
- unstable_entries: a dict of {entry: coordinates} for all unstable
nodes in the phase diagram.
- Return type:
A tuple containing three objects (lines, stable_entries, unstable_entries)
- plot_chempot_range_map(elements: Sequence[Element], referenced: bool = True) None[source]
Plot the chemical potential range _map using matplotlib. Currently works only for 3-component PDs. This shows the plot but does not return it.
Note: this functionality is now included in the ChemicalPotentialDiagram class (pymatgen.analysis.chempot_diagram).
- Parameters:
elements – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to uLi and uO, you will supply [Element(“Li”), Element(“O”)]
referenced – if True, gives the results with a reference being the energy of the elemental phase. If False, gives absolute values.
- plot_element_profile(element: Element, comp: Composition, show_label_index: list[int] | None = None, xlim: float = 5) Axes[source]
Draw the element profile plot for a composition varying different chemical potential of an element.
X value is the negative value of the chemical potential reference to elemental chemical potential. For example, if choose Element(“Li”), X= -(μLi-μLi0), which corresponds to the voltage versus metal anode. Y values represent for the number of element uptake in this composition (unit: per atom). All reactions are printed to help choosing the profile steps you want to show label in the plot.
- Parameters:
element (Element) – An element of which the chemical potential is considered. It also must be in the phase diagram.
comp (Composition) – A composition.
show_label_index (list of integers) – The labels for reaction products you want to show in the plot. Default to None (not showing any annotation for reaction products). For the profile steps you want to show the labels, just add it to the show_label_index. The profile step counts from zero. For example, you can set show_label_index=[0, 2, 5] to label profile step 0,2,5.
xlim (float) – The max x value. x value is from 0 to xlim. Default to 5 eV.
- Returns:
Plot of element profile evolution by varying the chemical potential of an element.
- show(*args, **kwargs) None[source]
Draw the phase diagram with the provided arguments and display it. This shows the figure but does not return it.
- Parameters:
*args – Passed to get_plot.
**kwargs – Passed to get_plot.
- write_image(stream: str | StringIO, image_format: str = 'svg', **kwargs) None[source]
Directly save the plot to a file. This is a wrapper for calling plt.savefig() or fig.write_image(), depending on the backend. For more customization, it is recommended to call those methods directly.
- Parameters:
stream (str | StringIO) – Filename or StringIO stream.
image_format (str) – Can be any supported image format for the plotting backend. Defaults to ‘svg’ (vector graphics).
**kwargs – Optinoal kwargs passed to the get_plot function.
- class PatchedPhaseDiagram(entries: Sequence[Entry] | set[Entry], elements: Sequence[Element] | None = None, keep_all_spaces: bool = False, verbose: bool = False, *, computed_data: dict[str, Any] | None = None)[source]
Bases:
PhaseDiagramComputing the Convex Hull of a large set of data in multiple dimensions is highly expensive. This class acts to breakdown large chemical spaces into smaller chemical spaces which can be computed much more quickly due to having both reduced dimensionality and data set sizes.
- subspaces ({str
{Element, }}): Dictionary of the sets of elements for each of the PhaseDiagrams within the PatchedPhaseDiagram.
- pds ({str
PhaseDiagram}): Dictionary of PhaseDiagrams within the PatchedPhaseDiagram.
- all_entries[source]
All entries provided for Phase Diagram construction. Note that this does not mean that all these entries are actually used in the phase diagram. For example, this includes the positive formation energy entries that are filtered out before Phase Diagram construction.
- Type:
list[PDEntry]
- min_entries[source]
List of the lowest energy entries for each composition in the data provided for Phase Diagram construction.
- Type:
list[PDEntry]
- el_refs[source]
List of elemental references for the phase diagrams. These are entries corresponding to the lowest energy element entries for simple compositional phase diagrams.
- Type:
list[PDEntry]
- NOTE following methods are inherited unchanged from PhaseDiagram:
__repr__
all_entries_hulldata
unstable_entries
stable_entries
get_form_energy
get_form_energy_per_atom
get_hull_energy
get_e_above_hull
get_decomp_and_e_above_hull
get_decomp_and_phase_separation_energy
get_phase_separation_energ
- Parameters:
entries (Sequence[Entry] | set[Entry]) – A list of Entry objects having an energy, energy_per_atom and composition.
elements (Sequence[Element], optional) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the entries themselves and are sorted alphabetically. If specified, element ordering (e.g. for pd coordinates) is preserved.
keep_all_spaces (bool) – Pass True to keep chemical spaces that are subspaces of other spaces.
verbose (bool) – Whether to show progress bar during convex hull construction.
computed_data (dict) – A dict containing pre-computed data. This allows PatchedPhaseDiagram object to be reconstituted without performing the expensive convex hull computation. The dict is the output from the PatchedPhaseDiagram._compute() method.
- as_dict() dict[str, Any][source]
Write the entries and elements used to construct the PatchedPhaseDiagram to a dictionary.
- classmethod from_dict(dct: dict) Self[source]
Reconstruct PatchedPhaseDiagram from dictionary serialization.
- Parameters:
dct (dict) – dictionary representation of PatchedPhaseDiagram.
- Returns:
PatchedPhaseDiagram
- get_decomp_and_e_above_hull(entry: PDEntry, allow_negative: bool = False, check_stable: bool = False, on_error: Literal['raise', 'warn', 'ignore'] = 'raise') tuple[dict[PDEntry, float], float] | tuple[None, None][source]
Same as method on parent class PhaseDiagram except check_stable defaults to False for speed. See https://github.com/materialsproject/pymatgen/issues/2840 for details.
- get_decomposition(comp: Composition) dict[PDEntry, float][source]
See PhaseDiagram.
- Parameters:
comp (Composition) – A composition
- Returns:
amount} where amount is the amount of the fractional composition.
- Return type:
Decomposition as a dict of {PDEntry
- get_equilibrium_reaction_energy(entry: Entry) float[source]
See PhaseDiagram.
NOTE this is only approximately the same as the what we would get from PhaseDiagram as we make use of the slsqp approach inside get_phase_separation_energy().
- Parameters:
entry (PDEntry) – A PDEntry like object
- Returns:
Equilibrium reaction energy of entry. Stable entries should have equilibrium reaction energy <= 0. The energy is given per atom.
- get_pd_for_entry(entry: Entry | Composition) PhaseDiagram[source]
Get the possible phase diagrams for an entry.
- Parameters:
entry (PDEntry | Composition) – A PDEntry or Composition-like object
- Returns:
phase diagram that the entry is part of
- Return type:
- Raises:
ValueError – If no suitable PhaseDiagram is found for the entry.
- class PhaseDiagram(entries: Collection[Entry], elements: Collection[Element] | None = None, *, computed_data: dict[str, Any] | None = None)[source]
Bases:
MSONableSimple phase diagram class taking in elements and entries as inputs. The algorithm is based on the work in the following papers:
Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from
First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807. doi:10.1021/cm702327g
Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities
of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first principles calculations. Electrochem. Comm., 2010, 12(3), 427-430. doi:10.1016/j.elecom.2010.01.010
- el_refs[source]
List of elemental references for the phase diagrams. These are entries corresponding to the lowest energy element entries for simple compositional phase diagrams.
- all_entries[source]
All entries provided for Phase Diagram construction. Note that this does not mean that all these entries are actually used in the phase diagram. For example, this includes the positive formation energy entries that are filtered out before Phase Diagram construction.
- qhull_entries[source]
Actual entries used in convex hull. Excludes all positive formation energy entries.
- qhull_data[source]
Data used in the convex hull operation. This is essentially a matrix of composition data and energy per atom values created from qhull_entries.
- facets[source]
Facets of the phase diagram in the form of [[1,2,3],[4,5,6]…]. For a ternary, it is the indices (references to qhull_entries and qhull_data) for the vertices of the phase triangles. Similarly extended to higher D simplices for higher dimensions.
- simplices[source]
The simplices of the phase diagram as a list of np.ndarray, i.e., the list of stable compositional coordinates in the phase diagram.
- Parameters:
entries (list[PDEntry]) – A list of PDEntry-like objects having an energy, energy_per_atom and composition.
elements (list[Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the entries themselves and are sorted alphabetically. If specified, element ordering (e.g. for pd coordinates) is preserved.
computed_data (dict) – A dict containing pre-computed data. This allows PhaseDiagram object to be reconstituted without performing the expensive convex hull computation. The dict is the output from the PhaseDiagram._compute() method and is stored in PhaseDiagram.computed_data when generated for the first time.
- classmethod from_dict(dct: dict[str, Any]) Self[source]
- Parameters:
dct (dict) – dictionary representation of PhaseDiagram.
- Returns:
PhaseDiagram
- get_all_chempots(comp: Composition) dict[str, dict[Element, float]][source]
Get chemical potentials at a given composition.
- Parameters:
comp (Composition) – Composition
- Returns:
Chemical potentials.
- get_chempot_range_map(elements: Sequence[Element], referenced: bool = True, joggle: bool = True) dict[Element, list[Simplex]][source]
Get a chemical potential range map for each stable entry.
- Parameters:
elements – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases with respect to mu_Li and mu_O, you will supply [Element(“Li”), Element(“O”)]
referenced – If True, gives the results with a reference being the energy of the elemental phase. If False, gives absolute values.
joggle (bool) – Whether to joggle the input to avoid precision errors.
- Returns:
[simplices]}. The list of simplices are the sides of the N-1 dim polytope bounding the allowable chemical potential range of each entry.
- Return type:
Returns a dict of the form {entry
- get_chempot_range_stability_phase(target_comp: Composition, open_elt: Element) dict[Element, tuple[float, float]][source]
Get a set of chemical potentials corresponding to the max and min chemical potential of the open element for a given composition. It is quite common to have for instance a ternary oxide (e.g., ABO3) for which you want to know what are the A and B chemical potential leading to the highest and lowest oxygen chemical potential (reducing and oxidizing conditions). This is useful for defect computations.
- Parameters:
target_comp – A Composition object
open_elt – Element that you want to constrain to be max or min
- Returns:
A dictionary of the form {Element: (min_mu, max_mu)} where min_mu and max_mu are the minimum and maximum chemical potentials for the given element (as “absolute” values, i.e. not referenced to 0).
- Return type:
dict[Element, (float, float)]
- get_composition_chempots(comp: Composition) dict[Element, float][source]
Get the chemical potentials for all elements at a given composition.
- Parameters:
comp (Composition) – Composition
- Returns:
Dictionary of chemical potentials.
- get_critical_compositions(comp1: Composition, comp2: Composition) list[Composition][source]
Get the critical compositions along the tieline between two compositions. I.e. where the decomposition products change. The endpoints are also returned.
- Parameters:
comp1 (Composition) – First composition to define the tieline
comp2 (Composition) – Second composition to define the tieline
- Returns:
- list of critical compositions. All are of
the form x * comp1 + (1-x) * comp2
- Return type:
[(Composition)]
- get_decomp_and_e_above_hull(entry: PDEntry, allow_negative: bool = False, check_stable: bool = True, on_error: Literal['raise', 'warn', 'ignore'] = 'raise') tuple[dict[PDEntry, float], float] | tuple[None, None][source]
Provides the decomposition and energy above convex hull for an entry. Due to caching, can be much faster if entries with the same composition are processed together.
- Parameters:
entry (PDEntry) – A PDEntry like object
allow_negative (bool) – Whether to allow negative e_above_hulls. Used to calculate equilibrium reaction energies. Defaults to False.
check_stable (bool) – Whether to first check whether an entry is stable. In normal circumstances, this is the faster option since checking for stable entries is relatively fast. However, if you have a huge proportion of unstable entries, then this check can slow things down. You should then set this to False.
on_error ('raise' | 'warn' | 'ignore') – What to do if no valid decomposition was found. ‘raise’ will throw ValueError. ‘warn’ will print return (None, None). ‘ignore’ just returns (None, None). Defaults to ‘raise’.
- Raises:
ValueError – If on_error is ‘raise’ and no valid decomposition exists in this phase diagram for given entry.
- Returns:
- The decomposition is provided
as a dict of {PDEntry: amount} where amount is the amount of the fractional composition. Stable entries should have energy above convex hull of 0. The energy is given per atom.
- Return type:
tuple[decomp, energy_above_hull]
- get_decomp_and_hull_energy_per_atom(comp: Composition) tuple[dict[PDEntry, float], float][source]
- Parameters:
comp (Composition) – Input composition.
- Returns:
Energy of lowest energy equilibrium at desired composition per atom
- get_decomp_and_phase_separation_energy(entry: PDEntry, space_limit: int = 200, stable_only: bool = False, tols: Sequence[float] = (1e-08,), maxiter: int = 1000, **kwargs: Any) tuple[dict[PDEntry, float], float] | tuple[None, None][source]
Provides the combination of entries in the PhaseDiagram that gives the lowest formation enthalpy with the same composition as the given entry excluding entries with the same composition and the energy difference per atom between the given entry and the energy of the combination found.
For unstable entries that are not polymorphs of stable entries (or completely novel entries) this is simply the energy above (or below) the convex hull.
For entries with the same composition as one of the stable entries in the phase diagram setting stable_only to False (Default) allows for entries not previously on the convex hull to be considered in the combination. In this case the energy returned is what is referred to as the decomposition enthalpy in:
- Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,
A critical examination of compound stability predictions from machine-learned formation energies, npj Computational Materials 6, 97 (2020)
For stable entries setting stable_only to True returns the same energy as get_equilibrium_reaction_energy. This function is based on a constrained optimization rather than recalculation of the convex hull making it algorithmically cheaper. However, if tol is too loose there is potential for this algorithm to converge to a different solution.
- Parameters:
entry (PDEntry) – A PDEntry like object.
space_limit (int) – The maximum number of competing entries to consider before calculating a second convex hull to reducing the complexity of the optimization.
stable_only (bool) – Only use stable materials as competing entries.
tols (list[float]) – Tolerances for convergence of the SLSQP optimization when finding the equilibrium reaction. Tighter tolerances tested first.
maxiter (int) – The maximum number of iterations of the SLSQP optimizer when finding the equilibrium reaction.
**kwargs – Passed to get_decomp_and_e_above_hull.
- Returns:
- The decomposition is given as a dict of {PDEntry, amount}
for all entries in the decomp reaction where amount is the amount of the fractional composition. The phase separation energy is given per atom.
- Return type:
tuple[decomp, energy]
- get_decomposition(comp: Composition) dict[PDEntry, float][source]
Provides the decomposition at a particular composition.
- Parameters:
comp (Composition) – A composition
- Returns:
amount} where amount is the amount of the fractional composition.
- Return type:
Decomposition as a dict of {PDEntry
- get_e_above_hull(entry: PDEntry, **kwargs: Any) float | None[source]
Provides the energy above convex hull for an entry.
- Parameters:
entry (PDEntry) – A PDEntry like object.
**kwargs – Passed to get_decomp_and_e_above_hull().
- Returns:
- Energy above convex hull of entry. Stable entries should have
energy above hull of 0. The energy is given per atom.
- Return type:
float | None
- get_element_profile(element: Element, comp: Composition, comp_tol: float = 1e-05) list[dict[str, Any]][source]
Provides the element evolution data for a composition. For example, can be used to analyze Li conversion voltages by varying mu_Li and looking at the phases formed. Also can be used to analyze O2 evolution by varying mu_O2.
- Parameters:
element – An element. Must be in the phase diagram.
comp – A Composition
comp_tol – The tolerance to use when calculating decompositions. Phases with amounts less than this tolerance are excluded. Defaults to 1e-5.
- Returns:
[ {‘chempot’: -10.487582, ‘evolution’: -2.0, ‘reaction’: Reaction Object], …]
- Return type:
Evolution data as a list of dictionaries of the following format
- get_equilibrium_reaction_energy(entry: PDEntry) float | None[source]
Provides the reaction energy of a stable entry from the neighboring equilibrium stable entries (also known as the inverse distance to hull).
- Parameters:
entry (PDEntry) – A PDEntry like object
- Returns:
- Equilibrium reaction energy of entry. Stable entries should have
equilibrium reaction energy <= 0. The energy is given per atom.
- Return type:
float | None
- get_form_energy(entry: PDEntry) float[source]
Get the formation energy for an entry (NOT normalized) from the elemental references.
- Parameters:
entry (PDEntry) – A PDEntry-like object.
- Returns:
Formation energy from the elemental references.
- Return type:
float
- get_form_energy_per_atom(entry: PDEntry) float[source]
Get the formation energy per atom for an entry from the elemental references.
- Parameters:
entry (PDEntry) – An PDEntry-like object
- Returns:
Formation energy per atom from the elemental references.
- get_hull_energy(comp: Composition) float[source]
- Parameters:
comp (Composition) – Input composition.
- Returns:
- Energy of lowest energy equilibrium at desired composition. Not
normalized by atoms, i.e. E(Li4O2) = 2 * E(Li2O)
- get_hull_energy_per_atom(comp: Composition, **kwargs) float[source]
- Parameters:
comp (Composition) – Input composition.
- Returns:
Energy of lowest energy equilibrium at desired composition.
- get_phase_separation_energy(entry: PDEntry, **kwargs)[source]
Provides the energy to the convex hull for the given entry. For stable entries already in the phase diagram the algorithm provides the phase separation energy which is referred to as the decomposition enthalpy in:
- Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,
A critical examination of compound stability predictions from machine-learned formation energies, npj Computational Materials 6, 97 (2020)
- Parameters:
entry (PDEntry) – A PDEntry like object
**kwargs –
Keyword args passed to get_decomp_and_phase_separation_energy space_limit (int): The maximum number of competing entries to consider. stable_only (bool): Only use stable materials as competing entries tol (float): The tolerance for convergence of the SLSQP optimization
when finding the equilibrium reaction.
- maxiter (int): The maximum number of iterations of the SLSQP optimizer
when finding the equilibrium reaction.
- Returns:
phase separation energy per atom of entry. Stable entries should have energies <= 0, Stable elemental entries should have energies = 0 and unstable entries should have energies > 0. Entries that have the same composition as a stable energy may have positive or negative phase separation energies depending on their own energy.
- get_plot(show_unstable: float = 0.2, backend: Literal['plotly', 'matplotlib'] = 'plotly', ternary_style: Literal['2d', '3d'] = '2d', label_stable: bool = True, label_unstable: bool = True, ordering: Sequence[Literal['Up', 'Left', 'Right']] | None = None, energy_colormap: str | Colormap | None = None, process_attributes: bool = False, ax: plt.Axes | None = None, label_uncertainties: bool = False, fill: bool = True, **kwargs) go.Figure | plt.Axes[source]
Convenient wrapper for PDPlotter. Initializes a PDPlotter object and calls get_plot() with provided combined arguments.
Plotting is only supported for phase diagrams with <=4 elements (unary, binary, ternary, or quaternary systems).
- Parameters:
show_unstable (float) – Whether unstable (above the hull) phases will be plotted. If a number > 0 is entered, all phases with e_hull < show_unstable (eV/atom) will be shown.
backend ("plotly" | "matplotlib") – Python package to use for plotting. Defaults to “plotly”.
ternary_style ("2d" | "3d") – Ternary phase diagrams are typically plotted in two-dimensions (2d), but can be plotted in three dimensions (3d) to visualize the depth of the hull. This argument only applies when backend=”plotly”. Defaults to “2d”.
label_stable – Whether to label stable compounds.
label_unstable – Whether to label unstable compounds.
ordering – Ordering of vertices (matplotlib backend only).
energy_colormap – Colormap for coloring energy (matplotlib backend only).
process_attributes – Whether to process the attributes (matplotlib backend only).
ax – Existing Axes object if plotting multiple phase diagrams (matplotlib backend only).
label_uncertainties – Whether to add error bars to the hull (plotly backend only). For binaries, this also shades the hull with the uncertainty window.
fill – Whether to shade the hull. For ternary_2d and quaternary plots, this colors facets arbitrarily for visual clarity. For ternary_3d plots, this shades the hull by formation energy (plotly backend only).
**kwargs (dict) – Keyword args passed to PDPlotter.get_plot(). Can be used to customize markers etc. If not set, the default is { “markerfacecolor”: “#4daf4a”, “markersize”: 10, “linewidth”: 3 }
- get_reference_energy(comp: Composition) float[source]
Sum of elemental reference energies over all elements in a composition.
- Parameters:
comp (Composition) – Input composition.
- Returns:
Reference energy
- Return type:
float
- get_reference_energy_per_atom(comp: Composition) float[source]
Sum of elemental reference energies over all elements in a composition.
- Parameters:
comp (Composition) – Input composition.
- Returns:
Reference energy per atom
- Return type:
float
- get_transition_chempots(element: Element) tuple[float, ...][source]
Get the critical chemical potentials for an element in the Phase Diagram.
- Parameters:
element – An element. Has to be in the PD in the first place.
- Returns:
A sorted sequence of critical chemical potentials, from less negative to more negative.
- getmu_vertices_stability_phase(target_comp: Composition, dep_elt: Element, tol_en: float = 0.01) list[dict[Element, float]] | None[source]
Get a set of chemical potentials corresponding to the vertices of the simplex in the chemical potential phase diagram. The simplex is built using all elements in the target_composition except dep_elt. The chemical potential of dep_elt is computed from the target composition energy. This method is useful to get the limiting conditions for defects computations for instance.
- Parameters:
target_comp – A Composition object
dep_elt – the element for which the chemical potential is computed from the energy of the stable phase at the target composition
tol_en – a tolerance on the energy to set
- Returns:
mu}]: An array of conditions on simplex vertices for which each element has a chemical potential set to a given value. “absolute” values (i.e., not referenced to element energies)
- Return type:
[{Element
- pd_coords(comp: Composition) ndarray[source]
The phase diagram is generated in a reduced dimensional space (n_elements - 1). This function returns the coordinates in that space. These coordinates are compatible with the stored simplex objects.
- Parameters:
comp (Composition) – A composition
- Returns:
The coordinates for a given composition in the PhaseDiagram’s basis
- exception PhaseDiagramError[source]
Bases:
ExceptionAn exception class for Phase Diagram generation.
- class ReactionDiagram(entry1: ComputedEntry, entry2: ComputedEntry, all_entries: list[ComputedEntry], tol: float = 0.0001, float_fmt: str = '%.4f')[source]
Bases:
objectAnalyzes the possible reactions between a pair of compounds, e.g. an electrolyte and an electrode.
- Parameters:
entry1 (ComputedEntry) – Entry for 1st component. Note that corrections, if any, must already be pre-applied. This is to give flexibility for different kinds of corrections, e.g. if a particular entry is fitted to an experimental data (such as EC molecule).
entry2 (ComputedEntry) – Entry for 2nd component. Note that corrections must already be pre-applied. This is to give flexibility for different kinds of corrections, e.g. if a particular entry is fitted to an experimental data (such as EC molecule).
all_entries ([ComputedEntry]) – All other entries to be considered in the analysis. Note that corrections, if any, must already be pre-applied.
tol (float) – Tolerance to be used to determine validity of reaction. Defaults to 1e-4.
float_fmt (str) – Formatting string to be applied to all floats. Determines number of decimal places in reaction string. Defaults to “%.4f”.
- get_compound_pd() CompoundPhaseDiagram[source]
Get the CompoundPhaseDiagram object, which can then be used for plotting.
- Returns:
CompoundPhaseDiagram
- class TransformedPDEntry(entry, sp_mapping, name=None)[source]
Bases:
PDEntryThis class represents a TransformedPDEntry, which allows for a PDEntry to be transformed to a different composition coordinate space. It is used in the construction of phase diagrams that do not have elements as the terminal compositions.
- Parameters:
entry (PDEntry) – Original entry to be transformed.
({Composition (sp_mapping) – DummySpecies}): dictionary mapping Terminal Compositions to Dummy Species.
- property composition: Composition[source]
The composition in the dummy species space.
- Returns:
Composition
- exception TransformedPDEntryError[source]
Bases:
ExceptionAn exception class for TransformedPDEntry.
- get_facets(qhull_data: ArrayLike, joggle: bool = False) ConvexHull[source]
Get the simplex facets for the Convex hull.
- Parameters:
qhull_data (np.ndarray) – The data from which to construct the convex hull as a Nxd array (N being number of data points and d being the dimension)
joggle (bool) – Whether to joggle the input to avoid precision errors.
- Returns:
with list of simplices of the convex hull.
- Return type:
scipy.spatial.ConvexHull
- order_phase_diagram(lines: list, stable_entries: dict[Any, PDEntry], unstable_entries: dict[PDEntry, Any], ordering: Sequence[Literal['Up', 'Left', 'Right']]) tuple[list, dict[Any, PDEntry], dict[PDEntry, Any]][source]
Orders the entries (their coordinates) in a phase diagram plot according to the user specified ordering. Ordering should be given as [‘Up’, ‘Left’, ‘Right’], where Up, Left and Right are the names of the entries in the upper, left and right corners of the triangle respectively.
- Parameters:
lines – list of list of coordinates for lines in the PD.
stable_entries – {coordinate : entry} for each stable node in the phase diagram. (Each coordinate can only have one stable phase)
unstable_entries – {entry: coordinates} for all unstable nodes in the phase diagram.
ordering – Ordering of the phase diagram, given as a list [‘Up’, ‘Left’,’Right’]
- Returns:
a list of list of coordinates for lines in the PD.
a {coordinate: entry} for each stable node
in the phase diagram. (Each coordinate can only have one stable phase) - a {entry: coordinates} for all unstable nodes in the phase diagram.
- Return type:
tuple[list, dict, dict]
- tet_coord(coord: ArrayLike) np.ndarray[source]
Convert a 3D coordinate into a tetrahedron based coordinate system for a prettier phase diagram.
- Parameters:
coord – coordinate used in the convex hull computation.
- Returns:
coordinates in a tetrahedron-based coordinate system.
- triangular_coord(coord: ArrayLike) np.ndarray[source]
Convert a 2D coordinate into a triangle-based coordinate system for a prettier phase diagram.
- Parameters:
coord – coordinate used in the convex hull computation.
- Returns:
coordinates in a triangular-based coordinate system.
- uniquelines(q: list[NDArray[int]]) set[tuple[int, int]][source]
Given all the facets, convert it into a set of unique lines. Specifically used for converting convex hull facets into line pairs of coordinates.
- Parameters:
q – A 2-dim sequence, where each row represents a facet. e.g. [[1, 2, 3], [3, 6, 7], …]
- Returns:
A set of tuple of lines. e.g. ((1, 2), (1, 3), …)
- Return type:
setoflines
pymatgen.analysis.piezo module
This module provides classes for the Piezoelectric tensor.
- class PiezoTensor(input_array: ArrayLike, tol: float = 0.001)[source]
Bases:
TensorThis class describes the 3x6 piezo tensor in Voigt notation.
Create an PiezoTensor object. The constructor throws an error if the shape of the input_matrix argument is not 3x3x3, i.e. in true tensor notation. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays.
- Parameters:
input_matrix (3x3x3 array-like) – the 3x6 array-like representing the piezo tensor
pymatgen.analysis.piezo_sensitivity module
Piezo sensitivity analysis module.
- class BornEffectiveCharge(structure: Structure, bec, pointops, tol: float = 0.001)[source]
Bases:
objectThis class describes the Nx3x3 born effective charge tensor.
Create an BornEffectiveChargeTensor object defined by a structure, point operations of the structure’s atomic sites. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays.
- Parameters:
input_matrix (Nx3x3 array-like) – the Nx3x3 array-like representing the born effective charge tensor
- get_BEC_operations(eigtol=1e-05, opstol=0.001)[source]
Get the symmetry operations which maps the tensors belonging to equivalent sites onto each other in the form [site index 1, site index 2, [Symmops mapping from site index 1 to site index 2]].
- Parameters:
eigtol (float) – tolerance for determining if two sites are
symmetry (related by)
opstol (float) – tolerance for determining if a symmetry
sites (operation relates two)
- Returns:
list of symmetry operations mapping equivalent sites and the indexes of those sites.
- class ForceConstantMatrix(structure: Structure, fcm, pointops, sharedops, tol: float = 0.001)[source]
Bases:
objectThis class describes the NxNx3x3 force constant matrix defined by a structure, point operations of the structure’s atomic sites, and the shared symmetry operations between pairs of atomic sites.
Create an ForceConstantMatrix object.
- Parameters:
input_matrix (NxNx3x3 array-like) – the NxNx3x3 array-like representing the force constant matrix
- get_FCM_operations(eigtol=1e-05, opstol=1e-05)[source]
Get the symmetry operations which maps the tensors belonging to equivalent sites onto each other in the form [site index 1a, site index 1b, site index 2a, site index 2b, [Symmops mapping from site index 1a, 1b to site index 2a, 2b]].
- Parameters:
eigtol (float) – tolerance for determining if two sites are
symmetry (related by)
opstol (float) – tolerance for determining if a symmetry
sites (operation relates two)
- Returns:
list of symmetry operations mapping equivalent sites and the indexes of those sites.
- get_asum_FCM(fcm: ndarray, numiter: int = 15)[source]
Generate a symmetrized force constant matrix that obeys the objects symmetry constraints and obeys the acoustic sum rule through an iterative procedure.
- Parameters:
fcm (numpy array) – 3Nx3N unsymmetrized force constant matrix
numiter (int) – number of iterations to attempt to obey the acoustic sum rule
- Returns:
numpy array representing the force constant matrix
- get_rand_FCM(asum=15, force=10)[source]
Generate a symmetrized force constant matrix from an unsymmetrized matrix that has no unstable modes and also obeys the acoustic sum rule through an iterative procedure.
- Parameters:
force (float) – maximum force constant
asum (int) – number of iterations to attempt to obey the acoustic sum rule
- Returns:
NxNx3x3 np.array representing the force constant matrix
- get_stable_FCM(fcm, fcmasum=10)[source]
Generate a symmetrized force constant matrix that obeys the objects symmetry constraints, has no unstable modes and also obeys the acoustic sum rule through an iterative procedure.
- Parameters:
fcm (numpy array) – unsymmetrized force constant matrix
fcmasum (int) – number of iterations to attempt to obey the acoustic sum rule
- Returns:
3Nx3N numpy array representing the force constant matrix
- get_symmetrized_FCM(unsymmetrized_fcm, max_force=1)[source]
Generate a symmetrized force constant matrix from an unsymmetrized matrix.
- Parameters:
unsymmetrized_fcm (numpy array) – unsymmetrized force constant matrix
max_charge (float) – maximum born effective charge value
- Returns:
3Nx3N numpy array representing the force constant matrix
- class InternalStrainTensor(structure: Structure, ist, pointops, tol: float = 0.001)[source]
Bases:
objectThis class describes the Nx3x3x3 internal tensor defined by a structure, point operations of the structure’s atomic sites.
Create an InternalStrainTensor object.
- Parameters:
input_matrix (Nx3x3x3 array-like) – the Nx3x3x3 array-like representing the internal strain tensor
- get_IST_operations(opstol=0.001) list[list[list]][source]
Get the symmetry operations which maps the tensors belonging to equivalent sites onto each other in the form [site index 1, site index 2, [SymmOps mapping from site index 1 to site index 2]].
- Parameters:
opstol (float) – tolerance for determining if a symmetry
sites (operation relates two)
- Returns:
symmetry operations mapping equivalent sites and the indexes of those sites.
- Return type:
list[list[list]]
- get_piezo(BEC, IST, FCM, rcond=0.0001)[source]
Generate a random piezoelectric tensor based on a structure and corresponding symmetry.
- Parameters:
BEC (numpy array) – Nx3x3 array representing the born effective charge tensor
IST (numpy array) – Nx3x3x3 array representing the internal strain tensor
FCM (numpy array) – NxNx3x3 array representing the born effective charge tensor
rcondy (float) – condition for excluding eigenvalues in the pseudoinverse
- Returns:
3x3x3 calculated Piezo tensor
- rand_piezo(struct, pointops, sharedops, BEC, IST, FCM, anumiter=10)[source]
Generate a random piezoelectric tensor based on a structure and corresponding symmetry.
- Parameters:
struct (pymatgen structure) – structure whose symmetry operations the piezo tensor must obey
pointops – list of point operations obeyed by a single atomic site
sharedops – list of point operations shared by a pair of atomic sites
BEC (numpy array) – Nx3x3 array representing the born effective charge tensor
IST (numpy array) – Nx3x3x3 array representing the internal strain tensor
FCM (numpy array) – NxNx3x3 array representing the born effective charge tensor
anumiter (int) – number of iterations for acoustic sum rule convergence
- Returns:
list in the form of [Nx3x3 random born effective charge tenosr, Nx3x3x3 random internal strain tensor, NxNx3x3 random force constant matrix, 3x3x3 piezo tensor]
pymatgen.analysis.pourbaix_diagram module
This module is intended to be used to compute Pourbaix diagrams of arbitrary compositions and formation energies.
- class IonEntry(ion: Ion, energy: float, name: str | None = None, attribute=None)[source]
Bases:
PDEntryObject similar to PDEntry, but contains an Ion object instead of a Composition object.
- name[source]
A name for the entry. This is the string shown in the phase diagrams. By default, this is the reduced formula for the composition, but can be set to some other string for display purposes.
- Type:
str
- Parameters:
ion – Ion object
energy – Energy for composition.
name – Optional parameter to name the entry. Defaults to the chemical formula.
attribute – Optional attribute of the entry, e.g. band gap.
- class MultiEntry(entry_list: Sequence[PourbaixEntry], weights: list[float] | None = None)[source]
Bases:
PourbaixEntryPourbaixEntry-like object for constructing multi-elemental Pourbaix diagrams.
Initialize a MultiEntry.
- Parameters:
entry_list (Sequence[PourbaixEntry]) – Component PourbaixEntries.
weights (list[float]) – Weights associated with each entry. Default is None
- class PourbaixDiagram(entries: list[PourbaixEntry] | list[MultiEntry], comp_dict: dict[str, float] | None = None, conc_dict: dict[str, float] | None = None, filter_solids: bool = True, nproc: int | None = None)[source]
Bases:
MSONableCreate a Pourbaix diagram from entries.
- Parameters:
entries ([PourbaixEntry] or [MultiEntry]) – Entries list containing Solids and Ions or a list of MultiEntries
comp_dict (dict[str, float]) – Dictionary of compositions, defaults to equal parts of each elements
conc_dict (dict[str, float]) – Dictionary of ion concentrations, defaults to 1e-6 for each element
filter_solids (bool) – applying this filter to a Pourbaix diagram ensures all included solid phases are filtered by stability on the compositional phase diagram. Defaults to True. The practical consequence of this is that highly oxidized or reduced phases that might show up in experiments due to kinetic limitations on oxygen/hydrogen evolution won’t appear in the diagram, but they are not actually “stable” (and are frequently overstabilized from DFT errors). Hence, including only the stable solid phases generally leads to the most accurate Pourbaix diagrams.
nproc (int) – number of processes to generate multi-entries with in parallel. Defaults to None (serial processing).
- find_stable_entry(pH: float, V: float) PourbaixEntry[source]
Find stable entry at a pH,V condition.
- Parameters:
pH (float) – pH to find stable entry
V (float) – V to find stable entry.
- Returns:
stable entry at pH, V
- Return type:
- classmethod from_dict(dct: dict) Self[source]
- Parameters:
dct (dict) – Dict representation.
- Returns:
PourbaixDiagram
- get_decomposition_energy(entry: PourbaixEntry, pH: float, V: float) NDArray[source]
Find decomposition to most stable entries in eV/atom, supports vectorized inputs for pH and V.
- Parameters:
entry (PourbaixEntry) – PourbaixEntry corresponding to compound to find the decomposition for
pH (float) – pH at which to find the decomposition
V (float) – voltage at which to find the decomposition
- Returns:
- Decomposition energy for the entry, i.e. the energy above
the “Pourbaix hull” in eV/atom at the given conditions
- get_hull_energy(pH: float | list[float], V: float | list[float]) NDArray[source]
Get the minimum energy of the Pourbaix “basin” that is formed from the stable Pourbaix planes. Vectorized.
- Parameters:
pH (float | list[float]) – pH at which to find the hull energy
V (float | list[float]) – V at which to find the hull energy
- Returns:
minimum Pourbaix energy at conditions
- Return type:
np.array
- static get_pourbaix_domains(pourbaix_entries: list[PourbaixEntry], limits: list[list[float]] | None = None) tuple[dict, dict][source]
Get a set of Pourbaix stable domains (i.e. polygons) in pH-V space from a list of pourbaix_entries.
This function works by using scipy’s HalfspaceIntersection function to construct all of the 2-D polygons that form the boundaries of the planes corresponding to individual entry gibbs free energies as a function of pH and V. Hyperplanes of the form a*pH + b*V + 1 - g(0, 0) are constructed and supplied to HalfspaceIntersection, which then finds the boundaries of each Pourbaix region using the intersection points.
- Parameters:
pourbaix_entries (list[PourbaixEntry]) – Pourbaix entries with which to construct stable Pourbaix domains
limits (list[list[float]]) – limits in which to do the pourbaix analysis
- Returns:
The first dict is of form: {entry: [boundary_points]}. The list of boundary points are the sides of the N-1 dim polytope bounding the allowable ph-V range of each entry.
- Return type:
tuple[dict[PourbaixEntry, list], dict[PourbaixEntry, NDArray]
- get_stable_entry(pH: float, V: float) PourbaixEntry | MultiEntry[source]
Get the stable entry at a given pH, V condition.
- Parameters:
pH (float) – pH at a given condition
V (float) – V at a given condition
- Returns:
- Pourbaix or multi-entry
corresponding to the minimum energy entry at a given pH, V condition
- Return type:
- static process_multientry(entry_list: Sequence, prod_comp: Composition, coeff_threshold: float = 0.0001) MultiEntry | None[source]
Static method for finding a multientry based on a list of entries and a product composition. Essentially checks to see if a valid aqueous reaction exists between the entries and the product composition and returns a MultiEntry with weights according to the coefficients if so.
- Parameters:
entry_list (Sequence[Entry]) – Entries from which to create a MultiEntry
prod_comp (Composition) – composition constraint for setting weights of MultiEntry
coeff_threshold (float) – threshold of stoichiometric coefficients to filter, if weights are lower than this value, the entry is not returned
- class PourbaixEntry(entry: ComputedEntry | ComputedStructureEntry, entry_id: str | None = None, concentration: float = 1e-06)[source]
Bases:
MSONable,StringifyAn object encompassing all data relevant to a solid or ion in a Pourbaix diagram. Each bulk solid/ion has an energy g of the form: e = e0 + 0.0591 log10(conc) - nO mu_H2O + (nH - 2nO) pH + phi (-nH + 2nO + q).
Note that the energies corresponding to the input entries should be formation energies with respect to hydrogen and oxygen gas in order for the Pourbaix diagram formalism to work. This may be changed to be more flexible in the future.
- Parameters:
entry (ComputedEntry | ComputedStructureEntry | PDEntry | IonEntry) – An entry object
entry_id (str) – A string id for the entry
concentration (float) – Concentration of the entry in M. Defaults to 1e-6.
- as_dict()[source]
Get dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object.
- property composition: Composition[source]
Composition.
- property conc_term: float[source]
The concentration contribution to the free energy. Should only be present when there are ions in the entry.
- property elements: list[Element | Species | DummySpecies][source]
Elements in the entry.
- energy_at_conditions(pH: float, V: float) float[source]
Get free energy for a given pH and V.
- Parameters:
pH (float) – pH at which to evaluate free energy
V (float) – voltage at which to evaluate free energy
- Returns:
free energy at conditions
- get_element_fraction(element: Element | str) float[source]
Get the elemental fraction of a given non-OH element.
- Parameters:
element (Element or str) – string or element corresponding to element to get from composition
- Returns:
fraction of element / sum(all non-OH elements)
- property normalization_factor: float[source]
Sum of number of atoms minus the number of H and O in composition.
- property normalized_energy: float[source]
Energy normalized by number of non H or O atoms, e.g. for Zn2O6, energy / 2 or for AgTe3(OH)3, energy / 4.
- normalized_energy_at_conditions(pH: float, V: float) float[source]
Energy at an electrochemical condition, compatible with numpy arrays for pH/V input.
- Parameters:
pH (float) – pH at condition
V (float) – applied potential at condition
- Returns:
energy normalized by number of non-O/H atoms at condition
- class PourbaixPlotter(pourbaix_diagram: PourbaixDiagram)[source]
Bases:
objectA plotter class for phase diagrams.
- Parameters:
pourbaix_diagram (PourbaixDiagram) – A PourbaixDiagram object.
- domain_vertices(entry) list[source]
Get the vertices of the Pourbaix domain.
- Parameters:
entry – Entry for which domain vertices are desired
- Returns:
list of vertices
- get_pourbaix_plot(limits: tuple[tuple[float, float], tuple[float, float]] | None = None, title: str = '', label_domains: bool = True, label_fontsize: int = 20, show_water_lines: bool = True, show_neutral_axes: bool = True, ax: plt.Axes = None) plt.Axes[source]
Plot Pourbaix diagram.
- Parameters:
limits – tuple containing limits of the Pourbaix diagram of the form ((xlo, xhi), (ylo, yhi)).
title (str) – Title to display on plot
label_domains (bool) – whether to label Pourbaix domains
label_fontsize – font size for domain labels
show_water_lines – whether to show dashed lines indicating the region of water stability.
lines (show_neutral_axes; whether to show dashed horizontal and vertical) – at 0 V and pH 7, respectively.
ax (Axes) – Matplotlib Axes instance for plotting
- Returns:
matplotlib Axes object with Pourbaix diagram
- Return type:
Axes
- plot_entry_stability(entry: Any, pH_range: tuple[float, float] = (-2, 16), pH_resolution: int = 100, V_range: tuple[float, float] = (-3, 3), V_resolution: int = 100, e_hull_max: float = 1, cmap: str = 'RdYlBu_r', ax: plt.Axes | None = None, **kwargs: Any) plt.Axes[source]
Plots the stability of an entry in the Pourbaix diagram.
- Parameters:
entry (Any) – The entry to plot stability for.
pH_range (tuple[float, float]) – pH range for the plot. Defaults to (-2, 16).
pH_resolution (int) – pH resolution. Defaults to 100.
V_range (tuple[float, float]) – Voltage range for the plot. Defaults to (-3, 3).
V_resolution (int) – Voltage resolution. Defaults to 100.
e_hull_max (float) – Maximum energy above the hull. Defaults to 1.
cmap (str) – Colormap for the plot. Defaults to “RdYlBu_r”.
ax (Axes, optional) – Existing matplotlib Axes object for plotting. Defaults to None.
**kwargs (Any) – Additional keyword arguments passed to get_pourbaix_plot.
- Returns:
Matplotlib Axes object with the plotted stability.
- Return type:
plt.Axes
- ion_or_solid_comp_object(formula: str) Composition | Ion[source]
Get an Ion or Composition from a formula.
- Parameters:
formula (str) – Formula. E.g. of ion: NaOH(aq), Na[+], Na+; E.g. of solid: Fe2O3(s), Fe(s), Na2O.
- Returns:
Composition/Ion object.
pymatgen.analysis.quasiharmonic module
This module implements the Quasi-harmonic Debye approximation that can be used to compute thermal properties.
See the following papers for more info:
- class QuasiHarmonicDebyeApprox(energies, volumes, structure, t_min=300.0, t_step=100, t_max=300.0, eos='vinet', pressure=0.0, poisson=0.25, use_mie_gruneisen=False, anharmonic_contribution=False)[source]
Bases:
objectQuasi-harmonic approximation.
- Parameters:
energies (list) – list of DFT energies in eV
volumes (list) – list of volumes in Ang^3
structure (Structure) – pymatgen structure object
t_min (float) – min temperature
t_step (float) – temperature step
t_max (float) – max temperature
eos (str) –
equation of state used for fitting the energies and the volumes. options supported by pymatgen: “quadratic”, “murnaghan”, “birch”,
”birch_murnaghan”, “pourier_tarantola”, “vinet”, “deltafactor”, “numerical_eos”
pressure (float) – in GPa, optional.
poisson (float) – poisson ratio.
use_mie_gruneisen (bool) – whether or not to use the mie-gruneisen formulation to compute the gruneisen parameter. The default is the slater-gamma formulation.
anharmonic_contribution (bool) – whether or not to consider the anharmonic contribution to the Debye temperature. Cannot be used with use_mie_gruneisen. Defaults to False.
- static debye_integral(y)[source]
Debye integral. Eq(5) in doi.org/10.1016/j.comphy.2003.12.001.
- Parameters:
y (float) – Debye temperature / T, upper limit
- Returns:
unitless
- Return type:
float
- debye_temperature(volume: float) float[source]
Calculates the Debye temperature. Eq(6) in doi.org/10.1016/j.comphy.2003.12.001. Thanks to Joey.
Eq(6) above is equivalent to Eq(3) in doi.org/10.1103/PhysRevB.37.790 which does not consider anharmonic effects. Eq(20) in the same paper and Eq(18) in doi.org/10.1016/j.commatsci.2009.12.006 both consider anharmonic contributions to the Debye temperature through the Gruneisen parameter at 0K (Gruneisen constant).
The anharmonic contribution is toggled by setting the anharmonic_contribution to True or False in the QuasiHarmonicDebyeApprox constructor.
- Parameters:
volume (float) – in Ang^3
- Returns:
Debye temperature in K
- Return type:
float
- gruneisen_parameter(temperature, volume)[source]
- Slater-gamma formulation(the default):
- gruneisen parameter = - d log(theta)/ d log(V) = - (1/6 + 0.5 d log(B)/ d log(V))
= - (1/6 + 0.5 V/B dB/dV), where dB/dV = d^2E/dV^2 + V * d^3E/dV^3.
- Mie-gruneisen formulation:
Eq(31) in doi.org/10.1016/j.comphy.2003.12.001 Eq(7) in Blanco et. al. Journal of Molecular Structure (Theochem)
368 (1996) 245-255
- Also see J.P. Poirier, Introduction to the Physics of the Earth’s
Interior, 2nd ed. (Cambridge University Press, Cambridge, 2000) Eq(3.53)
- Parameters:
temperature (float) – temperature in K
volume (float) – in Ang^3
- Returns:
unitless
- Return type:
float
- optimize_gibbs_free_energy()[source]
Evaluate the Gibbs free energy as a function of V, T and P i.e G(V, T, P), minimize G(V, T, P) w.r.t. V for each T and store the optimum values.
- Note: The data points for which the equation of state fitting fails
are skipped.
- optimizer(temperature)[source]
Evaluate G(V, T, P) at the given temperature(and pressure) and minimize it w.r.t. V.
Compute the vibrational Helmholtz free energy, A_vib.
- Compute the Gibbs free energy as a function of volume, temperature
and pressure, G(V,T,P).
- Perform an equation of state fit to get the functional form of
Gibbs free energy:G(V, T, P).
Finally G(V, P, T) is minimized with respect to V.
- Parameters:
temperature (float) – temperature in K
- Returns:
G_opt(V_opt, T, P) in eV and V_opt in Ang^3.
- Return type:
float, float
- thermal_conductivity(temperature: float, volume: float) float[source]
Eq(17) in 10.1103/PhysRevB.90.174107.
- Parameters:
temperature (float) – temperature in K
volume (float) – in Ang^3
- Returns:
thermal conductivity in W/K/m
- Return type:
float
- class QuasiharmonicDebyeApprox(energies, volumes, structure, t_min=300.0, t_step=100, t_max=300.0, eos='vinet', pressure=0.0, poisson=0.25, use_mie_gruneisen=False, anharmonic_contribution=False)[source]
Bases:
QuasiHarmonicDebyeApprox- Parameters:
energies (list) – list of DFT energies in eV
volumes (list) – list of volumes in Ang^3
structure (Structure) – pymatgen structure object
t_min (float) – min temperature
t_step (float) – temperature step
t_max (float) – max temperature
eos (str) –
equation of state used for fitting the energies and the volumes. options supported by pymatgen: “quadratic”, “murnaghan”, “birch”,
”birch_murnaghan”, “pourier_tarantola”, “vinet”, “deltafactor”, “numerical_eos”
pressure (float) – in GPa, optional.
poisson (float) – poisson ratio.
use_mie_gruneisen (bool) – whether or not to use the mie-gruneisen formulation to compute the gruneisen parameter. The default is the slater-gamma formulation.
anharmonic_contribution (bool) – whether or not to consider the anharmonic contribution to the Debye temperature. Cannot be used with use_mie_gruneisen. Defaults to False.
pymatgen.analysis.quasirrho module
A module to calculate free energies using the Quasi-Rigid Rotor Harmonic Oscillator approximation. Modified from a script by Steven Wheeler. See: Grimme, S. Chem. Eur. J. 2012, 18, 9955.
- class QuasiRRHO(mol: Molecule, frequencies: list[float], energy: float, mult: int, sigma_r: float = 1, temp: float = 298.15, press: float = 101317, v0: float = 100)[source]
Bases:
objectCalculate thermochemistry using Grimme’s Quasi-RRHO approximation. All outputs are in atomic units, e.g. energy outputs are in Hartrees. Citation: Grimme, S. Chemistry - A European Journal 18, 9955-9964 (2012).
- entropy_ho[source]
Total entropy calculated with a harmonic oscillator approximation for the vibrational entropy [Ha/K]
- Type:
float
- free_energy_ho[source]
Free energy calculated without the Quasi-RRHO method, i.e. with a harmonic oscillator approximation for the vibrational entropy [Ha]
- Type:
float
- Parameters:
mol (Molecule) – Pymatgen molecule
frequencies (list) – List of frequencies (float) [cm^-1]
energy (float) – Electronic energy [Ha]
mult (int) – Spin multiplicity
sigma_r (int) – Rotational symmetry number. Defaults to 1.
temp (float) – Temperature [K]. Defaults to 298.15.
press (float) – Pressure [Pa]. Defaults to 101_317.
v0 (float) – Cutoff frequency for Quasi-RRHO method [cm^-1]. Defaults to 100.
- classmethod from_gaussian_output(output: GaussianOutput, **kwargs) Self[source]
- Parameters:
output (GaussianOutput) – Pymatgen GaussianOutput object.
- Returns:
QuasiRRHO class instantiated from a Gaussian Output
- Return type:
pymatgen.analysis.reaction_calculator module
This module provides classes that define a chemical reaction.
- class BalancedReaction(reactants_coeffs: Mapping[CompositionLike, float], products_coeffs: Mapping[CompositionLike, float])[source]
Bases:
MSONableRepresent a complete chemical reaction.
Reactants and products to be specified as dict of {Composition: coeff}.
- Parameters:
reactants_coeffs (dict[Composition, float]) – Reactants as dict of {Composition: amt}.
products_coeffs (dict[Composition, float]) – Products as dict of {Composition: amt}.
- property all_comp: list[Composition][source]
List of all compositions in the reaction.
- as_entry(energies) ComputedEntry[source]
Get a ComputedEntry representation of the reaction.
- calculate_energy(energies: dict[Composition, ufloat]) AffineScalarFunc[source]
- calculate_energy(energies: dict[Composition, float]) float
Calculates the energy of the reaction.
- Parameters:
({Composition (energies) – float}): Energy for each composition. E.g ., {comp1: energy1, comp2: energy2}.
- Returns:
reaction energy as a float.
- classmethod from_dict(dct: dict) Self[source]
- Parameters:
dct (dict) – from as_dict().
- Returns:
BalancedReaction
- classmethod from_str(rxn_str: str) Self[source]
Generate a balanced reaction from a string. The reaction must already be balanced.
- Parameters:
rxn_string (str) – The reaction string. For example, “4 Li + O2 -> 2Li2O”
- Returns:
BalancedReaction
- get_coeff(comp: Composition) float[source]
Get coefficient for a particular composition.
- get_el_amount(element: Element | Species) float[source]
Get the amount of the element in the reaction.
- Parameters:
element (SpeciesLike) – Element in the reaction
- Returns:
Amount of that element in the reaction.
- normalize_to(comp: Composition, factor: float = 1) None[source]
Normalizes the reaction to one of the compositions. By default, normalizes such that the composition given has a coefficient of 1. Another factor can be specified.
- Parameters:
comp (Composition) – Composition to normalize to
factor (float) – Factor to normalize to. Defaults to 1.
- normalize_to_element(element: Species | Element, factor: float = 1) None[source]
Normalizes the reaction to one of the elements. By default, normalizes such that the amount of the element is 1. Another factor can be specified.
- Parameters:
element (SpeciesLike) – Element to normalize to.
factor (float) – Factor to normalize to. Defaults to 1.
- property normalized_repr: str[source]
A normalized representation of the reaction. All factors are converted to lowest common factors.
- normalized_repr_and_factor() tuple[str, float][source]
Normalized representation for a reaction For example,
4 Li + 2 O -> 2Li2Obecomes2 Li + O -> Li2O.
- property products: list[Composition][source]
List of products.
- property reactants: list[Composition][source]
List of reactants.
- class ComputedReaction(reactant_entries: list[ComputedEntry], product_entries: list[ComputedEntry])[source]
Bases:
ReactionConvenience class to generate a reaction from ComputedEntry objects, with some additional attributes, such as a reaction energy based on computed energies.
- Parameters:
reactant_entries ([ComputedEntry]) – List of reactant_entries.
product_entries ([ComputedEntry]) – List of product_entries.
- property all_entries[source]
Equivalent of all_comp but returns entries, in the same order as the coefficients.
- class Reaction(reactants: list[Composition], products: list[Composition])[source]
Bases:
BalancedReactionA more flexible class representing a Reaction. The reaction amounts will be automatically balanced. Reactants and products can swap sides so that all coefficients are positive, however this class will find the solution with the minimum number of swaps and coefficients of 0. Normalizes so that the FIRST product (or products, if underdetermined) has a coefficient of one.
Reactants and products to be specified as list of pymatgen.core.structure.Composition. e.g. [comp1, comp2].
- Parameters:
reactants ([Composition]) – List of reactants.
products ([Composition]) – List of products.
pymatgen.analysis.structure_analyzer module
This module provides classes to perform topological analyses of structures.
pymatgen.analysis.structure_matcher module
This module provides classes to perform fitting of structures.
pymatgen.analysis.surface_analysis module
This module defines tools to analyze surface and adsorption related quantities as well as related plots. If you use this module, please consider citing the following works:
Tran, Z. Xu, B. Radhakrishnan, D. Winston, W. Sun, K. A. Persson,
S. P. Ong, “Surface Energies of Elemental Crystals”, Scientific Data, 2016, 3:160080, doi: 10.1038/sdata.2016.80.
and
Kang, S., Mo, Y., Ong, S. P., & Ceder, G. (2014). Nanoscale stabilization of sodium oxides: Implications for Na-O2 batteries. Nano Letters, 14(2), 1016-1020. https://doi.org/10.1021/nl404557w
and
- Montoya, J. H., & Persson, K. A. (2017). A high-throughput framework
for determining adsorption energies on solid surfaces. Npj Computational Materials, 3(1), 14. https://doi.org/10.1038/s41524-017-0017-z
Todo: - Still assumes individual elements have their own chempots
in a molecular adsorbate instead of considering a single chempot for a single molecular adsorbate. E.g. for an OH adsorbate, the surface energy is a function of delu_O and delu_H instead of delu_OH
- Need a method to automatically get chempot range when
dealing with non-stoichiometric slabs
- Simplify the input for SurfaceEnergyPlotter such that the
user does not need to generate a dict
- class NanoscaleStability(se_analyzers, symprec=1e-05)[source]
Bases:
objectA class for analyzing the stability of nanoparticles of different polymorphs with respect to size. The Wulff shape will be the model for the nanoparticle. Stability will be determined by an energetic competition between the weighted surface energy (surface energy of the Wulff shape) and the bulk energy. A future release will include a 2D phase diagram (e.g. w.r.t. size vs chempot for adsorbed or non-stoichiometric surfaces). Based on the following work:
- Kang, S., Mo, Y., Ong, S. P., & Ceder, G. (2014). Nanoscale
stabilization of sodium oxides: Implications for Na-O2 batteries. Nano Letters, 14(2), 1016-1020. https://doi.org/10.1021/nl404557w
- se_analyzers[source]
Each item corresponds to a different polymorph.
- Type:
list[SurfaceEnergyPlotter]
Analyzes the nanoscale stability of different polymorphs.
- static bulk_gform(bulk_entry)[source]
Get the formation energy of the bulk.
- Parameters:
bulk_entry (ComputedStructureEntry) – Entry of the corresponding bulk.
- Returns:
bulk formation energy (in eV)
- Return type:
float
- plot_all_stability_map(max_r, increments=50, delu_dict=None, delu_default=0, ax=None, labels=None, from_sphere_area=False, e_units='keV', r_units='nanometers', normalize=False, scale_per_atom=False)[source]
- Get the plot of the formation energy of a particles
of different polymorphs against its effect radius.
- Parameters:
max_r (float) – The maximum radius of the particle to plot up to.
increments (int) – Number of plot points
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
plt (pyplot) – Plot
labels (list) – List of labels for each plot, corresponds to the list of se_analyzers
from_sphere_area (bool) – There are two ways to calculate the bulk formation energy. Either by treating the volume and thus surface area of the particle as a perfect sphere, or as a Wulff shape.
- Returns:
matplotlib Axes object
- Return type:
plt.Axes
- plot_one_stability_map(analyzer, max_r, delu_dict=None, label='', increments=50, delu_default=0, ax=None, from_sphere_area=False, e_units='keV', r_units='nanometers', normalize=False, scale_per_atom=False)[source]
- Get the plot of the formation energy of a particle against its
effect radius.
- Parameters:
analyzer (SurfaceEnergyPlotter) – Analyzer associated with the first polymorph
max_r (float) – The maximum radius of the particle to plot up to.
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
label (str) – Label of the plot for legend
increments (int) – Number of plot points
delu_default (float) – Default value for all unset chemical potentials
plt (pyplot) – Plot
from_sphere_area (bool) – There are two ways to calculate the bulk formation energy. Either by treating the volume and thus surface area of the particle as a perfect sphere, or as a Wulff shape.
r_units (str) – Can be nanometers or Angstrom
e_units (str) – Can be keV or eV
normalize (str) – Whether or not to normalize energy by volume
- Returns:
matplotlib Axes object
- Return type:
plt.Axes
- scaled_wulff(wulff_shape, r)[source]
- Scales the Wulff shape with an effective radius r. Note that the resulting
Wulff does not necessarily have the same effective radius as the one provided. The Wulff shape is scaled by its surface energies where first the surface energies are scale by the minimum surface energy and then multiplied by the given effective radius.
- Parameters:
wulff_shape (WulffShape) – Initial, unscaled WulffShape
r (float) – Arbitrary effective radius of the WulffShape
- Returns:
WulffShape (scaled by r)
- solve_equilibrium_point(analyzer1, analyzer2, delu_dict=None, delu_default=0, units='nanometers')[source]
Get the radial size of two particles where equilibrium is reached between both particles. NOTE: the solution here is not the same as the solution visualized in the plot because solving for r requires that both the total surface area and volume of the particles are functions of r.
- Parameters:
analyzer1 (SurfaceEnergyPlotter) – Analyzer associated with the first polymorph
analyzer2 (SurfaceEnergyPlotter) – Analyzer associated with the second polymorph
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
units (str) – Can be nanometers or Angstrom
- Returns:
Particle radius in nm or Angstrom
- Return type:
float
- wulff_gform_and_r(wulff_shape, bulk_entry, r, from_sphere_area=False, r_units='nanometers', e_units='keV', normalize=False, scale_per_atom=False)[source]
Calculates the formation energy of the particle with arbitrary radius r.
- Parameters:
wulff_shape (WulffShape) – Initial unscaled WulffShape
bulk_entry (ComputedStructureEntry) – Entry of the corresponding bulk.
r (float (Ang)) – Arbitrary effective radius of the WulffShape
from_sphere_area (bool) – There are two ways to calculate the bulk formation energy. Either by treating the volume and thus surface area of the particle as a perfect sphere, or as a Wulff shape.
r_units (str) – Can be nanometers or Angstrom
e_units (str) – Can be keV or eV
normalize (bool) – Whether or not to normalize energy by volume
scale_per_atom (True) – Whether or not to normalize by number of atoms in the particle
- Returns:
particle formation energy (float in keV), effective radius
- class SlabEntry(structure, energy, miller_index, correction=0.0, parameters=None, data=None, entry_id=None, label=None, adsorbates=None, clean_entry=None, marker=None, color=None)[source]
Bases:
ComputedStructureEntry- A ComputedStructureEntry object encompassing all data relevant to a
slab for analyzing surface thermodynamics.
- ads_entries_dict[source]
Dictionary where the key is the reduced composition of the adsorbate entry and value is the entry itself.
- Type:
dict
Make a SlabEntry containing all relevant surface thermodynamics data.
- Parameters:
structure (Slab) – The primary slab associated with this entry.
energy (float) – Energy from total energy calculation
miller_index (tuple(h, k, l)) – Miller index of plane parallel to surface
correction (float) – See ComputedSlabEntry
parameters (dict) – See ComputedSlabEntry
data (dict) – See ComputedSlabEntry
entry_id (str) – See ComputedSlabEntry
data – See ComputedSlabEntry
entry_id – See ComputedSlabEntry
label (str) – Any particular label for this slab, e.g. “Tasker 2”, “non-stoichiometric”, “reconstructed”
adsorbates ([ComputedStructureEntry]) – List of reference entries for the adsorbates on the slab, can be an isolated molecule (e.g. O2 for O or O2 adsorption), a bulk structure (eg. fcc Cu for Cu adsorption) or anything.
clean_entry (ComputedStructureEntry) – If the SlabEntry is for an adsorbed slab, this is the corresponding SlabEntry for the clean slab
marker (str) – Custom marker for gamma plots (”–” and “-” are typical)
color (str or rgba) – Custom color for gamma plots
- property create_slab_label[source]
A label (str) for this particular slab based on composition, coverage and Miller index.
- classmethod from_computed_structure_entry(entry, miller_index, label=None, adsorbates=None, clean_entry=None, **kwargs) Self[source]
Get SlabEntry from a ComputedStructureEntry.
- property get_unit_primitive_area[source]
The surface area of the adsorbed system per unit area of the primitive slab system.
- gibbs_binding_energy(eads=False)[source]
Get the adsorption energy or Gibbs binding energy of an adsorbate on a surface.
- Parameters:
eads (bool) – Whether to calculate the adsorption energy (True) or the binding energy (False) which is just adsorption energy normalized by number of adsorbates.
- surface_energy(ucell_entry, ref_entries=None)[source]
Calculates the surface energy of this SlabEntry.
- Parameters:
ucell_entry (entry) – An entry object for the bulk
(list (ref_entries) – [entry]): A list of entries for each type of element to be used as a reservoir for non-stoichiometric systems. The length of this list MUST be n-1 where n is the number of different elements in the bulk entry. The chempot of the element ref_entry that is not in the list will be treated as a variable.
- Returns:
The surface energy of the slab.
- Return type:
float
- class SurfaceEnergyPlotter(all_slab_entries, ucell_entry, ref_entries=None)[source]
Bases:
objectA class used for generating plots to analyze the thermodynamics of surfaces of a material. Produces stability maps of different slab configurations, phases diagrams of two parameters to determine stability of configurations (future release), and Wulff shapes.
- all_slab_entries[source]
Either a list of SlabEntry objects (note for a list, the SlabEntry must have the adsorbates and clean_entry parameter plugged in) or a Nested dictionary containing a list of entries for slab calculations as items and the corresponding Miller index of the slab as the key. To account for adsorption, each value is a sub-dictionary with the entry of a clean slab calculation as the sub-key and a list of entries for adsorption calculations as the sub-value. The sub-value can contain different adsorption configurations such as a different site or a different coverage, however, ordinarily only the most stable configuration for a particular coverage will be considered as the function of the adsorbed surface energy has an intercept dependent on the adsorption energy (ie an adsorption site with a higher adsorption energy will always provide a higher surface energy than a site with a lower adsorption energy). An example parameter is provided: {(h1,k1,l1): {clean_entry1: [ads_entry1, ads_entry2, …], clean_entry2: […], …}, (h2,k2,l2): {…}} where clean_entry1 can be a pristine surface and clean_entry2 can be a reconstructed surface while ads_entry1 can be adsorption at site 1 with a 2x2 coverage while ads_entry2 can have a 3x3 coverage. If adsorption entries are present (i.e. if all_slab_entries[(h,k,l)][clean_entry1]), we consider adsorption in all plots and analysis for this particular facet.
- Type:
dict | list
- color_dict[source]
Dictionary of colors (r,g,b,a) when plotting surface energy stability. The keys are individual surface entries where clean surfaces have a solid color while the corresponding adsorbed surface will be transparent.
- Type:
dict
- ucell_entry[source]
ComputedStructureEntry of the bulk reference for this particular material.
- Type:
- ref_entries[source]
List of ComputedStructureEntries to be used for calculating chemical potential.
- Type:
list
- facet_color_dict[source]
Randomly generated dictionary of colors associated with each facet.
- Type:
dict
- Object for plotting surface energy in different ways for clean and
adsorbed surfaces.
- Parameters:
all_slab_entries (dict or list) – Dictionary or list containing all entries for slab calculations. See attributes.
ucell_entry (ComputedStructureEntry) – ComputedStructureEntry of the bulk reference for this particular material.
ref_entries ([ComputedStructureEntries]) – A list of entries for each type of element to be used as a reservoir for non-stoichiometric systems. The length of this list MUST be n-1 where n is the number of different elements in the bulk entry. The bulk energy term in the grand surface potential can be defined by a summation of the chemical potentials for each element in the system. As the bulk energy is already provided, one can solve for one of the chemical potentials as a function of the other chemical potentials and bulk energy. i.e. there are n-1 variables (chempots). e.g. if your ucell_entry is for LiFePO4 than your ref_entries should have an entry for Li, Fe, and P if you want to use the chempot of O as the variable.
- BE_vs_clean_SE(delu_dict, delu_default=0, plot_eads=False, annotate_monolayer=True, JPERM2=False)[source]
- For each facet, plot the clean surface energy against the most
stable binding energy.
- Parameters:
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
plot_eads (bool) – Option to plot the adsorption energy (binding energy multiplied by number of adsorbates) instead.
annotate_monolayer (bool) – Whether or not to label each data point with its monolayer (adsorbate density per unit primiitve area)
JPERM2 (bool) – Whether to plot surface energy in /m^2 (True) or eV/A^2 (False)
- Returns:
- Plot of clean surface energy vs binding energy for
all facets.
- Return type:
Plot
- area_frac_vs_chempot_plot(ref_delu: Symbol, chempot_range: list[float], delu_dict: dict[Symbol, float] | None = None, delu_default: float = 0, increments: int = 10, no_clean: bool = False, no_doped: bool = False) Axes[source]
1D plot. Plots the change in the area contribution of each facet as a function of chemical potential.
- Parameters:
ref_delu (Symbol) – The free variable chempot with the format: Symbol(“delu_el”) where el is the name of the element.
chempot_range (list[float]) – Min/max range of chemical potential to plot along.
delu_dict (dict[Symbol, float]) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials.
increments (int) – Number of data points between min/max or point of intersection. Defaults to 10 points.
no_clean (bool) – Some parameter, description missing.
no_doped (bool) – Some parameter, description missing.
- Returns:
Plot of area frac on the Wulff shape for each facet vs chemical potential.
- Return type:
plt.Axes
- static chempot_plot_addons(ax, xrange, ref_el, pad=2.4, rect=None, ylim=None)[source]
Helper function to a chempot plot look nicer.
- Parameters:
plt (Plot)
xrange (list) – xlim parameter
ref_el (str) – Element of the referenced chempot.
axes (axes)
pad (float)
rect (list) – For tight layout
ylim (ylim parameter)
return (Plot): Modified plot with addons. return (Plot): Modified plot with addons.
- chempot_vs_gamma(ref_delu, chempot_range, miller_index=(), delu_dict=None, delu_default=0, JPERM2=False, show_unstable=False, ylim=None, plt=None, no_clean=False, no_doped=False, use_entry_labels=False, no_label=False)[source]
- Plots the surface energy as a function of chemical potential.
Each facet will be associated with its own distinct colors. Dashed lines will represent stoichiometries different from that of the mpid’s compound. Transparent lines indicates adsorption.
- Parameters:
ref_delu (sympy Symbol) – The range stability of each slab is based on the chempot range of this chempot. Should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element
chempot_range ([max_chempot, min_chempot]) – Range to consider the stability of the slabs.
miller_index (list) – Miller index for a specific facet to get a dictionary for.
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
JPERM2 (bool) – Whether to plot surface energy in /m^2 (True) or eV/A^2 (False)
show_unstable (bool) – Whether or not to show parts of the surface energy plot outside the region of stability.
ylim ([ymax, ymin]) – Range of y axis
no_doped (bool) – Whether to plot for the clean slabs only.
no_clean (bool) – Whether to plot for the doped slabs only.
use_entry_labels (bool) – If True, will label each slab configuration according to their given label in the SlabEntry object.
no_label (bool) – Option to turn off labels.
- Returns:
Plot of surface energy vs chempot for all entries.
- Return type:
Plot
- chempot_vs_gamma_plot_one(ax: Axes, entry: SlabEntry, ref_delu: Symbol, chempot_range: list[float], delu_dict: dict[Symbol, float] | None = None, delu_default: float = 0, label: str = '', JPERM2: bool = False) Axes[source]
Helper function to help plot the surface energy of a single SlabEntry as a function of chemical potential.
- Parameters:
ax (plt.Axes) – Matplotlib Axes instance for plotting.
entry – Entry of the slab whose surface energy we want to plot. (Add appropriate description for type)
ref_delu (Symbol) – The range stability of each slab is based on the chempot range of this chempot.
chempot_range (list[float]) – Range to consider the stability of the slabs.
delu_dict (dict[Symbol, float]) – Dictionary of the chemical potentials.
delu_default (float) – Default value for all unset chemical potentials.
label (str) – Label of the slab for the legend.
JPERM2 (bool) – Whether to plot surface energy in /m^2 (True) or eV/A^2 (False).
- Returns:
Plot of surface energy vs chemical potential for one entry.
- Return type:
plt.Axes
- color_palette_dict(alpha=0.35)[source]
Helper function to assign each facet a unique color using a dictionary.
- Parameters:
alpha (float) – Degree of transparency
- return (dict): Dictionary of colors (r,g,b,a) when plotting surface
energy stability. The keys are individual surface entries where clean surfaces have a solid color while the corresponding adsorbed surface will be transparent.
- get_stable_entry_at_u(miller_index, delu_dict=None, delu_default=0, no_doped=False, no_clean=False) tuple[SlabEntry, float][source]
- Get the entry corresponding to the most stable slab for a particular
facet at a specific chempot. We assume that surface energy is constant so all free variables must be set with delu_dict, otherwise they are assumed to be equal to delu_default.
- Parameters:
miller_index ((h,k,l)) – The facet to find the most stable slab in
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
no_doped (bool) – Consider stability of clean slabs only.
no_clean (bool) – Consider stability of doped slabs only.
- Returns:
The most stable slab entry and its surface energy.
- Return type:
tuple[SlabEntry, float]
- get_surface_equilibrium(slab_entries, delu_dict=None)[source]
- Takes in a list of SlabEntries and calculates the chemical potentials
at which all slabs in the list coexists simultaneously. Useful for building surface phase diagrams. Note that to solve for x equations (x slab_entries), there must be x free variables (chemical potentials). Adjust delu_dict as need be to get the correct number of free variables.
- Parameters:
slab_entries (array) – The coefficients of the first equation
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
- Returns:
- Array containing a solution to x equations with x
variables (x-1 chemical potential and 1 surface energy)
- Return type:
array
- monolayer_vs_BE(plot_eads=False)[source]
- Plots the binding energy as a function of monolayers (ML), i.e.
the fractional area adsorbate density for all facets. For each facet at a specific monolayer, only plot the lowest binding energy.
- Parameters:
plot_eads (bool) – Option to plot the adsorption energy (binding energy multiplied by number of adsorbates) instead.
- Returns:
Plot of binding energy vs monolayer for all facets.
- Return type:
Plot
- set_all_variables(delu_dict, delu_default)[source]
- Set all chemical potential values and returns a dictionary where
the key is a sympy Symbol and the value is a float (chempot).
- Parameters:
entry (SlabEntry) – Computed structure entry of the slab
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
- Returns:
Dictionary of set chemical potential values
- stable_u_range_dict(chempot_range, ref_delu, no_doped=True, no_clean=False, delu_dict=None, miller_index=(), dmu_at_0=False, return_se_dict=False)[source]
Creates a dictionary where each entry is a key pointing to a chemical potential range where the surface of that entry is stable. Does so by enumerating through all possible solutions (intersect) for surface energies of a specific facet.
- Parameters:
chempot_range ([max_chempot, min_chempot]) – Range to consider the stability of the slabs.
ref_delu (sympy Symbol) – The range stability of each slab is based on the chempot range of this chempot. Should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element
no_doped (bool) – Consider stability of clean slabs only.
no_clean (bool) – Consider stability of doped slabs only.
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
miller_index (list) – Miller index for a specific facet to get a dictionary for.
dmu_at_0 (bool) – If True, if the surface energies corresponding to the chemical potential range is between a negative and positive value, the value is a list of three chemical potentials with the one in the center corresponding a surface energy of 0. Uselful in identifying unphysical ranges of surface energies and their chemical potential range.
return_se_dict (bool) – Whether or not to return the corresponding dictionary of surface energies
- surface_chempot_range_map(elements, miller_index, ranges, incr=50, no_doped=False, no_clean=False, delu_dict=None, ax=None, annotate=True, show_unphysical_only=False, fontsize=10) Axes[source]
- Adapted from the get_chempot_range_map() method in the PhaseDiagram
class. Plot the chemical potential range map based on surface energy stability. Currently works only for 2-component PDs. At the moment uses a brute force method by enumerating through the range of the first element chempot with a specified increment and determines the chempot range of the second element for each SlabEntry. Future implementation will determine the chempot range map first by solving systems of equations up to 3 instead of 2.
- Parameters:
elements (list) – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to duLi and duO, you will supply [Element(“Li”), Element(“O”)]
miller_index ([h, k, l]) – Miller index of the surface we are interested in
ranges ([[range1], [range2]]) – List of chempot ranges (max and min values) for the first and second element.
incr (int) – Number of points to sample along the range of the first chempot
no_doped (bool) – Whether or not to include doped systems.
no_clean (bool) – Whether or not to include clean systems.
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
ax (plt.Axes) – Axes object to plot on. If None, will create a new plot.
annotate (bool) – Whether to annotate each “phase” with the label of the entry. If no label, uses the reduced formula
show_unphysical_only (bool) – Whether to only show the shaded region where surface energy is negative. Useful for drawing other chempot range maps.
fontsize (int) – Font size of the annotation
- wulff_from_chempot(delu_dict=None, delu_default=0, symprec=1e-05, no_clean=False, no_doped=False) WulffShape[source]
Method to get the Wulff shape at a specific chemical potential.
- Parameters:
delu_dict (dict) – Dictionary of the chemical potentials to be set as constant. Note the key should be a sympy Symbol object of the format: Symbol(“delu_el”) where el is the name of the element.
delu_default (float) – Default value for all unset chemical potentials
symprec (float) – See WulffShape.
no_doped (bool) – Consider stability of clean slabs only.
no_clean (bool) – Consider stability of doped slabs only.
- Returns:
The WulffShape at u_ref and u_ads.
- Return type:
- class WorkFunctionAnalyzer(structure: Structure, locpot_along_c, efermi, shift=0, blength=3.5)[source]
Bases:
objectA class used for calculating the work function from a slab model and visualizing the behavior of the local potential along the slab.
- vacuum_locpot[source]
The maximum local potential along the c direction for the slab model, i.e. the potential at the vacuum.
- Type:
float
- work_function[source]
The minimum energy needed to move an electron from the surface to infinity. Defined as the difference between the potential at the vacuum and the Fermi energy.
- Type:
float
- along_c[source]
Points along the c direction with same increments as the locpot in the c axis.
- Type:
list
Initialize the WorkFunctionAnalyzer class.
- Parameters:
structure (Structure) – Structure object modelling the surface
locpot_along_c (list) – Local potential along the c direction
outcar (MSONable) – Outcar vasp output object
shift (float) – Parameter to translate the slab (and therefore the vacuum) of the slab structure, thereby translating the plot along the x axis.
blength (float (Ang)) – The longest bond length in the material. Used to handle pbc for noncontiguous slab layers
- classmethod from_files(poscar_filename, locpot_filename, outcar_filename, shift=0, blength=3.5) Self[source]
Initialize a WorkFunctionAnalyzer from POSCAR, LOCPOT, and OUTCAR files.
- Parameters:
poscar_filename (str) – The path to the POSCAR file.
locpot_filename (str) – The path to the LOCPOT file.
outcar_filename (str) – The path to the OUTCAR file.
shift (float) – The shift value. Defaults to 0.
blength (float) – The longest bond length in the material. Used to handle pbc for noncontiguous slab layers. Defaults to 3.5.
- Returns:
A WorkFunctionAnalyzer instance.
- Return type:
- get_labels(plt, label_fontsize=10)[source]
Handles the optional labelling of the plot with relevant quantities.
- Parameters:
plt (plt) – Plot of the locpot vs c axis
label_fontsize (float) – Fontsize of labels
Returns Labelled plt.
- get_locpot_along_slab_plot(label_energies=True, plt=None, label_fontsize=10)[source]
- Get a plot of the local potential (eV) vs the
position along the c axis of the slab model (Ang).
- Parameters:
label_energies (bool) – Whether to label relevant energy quantities such as the work function, Fermi energy, vacuum locpot, bulk-like locpot
plt (plt) – Matplotlib pyplot object
label_fontsize (float) – Fontsize of labels
Returns plt of the locpot vs c axis
- is_converged(min_points_frac=0.015, tol: float = 0.0025)[source]
- A well converged work function should have a flat electrostatic
potential within some distance (min_point) about where the peak electrostatic potential is found along the c direction of the slab. This is dependent on the size of the slab.
- Parameters:
min_point (fractional coordinates) – The number of data points +/- the point of where the electrostatic potential is at its peak along the c direction.
tol (float) – If the electrostatic potential stays the same within this tolerance, within the min_points, it is converged.
Returns a bool (whether or not the work function is converged)
- entry_dict_from_list(all_slab_entries) dict[source]
Converts a list of SlabEntry to an appropriate dictionary. It is assumed that if there is no adsorbate, then it is a clean SlabEntry and that adsorbed SlabEntry has the clean_entry parameter set.
- Parameters:
all_slab_entries (list) – List of SlabEntry objects
- Returns:
- Dictionary of SlabEntry with the Miller index as the main
key to a dictionary with a clean SlabEntry as the key to a list of adsorbed SlabEntry.
- Return type:
dict
- sub_chempots(gamma_dict, chempots)[source]
- Uses dot product of numpy array to sub chemical potentials
into the surface grand potential. This is much faster than using the subs function in sympy.
- Parameters:
gamma_dict (dict) – Surface grand potential equation as a coefficient dictionary
chempots (dict) – Dictionary assigning each chemical potential (key) in gamma a value
- Returns:
Surface energy as a float
pymatgen.analysis.thermochemistry module
A module to perform experimental thermochemical data analysis.
- class ThermoData(data_type, cpdname, phaseinfo, formula, value, ref='', method='', temp_range=(298, 298), uncertainty=None)[source]
Bases:
objectContainer for experimental thermo-chemical data.
- Parameters:
data_type – The thermochemical data type. Should be one of the following: fH - Formation enthalpy, S - Entropy, A, B, C, D, E, F, G, H - variables for use in the various equations for generating formation enthalpies or Cp at various temperatures.
cpdname (str) – A name for the compound. For example, hematite for Fe2O3.
phaseinfo (str) – Denoting the phase. For example, “solid”, “liquid”, “gas” or “tetragonal”.
formula (str) – A proper string formula, e.g. Fe2O3
value (float) – The value of the data.
ref (str) – A reference, if any, for the data.
method (str) – The method by which the data was determined, if available.
temp_range ([float, float]) – Temperature range of validity for the data in Kelvin. Defaults to 298 K only.
uncertainty (float) – An uncertainty for the data, if available.
pymatgen.analysis.transition_state module
Some reimplementation of Henkelman’s Transition State Analysis utilities, which are originally in Perl. Additional features beyond those offered by Henkelman’s utilities will be added.
- class NEBAnalysis(r: ArrayLike, energies: ArrayLike, forces: ArrayLike, structures: list[Structure], spline_options: dict | None = None, zero_slope_saddle: bool = False)[source]
Bases:
MSONableAn NEBAnalysis class.
Initialize an NEBAnalysis from the cumulative root mean squared distances between structures, the energies, the forces and the structures for the analysis.
- Parameters:
r (ArrayLike) – Root mean square distances between structures.
energies (ArrayLike) – Energies of each structure along reaction coordinate.
forces (ArrayLike) – Tangent forces along the reaction coordinate.
structures (list[Structure]) – Structures along reaction coordinate.
spline_options (dict, optional) – [Deprecated] Use zero_slope_saddle instead.
zero_slope_saddle (bool) – If True, enforces zero slope at saddle point.
- as_dict() dict[str, Any][source]
Dict representation of NEBAnalysis.
- Returns:
JSON-serializable dict representation.
- classmethod from_dir(root_dir: PathLike, relaxation_dirs: tuple[PathLike, PathLike] | None = None, **kwargs) Self[source]
Initialize an NEBAnalysis object from a directory of an NEB run.
Note that OUTCARs must be present in all image directories. For the terminal OUTCARs from relaxation calculations, you can specify the locations using relaxation_dir. If these are not specified, the code will attempt to look for the OUTCARs in 00 and 0n directories, followed by subdirs (“start”, “end”) or (“initial”, “final”) in the root_dir. These are just some typical conventions used preferentially in Shyue Ping’s MAVRL research group.
For the non-terminal points, the CONTCAR is read to obtain structures. For terminal points, the POSCAR is used. The image directories are assumed to be the only directories that can be resolved to integers. e.g. “00”, “01”, …, “06”. The minimum sub-directory structure that can be parsed is of the following form (a 5-image example is shown):
- 00:
POSCAR
OUTCAR
- 01-05:
CONTCAR
OUTCAR
- 06:
POSCAR
OUTCAR
- Parameters:
root_dir (PathLike) – Path to the root directory of the NEB calculation.
relaxation_dirs (tuple) – The (start, end) directories from which the OUTCARs are read for the terminal points for the energies.
- Returns:
NEBAnalysis object.
- classmethod from_outcars(outcars: list[Outcar], structures: list[Structure], **kwargs) Self[source]
Initialize an NEBAnalysis from Outcar and Structure objects. Use the static constructors, e.g. from_dir instead if you prefer to have these automatically generated from a directory of NEB calculations.
- get_extrema(normalize_rxn_coordinate: bool = True) tuple[list[tuple[float, float]], list[tuple[float, float]]][source]
Get the positions of the extrema in meV along the minimum energy path (MEP). Both local minimums and maximums are returned.
- Parameters:
normalize_rxn_coordinate (bool) – Whether to normalize the reaction coordinate to between 0 and 1. Defaults to True.
- Returns:
where the extrema are given as [(x1, y1), (x2, y2), …].
- Return type:
tuple[min_extrema, max_extrema]
- get_plot(normalize_rxn_coordinate: bool = True, label_barrier: bool = True) Axes[source]
Get an NEB plot. Uses Henkelman’s approach of spline fitting each section of the reaction path based on tangent force and energies.
- Parameters:
normalize_rxn_coordinate (bool) – Whether to normalize the reaction coordinate to between 0 and 1. Defaults to True.
label_barrier (bool) – Whether to label the maximum barrier. Defaults to True.
- Returns:
matplotlib axes object.
- Return type:
plt.Axes
- setup_spline(spline_options: dict | None = None, zero_slope_saddle: bool = False) None[source]
Set up the cubic spline interpolation of the MEP.
- Parameters:
spline_options (dict, optional) – [Deprecated] Dictionary of options. Set to {“saddle_point”: “zero_slope”} to enforce zero slope at saddle.
zero_slope_saddle (bool) – New preferred argument. If True, enforces zero slope at the saddle point.
- combine_neb_plots(neb_analyses: list[NEBAnalysis], arranged_neb_analyses: bool = False, reverse_plot: bool = False) NEBAnalysis[source]
Combine NEB plots.
- Parameters:
neb_analyses – a list of NEBAnalysis objects.
arranged_neb_analyses – The code connects two end points with the smallest-energy difference. If all end points have very close energies, it’s likely to result in an inaccurate connection. Manually arrange neb_analyses if the combined plot is not as expected compared with all individual plots. e.g. if there are two NEBAnalysis objects to combine, arrange in such a way that the end-point energy of the first NEBAnalysis object is the start-point energy of the second NEBAnalysis object. Note that the barrier labeled in y-axis in the combined plot might be different from that in the individual plot due to the reference energy used. reverse_plot: reverse the plot or percolation direction.
- Returns:
NEBAnalysis object
pymatgen.analysis.wulff module
This module define a WulffShape class to generate the Wulff shape from a lattice, a list of indices and their corresponding surface energies, and the total area and volume of the Wulff shape, the weighted surface energy, the anisotropy and shape_factor can also be calculated. In support of plotting from a given view in terms of miller index.
The lattice is from the conventional unit cell, and (hkil) for hexagonal lattices.
If you use this code extensively, consider citing the following:
Tran, R.; Xu, Z.; Radhakrishnan, B.; Winston, D.; Persson, K. A.; Ong, S. P. (2016). Surface energies of elemental crystals. Scientific Data.
- class WulffFacet(normal, e_surf, normal_pt, dual_pt, index, m_ind_orig, miller)[source]
Bases:
objectHelper container for each Wulff plane.
- Parameters:
normal
e_surf
normal_pt
dual_pt
index
m_ind_orig
miller
- class WulffShape(lattice: Lattice, miller_list, e_surf_list, symprec=1e-05)[source]
Bases:
objectGenerate Wulff Shape from list of miller index and surface energies, with given conventional unit cell. surface energy (Jm^2) is the length of normal.
Wulff shape is the convex hull. Based on: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html
- Process:
get Wulff simplices
label with color
get wulff_area and other properties
- color_area[source]
List for all input_miller, total area on the Wulff shape, off_wulff = 0.
- Type:
list
- Parameters:
lattice – Lattice object of the conventional unit cell
miller_list ([(hkl) – list of hkl or hkil for hcp
e_surf_list ([float]) – list of corresponding surface energies
symprec (float) – for reciprocal lattice operation, default is 1e-5.
- property anisotropy: float[source]
Returns: float: Coefficient of Variation from weighted surface energy. The ideal sphere is 0.
- property area_fraction_dict: dict[tuple, float][source]
Returns: dict: {hkl: area_hkl/total area on wulff}.
- property effective_radius: float[source]
Radius of the WulffShape (in Angstroms) when the WulffShape is approximated as a sphere.
- Returns:
radius R_eff
- Return type:
float
- get_plot(color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors=None)[source]
Get the Wulff shape plot.
- Parameters:
color_set – default is ‘PuBu’
grid_off (bool) – default is True
axis_off (bool) – default is True
show_area (bool) – default is False
alpha (float) – chosen from 0 to 1 (float), default is 1
off_color – Default color for facets not present on the Wulff shape.
direction – default is (1, 1, 1)
bar_pos – default is [0.75, 0.15, 0.05, 0.65]
bar_on (bool) – default is False
legend_on (bool) – default is True
aspect_ratio – default is (8, 8)
({(h (custom_colors) – [r,g,b,alpha]}): Customize color of each facet with a dictionary. The key is the corresponding Miller index and value is the color. Undefined facets will use default color site. Note: If you decide to set your own colors, it probably won’t make any sense to have the color bar on.
k – [r,g,b,alpha]}): Customize color of each facet with a dictionary. The key is the corresponding Miller index and value is the color. Undefined facets will use default color site. Note: If you decide to set your own colors, it probably won’t make any sense to have the color bar on.
l} – [r,g,b,alpha]}): Customize color of each facet with a dictionary. The key is the corresponding Miller index and value is the color. Undefined facets will use default color site. Note: If you decide to set your own colors, it probably won’t make any sense to have the color bar on.
units_in_JPERM2 (bool) – Units of surface energy, defaults to Joules per square meter (True)
- Returns:
3D plot of the Wulff shape.
- Return type:
mpl_toolkits.mplot3d.Axes3D
- get_plotly(color_set='PuBu', off_color='red', alpha=1, custom_colors=None, units_in_JPERM2=True)[source]
Get the Wulff shape as a plotly Figure object.
- Parameters:
color_set – default is ‘PuBu’
alpha (float) – chosen from 0 to 1 (float), default is 1
off_color – Default color for facets not present on the Wulff shape.
({(h (custom_colors) – [r,g,b,alpha}): Customize color of each facet with a dictionary. The key is the corresponding Miller index and value is the color. Undefined facets will use default color site. Note: If you decide to set your own colors, it probably won’t make any sense to have the color bar on.
k – [r,g,b,alpha}): Customize color of each facet with a dictionary. The key is the corresponding Miller index and value is the color. Undefined facets will use default color site. Note: If you decide to set your own colors, it probably won’t make any sense to have the color bar on.
l} – [r,g,b,alpha}): Customize color of each facet with a dictionary. The key is the corresponding Miller index and value is the color. Undefined facets will use default color site. Note: If you decide to set your own colors, it probably won’t make any sense to have the color bar on.
units_in_JPERM2 (bool) – Units of surface energy, defaults to Joules per square meter (True)
- Returns:
(plotly.graph_objects.Figure)
- property shape_factor: float[source]
Determine the critical nucleus size. A large shape factor indicates great anisotropy. See Ballufi, R. W., Allen, S. M. & Carter, W. C. Kinetics
of Materials. (John Wiley & Sons, 2005), p.461.
- Returns:
Shape factor.
- Return type:
float
- show(*args, **kwargs)[source]
Show the Wulff plot.
- Parameters:
*args – Passed to get_plot.
**kwargs – Passed to get_plot.
- property tot_corner_sites[source]
The number of vertices in the convex hull. Useful for identifying catalytically active sites.
- property tot_edges[source]
The number of edges in the convex hull. Useful for identifying catalytically active sites.
pymatgen.analysis.xps module
This is a module for XPS analysis. It is modelled after the Galore package (https://github.com/SMTG-UCL/galore), but with some modifications for easier analysis from pymatgen itself. Please cite the following original work if you use this:
Adam J. Jackson, Alex M. Ganose, Anna Regoutz, Russell G. Egdell, David O. Scanlon (2018). Galore: Broadening and weighting for simulation of photoelectron spectroscopy. Journal of Open Source Software, 3(26), 773, doi: 10.21105/joss.007733
You may wish to look at the optional dependency galore for more functionality such as plotting and other cross-sections. Note that the atomic_subshell_photoionization_cross_sections.csv has been reparsed from the original compilation:
Yeh, J. J.; Lindau, I. Atomic Subshell Photoionization Cross Sections and Asymmetry Parameters: 1 ⩽ Z ⩽ 103. Atomic Data and Nuclear Data Tables 1985, 32 (1), 1-155. https://doi.org/10.1016/0092-640X(85)90016-6.
This version contains all detailed information for all orbitals.
- class XPS(x: ArrayLike, y: ArrayLike, *args, **kwargs)[source]
Bases:
SpectrumAn X-ray photoelectron spectra.
- Parameters:
x (ndarray) – A ndarray of N values.
y (ndarray) – A ndarray of N x k values. The first dimension must be the same as that of x. Each of the k values are interpreted as separate.
*args – All subclasses should provide args other than x and y when calling super, e.g. super().__init__( x, y, arg1, arg2, kwarg1=val1, ..). This guarantees the +, -, *, etc. operators work properly.
**kwargs – Same as that for *args.
- classmethod from_dos(dos: CompleteDos) Self[source]
- Parameters:
dos – CompleteDos object with project element-orbital DOS.
Vasprun.get_complete_dos. (Can be obtained from)
sigma – Smearing for Gaussian.
- Returns:
X-ray photoelectron spectrum.
- Return type: