def _fit_elastic_tensor(stresses, strains, strain_magnitudes, equilibrium_structure, equilibrium_stress, symmetric_strains_only=True): symm_eql_stresses = copy.deepcopy(stresses) symm_eql_strains = copy.deepcopy(strains) if symmetric_strains_only: all_deformations = _get_deformed_structures(equilibrium_structure, strain_magnitudes, symmetric_strains_only=False)[0] symmetry_operations_dict = symmetry_reduce(all_deformations, equilibrium_structure) deformations = [deformation for deformation in symmetry_operations_dict] for i in range(len(deformations)): deformation = deformations[i] symmetry_operations = [x for x in symmetry_operations_dict[deformation]] for symm_op in symmetry_operations: symm_eql_strains.append(strains[i].transform(symm_op)) symm_eql_stresses.append(stresses[i].transform(symm_op)) # Fit the elastic constants compliance_tensor = ElasticTensor.from_independent_strains( stresses=symm_eql_stresses, strains=symm_eql_strains, eq_stress=equilibrium_stress ) compliance_tensor = -1.0 * compliance_tensor # pymatgen has opposite sign convention return symm_eql_stresses, symm_eql_strains, compliance_tensor
def set_outputs(self): self.report('Setting Outputs') elastic_outputs = ArrayData() #An ugly ugly function to make the symmetry_operations_dict storable def make_symmopdict_aiidafriendly(symmopdict): aiida_symmopdict = dict((str(k).replace('.',','), [x.as_dict() for x in v]) for k, v in symmopdict.items()) return aiida_symmopdict equilibrium_structure = self.ctx.equilibrium_structure.get_pymatgen_structure() symmetry_operations_dict = symmetry_reduce(self.ctx.deformations, equilibrium_structure) symmetry_mapping = make_symmopdict_aiidafriendly(symmetry_operations_dict) symmetry_mapping = Dict(dict=symmetry_mapping) elastic_outputs.set_array('strains', np.array(self.ctx.strains)) elastic_outputs.set_array('stresses', np.array(self.ctx.stresses)) elastic_outputs.set_array('elastic_tensor', np.array(self.ctx.elastic_tensor)) elastic_outputs.set_array("symm_eql_strains", np.array(self.ctx.symm_eql_strains)) elastic_outputs.set_array("symm_eql_stresses", np.array(self.ctx.symm_eql_stresses)) elastic_outputs.store() symmetry_mapping.store() self.out('equilibrium_structure', self.ctx.equilibrium_structure) self.out('elastic_outputs', elastic_outputs) self.out('symmetry_mapping', symmetry_mapping)
def generate_elastic_workflow(structure, tags=None): """ Generates a standard production workflow. Notes: Uses a primitive structure transformed into the conventional basis (for equivalent deformations). Adds the "minimal" category to the minimal portion of the workflow necessary to generate the elastic tensor, and the "minimal_full_stencil" category to the portion that includes all of the strain stencil, but is symmetrically complete """ if tags == None: tags = [] # transform the structure ieee_rot = Tensor.get_ieee_rotation(structure) if not SquareTensor(ieee_rot).is_rotation(tol=0.005): raise ValueError( "Rotation matrix does not satisfy rotation conditions") symm_op = SymmOp.from_rotation_and_translation(ieee_rot) ieee_structure = structure.copy() ieee_structure.apply_operation(symm_op) # construct workflow wf = wf_elastic_constant(ieee_structure) # Set categories, starting with optimization opt_fws = get_fws_and_tasks(wf, fw_name_constraint="optimization") wf.fws[opt_fws[0][0]].spec['elastic_category'] = "minimal" # find minimal set of fireworks using symmetry reduction fws_by_strain = { Strain(fw.tasks[-1]['pass_dict']['strain']): n for n, fw in enumerate(wf.fws) if 'deformation' in fw.name } unique_tensors = symmetry_reduce(list(fws_by_strain.keys()), ieee_structure) for unique_tensor in unique_tensors: fw_index = get_tkd_value(fws_by_strain, unique_tensor) if np.isclose(unique_tensor, 0.005).any(): wf.fws[fw_index].spec['elastic_category'] = "minimal" else: wf.fws[fw_index].spec['elastic_category'] = "minimal_full_stencil" # Add tags if tags: wf = add_tags(wf, tags) wf = add_modify_incar(wf) priority = 500 - structure.num_sites wf = add_priority(wf, priority) for fw in wf.fws: if fw.spec.get('elastic_category') == 'minimal': fw.spec['_priority'] += 2000 elif fw.spec.get('elastic_category') == 'minimal_full_stencil': fw.spec['_priority'] += 1000 return wf
def test_symmetry_reduce(self): tbs = [Tensor.from_voigt(row) for row in np.eye(6) * 0.01] reduced = symmetry_reduce(tbs, self.get_structure("Sn")) self.assertEqual(len(reduced), 2) self.assertArrayEqual([len(i) for i in reduced.values()], [2, 2]) reconstructed = [] for k, v in reduced.items(): reconstructed.extend([k.voigt] + [k.transform(op).voigt for op in v]) reconstructed = sorted(reconstructed, key=lambda x: np.argmax(x)) self.assertArrayAlmostEqual([tb for tb in reconstructed], np.eye(6) * 0.01)
def test_tensor_mapping(self): # Test get tbs = [Tensor.from_voigt(row) for row in np.eye(6) * 0.01] reduced = symmetry_reduce(tbs, self.get_structure("Sn")) tkey = Tensor.from_values_indices([0.01], [(0, 0)]) tval = reduced[tkey] for tens_1, tens_2 in zip(tval, reduced[tbs[0]]): self.assertAlmostEqual(tens_1, tens_2) # Test set reduced[tkey] = "test_val" self.assertEqual(reduced[tkey], "test_val") # Test empty initialization empty = TensorMapping() self.assertEqual(empty._tensor_list, [])
def test_process_elastic_calcs_toec(self): # Test TOEC tasks test_struct = PymatgenTest.get_structure('Sn') # use cubic test struct strain_states = get_default_strain_states(3) # Default stencil in atomate, this maybe shouldn't be hard-coded stencil = np.linspace(-0.075, 0.075, 7) strains = [ Strain.from_voigt(s * np.array(strain_state)) for s, strain_state in product(stencil, strain_states) ] strains = [s for s in strains if not np.allclose(s, 0)] sym_reduced = symmetry_reduce(strains, test_struct) opt_task = { "output": { "structure": test_struct.as_dict() }, "input": { "structure": test_struct.as_dict() } } defo_tasks = [] for n, strain in enumerate(sym_reduced): defo = strain.get_deformation_matrix() new_struct = defo.apply_to_structure(test_struct) defo_task = { "output": { "structure": new_struct.as_dict(), "stress": (strain * 5).tolist() }, "input": None, "task_id": n, "completed_at": datetime.utcnow() } defo_task.update({ "transmuter": { "transformation_params": [{ "deformation": defo }] } }) defo_tasks.append(defo_task) explicit, derived = process_elastic_calcs(opt_task, defo_tasks) self.assertEqual(len(explicit), len(sym_reduced)) self.assertEqual(len(derived), len(strains) - len(sym_reduced)) for calc in derived: self.assertTrue( np.allclose(calc['strain'], calc['cauchy_stress'] / -0.5))
def _get_deformed_structures(equilibrium_structure, strain_magnitudes, symmetric_strains_only=True): deformed_mat_set = DeformedStructureSet(equilibrium_structure, norm_strains=strain_magnitudes, shear_strains=strain_magnitudes) symmetry_operations_dict = {} deformations = deformed_mat_set.deformations if symmetric_strains_only: symmetry_operations_dict = symmetry_reduce(deformations,equilibrium_structure) deformations = [x for x in symmetry_operations_dict] deformed_structures = [] for i in range(len(deformations)): mg_deformed_structure = deformations[i].apply_to_structure(equilibrium_structure) deformed_structure = StructureData(pymatgen_structure=mg_deformed_structure) deformed_structures.append(deformed_structure) return deformations, deformed_structures
def __init__(self, structure, norm_strains=None, shear_strains=None, symmetry=False): """ constructs the deformed geometries of a structure. Generates m + n deformed structures according to the supplied parameters. Args: structure (Structure): structure to undergo deformation norm_strains (list of floats): strain values to apply to each normal mode. shear_strains (list of floats): strain values to apply to each shear mode. symmetry (bool): whether or not to use symmetry reduction. """ norm_strains = norm_strains or [-0.01, -0.005, 0.005, 0.01] shear_strains = shear_strains or [-0.06, -0.03, 0.03, 0.06] self.undeformed_structure = structure self.deformations = [] self.def_structs = [] # Generate deformations for ind in [(0, 0), (1, 1), (2, 2)]: for amount in norm_strains: strain = Strain.from_index_amount(ind, amount) self.deformations.append(strain.get_deformation_matrix()) for ind in [(0, 1), (0, 2), (1, 2)]: for amount in shear_strains: strain = Strain.from_index_amount(ind, amount) self.deformations.append(strain.get_deformation_matrix()) # Perform symmetry reduction if specified if symmetry: self.sym_dict = symmetry_reduce(self.deformations, structure) self.deformations = list(self.sym_dict.keys()) self.deformed_structures = [ defo.apply_to_structure(structure) for defo in self.deformations ]
def create(**kwargs): """ Generate deformed structures for calculating deformation potentials. """ from pymatgen.core.structure import Structure from pymatgen.core.tensors import symmetry_reduce from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.util.string import unicodeify_spacegroup from amset.deformation.common import get_formatted_tensors from amset.deformation.generation import get_deformations, get_deformed_structures from amset.deformation.io import write_deformed_poscars symprec = _parse_symprec(kwargs["symprec"]) structure = Structure.from_file(kwargs["filename"]) click.echo("Generating deformations:") click.echo(" - Strain distance: {:g}".format(kwargs["distance"])) deformations = get_deformations(kwargs["distance"]) click.echo(" - # Total deformations: {}".format(len(deformations))) if symprec is not None: sga = SpacegroupAnalyzer(structure, symprec=symprec) spg_symbol = unicodeify_spacegroup(sga.get_space_group_symbol()) spg_number = sga.get_space_group_number() click.echo(" - Spacegroup: {} ({})".format(spg_symbol, spg_number)) deformations = list(symmetry_reduce(deformations, structure, symprec=symprec)) click.echo(" - # Inequivalent deformations: {}".format(len(deformations))) click.echo("\nDeformations:") click.echo(" - " + "\n - ".join(get_formatted_tensors(deformations))) deformed_structures = get_deformed_structures(structure, deformations) write_deformed_poscars(deformed_structures, directory=kwargs["directory"]) click.echo("\nDeformed structures have been created")
def get_strained_structures(equilibrium_structure, norm_strains, shear_strains, symmetric_strains_only=True): import pymatgen as mg from pymatgen.analysis.elasticity import DeformedStructureSet from pymatgen.io.ase import AseAtomsAdaptor from pymatgen.core.tensors import symmetry_reduce #global debug_global #debug_global += 1 #equilibrium_structure.write("/tmp/tmp_POSCAR/POSCAR_{}".format(debug_global), # format='vasp') try: equilibrium_structure_mg = AseAtomsAdaptor.get_structure( equilibrium_structure) deformed_mat_set = DeformedStructureSet(equilibrium_structure_mg, norm_strains=norm_strains, shear_strains=shear_strains) except Exception: equilibrium_structure.write("/tmp/POSCAR_fail", format='vasp') raise Exception("Something spoooky!") symmetry_operations_dict = {} deformations = deformed_mat_set.deformations if symmetric_strains_only: symmetry_operations_dict = symmetry_reduce(deformations, equilibrium_structure_mg) deformations = [x for x in symmetry_operations_dict] strained_structures = [] for i in range(len(deformations)): mg_deformed_structure = deformations[i].apply_to_structure( equilibrium_structure_mg) deformed_structure = AseAtomsAdaptor.get_atoms(mg_deformed_structure) strained_structures.append(deformed_structure) deformations = [np.array(x).tolist() for x in deformations] return deformations, strained_structures
def __init__(self, structure, norm_strains=None, shear_strains=None, symmetry=False): """ constructs the deformed geometries of a structure. Generates m + n deformed structures according to the supplied parameters. Args: structure (Structure): structure to undergo deformation norm_strains (list of floats): strain values to apply to each normal mode. shear_strains (list of floats): strain values to apply to each shear mode. symmetry (bool): whether or not to use symmetry reduction. """ norm_strains = norm_strains or [-0.01, -0.005, 0.005, 0.01] shear_strains = shear_strains or [-0.06, -0.03, 0.03, 0.06] self.undeformed_structure = structure self.deformations = [] self.def_structs = [] # Generate deformations for ind in [(0, 0), (1, 1), (2, 2)]: for amount in norm_strains: strain = Strain.from_index_amount(ind, amount) self.deformations.append(strain.get_deformation_matrix()) for ind in [(0, 1), (0, 2), (1, 2)]: for amount in shear_strains: strain = Strain.from_index_amount(ind, amount) self.deformations.append(strain.get_deformation_matrix()) # Perform symmetry reduction if specified if symmetry: self.sym_dict = symmetry_reduce(self.deformations, structure) self.deformations = list(self.sym_dict.keys()) self.deformed_structures = [defo.apply_to_structure(structure) for defo in self.deformations]
def get_wf_elastic_constant(structure, metadata, strain_states=None, stencils=None, db_file=None, conventional=False, order=2, vasp_input_set=None, analysis=True, sym_reduce=False, tag='elastic', copy_vasp_outputs=False, **kwargs): """ Returns a workflow to calculate elastic constants. Firework 1 : write vasp input set for structural relaxation, run vasp, pass run location, database insertion. Firework 2 - number of total deformations: Static runs on the deformed structures last Firework : Analyze Stress/Strain data and fit the elastic tensor Args: structure (Structure): input structure to be optimized and run. strain_states (list of Voigt-notation strains): list of ratios of nonzero elements of Voigt-notation strain, e. g. [(1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), etc.]. stencils (list of floats, or list of list of floats): values of strain to multiply by for each strain state, i. e. stencil for the perturbation along the strain state direction, e. g. [-0.01, -0.005, 0.005, 0.01]. If a list of lists, stencils must correspond to each strain state provided. db_file (str): path to file containing the database credentials. conventional (bool): flag to convert input structure to conventional structure, defaults to False. order (int): order of the tensor expansion to be determined. Defaults to 2 and currently supports up to 3. vasp_input_set (VaspInputSet): vasp input set to be used. Defaults to static set with ionic relaxation parameters set. Take care if replacing this, default ensures that ionic relaxation is done and that stress is calculated for each vasp run. analysis (bool): flag to indicate whether analysis task should be added and stresses and strains passed to that task sym_reduce (bool): Whether or not to apply symmetry reductions tag (str): copy_vasp_outputs (bool): whether or not to copy previous vasp outputs. kwargs (keyword arguments): additional kwargs to be passed to get_wf_deformations Returns: Workflow """ # Convert to conventional if specified if conventional: structure = SpacegroupAnalyzer( structure).get_conventional_standard_structure() uis_elastic = { "IBRION": 2, "NSW": 99, "ISIF": 2, "ISTART": 1, "PREC": "High" } vis = vasp_input_set or MPStaticSet(structure, user_incar_settings=uis_elastic) strains = [] if strain_states is None: strain_states = get_default_strain_states(order) if stencils is None: stencils = [np.linspace(-0.01, 0.01, 5 + (order - 2) * 2)] * len(strain_states) if np.array(stencils).ndim == 1: stencils = [stencils] * len(strain_states) for state, stencil in zip(strain_states, stencils): strains.extend( [Strain.from_voigt(s * np.array(state)) for s in stencil]) # Remove zero strains strains = [strain for strain in strains if not (abs(strain) < 1e-10).all()] # Adding the zero strains for the purpose of calculating at finite pressure or thermal expansion _strains = [Strain.from_deformation([[1, 0, 0], [0, 1, 0], [0, 0, 1]])] strains.extend(_strains) """ """ vstrains = [strain.voigt for strain in strains] if np.linalg.matrix_rank(vstrains) < 6: # TODO: check for sufficiency of input for nth order raise ValueError( "Strain list is insufficient to fit an elastic tensor") deformations = [s.get_deformation_matrix() for s in strains] """ print(strains) print(deformations) """ if sym_reduce: # Note this casts deformations to a TensorMapping # with unique deformations as keys to symmops deformations = symmetry_reduce(deformations, structure) wf_elastic = get_wf_deformations(structure, deformations, tag=tag, db_file=db_file, vasp_input_set=vis, copy_vasp_outputs=copy_vasp_outputs, **kwargs) if analysis: defo_fws_and_tasks = get_fws_and_tasks( wf_elastic, fw_name_constraint="deformation", task_name_constraint="Transmuted") for idx_fw, idx_t in defo_fws_and_tasks: defo = \ wf_elastic.fws[idx_fw].tasks[idx_t]['transformation_params'][0][ 'deformation'] pass_dict = { 'strain': Deformation(defo).green_lagrange_strain.tolist(), 'stress': '>>output.ionic_steps.-1.stress', 'deformation_matrix': defo } if sym_reduce: pass_dict.update({'symmops': deformations[defo]}) mod_spec_key = "deformation_tasks->{}".format(idx_fw) pass_task = pass_vasp_result(pass_dict=pass_dict, mod_spec_key=mod_spec_key) wf_elastic.fws[idx_fw].tasks.append(pass_task) fw_analysis = Firework(ElasticTensorToDb(structure=structure, db_file=db_file, order=order, fw_spec_field='tags', metadata=metadata, vasp_input_set=vis), name="Analyze Elastic Data", spec={"_allow_fizzled_parents": True}) wf_elastic.append_wf(Workflow.from_Firework(fw_analysis), wf_elastic.leaf_fw_ids) wf_elastic.name = "{}:{}".format(structure.composition.reduced_formula, "elastic constants") return wf_elastic
def get_wf_elastic_constant(structure, strain_states=None, stencils=None, db_file=None, conventional=False, order=2, vasp_input_set=None, analysis=True, sym_reduce=False, tag='elastic', copy_vasp_outputs=False, **kwargs): """ Returns a workflow to calculate elastic constants. Firework 1 : write vasp input set for structural relaxation, run vasp, pass run location, database insertion. Firework 2 - number of total deformations: Static runs on the deformed structures last Firework : Analyze Stress/Strain data and fit the elastic tensor Args: structure (Structure): input structure to be optimized and run. strain_states (list of Voigt-notation strains): list of ratios of nonzero elements of Voigt-notation strain, e. g. [(1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), etc.]. stencils (list of floats, or list of list of floats): values of strain to multiply by for each strain state, i. e. stencil for the perturbation along the strain state direction, e. g. [-0.01, -0.005, 0.005, 0.01]. If a list of lists, stencils must correspond to each strain state provided. db_file (str): path to file containing the database credentials. conventional (bool): flag to convert input structure to conventional structure, defaults to False. order (int): order of the tensor expansion to be determined. Defaults to 2 and currently supports up to 3. vasp_input_set (VaspInputSet): vasp input set to be used. Defaults to static set with ionic relaxation parameters set. Take care if replacing this, default ensures that ionic relaxation is done and that stress is calculated for each vasp run. analysis (bool): flag to indicate whether analysis task should be added and stresses and strains passed to that task sym_reduce (bool): Whether or not to apply symmetry reductions tag (str): copy_vasp_outputs (bool): whether or not to copy previous vasp outputs. kwargs (keyword arguments): additional kwargs to be passed to get_wf_deformations Returns: Workflow """ # Convert to conventional if specified if conventional: structure = SpacegroupAnalyzer( structure).get_conventional_standard_structure() uis_elastic = {"IBRION": 2, "NSW": 99, "ISIF": 2, "ISTART": 1, "PREC": "High"} vis = vasp_input_set or MPStaticSet(structure, user_incar_settings=uis_elastic) strains = [] if strain_states is None: strain_states = get_default_strain_states(order) if stencils is None: stencils = [np.linspace(-0.01, 0.01, 5 + (order - 2) * 2)] * len( strain_states) if np.array(stencils).ndim == 1: stencils = [stencils] * len(strain_states) for state, stencil in zip(strain_states, stencils): strains.extend( [Strain.from_voigt(s * np.array(state)) for s in stencil]) # Remove zero strains strains = [strain for strain in strains if not (abs(strain) < 1e-10).all()] vstrains = [strain.voigt for strain in strains] if np.linalg.matrix_rank(vstrains) < 6: # TODO: check for sufficiency of input for nth order raise ValueError("Strain list is insufficient to fit an elastic tensor") deformations = [s.get_deformation_matrix() for s in strains] if sym_reduce: # Note this casts deformations to a TensorMapping # with unique deformations as keys to symmops deformations = symmetry_reduce(deformations, structure) wf_elastic = get_wf_deformations(structure, deformations, tag=tag, db_file=db_file, vasp_input_set=vis, copy_vasp_outputs=copy_vasp_outputs, **kwargs) if analysis: defo_fws_and_tasks = get_fws_and_tasks(wf_elastic, fw_name_constraint="deformation", task_name_constraint="Transmuted") for idx_fw, idx_t in defo_fws_and_tasks: defo = \ wf_elastic.fws[idx_fw].tasks[idx_t]['transformation_params'][0][ 'deformation'] pass_dict = { 'strain': Deformation(defo).green_lagrange_strain.tolist(), 'stress': '>>output.ionic_steps.-1.stress', 'deformation_matrix': defo} if sym_reduce: pass_dict.update({'symmops': deformations[defo]}) mod_spec_key = "deformation_tasks->{}".format(idx_fw) pass_task = pass_vasp_result(pass_dict=pass_dict, mod_spec_key=mod_spec_key) wf_elastic.fws[idx_fw].tasks.append(pass_task) fw_analysis = Firework( ElasticTensorToDb(structure=structure, db_file=db_file, order=order, fw_spec_field='tags'), name="Analyze Elastic Data", spec={"_allow_fizzled_parents": True}) wf_elastic.append_wf(Workflow.from_Firework(fw_analysis), wf_elastic.leaf_fw_ids) wf_elastic.name = "{}:{}".format(structure.composition.reduced_formula, "elastic constants") return wf_elastic