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_new(self): test_strain = Strain([[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]]) self.assertArrayAlmostEqual( test_strain, test_strain.get_deformation_matrix().green_lagrange_strain) self.assertRaises(ValueError, Strain, [[0.1, 0.1, 0], [0, 0, 0], [0, 0, 0]])
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 setUp(self): self.norm_str = Strain.from_deformation([[1.02, 0, 0], [0, 1, 0], [0, 0, 1]]) self.ind_str = Strain.from_deformation([[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) self.non_ind_str = Strain.from_deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]]) with warnings.catch_warnings(record=True): warnings.simplefilter("always") self.no_dfm = Strain([[0.0, 0.01, 0.0], [0.01, 0.0002, 0.0], [0.0, 0.0, 0.0]])
def _compute_lower(self, output_file, all_tasks, all_res): output_file = os.path.abspath(output_file) res_data = {} ptr_data = output_file + '\n' equi_stress = Stress( np.loadtxt( os.path.join(os.path.dirname(output_file), 'equi.stress.out'))) lst_strain = [] lst_stress = [] for ii in all_tasks: with open(os.path.join(ii, 'inter.json')) as fp: idata = json.load(fp) inter_type = idata['type'] strain = np.loadtxt(os.path.join(ii, 'strain.out')) if inter_type == 'vasp': stress = vasp.get_stress(os.path.join(ii, 'OUTCAR')) # convert from pressure in kB to stress stress *= -1000 lst_strain.append(Strain(strain)) lst_stress.append(Stress(stress)) elif inter_type in ['deepmd', 'meam', 'eam_fs', 'eam_alloy']: stress = lammps.get_stress(os.path.join(ii, 'log.lammps')) # convert from pressure to stress stress = -stress lst_strain.append(Strain(strain)) lst_stress.append(Stress(stress)) et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress=equi_stress, vasp=False) res_data['elastic_tensor'] = [] for ii in range(6): for jj in range(6): res_data['elastic_tensor'].append(et.voigt[ii][jj] / 1e4) ptr_data += "%7.2f " % (et.voigt[ii][jj] / 1e4) ptr_data += '\n' BV = et.k_voigt / 1e4 GV = et.g_voigt / 1e4 EV = 9 * BV * GV / (3 * BV + GV) uV = 0.5 * (3 * BV - 2 * GV) / (3 * BV + GV) res_data['BV'] = BV res_data['GV'] = GV res_data['EV'] = EV res_data['uV'] = uV ptr_data += "# Bulk Modulus BV = %.2f GPa\n" % BV ptr_data += "# Shear Modulus GV = %.2f GPa\n" % GV ptr_data += "# Youngs Modulus EV = %.2f GPa\n" % EV ptr_data += "# Poission Ratio uV = %.2f " % uV with open(output_file, 'w') as fp: json.dump(res_data, fp, indent=4) return res_data, ptr_data
def test_from_index_amount(self): # From voigt index test = Strain.from_index_amount(2, 0.01) should_be = np.zeros((3, 3)) should_be[2, 2] = 0.01 self.assertArrayAlmostEqual(test, should_be) # from full-tensor index test = Strain.from_index_amount((1, 2), 0.01) should_be = np.zeros((3, 3)) should_be[1, 2] = should_be[2, 1] = 0.01 self.assertArrayAlmostEqual(test, should_be)
def energy_density(self, strain): """ Calculates the elastic energy density due to a strain """ # Conversion factor for GPa to eV/Angstrom^3 GPA_EV = 0.000624151 with warnings.catch_warnings(record=True): e_density = np.dot(np.transpose(Strain(strain).voigt), np.dot(self.voigt, Strain(strain).voigt)) / 2 * GPA_EV return e_density
def energy_density(self, strain): """ Calculates the elastic energy density due to a strain """ # Conversion factor for GPa to eV/Angstrom^3 GPA_EV = 0.000624151 e_density = np.dot(np.transpose(Strain(strain).voigt), np.dot(self, Strain(strain).voigt)) / 2 * 0.000624151 return e_density
def setUp(self): self.norm_str = Strain.from_deformation([[1.02, 0, 0], [0, 1, 0], [0, 0, 1]]) self.ind_str = Strain.from_deformation([[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) self.non_ind_str = Strain.from_deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]]) with warnings.catch_warnings(record=True): warnings.simplefilter("always") self.no_dfm = Strain([[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]])
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 setUp(self): with open(os.path.join(test_dir, 'test_toec_data.json')) as f: self.data_dict = json.load(f) self.strains = [Strain(sm) for sm in self.data_dict['strains']] self.pk_stresses = [Stress(d) for d in self.data_dict['pk_stresses']] self.c2 = NthOrderElasticTensor.from_voigt(self.data_dict["C2_raw"]) self.c3 = NthOrderElasticTensor.from_voigt(self.data_dict["C3_raw"])
def setUp(self): with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "test_toec_data.json")) as f: self.data_dict = json.load(f) self.strains = [Strain(sm) for sm in self.data_dict["strains"]] self.pk_stresses = [Stress(d) for d in self.data_dict["pk_stresses"]] self.c2 = NthOrderElasticTensor.from_voigt(self.data_dict["C2_raw"]) self.c3 = NthOrderElasticTensor.from_voigt(self.data_dict["C3_raw"])
def setUp(self): with open( os.path.join(PymatgenTest.TEST_FILES_DIR, "test_toec_data.json")) as f: self.data_dict = json.load(f) self.strains = [Strain(sm) for sm in self.data_dict["strains"]] self.pk_stresses = [Stress(d) for d in self.data_dict["pk_stresses"]]
def test_energy_density(self): film_elac = ElasticTensor.from_voigt( [[324.32, 187.3, 170.92, 0., 0., 0.], [187.3, 324.32, 170.92, 0., 0., 0.], [170.92, 170.92, 408.41, 0., 0., 0.], [0., 0., 0., 150.73, 0., 0.], [0., 0., 0., 0., 150.73, 0.], [0., 0., 0., 0., 0., 238.74]]) dfm = Deformation([[-9.86004855e-01, 2.27539582e-01, -4.64426035e-17], [-2.47802121e-01, -9.91208483e-01, -7.58675185e-17], [-6.12323400e-17, -6.12323400e-17, 1.00000000e+00]]) self.assertAlmostEqual( film_elac.energy_density(dfm.green_lagrange_strain), 0.00125664672793) film_elac.energy_density( Strain.from_deformation([[0.99774738, 0.11520994, -0.], [-0.11520994, 0.99774738, 0.], [ -0., -0., 1., ]]))
def setUp(self): with open(os.path.join(test_dir, 'test_toec_data.json')) as f: self.data_dict = json.load(f) self.strains = [Strain(sm) for sm in self.data_dict['strains']] self.pk_stresses = [Stress(d) for d in self.data_dict['pk_stresses']] self.c2 = self.data_dict["C2_raw"] self.c3 = self.data_dict["C3_raw"] self.exp = ElasticTensorExpansion.from_voigt([self.c2, self.c3]) self.cu = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.623), ["Cu"], [[0] * 3]) indices = [(0, 0), (0, 1), (3, 3)] values = [167.8, 113.5, 74.5] cu_c2 = ElasticTensor.from_values_indices(values, indices, structure=self.cu, populate=True) indices = [(0, 0, 0), (0, 0, 1), (0, 1, 2), (0, 3, 3), (0, 5, 5), (3, 4, 5)] values = [-1507., -965., -71., -7., -901., 45.] cu_c3 = Tensor.from_values_indices(values, indices, structure=self.cu, populate=True) self.exp_cu = ElasticTensorExpansion([cu_c2, cu_c3]) cu_c4 = Tensor.from_voigt(self.data_dict["Cu_fourth_order"]) self.exp_cu_4 = ElasticTensorExpansion([cu_c2, cu_c3, cu_c4]) warnings.simplefilter("ignore")
def cmpt_deepmd_lammps(jdata, conf_dir, task_name): deepmd_model_dir = jdata['deepmd_model_dir'] deepmd_type_map = jdata['deepmd_type_map'] ntypes = len(deepmd_type_map) conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, task_name) equi_stress = Stress(np.loadtxt(os.path.join(task_path, 'equi.stress.out'))) lst_dfm_path = glob.glob(os.path.join(task_path, 'dfm-*')) lst_strain = [] lst_stress = [] for ii in lst_dfm_path: strain = np.loadtxt(os.path.join(ii, 'strain.out')) stress = lammps.get_stress(os.path.join(ii, 'log.lammps')) # convert from pressure to stress stress = -stress lst_strain.append(Strain(strain)) lst_stress.append(Stress(stress)) et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress=equi_stress, vasp=False) # et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress = None) # bar to GPa # et = -et / 1e4 print_et(et)
def test_new(self): # test warning for constructing Strain without defo. matrix with warnings.catch_warnings(record=True) as w: Strain([[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]]) self.assertEqual(len(w), 1) self.assertRaises(ValueError, Strain, [[0.1, 0.1, 0], [0, 0, 0], [0, 0, 0]])
def cmpt_vasp(jdata, conf_dir): fp_params = jdata['vasp_params'] kspacing = fp_params['kspacing'] kgamma = fp_params['kgamma'] conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') task_path = re.sub('confs', global_task_name, conf_path) if 'relax_incar' in jdata.keys(): vasp_str = 'vasp-relax_incar' else: vasp_str = 'vasp-k%.2f' % kspacing task_path = os.path.join(task_path, vasp_str) equi_stress = Stress(np.loadtxt(os.path.join(task_path, 'equi.stress.out'))) lst_dfm_path = glob.glob(os.path.join(task_path, 'dfm-*')) lst_strain = [] lst_stress = [] for ii in lst_dfm_path: strain = np.loadtxt(os.path.join(ii, 'strain.out')) stress = vasp.get_stress(os.path.join(ii, 'OUTCAR')) # convert from pressure in kB to stress stress *= -1000 lst_strain.append(Strain(strain)) lst_stress.append(Stress(stress)) et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress=equi_stress, vasp=False) # et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress = None) # bar to GPa # et = -et / 1e4 print_et(et)
def cmpt_deepmd_lammps(jdata, conf_dir, task_name) : conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, task_name) equi_stress = Stress(np.loadtxt(os.path.join(task_path, 'equi.stress.out'))) lst_dfm_path = glob.glob(os.path.join(task_path, 'dfm-*')) lst_strain = [] lst_stress = [] for ii in lst_dfm_path : strain = np.loadtxt(os.path.join(ii, 'strain.out')) stress = lammps.get_stress(os.path.join(ii, 'log.lammps')) # convert from pressure to stress stress = -stress lst_strain.append(Strain(strain)) lst_stress.append(Stress(stress)) et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress = equi_stress, vasp = False) # et = ElasticTensor.from_independent_strains(lst_strain, lst_stress, eq_stress = None) # bar to GPa # et = -et / 1e4 print_et(et) result = os.path.join(task_path,'result') result_et(et,conf_dir,result) if 'upload_username' in jdata.keys() and task_name=='deepmd': upload_username=jdata['upload_username'] util.insert_data('elastic','deepmd',upload_username,result)
def get_strain_state_dict(strains, stresses, eq_stress=None, tol=1e-10, add_eq=True, sort=True): """ Creates a dictionary of voigt-notation stress-strain sets keyed by "strain state", i. e. a tuple corresponding to the non-zero entries in ratios to the lowest nonzero value, e.g. [0, 0.1, 0, 0.2, 0, 0] -> (0,1,0,2,0,0) This allows strains to be collected in stencils as to evaluate parameterized finite difference derivatives Args: strains (Nx3x3 array-like): strain matrices stresses (Nx3x3 array-like): stress matrices eq_stress (Nx3x3 array-like): equilibrium stress tol (float): tolerance for sorting strain states add_eq (bool): flag for whether to add eq_strain to stress-strain sets for each strain state sort (bool): flag for whether to sort strain states Returns: OrderedDict with strain state keys and dictionaries with stress-strain data corresponding to strain state """ # Recast stress/strains vstrains = np.array([Strain(s).zeroed(tol).voigt for s in strains]) vstresses = np.array([Stress(s).zeroed(tol).voigt for s in stresses]) # Collect independent strain states: independent = set([tuple(np.nonzero(vstrain)[0].tolist()) for vstrain in vstrains]) strain_state_dict = OrderedDict() if add_eq: if eq_stress is not None: veq_stress = Stress(eq_stress).voigt else: veq_stress = find_eq_stress(strains, stresses).voigt for n, ind in enumerate(independent): # match strains with templates template = np.zeros(6, dtype=bool) np.put(template, ind, True) template = np.tile(template, [vstresses.shape[0], 1]) mode = (template == (np.abs(vstrains) > 1e-10)).all(axis=1) mstresses = vstresses[mode] mstrains = vstrains[mode] if add_eq: # add zero strain state mstrains = np.vstack([mstrains, np.zeros(6)]) mstresses = np.vstack([mstresses, veq_stress]) # sort strains/stresses by strain values if sort: mstresses = mstresses[mstrains[:, ind[0]].argsort()] mstrains = mstrains[mstrains[:, ind[0]].argsort()] # Get "strain state", i.e. ratio of each value to minimum strain strain_state = mstrains[-1] / np.min(np.take(mstrains[-1], ind)) strain_state = tuple(strain_state) strain_state_dict[strain_state] = {"strains": mstrains, "stresses": mstresses} return strain_state_dict
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_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 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_toec_fit(self): with open(os.path.join(test_dir, 'test_toec_data.json')) as f: toec_dict = json.load(f) strains = [Strain(sm) for sm in toec_dict['strains']] pk_stresses = [Stress(d) for d in toec_dict['pk_stresses']] with warnings.catch_warnings(record=True) as w: c2, c3 = toec_fit(strains, pk_stresses, eq_stress=toec_dict["eq_stress"]) self.assertArrayAlmostEqual(c2.voigt, toec_dict["C2_raw"]) self.assertArrayAlmostEqual(c3.voigt, toec_dict["C3_raw"])
def test_from_strain_stress_list(self): strain_list = [Strain.from_deformation(def_matrix) for def_matrix in self.def_stress_dict['deformations']] stress_list = [stress for stress in self.def_stress_dict['stresses']] with warnings.catch_warnings(record = True): et_fl = -0.1*ElasticTensor.from_strain_stress_list(strain_list, stress_list) self.assertArrayAlmostEqual(et_fl.round(2), [[59.29, 24.36, 22.46, 0, 0, 0], [28.06, 56.91, 22.46, 0, 0, 0], [28.06, 25.98, 54.67, 0, 0, 0], [0, 0, 0, 26.35, 0, 0], [0, 0, 0, 0, 26.35, 0], [0, 0, 0, 0, 0, 26.35]])
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_from_pseudoinverse(self): strain_list = [Strain.from_deformation(def_matrix) for def_matrix in self.def_stress_dict['deformations']] stress_list = [stress for stress in self.def_stress_dict['stresses']] with warnings.catch_warnings(record=True): et_fl = -0.1*ElasticTensor.from_pseudoinverse(strain_list, stress_list).voigt self.assertArrayAlmostEqual(et_fl.round(2), [[59.29, 24.36, 22.46, 0, 0, 0], [28.06, 56.91, 22.46, 0, 0, 0], [28.06, 25.98, 54.67, 0, 0, 0], [0, 0, 0, 26.35, 0, 0], [0, 0, 0, 0, 26.35, 0], [0, 0, 0, 0, 0, 26.35]])
def test_properties(self): # deformation matrix self.assertArrayAlmostEqual(self.ind_str.deformation_matrix, [[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) symm_dfm = Strain(self.no_dfm, dfm_shape="symmetric") self.assertArrayAlmostEqual( symm_dfm.deformation_matrix, [[0.99995, 0.0099995, 0], [0.0099995, 1.00015, 0], [0, 0, 1]]) self.assertArrayAlmostEqual(self.no_dfm.deformation_matrix, [[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) # voigt self.assertArrayAlmostEqual(self.non_ind_str.voigt, [0, 0.0002, 0.0002, 0.0004, 0.02, 0.02])
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 run_task(self, fw_spec): v, _ = get_vasprun_outcar(self.get("calc_dir", "."), parse_dos=False, parse_eigen=False) stress = v.ionic_steps[-1]['stress'] defo = self['deformation'] d_ind = np.nonzero(defo - np.eye(3)) delta = Decimal((defo - np.eye(3))[d_ind][0]) # Shorthand is d_X_V, X is voigt index, V is value dtype = "_".join(["d", str(reverse_voigt_map[d_ind][0]), "{:.0e}".format(delta)]) strain = Strain.from_deformation(defo) defo_dict = {'deformation_matrix': defo, 'strain': strain.tolist(), 'stress': stress} return FWAction(mod_spec=[{'_set': { 'deformation_tasks->{}'.format(dtype): defo_dict}}])
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 from_strain_stress_list(cls, strains, stresses): """ Class method to fit an elastic tensor from stress/strain data. Method uses Moore-Penrose pseudoinverse to invert the s = C*e equation with elastic tensor, stress, and strain in voigt notation Args: stresses (Nx3x3 array-like): list or array of stresses strains (Nx3x3 array-like): list or array of strains """ # convert the stress/strain to Nx6 arrays of voigt-notation warnings.warn("Linear fitting of Strain/Stress lists may yield " "questionable results from vasp data, use with caution.") stresses = np.array([Stress(stress).voigt for stress in stresses]) with warnings.catch_warnings(record=True): strains = np.array([Strain(strain).voigt for strain in strains]) return cls(np.transpose(np.dot(np.linalg.pinv(strains), stresses)))
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 test_energy_density(self): film_elac = ElasticTensor.from_voigt([ [324.32, 187.3, 170.92, 0., 0., 0.], [187.3, 324.32, 170.92, 0., 0., 0.], [170.92, 170.92, 408.41, 0., 0., 0.], [0., 0., 0., 150.73, 0., 0.], [0., 0., 0., 0., 150.73, 0.], [0., 0., 0., 0., 0., 238.74]]) dfm = Deformation([[ -9.86004855e-01,2.27539582e-01,-4.64426035e-17], [ -2.47802121e-01,-9.91208483e-01,-7.58675185e-17], [ -6.12323400e-17,-6.12323400e-17,1.00000000e+00]]) self.assertAlmostEqual(film_elac.energy_density(dfm.green_lagrange_strain), 0.00125664672793) film_elac.energy_density(Strain.from_deformation([[ 0.99774738, 0.11520994, -0. ], [-0.11520994, 0.99774738, 0. ], [-0., -0., 1., ]]))
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
class StrainTest(PymatgenTest): def setUp(self): self.norm_str = Strain.from_deformation([[1.02, 0, 0], [0, 1, 0], [0, 0, 1]]) self.ind_str = Strain.from_deformation([[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) self.non_ind_str = Strain.from_deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]]) with warnings.catch_warnings(record=True): warnings.simplefilter("always") self.no_dfm = Strain([[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]]) def test_new(self): test_strain = Strain([[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]]) self.assertArrayAlmostEqual( test_strain, test_strain.get_deformation_matrix().green_lagrange_strain) self.assertRaises(ValueError, Strain, [[0.1, 0.1, 0], [0, 0, 0], [0, 0, 0]]) def test_from_deformation(self): self.assertArrayAlmostEqual(self.norm_str, [[0.0202, 0, 0], [0, 0, 0], [0, 0, 0]]) self.assertArrayAlmostEqual(self.ind_str, [[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]]) self.assertArrayAlmostEqual(self.non_ind_str, [[0., 0.01, 0.01], [0.01, 0.0002, 0.0002], [0.01, 0.0002, 0.0002]]) def test_from_index_amount(self): # From voigt index test = Strain.from_index_amount(2, 0.01) should_be = np.zeros((3, 3)) should_be[2, 2] = 0.01 self.assertArrayAlmostEqual(test, should_be) # from full-tensor index test = Strain.from_index_amount((1, 2), 0.01) should_be = np.zeros((3, 3)) should_be[1, 2] = should_be[2, 1] = 0.01 self.assertArrayAlmostEqual(test, should_be) def test_properties(self): # deformation matrix self.assertArrayAlmostEqual(self.ind_str.get_deformation_matrix(), [[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) symm_dfm = Strain(self.no_dfm).get_deformation_matrix(shape="symmetric") self.assertArrayAlmostEqual(symm_dfm, [[0.99995,0.0099995, 0], [0.0099995,1.00015, 0], [0, 0, 1]]) self.assertArrayAlmostEqual(self.no_dfm.get_deformation_matrix(), [[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) # voigt self.assertArrayAlmostEqual(self.non_ind_str.voigt, [0, 0.0002, 0.0002, 0.0004, 0.02, 0.02]) def test_convert_strain_to_deformation(self): strain = Tensor(np.random.random((3, 3))).symmetrized while not (np.linalg.eigvals(strain) > 0).all(): strain = Tensor(np.random.random((3, 3))).symmetrized upper = convert_strain_to_deformation(strain, shape="upper") symm = convert_strain_to_deformation(strain, shape="symmetric") self.assertArrayAlmostEqual(np.triu(upper), upper) self.assertTrue(Tensor(symm).is_symmetric()) for defo in upper, symm: self.assertArrayAlmostEqual(defo.green_lagrange_strain, strain)