def test_get_strain_state_dict(self): strain_inds = [(0,), (1,), (2,), (1, 3), (1, 2, 3)] vecs = {} strain_states = [] for strain_ind in strain_inds: ss = np.zeros(6) np.put(ss, strain_ind, 1) strain_states.append(tuple(ss)) vec = np.zeros((4, 6)) rand_values = np.random.uniform(0.1, 1, 4) for i in strain_ind: vec[:, i] = rand_values vecs[strain_ind] = vec all_strains = [Strain.from_voigt(v).zeroed() for vec in vecs.values() for v in vec] random.shuffle(all_strains) all_stresses = [Stress.from_voigt(np.random.random(6)).zeroed() for s in all_strains] strain_dict = {k.tostring():v for k,v in zip(all_strains, all_stresses)} ss_dict = get_strain_state_dict(all_strains, all_stresses, add_eq=False) # Check length of ss_dict self.assertEqual(len(strain_inds), len(ss_dict)) # Check sets of strain states are correct self.assertEqual(set(strain_states), set(ss_dict.keys())) for strain_state, data in ss_dict.items(): # Check correspondence of strains/stresses for strain, stress in zip(data["strains"], data["stresses"]): self.assertArrayAlmostEqual(Stress.from_voigt(stress), strain_dict[Strain.from_voigt(strain).tostring()])
def get_strains(distance=0.005): strain_fields = get_strain_fields() strains = [] for strain_field in strain_fields: strains.append(Strain.from_voigt(strain_field * abs(distance))) strains.append(Strain.from_voigt(strain_field * -abs(distance))) return strains
def test_find_eq_stress(self): random_strains = [Strain.from_voigt(s) for s in np.random.uniform(0.1, 1, (20, 6))] random_stresses = [Strain.from_voigt(s) for s in np.random.uniform(0.1, 1, (20, 6))] with warnings.catch_warnings(record=True): no_eq = find_eq_stress(random_strains, random_stresses) self.assertArrayAlmostEqual(no_eq, np.zeros((3,3))) random_strains[12] = Strain.from_voigt(np.zeros(6)) eq_stress = find_eq_stress(random_strains, random_stresses) self.assertArrayAlmostEqual(random_stresses[12], eq_stress)
def test_get_compliance_expansion(self): ce_exp = self.exp_cu.get_compliance_expansion() et_comp = ElasticTensorExpansion(ce_exp) strain_orig = Strain.from_voigt([0.01, 0, 0, 0, 0, 0]) stress = self.exp_cu.calculate_stress(strain_orig) strain_revert = et_comp.calculate_stress(stress) self.assertArrayAlmostEqual(strain_orig, strain_revert, decimal=4)
def test_get_strain_from_stress(self): strain = Strain.from_voigt([0.05, 0, 0, 0, 0, 0]) stress3 = self.exp_cu.calculate_stress(strain) strain_revert3 = self.exp_cu.get_strain_from_stress(stress3) self.assertArrayAlmostEqual(strain, strain_revert3, decimal=2) # fourth order stress4 = self.exp_cu_4.calculate_stress(strain) strain_revert4 = self.exp_cu_4.get_strain_from_stress(stress4) self.assertArrayAlmostEqual(strain, strain_revert4, decimal=2)
def test_find_eq_stress(self): test_strains = deepcopy(self.strains) test_stresses = deepcopy(self.pk_stresses) with warnings.catch_warnings(record=True): no_eq = find_eq_stress(test_strains, test_stresses) self.assertArrayAlmostEqual(no_eq, np.zeros((3,3))) test_strains[3] = Strain.from_voigt(np.zeros(6)) eq_stress = find_eq_stress(test_strains, test_stresses) self.assertArrayAlmostEqual(test_stresses[3], eq_stress)
def test_find_eq_stress(self): test_strains = deepcopy(self.strains) test_stresses = deepcopy(self.pk_stresses) with warnings.catch_warnings(record=True): no_eq = find_eq_stress(test_strains, test_stresses) self.assertArrayAlmostEqual(no_eq, np.zeros((3, 3))) test_strains[3] = Strain.from_voigt(np.zeros(6)) eq_stress = find_eq_stress(test_strains, test_stresses) self.assertArrayAlmostEqual(test_stresses[3], eq_stress)
def calculate_stress(self, strain): """ Calculate's a given elastic tensor's contribution to the stress using Einstein summation Args: strain (3x3 array-like): matrix corresponding to strain """ strain = np.array(strain) if strain.shape == (6,): strain = Strain.from_voigt(strain) assert strain.shape == (3, 3), "Strain must be 3x3 or voigt-notation" stress_matrix = self.einsum_sequence([strain] * (self.order - 1)) / factorial(self.order - 1) return Stress(stress_matrix)
def calculate_stress(self, strain): """ Calculate's a given elastic tensor's contribution to the stress using Einstein summation Args: strain (3x3 array-like): matrix corresponding to strain """ strain = np.array(strain) if strain.shape == (6,): strain = Strain.from_voigt(strain) assert strain.shape == (3, 3), "Strain must be 3x3 or voigt-notation" stress_matrix = self.einsum_sequence([strain]*(self.order - 1)) \ / factorial(self.order - 1) return Stress(stress_matrix)
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 calculate_stress(self, strain): """ Calculate's a given elastic tensor's contribution to the stress using Einstein summation Args: strain (3x3 array-like): matrix corresponding to strain """ strain = np.array(strain) if strain.shape == (6, ): strain = Strain.from_voigt(strain) assert strain.shape == (3, 3), "Strain must be 3x3 or voigt-notation" lc = string.ascii_lowercase[:self.rank - 2] lc_pairs = map(''.join, zip(*[iter(lc)] * 2)) einsum_string = "ij" + lc + ',' + ','.join(lc_pairs) + "->ij" einsum_args = [self] + [strain] * (self.order - 1) stress_matrix = np.einsum(einsum_string, *einsum_args) \ / factorial(self.order - 1) return Stress(stress_matrix)
def calculate_stress(self, strain): """ Calculate's a given elastic tensor's contribution to the stress using Einstein summation Args: strain (3x3 array-like): matrix corresponding to strain """ strain = np.array(strain) if strain.shape == (6,): strain = Strain.from_voigt(strain) assert strain.shape == (3, 3), "Strain must be 3x3 or voigt-notation" lc = string.ascii_lowercase[:self.rank-2] lc_pairs = map(''.join, zip(*[iter(lc)]*2)) einsum_string = "ij" + lc + ',' + ','.join(lc_pairs) + "->ij" einsum_args = [self] + [strain] * (self.order - 1) stress_matrix = np.einsum(einsum_string, *einsum_args) \ / factorial(self.order - 1) return Stress(stress_matrix)
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
def process_elastic_calcs(opt_doc, defo_docs, add_derived=True, tol=0.002): """ Generates the list of calcs from deformation docs, along with 'derived stresses', i. e. stresses derived from symmop transformations of existing calcs from transformed strains resulting in an independent strain not in the input list Args: opt_doc (dict): document for optimization task defo_docs ([dict]) list of documents for deformation tasks add_derived (bool): flag for whether or not to add derived stress-strain pairs based on symmetry tol (float): tolerance for assigning equivalent stresses/strains Returns ([dict], [dict]): Two lists of summary documents corresponding to strains and stresses, one explicit and one derived """ structure = Structure.from_dict(opt_doc['output']['structure']) input_structure = Structure.from_dict(opt_doc['input']['structure']) # Process explicit calcs, store in dict keyed by strain explicit_calcs = TensorMapping() for doc in defo_docs: calc = { "type": "explicit", "input": doc["input"], "output": doc["output"], "task_id": doc["task_id"], "completed_at": doc["completed_at"] } deformed_structure = Structure.from_dict(doc['output']['structure']) defo = Deformation(calculate_deformation(structure, deformed_structure)) # Warning if deformation is not equivalent to stored deformation stored_defo = doc['transmuter']['transformation_params'][0]\ ['deformation'] if not np.allclose(defo, stored_defo, atol=1e-5): wmsg = "Inequivalent stored and calc. deformations." logger.debug(wmsg) calc["warnings"] = wmsg cauchy_stress = -0.1 * Stress(doc['output']['stress']) pk_stress = cauchy_stress.piola_kirchoff_2(defo) strain = defo.green_lagrange_strain calc.update({ "deformation": defo, "cauchy_stress": cauchy_stress, "strain": strain, "pk_stress": pk_stress }) if strain in explicit_calcs: existing_value = explicit_calcs[strain] if doc['completed_at'] > existing_value['completed_at']: explicit_calcs[strain] = calc else: explicit_calcs[strain] = calc if not add_derived: return explicit_calcs.values(), None # Determine all of the implicit calculations to include sga = SpacegroupAnalyzer(structure, symprec=0.1) symmops = sga.get_symmetry_operations(cartesian=True) derived_calcs_by_strain = TensorMapping(tol=0.002) for strain, calc in explicit_calcs.items(): # Generate all transformed strains task_id = calc['task_id'] tstrains = [(symmop, strain.transform(symmop)) for symmop in symmops] # Filter strains by those which are independent and new # For second order if len(explicit_calcs) < 30: tstrains = [(symmop, tstrain) for symmop, tstrain in tstrains if tstrain.get_deformation_matrix().is_independent(tol) and not tstrain in explicit_calcs] # For third order else: 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) valid_strains = [ Strain.from_voigt(s * np.array(strain_state)) for s, strain_state in product(stencil, strain_states) ] valid_strains = [v for v in valid_strains if not np.allclose(v, 0)] valid_strains = TensorMapping(valid_strains, [True] * len(valid_strains)) tstrains = [ (symmop, tstrain) for symmop, tstrain in tstrains if tstrain in valid_strains and not tstrain in explicit_calcs ] # Add surviving tensors to derived_strains dict for symmop, tstrain in tstrains: # curr_set = derived_calcs_by_strain[tstrain] if tstrain in derived_calcs_by_strain: curr_set = derived_calcs_by_strain[tstrain] curr_task_ids = [c[1] for c in curr_set] if task_id not in curr_task_ids: curr_set.append((symmop, calc['task_id'])) else: derived_calcs_by_strain[tstrain] = [(symmop, calc['task_id'])] # Process derived calcs explicit_calcs_by_id = {d['task_id']: d for d in explicit_calcs.values()} derived_calcs = [] for strain, calc_set in derived_calcs_by_strain.items(): symmops, task_ids = zip(*calc_set) task_strains = [ Strain(explicit_calcs_by_id[task_id]['strain']) for task_id in task_ids ] task_stresses = [ explicit_calcs_by_id[task_id]['cauchy_stress'] for task_id in task_ids ] derived_strains = [ tstrain.transform(symmop) for tstrain, symmop in zip(task_strains, symmops) ] for derived_strain in derived_strains: if not np.allclose(derived_strain, strain, atol=2e-3): logger.info("Issue with derived strains") raise ValueError("Issue with derived strains") derived_stresses = [ tstress.transform(sop) for sop, tstress in zip(symmops, task_stresses) ] input_docs = [{ "task_id": task_id, "strain": task_strain, "cauchy_stress": task_stress, "symmop": symmop } for task_id, task_strain, task_stress, symmop in zip( task_ids, task_strains, task_stresses, symmops)] calc = { "strain": strain, "cauchy_stress": Stress(np.average(derived_stresses, axis=0)), "deformation": strain.get_deformation_matrix(), "input_tasks": input_docs, "type": "derived" } calc['pk_stress'] = calc['cauchy_stress'].piola_kirchoff_2( calc['deformation']) derived_calcs.append(calc) return list(explicit_calcs.values()), derived_calcs