def test_phbst_file_with_loto(self): """Testing PHBST file with LOTO terms from anaddb.nc.""" with abilab.abiopen(abidata.ref_file("ZnSe_hex_886.out_PHBST.nc")) as ncfile: phbands = ncfile.phbands # Phonon frequencies with non analytical contributions, if calculated, are saved # in the anaddb.nc file produced by anaddb. The results should be fetched from there # and added to the phonon bands. phbands.read_non_anal_from_file(abidata.ref_file("ZnSe_hex_886.anaddb.nc")) nana = phbands.non_anal_ph assert nana.structure == phbands.structure str(nana.structure.reciprocal_lattice) self.assert_almost_equal(nana.directions.ravel(), [0.1234510847, -0.071274517, 0, 0.1646014463, 0, 0, 0, 0, 0.0751616546]) for i, cart_direc in enumerate(nana.directions): assert nana.has_direction(cart_direc, cartesian=True) red_direc = phbands.structure.reciprocal_lattice.get_fractional_coords(cart_direc) idir, qdir = phbands.qindex_qpoint(red_direc, is_non_analytical_direction=True) assert i == idir idir, qdir = phbands.qindex_qpoint(qdir, is_non_analytical_direction=True) assert i == idir if self.has_matplotlib(): assert phbands.plot(title="ZnSe with LO-TO splitting", show=False) red_direc = phbands.structure.reciprocal_lattice.get_fractional_coords(nana.directions[1]) assert phbands.plot_phdispl(qpoint=red_direc, is_non_analytical_direction=True, show=False) assert phbands.plot_phdispl(qpoint=red_direc, is_non_analytical_direction=True, use_eigvec=True, show=False)
def test_base(self): """Testing DielectricTensor""" anaddbnc_fname = abidata.ref_file("AlAs_nl_dte_anaddb.nc") phbstnc_fname = abidata.ref_file("AlAs_nl_dte_PHBST.nc") d = DielectricTensorGenerator.from_files(phbstnc_fname, anaddbnc_fname) assert d.eps0.shape == (3, 3) df = d.epsinf.get_dataframe() assert d.epsinf._repr_html_() repr(d); str(d) assert d.to_string(verbose=2) df = d.get_oscillator_dataframe(reim="all", tol=1e-8) df = d.get_oscillator_dataframe(reim="im", tol=1e-8) df = d.get_oscillator_dataframe(reim="re", tol=1e-8) self.assertAlmostEqual(d.tensor_at_frequency(0.001, units='Ha', gamma_ev=0.0)[0, 0], 11.917178540635028) d = DielectricTensorGenerator.from_objects(PhononBands.from_file(phbstnc_fname), AnaddbNcFile.from_file(anaddbnc_fname)) self.assertAlmostEqual(d.tensor_at_frequency(0.001, units='Ha', gamma_ev=0.0)[0, 0], 11.917178540635028) if self.has_matplotlib(): assert d.plot_vs_w(w_min=0.0001, w_max=0.01, num=10, units="Ha", show=False) assert d.plot_vs_w(w_min=0, w_max=None, num=10, units="cm-1", show=False) for comp in ["diag", "all", "diag_av"]: assert d.plot_vs_w(num=10, component=comp, units="cm-1", show=False)
def test_jdos(self): """Test JDOS methods.""" bands = ElectronBands.from_file(data.ref_file("si_scf_GSR.nc")) spin = 0 conduction = [4,] for v in range(1,5): valence = range(0,v) jdos = bands.get_ejdos(spin, valence, conduction) intg = jdos.integral()[-1][-1] self.assert_almost_equal(intg, len(conduction) * len(valence)) self.serialize_with_pickle(jdos, protocols=[-1]) nscf_bands = ElectronBands.from_file(data.ref_file("si_nscf_GSR.nc")) # Test the detection of denerate states. degs = nscf_bands.degeneracies(spin=0, kpoint=[0,0,0], bands_range=range(8)) ref_degbands = [[0], [1,2,3], [4,5,6], [7]] for i, (e, deg_bands) in enumerate(degs): self.assertEqual(deg_bands, ref_degbands[i]) # JDOS a homogeneous sampling. with self.assertRaises(ValueError): nscf_bands.get_ejdos(spin, 0, 4)
def test_potentials(self): """Testing Potentials.""" vxc = VxcPotential.from_file(abidata.ref_file("ni_666k_VXC.nc")) assert vxc.nsppol == 2 and vxc.nspden == 2 assert vxc.is_collinear assert not vxc.is_density_like assert vxc.is_potential_like assert vxc.datar.dtype == np.float fact = pmgu.Ha_to_eV / pmgu.bohr_to_angstrom ** 3 self.assert_almost_equal(vxc.datar[0, 0, 0, 0], -2.40411892342838 * fact) self.assert_almost_equal(vxc.datar[0, 0, 0, 1], -2.31753083824603 * fact) if self.has_matplotlib(): assert vxc.plot_line([0, 0, 0], [1, 1, 1], num=1000, show=False) vh = VhartreePotential.from_file(abidata.ref_file("ni_666k_VHA.nc")) assert vh.nsppol == 2 and vh.nspden == 2 assert vh.is_collinear assert not vh.is_density_like assert vh.is_potential_like vhxc = VhxcPotential.from_file(abidata.ref_file("ni_666k_VHXC.nc")) assert vhxc.nsppol == 2 and vhxc.nspden == 2 assert vhxc.is_collinear assert not vhxc.is_density_like assert vhxc.is_potential_like # VH + VXC = VHXC self.assert_almost_equal((vh + 1.0 * vxc).datar, vhxc.datar)
def test_builder(self): """Testing ScissorsBuilder.""" builder = ScissorsBuilder.from_file(abidata.ref_file("si_g0w0ppm_nband30_SIGRES.nc")) assert builder.nsppol == 1 # To select the domains esplicitly (optional) builder.build(domains_spin=[[-10, 6.02], [6.1, 20]]) # Test pickle. tmp_path = self.get_tmpname(suffix=".pickle") builder.pickle_dump(tmp_path) new = ScissorsBuilder.pickle_load(tmp_path) if self.has_matplotlib(): # To plot the QP results as function of the KS energy: assert builder.plot_qpe_vs_e0(show=False) # To compare the fitted results with the ab-initio data: assert builder.plot_fit(show=False) # To plot the corrected bands: bands_filepath = abidata.ref_file("si_nscf_WFK.nc") assert builder.plot_qpbands(bands_filepath, show=False) dos_filepath = abidata.ref_file("si_scf_GSR.nc") assert builder.plot_qpbands(bands_filepath, dos_filepath=dos_filepath, dos_args=None, show=False)
def test_dte_result(self): doc = DteResult(mp_id="mp-1", time_report= {"test": 1}, fw_id=1, relax_db={"test": 1}, relax_id="id_string") doc.abinit_input.structure = self.si_structure.as_dict() doc.abinit_input.gs_input = self.scf_inp.as_dict() doc.abinit_input.ddk_input = self.scf_inp.as_dict() doc.abinit_input.dde_input = self.scf_inp.as_dict() doc.abinit_input.dte_input = self.scf_inp.as_dict() doc.abinit_input.phonon_input = self.scf_inp.as_dict() doc.abinit_input.kppa = 1000 doc.abinit_input.with_phonons = True doc.abinit_output.structure = self.si_structure.as_dict() doc.abinit_output.emacro = np.eye(3).tolist() doc.abinit_output.emacro_rlx = np.eye(3).tolist() doc.abinit_output.dchide = np.arange(36).reshape((4,3,3)).tolist() doc.abinit_output.dchidt = np.arange(36).reshape((2,2,3,3)).tolist() if has_mongodb(): gsr_path = abidata.ref_file('si_scf_GSR.nc') with open(gsr_path, "rb") as gsr: doc.abinit_output.gs_gsr.put(gsr) gs_outfile_path = self.out_file # read/write in binary for py3k compatibility with mongoengine with open(gs_outfile_path, "rb") as gs_outfile: doc.abinit_output.gs_outfile.put(gs_outfile) anaddb_nc_path = abidata.ref_file('ZnSe_hex_886.anaddb.nc') with open(anaddb_nc_path, "rb") as anaddb_nc: doc.abinit_output.anaddb_nc.put(anaddb_nc) doc.save() query_result = DteResult.objects() assert len(query_result) == 1 saved_doc = query_result[0] with tempfile.NamedTemporaryFile(mode="wb") as db_file: db_file.write(saved_doc.abinit_output.gs_gsr.read()) db_file.seek(0) assert filecmp.cmp(gsr_path, db_file.name) with tempfile.NamedTemporaryFile(mode="wt") as db_file: saved_doc.abinit_output.gs_outfile.unzip(filepath=db_file.name) db_file.seek(0) assert filecmp.cmp(gs_outfile_path, db_file.name) with tempfile.NamedTemporaryFile(mode="wb") as db_file: db_file.write(saved_doc.abinit_output.anaddb_nc.read()) db_file.seek(0) assert filecmp.cmp(anaddb_nc_path, db_file.name)
def test_gsr_silicon(self): """spin unpolarized GSR file""" almost_equal = self.assertAlmostEqual with GsrFile(data.ref_file("si_scf_GSR.nc")) as gsr: print(repr(gsr)) print(gsr) print(gsr.ebands) assert gsr.filepath == data.ref_file("si_scf_GSR.nc") assert gsr.nsppol == 1 assert gsr.mband == 8 and gsr.nband == 8 and gsr.nelect == 8 and len(gsr.kpoints) == 29 almost_equal(gsr.energy.to("Ha"), -8.86527676798556) almost_equal(gsr.energy_per_atom * len(gsr.structure), gsr.energy) # Test energy_terms eterm = gsr.energy_terms print(eterm) almost_equal(eterm.e_xc.to("Ha"), -3.51815936301812) almost_equal(eterm.e_nonlocalpsp.to("Ha"), 1.91660690901782) almost_equal(eterm.e_kinetic.to("Ha"), 2.96421325671218) almost_equal(eterm.e_fermie.to("Ha"), 0.205739364929368) # Forces and stress self.assert_almost_equal(gsr.cart_forces.flat, [-5.98330096024095e-30, -5.64111024387213e-30, 1.49693284867669e-29, 5.98330096024095e-30, 5.64111024387213e-30, -1.49693284867669e-29]) almost_equal(gsr.max_force, 0) print(gsr.force_stats()) #self.assert_almost_equal(gsr.cart_stress_tensor.flat, # Cartesian components of stress tensor (hartree/bohr^3) # sigma(1 1)= 1.77139311E-04 sigma(3 2)= 0.00000000E+00 # sigma(2 2)= 1.77139311E-04 sigma(3 1)= 0.00000000E+00 # sigma(3 3)= 1.77139311E-04 sigma(2 1)= 2.67294316E-15 almost_equal(gsr.pressure, -5.21162150) # Test gsr.density. print(gsr.density) almost_equal(gsr.magnetization, 0) # Test as_dict pprint(gsr.as_dict()) #import json #with open("hello.json", "w") as fp: # json.dump(gsr.as_dict(), fp) #assert 0 # Test pymatgen computed_entries for inc_structure in (True, False): e = gsr.get_computed_entry(inc_structure=inc_structure) print(e) print(e.as_dict()) assert gsr.energy == e.energy
def test_interpolator(self): """Test QP interpolation.""" # Get quasiparticle results from the SIGRES.nc database. sigres = abilab.abiopen(abidata.ref_file("si_g0w0ppm_nband30_SIGRES.nc")) # Interpolate QP corrections and apply them on top of the KS band structures. # QP band energies are returned in r.qp_ebands_kpath and r.qp_ebands_kmesh. # Just to test call without ks_ebands. r = sigres.interpolate(lpratio=5, ks_ebands_kpath=None, ks_ebands_kmesh=None, verbose=0, filter_params=[1.0, 1.0], line_density=10) r = sigres.interpolate(lpratio=5, ks_ebands_kpath=abidata.ref_file("si_nscf_GSR.nc"), ks_ebands_kmesh=abidata.ref_file("si_scf_GSR.nc"), verbose=0, filter_params=[1.0, 1.0], line_density=10) assert r.qp_ebands_kpath is not None assert r.qp_ebands_kpath.kpoints.is_path #print(r.qp_ebands_kpath.kpoints.ksampling, r.qp_ebands_kpath.kpoints.mpdivs_shifts) assert r.qp_ebands_kpath.kpoints.mpdivs_shifts == (None, None) assert r.qp_ebands_kmesh is not None assert r.qp_ebands_kmesh.kpoints.is_ibz assert r.qp_ebands_kmesh.kpoints.ksampling is not None assert r.qp_ebands_kmesh.kpoints.is_mpmesh qp_mpdivs, qp_shifts = r.qp_ebands_kmesh.kpoints.mpdivs_shifts assert qp_mpdivs is not None assert qp_shifts is not None ks_mpdivs, ks_shifts = r.ks_ebands_kmesh.kpoints.mpdivs_shifts self.assert_equal(qp_mpdivs, ks_mpdivs) self.assert_equal(qp_shifts, ks_shifts) # Get DOS from interpolated energies. ks_edos = r.ks_ebands_kmesh.get_edos() qp_edos = r.qp_ebands_kmesh.get_edos() r.qp_ebands_kmesh.to_bxsf(self.get_tmpname(text=True)) points = sigres.get_points_from_ebands(r.qp_ebands_kpath, size=24, verbose=2) # Plot the LDA and the QPState band structure with matplotlib. plotter = abilab.ElectronBandsPlotter() plotter.add_ebands("LDA", r.ks_ebands_kpath, edos=ks_edos) plotter.add_ebands("GW (interpolated)", r.qp_ebands_kpath, edos=qp_edos) if self.has_matplotlib(): assert plotter.combiplot(title="Silicon band structure", show=False) assert plotter.gridplot(title="Silicon band structure", show=False) assert r.qp_ebands_kpath.plot(points=points, show=False) sigres.close()
def test_frame_from_ebands(self): """Testing dataframe_from_ebands.""" gsr_kmesh = abidata.ref_file("si_scf_GSR.nc") si_ebands_kmesh = ElectronBands.as_ebands(gsr_kmesh) gsr_nscf_path = abidata.ref_file("si_nscf_GSR.nc") index = ["foo", "bar", "hello"] df = dataframe_from_ebands([gsr_kmesh, si_ebands_kmesh, gsr_nscf_path], index=index, with_spglib=True) #str(df) assert all(f == "Si2" for f in df["formula"]) assert all(num == 227 for num in df["abispg_num"]) assert all(df["spglib_num"] == df["abispg_num"])
def test_MgB2_fatbands(self): """Testing MgB2 fatbands with prtdos 3.""" fbnc_kpath = FatBandsFile(abidata.ref_file("mgb2_kpath_FATBANDS.nc")) repr(fbnc_kpath); str(fbnc_kpath) assert fbnc_kpath.to_string(verbose=2) assert fbnc_kpath.ebands.kpoints.is_path assert not fbnc_kpath.ebands.kpoints.is_ibz assert fbnc_kpath.prtdos == 3 assert fbnc_kpath.prtdosm == 0 assert fbnc_kpath.mbesslang == 5 assert fbnc_kpath.pawprtdos == 0 assert fbnc_kpath.usepaw == 0 assert fbnc_kpath.nsppol == 1 assert fbnc_kpath.nspden == 1 assert fbnc_kpath.nspinor == 1 assert fbnc_kpath.nkpt == 78 assert fbnc_kpath.mband == 8 assert fbnc_kpath.natsph_extra == 0 assert not fbnc_kpath.ebands.has_metallic_scheme assert fbnc_kpath.params["nkpt"] == 78 if self.has_matplotlib(): assert fbnc_kpath.plot_fatbands_typeview(tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_lview(tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_siteview(e0=None, view="inequivalent", fact=2.0, bdist=[1, 2, 3], show=False) if self.has_nbformat(): fbnc_kpath.write_notebook(nbpath=self.get_tmpname(text=True)) fbnc_kmesh = FatBandsFile(abidata.ref_file("mgb2_kmesh181818_FATBANDS.nc")) repr(fbnc_kmesh); str(fbnc_kmesh) assert fbnc_kmesh.ebands.kpoints.is_ibz assert fbnc_kmesh.ebands.has_metallic_scheme if self.has_matplotlib(): assert fbnc_kmesh.plot_pjdos_typeview(tight_layout=True, show=False) assert fbnc_kmesh.plot_pjdos_lview(tight_layout=True, stacked=True, show=False) assert fbnc_kmesh.plot_pjdos_lview(tight_layout=True, stacked=False, show=False) assert fbnc_kpath.plot_fatbands_with_pjdos(pjdosfile=fbnc_kmesh, view="type", tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_with_pjdos(pjdosfile=fbnc_kmesh, view="lview", tight_layout=True, show=False) assert fbnc_kpath.plot_spilling(e0=0, tight_layout=True, show=False) # These calls should return None #assert fbnc_kpath.plot_fatbands_spinor() is None assert fbnc_kpath.plot_pjdos_lview() is None assert fbnc_kpath.plot_pawdos_terms() is None #assert fbnc_kpath.plot_pjdos_spinor() is None assert fbnc_kpath.plot_fatbands_mview(iatom=0) is None fbnc_kpath.close() fbnc_kmesh.close()
def test_dos(self): """Test DOS methods.""" gs_bands = ElectronBands.from_file(data.ref_file("si_scf_GSR.nc")) dos = gs_bands.get_edos() print(dos) assert ElectronDos.as_edos(dos, {}) is dos edos_samevals = ElectronDos.as_edos(gs_bands, {}) assert ElectronDos.as_edos(gs_bands, {}) == dos assert ElectronDos.as_edos(data.ref_file("si_scf_GSR.nc"), {}) == dos mu = dos.find_mu(8) imu = dos.tot_idos.find_mesh_index(mu) self.assert_almost_equal(dos.tot_idos[imu][1], 8, decimal=2) self.serialize_with_pickle(dos, protocols=[-1], test_eq=False)
def test_ph_output(self): """Testing AbinitOutputFile with phonon calculations.""" abo_path = abidata.ref_file("refs/gs_dfpt.abo") with AbinitOutputFile(abo_path) as abo: repr(abo); str(abo) assert abo.to_string(verbose=2) assert abo.version == "8.3.2" assert abo.run_completed assert not abo.dryrun_mode assert abo.ndtset == 3 assert abo.has_same_initial_structures assert abo.has_same_final_structures assert len(abo.initial_structures) == 3 assert abo.initial_structure is not None assert abo.initial_structure.abi_spacegroup is not None assert abo.initial_structure == abo.final_structure gs_cycle = abo.next_gs_scf_cycle() assert gs_cycle is not None ph_cycle = abo.next_d2de_scf_cycle() assert ph_cycle is not None if self.has_matplotlib(): assert ph_cycle.plot(show=False) assert abo.compare_d2de_scf_cycles([abo_path], show=False) abo.plot(show=False) if self.has_nbformat(): abo.write_notebook(nbpath=self.get_tmpname(text=True))
def test_dryrun_output(self): """Testing AbinitOutputFile with file produced in dry-run mode.""" with abilab.abiopen(abidata.ref_file("refs/dryrun.abo")) as abo: repr(abo); str(abo) assert abo.to_string(verbose=2) assert abo.dryrun_mode assert abo.ndtset == 1 assert abo.has_same_initial_structures assert abo.has_same_final_structures assert len(abo.initial_structures) == 1 assert abo.initial_structure.abi_spacegroup is not None # This to test get_dims_spginfo_dataset with one dataset. dims_dataset, spg_dataset = abo.get_dims_spginfo_dataset() assert len(dims_dataset) == 1 dims = dims_dataset[1] assert dims["nsppol"] == 1 assert dims["nsym"] == 48 assert dims["nkpt"] == 29 self.assert_almost_equal(dims["mem_per_proc_mb"], 3.389) self.assert_almost_equal(dims["wfk_size_mb"], 0.717) self.assert_almost_equal(dims["denpot_size_mb"], 0.046) assert spg_dataset[1]["spg_symbol"] == "Fd-3m" assert spg_dataset[1]["spg_number"] == 227 assert spg_dataset[1]["bravais"] == "Bravais cF (face-center cubic)"
def test_vpot_ncfile(self): """Testing POT netcdf file.""" with abilab.abiopen(abidata.ref_file("ni_666k_POT.nc")) as ncfile: repr(ncfile); str(ncfile) assert ncfile.ebands.nsppol == 2 and ncfile.ebands.nspden == 2 assert ncfile.structure.formula == "Ni1" assert ncfile.ebands.structure == ncfile.structure assert str(ncfile.xc) == "PBE" vks = ncfile.vks assert vks.netcdf_name == "vtrial" assert vks.nspinor == 1 and vks.nsppol == 2 and vks.nspden == 2 assert vks.is_potential_like assert not vks.is_density_like ## Test converters. #ncfile.write_chgcar(filename=self.get_tmpname(text=True)) #ncfile.write_xsf(filename=self.get_tmpname(text=True, suffix=".xsf")) #ncfile.write_cube(filename=self.get_tmpname(text=True), spin="total") if self.has_matplotlib(): assert ncfile.ebands.plot(show=False) # Test ipython notebooks. if self.has_nbformat(): ncfile.write_notebook(nbpath=self.get_tmpname(text=True))
def test_base(self): """Test SIGRES File.""" sigres = abiopen(data.ref_file("tgw1_9o_DS4_SIGRES.nc")) self.assertTrue(sigres.nsppol == 1) # Markers are initialied in __init__ self.assertTrue(sigres.ebands.markers) # In this run IBZ = kptgw self.assertTrue(len(sigres.ibz) == 6) self.assertTrue(sigres.gwkpoints == sigres.ibz) kptgw_coords = np.reshape([ -0.25, -0.25, 0, -0.25, 0.25, 0, 0.5, 0.5, 0, -0.25, 0.5, 0.25, 0.5, 0, 0, 0, 0, 0 ], (-1,3)) self.assert_almost_equal(sigres.ibz.frac_coords, kptgw_coords) qpgaps = [3.53719151871085, 4.35685250045637, 4.11717896881632, 8.71122659251508, 3.29693118466282, 3.125545059031] self.assert_almost_equal(sigres.qpgaps, np.reshape(qpgaps, (1,6)))
def test_mgo_becs_emacro(self): """ Testing DDB for MgO with with Born effective charges and E_macro. Large breaking of the ASR. """ with abilab.abiopen(abidata.ref_file("mp-1009129-9x9x10q_ebecs_DDB")) as ddb: assert ddb.structure.formula == "Mg1 O1" assert len(ddb.qpoints) == 72 assert ddb.has_epsinf_terms() assert ddb.has_epsinf_terms(select="at_least_one_diagoterm") assert ddb.has_bec_terms() if self.has_matplotlib(): plotter = ddb.anacompare_asr(asr_list=(0, 2), chneut_list=(0, 1), dipdip=1, nqsmall=2, ndivsm=5, dos_method="tetra", ngqpt=None, verbose=2) str(plotter) assert plotter.combiplot(show=False) # Test nqsmall == 0 plotter = ddb.anacompare_asr(asr_list=(0, 2), chneut_list=(0, 1), dipdip=1, nqsmall=0, ndivsm=5, dos_method="tetra", ngqpt=None, verbose=2) assert plotter.gridplot(show=False) plotter = ddb.anacompare_dipdip(chneut_list=(0, 1), asr=1, nqsmall=0, ndivsm=5, dos_method="gaussian", ngqpt=None, verbose=2) assert plotter.gridplot(show=False)
def test_ddb_robot(self): """Testing DDB robots.""" assert not abilab.DdbRobot.class_handles_filename("foo_DDB.nc") assert abilab.DdbRobot.class_handles_filename("foo_DDB") path = abidata.ref_file("refs/znse_phonons/ZnSe_hex_qpt_DDB") robot = abilab.DdbRobot.from_files(path) robot.add_file("same_ddb", path) repr(robot); str(robot) assert robot.to_string(verbose=2) assert len(robot) == 2 assert robot.EXT == "DDB" data = robot.get_dataframe_at_qpoint(qpoint=[0, 0, 0], asr=2, chneut=1, dipdip=0, with_geo=True, abspath=True) assert "mode1" in data and "alpha" in data r = robot.anaget_phonon_plotters(nqsmall=2, ndivsm=2, dipdip=0, verbose=2) if self.has_matplotlib(): assert r.phbands_plotter.gridplot(show=False) assert r.phdos_plotter.gridplot(show=False) if self.has_nbformat(): assert robot.write_notebook(nbpath=self.get_tmpname(text=True)) robot.close()
def test_ebands_skw_interpolation(self): """Testing SKW interpolation.""" si_ebands_kmesh = ElectronBands.from_file(abidata.ref_file("si_scf_GSR.nc")) # Test interpolation. vertices_names = [((0.0, 0.0, 0.0), "G"), ((0.5, 0.5, 0.0), "M")] r = si_ebands_kmesh.interpolate(lpratio=10, vertices_names=vertices_names, kmesh=[8, 8, 8], verbose=1) assert r.ebands_kpath is not None assert r.ebands_kpath.kpoints.is_path assert not r.ebands_kpath.kpoints.is_ibz mpdivs, shifts = r.ebands_kpath.kpoints.mpdivs_shifts assert mpdivs is None and shifts is None assert r.ebands_kmesh is not None assert r.ebands_kmesh.kpoints.is_ibz assert not r.ebands_kmesh.kpoints.is_path assert r.ebands_kmesh.kpoints.ksampling is not None assert r.ebands_kmesh.kpoints.is_mpmesh mpdivs, shifts = r.ebands_kmesh.kpoints.mpdivs_shifts self.assert_equal(mpdivs, [8, 8, 8]) self.assert_equal(shifts.flatten(), [0, 0, 0]) # Export it in BXSF format. r.ebands_kmesh.to_bxsf(self.get_tmpname(text=True))
def test_frozen(self): """Base tests for FrozenPhonon""" filename = abidata.ref_file("trf2_5.out_PHBST.nc") phbands = PhononBands.from_file(filename) qpt_frac_coords = [0.5, 0.5, 0.5] fp = FrozenPhonon.from_phbands(phbands, qpt_frac_coords, 0 , etas=[-0.2, -0.1, 0, 0.1, 0.2], max_supercell=[5,5,5]) self.assertArrayEqual(fp.scale_matrix, [[-1, 0, 1], [-1, 1, 0], [-1, -1, 0]]) w = phbands.phfreqs[phbands.qindex(qpt_frac_coords), 0] energies = [0.0704, 0.0176, 0. , 0.0175, 0.0703] with self.assertRaises(ValueError): fp.energies = energies[:3] fp.energies = energies assert fp.ieta0 == 2 assert fp.n_displ == 5 fit_data = fp.fit_to_frequency() self.assertAlmostEqual(w, fit_data.freq, places=5) fit_data = fp.fit_to_frequency(min_fit_eta=-0.15, max_fit_eta=0.15) self.assertNotAlmostEqual(w, fit_data.freq, places=5) self.assertArrayAlmostEqual(fp.qpt_cart_coords, [0.55954285702497808, 0.55954285702497808, 0.55954285702497808]) if self.has_matplotlib(): assert fp.plot_fit_energies(freq=w, show=False) assert fp.plot_anharmonic_contribution(freq=w, show=False) assert fp.plot_anharmonic_contribution(freq=w, relative=True, show=False)
def build_flow(options): # Working directory (default is the name of the script with '.py' removed and "run_" replaced by "flow_") workdir = options.workdir if not options.workdir: workdir = os.path.basename(__file__).replace(".py", "").replace("run_","flow_") # Instantiate the TaskManager. manager = abilab.TaskManager.from_user_config() if not options.manager else \ abilab.TaskManager.from_file(options.manager) # Get the SCF and the NSCF input. scf_input, nscf_input = make_scf_nscf_inputs() # Build the flow. flow = abilab.Flow(workdir, manager=manager) # Create a Work, all tasks in work will read the file f # Note that the file must exist when the work is created # Use the standard approach based on tasks and works if # there's a node who needs a file produced in the future. work = abilab.Work() denfile = abidata.ref_file("si_DEN-etsf.nc") work.register(nscf_input, deps={denfile: "DEN"}) flow.register_work(work) return flow.allocate()
def test_vhxc_ncfile(self): """Testing VHXC netcdf file.""" with abilab.abiopen(abidata.ref_file("ni_666k_VHXC.nc")) as ncfile: repr(ncfile); str(ncfile) assert ncfile.ebands.nsppol == 2 and ncfile.ebands.nspden == 2 assert ncfile.structure.formula == "Ni1" assert ncfile.ebands.structure == ncfile.structure assert str(ncfile.xc) == "PBE" # Kpoint sampling #ngkpt 6 6 6 nshiftk 4 #shiftk 1/2 1/2 1/2 1/2 0.0 0.0 0.0 1/2 0.0 0.0 0.0 1/2 assert not ncfile.ebands.kpoints.is_mpmesh assert not ncfile.ebands.kpoints.is_path vhxc = ncfile.vhxc assert vhxc.netcdf_name == "vhxc" assert vhxc.netcdf_name == "vhxc" assert vhxc.nspinor == 1 and vhxc.nsppol == 2 and vhxc.nspden == 2 assert vhxc.is_potential_like assert not vhxc.is_density_like ## Test converters. #ncfile.write_chgcar(filename=self.get_tmpname(text=True)) #ncfile.write_xsf(filename=self.get_tmpname(text=True, suffix=".xsf")) #ncfile.write_cube(filename=self.get_tmpname(text=True), spin="total") if self.has_matplotlib(): assert ncfile.ebands.plot(show=False) # Test ipython notebooks. if self.has_nbformat(): ncfile.write_notebook(nbpath=self.get_tmpname(text=True))
def test_base(self): """Base tests for NLOpticalSusceptibilityTensor""" anaddbnc_fname = abidata.ref_file("AlAs_nl_dte_anaddb.nc") tensor = NLOpticalSusceptibilityTensor.from_file(anaddbnc_fname) repr(tensor) str(tensor)
def test_phbst_file(self): """Testing PHBST file.""" with abilab.abiopen(abidata.ref_file("trf2_5.out_PHBST.nc")) as ncfile: assert ncfile.phbands is not None for iq, qpt in enumerate(ncfile.qpoints): assert hasattr(qpt, "frac_coords") assert ncfile.qpoints[ncfile.qindex(qpt)] == qpt ii = ncfile.qindex(qpt) #print("iq", iq, "qpt", qpt, "ii", ii, "qpoints[ii]", ncfile.qpoints[ii]) same_ii, same_qpt = ncfile.qindex_qpoint(ii) assert same_ii == ii and qpt == same_qpt same_ii, same_qpt = ncfile.phbands.qindex_qpoint(qpt) assert same_ii == ii and qpt == same_qpt qpoint = ncfile.qpoints[0] frame = ncfile.get_phframe(qpoint) assert frame.qpoint == qpoint mode0 = ncfile.get_phmode(qpoint, 0) repr(mode0); str(mode0) mode0.to_string(with_displ=True) assert mode0.qpoint == qpoint self.serialize_with_pickle(mode0, test_eq=False) last_mode = ncfile.get_phmode(ncfile.qpoints[0], -1) assert last_mode > mode0 # Test notebook if self.has_nbformat(): ncfile.write_notebook(nbpath=self.get_tmpname(text=True))
def test_TSR(self): """Test the computation of Tensor""" mdf_file = MdfFile(data.ref_file("tbs_4o_DS2_MDF.nc")) exc_tsr = mdf_file.get_tensor("exc") rpa_tsr = mdf_file.get_tensor("rpa") gw_tsr = mdf_file.get_tensor("gwrpa")
def test_convert(self): """Testing abistruct convert""" ncfile = abidata.ref_file("tgw1_9o_DS4_SIGRES.nc") env = self.get_env() for fmt in ["cif", "cssr", "POSCAR", "json", "mson", "abivars"]: r = env.run(self.script, "convert", ncfile, "-f", fmt, self.loglevel, self.verbose, expect_stderr=self.expect_stderr)
def test_abiopen(self): """Testing abiopen.py script""" env = self.get_env() gan2_cif = abidata.cif_file("gan2.cif") r = env.run(self.script, gan2_cif, "-p", self.loglevel, self.verbose, expect_stderr=self.expect_stderr) for f in ["tgw1_9o_DS4_SIGRES.nc", "si_scf_WFK.nc"]: path = abidata.ref_file(f) r = env.run(self.script, path, "-p", self.loglevel, self.verbose, expect_stderr=self.expect_stderr)
def test_phbands_plotter(self): """Testing phbands plotter.""" phbst_paths = 2 * [abidata.ref_file("trf2_5.out_PHBST.nc")] phdos_paths = 2 * [abidata.ref_file("trf2_5.out_PHDOS.nc")] plotter = PhononBandsPlotter() plotter.add_phbands("AlAs", phbst_paths[0], phdos=phdos_paths[0]) plotter.add_phbands("Same-AlAs", phbst_paths[1], phdos=phdos_paths[1]) repr(plotter); str(plotter) assert len(plotter.phbands_list) == 2 assert len(plotter.phdoses_list) == 2 assert plotter.has_same_formula() # __add__ merges two plotters: p2 = plotter.add_plotter(plotter) assert len(p2.phbands_list) == 2 assert len(p2.phdoses_list) == 2 df = dataframe_from_phbands(plotter.phbands_list) assert "nqpt" in df df = plotter.get_phbands_frame() assert df is not None if self.has_matplotlib(): assert plotter.combiplot(units="eV", show=True) assert plotter.gridplot(units="meV", show=True) assert plotter.boxplot(units="cm-1", show=True) assert plotter.combiboxplot(units="Thz", show=True) assert plotter.animate(show=False) if self.has_nbformat(): plotter.write_notebook(nbpath=self.get_tmpname(text=True)) if self.has_ipywidgets(): assert plotter.ipw_select_plot() is not None # Plotter without PHDOS plotter = PhononBandsPlotter(key_phbands=[("foo", phbst_paths[0]), ("bar", phbst_paths[1])]) if self.has_matplotlib(): assert plotter.combiplot(units="EV", show=True) assert plotter.gridplot(units="MEV", show=True) assert plotter.boxplot(units="cm^-1", mode_range=[0, 3], swarm=True, show=True) assert plotter.combiboxplot(units="THZ", mode_range=[0, 3], show=True)
def setUp(self): with abilab.abiopen(abidata.ref_file("mgb2_kmesh181818_FATBANDS.nc")) as ncfile: self.mgb2 = ncfile.structure assert ncfile.ebands.kpoints.is_ibz self.kibz = [k.frac_coords for k in ncfile.ebands.kpoints] self.has_timrev = True #self.has_timrev = has_timrev_from_kptopt(kptopt) self.ngkpt = [18, 18, 18]
def test_dos(self): """Test DOS methods.""" gs_bands = ElectronBands.from_file(data.ref_file("si_scf_GSR.nc")) dos = gs_bands.get_edos() mu = dos.find_mu(8, atol=1.e-4) imu = dos.tot_idos.find_mesh_index(mu) self.assert_almost_equal(dos.tot_idos[imu][1], 8, decimal=2) self.serialize_with_pickle(dos, protocols=[-1], test_eq=False)
def test_ktables(self): """Testing abistruct ktables""" env = self.get_env() ncfile = abidata.ref_file("tgw1_9o_DS4_SIGRES.nc") r = env.run(self.script, "ktables", "--mesh", "2", "2", "2", "--is_shift", "1", "1", "1", "--no-time-reversal", ncfile, expect_stderr=self.expect_stderr) r = env.run(self.script, "abikmesh", "--ngkpt", "2", "2", "2", "--shiftk", "0", "0", "0", "--kptopt=1", ncfile, expect_stderr=self.expect_stderr)
#!/usr/bin/env python """ This example shows how to plot the L-projected fatbands of MgB2 using the results stored in the FATBANDS.nc files produced by abinit with prtdos 3. See also PhysRevLett.86.4656 """ import abipy.abilab as abilab import abipy.data as abidata # Open the file (alternatively one can use the shell and `abiopen.py FILE -nb` to open the file in a jupyter notebook # This fatbands file has been produced on a k-path so it's not suitable for DOS calculations. fbnc_kpath = abilab.abiopen(abidata.ref_file("mgb2_kpath_FATBANDS.nc")) # Print file info (dimensions, variables ...) # Note that prtdos = 3, so LM decomposition is not available. print(fbnc_kpath) # Plot the k-points belonging to the path. fbnc_kpath.ebands.kpoints.plot() # Plot the electronic fatbands grouped by atomic type. fbnc_kpath.plot_fatbands_typeview(tight_layout=True) # Plot the electronic fatbands grouped by L. fbnc_kpath.plot_fatbands_lview(tight_layout=True) # Now we read another FATBANDS file produced on 18x18x18 k-mesh fbnc_kmesh = abilab.abiopen(abidata.ref_file("mgb2_kmesh181818_FATBANDS.nc")) print(fbnc_kpath) #fbnc_kmesh.ebands.kpoints.plot()
#!/usr/bin/env python r""" Dielectric function with LFE ============================ This examples shows how to plot the macroscopic dielectric function computed in the GW code (optdriver 3) """ import abipy.data as abidata from abipy.abilab import abiopen with abiopen(abidata.ref_file("sio2_SCR.nc")) as ncfile: # The SCR file contains a structure and electron bands in the IBZ. # We can thus use the ebands object to plot bands + DOS. print(ncfile) edos = ncfile.ebands.get_edos() ncfile.ebands.plot_with_edos(edos, title="KS energies used to compute the SCR file.") # sphinx_gallery_thumbnail_number = 2 ncfile.plot_emacro(title="Macroscopic dielectric function of $SiO_2$ with local-field effects.") ncfile.plot_eelf(title="Electron Energy Loss Function of $SiO_2$")
def test_hist_api(self): """Testing HistFile API.""" hist = HistFile(abidata.ref_file("sic_relax_HIST.nc")) repr(hist) str(hist) hist.to_string(verbose=2) assert not hist.params an = hist.get_relaxation_analyzer() assert hist.num_steps == 7 assert len(hist.structures) == hist.num_steps assert hist.initial_structure is hist.structures[0] assert hist.final_structure is hist.structures[-1] assert hist.final_structure.composition.reduced_formula == "SiC" assert len(hist.final_structure) == hist.reader.natom assert len(hist.final_structure) == 2 assert len(hist.etotals) == hist.num_steps self.assert_almost_equal(hist.etotals.to("Ha"), [ -10.4914795629442, -10.491527362795, -10.4915307068041, -10.4915319277052, -10.4915319344634, -10.491531918083, -10.4915319353756 ]) last_stren = [ 5.01170783044364e-08, 5.01170783044364e-08, 5.01170783046533e-08, 0, 0, 0 ] self.assert_almost_equal( hist.reader.read_value("strten")[-1], last_stren) cart_forces_step = hist.reader.read_cart_forces(unit="Ha bohr^-1") #self.assert_almost_equal(cart_forces_step[0], [ # 6.42133418983323e-32, -1.92640025694997e-31, 6.42133418983323e-32, # -6.42133418983323e-32, 1.92640025694997e-31, -6.42133418983323e-32]) fred = hist.reader.read_reduced_forces() assert fred.shape == cart_forces_step.shape # Cartesian components of stress tensor (hartree/bohr^3) # sigma(1 1)= 5.01170783E-08 sigma(3 2)= 0.00000000E+00 # sigma(2 2)= 5.01170783E-08 sigma(3 1)= 0.00000000E+00 # sigma(3 3)= 5.01170783E-08 sigma(2 1)= 0.00000000E+00 #-Cartesian components of stress tensor (GPa) [Pressure= -1.4745E-03 GPa] #- sigma(1 1)= 1.47449510E-03 sigma(3 2)= 0.00000000E+00 #- sigma(2 2)= 1.47449510E-03 sigma(3 1)= 0.00000000E+00 #- sigma(3 3)= 1.47449510E-03 sigma(2 1)= 0.00000000E+00 cart_stress_tensors, pressures = hist.reader.read_cart_stress_tensors() self.assert_almost_equal(pressures[-1], -1.4745E-03) self.assert_almost_equal(cart_stress_tensors[-1, 1, 0], 0.0) for i in range(3): self.assert_almost_equal(cart_stress_tensors[-1, i, i], 5.01170783E-08 * abu.HaBohr3_GPa) same_structure = abilab.Structure.from_file( abidata.ref_file("sic_relax_HIST.nc")) self.assert_almost_equal(same_structure.frac_coords, hist.final_structure.frac_coords) # Test to_xdatcar converter xdatcar = hist.to_xdatcar(filepath=None, groupby_type=True) assert xdatcar.natoms == [1, 1] and len( xdatcar.structures) == hist.num_steps self.assert_almost_equal(xdatcar.structures[0].volume, hist.structures[0].volume) self.assert_almost_equal(xdatcar.structures[-1].frac_coords, hist.structures[-1].frac_coords) xdatcar_nogroup = hist.to_xdatcar(filepath=None, groupby_type=False) assert xdatcar.structures[0] == xdatcar_nogroup.structures[0] assert xdatcar.structures[-1] == xdatcar_nogroup.structures[-1] # Test matplotlib plots. if self.has_matplotlib(): assert hist.plot(show=False) assert hist.plot_energies(show=False) # Test notebook generation. if self.has_nbformat(): hist.write_notebook(nbpath=self.get_tmpname(text=True)) if self.has_mayavi(): assert hist.mvplot_trajectories(show=False) #assert hist.mvanimate(delay=100) if self.has_panel(): assert hasattr(hist.get_panel(), "show") hist.close()
#!/usr/bin/env python # This example shows how to plot the phonon band structure with markers. from abipy.abilab import abiopen import abipy.data as abidata # Create the object from file. with abiopen(abidata.ref_file("trf2_5.out_PHBST.nc")) as ncfile: phbands = ncfile.phbands # Create the marker. Here we just use the phonon frequency as size of the marker. x = [] for q in range(phbands.num_qpoints): x.extend(phbands.num_branches * [q]) xys = [ x, phbands.phfreqs.ravel(), phbands.phfreqs.ravel(), ] phbands.set_marker("fake marker", xys) # Plot the phonon frequencies. Note that the labels for the q-points # are found automatically by searching in an internal database. phbands.plot(title="AlAs phonon band structure with omega(q, nu) as marker", marker="fake marker:10000")
def setUp(self): self.sigres = sigres= abiopen(data.ref_file("tgw1_9o_DS4_SIGRES.nc")) self.qplist = sigres.get_qplist(spin=0, kpoint=sigres.gwkpoints[0])
#!/usr/bin/env python r""" Band structure plot =================== This example shows how to plot a band structure using the eigenvalues stored in the GSR file produced at the end of the GS run. """ from abipy.abilab import abiopen import abipy.data as abidata # Here we use one of the GSR files shipped with abipy. # Replace filename with the path to your GSR file or your WFK file. filename = abidata.ref_file("si_nscf_GSR.nc") # Open the GSR file and extract the band structure. # (alternatively one can use the shell and `abiopen.py OUT_GSR.nc -nb` # to open the file in a jupyter notebook. with abiopen(filename) as ncfile: ebands = ncfile.ebands # Plot the band energies. Note that the labels for the k-points # are found automatically in an internal database. ebands.plot(title="Silicon band structure") # Plot the BZ and the k-point path. ebands.kpoints.plot()
def test_a2fnc_file(self): """Tests for A2fFile.""" ncfile = abilab.abiopen(abidata.ref_file("al_888k_161616q_A2F.nc")) repr(ncfile); str(ncfile) assert ncfile.to_string(verbose=2) assert ncfile.params["nspinor"] == ncfile.nspinor assert "eph_fsewin" in ncfile.params assert ncfile.structure.formula == "Al1" and len(ncfile.structure) == 1 # Ebands assert ncfile.nsppol == 1 and ncfile.nspden == 1 and ncfile.nspinor == 1 assert ncfile.ebands.kpoints.is_ibz #self.assert_equal(ncfile.ebands.kpoints.ksampling.mpdivs, [8, 8, 8]) self.assert_equal(ncfile.ebands.kpoints.ksampling.mpdivs, [12, 12, 12]) # Phbands assert ncfile.phbands.qpoints.is_path assert ncfile.phbands.qpoints.ksampling is None assert ncfile.phbands.has_linewidths # Test ksampling ksamp = ncfile.reader.read_ksampling_info() assert ksamp.is_mesh and not ksamp.is_path assert ksamp.has_diagonal_kptrlatt self.assert_equal(ksamp.mpdivs, [12, 12, 12]) self.assert_equal(ksamp.shifts.ravel(), [0, 0, 0]) assert ksamp.to_string(title="Ksampling") # Test edos # TODO #ncfile.edos #if self.has_matplotlib(): #assert ncfile.edos.plot(show=False) # Test A2f(w) function. a2f = ncfile.a2f_qcoarse assert ncfile.get_a2f_qsamp("qcoarse") is a2f repr(a2f); str(a2f) a2f.to_string(verbose=2) assert a2f.nsppol == ncfile.nsppol and a2f.nmodes == 3 * len(ncfile.structure) assert a2f.iw0 == 0 #assert a2f.mesh #assert a2f.values_spin m1 = a2f.get_moment(n=1) #self.assert_almost_equal(m1/2, a2f.get_moment(n=1, spin=0)) #self.assert_almost_equal(self.lambda_iso, ) #self.assert_almost_equal(self.omega_log, ) tc = a2f.get_mcmillan_tc(mustar=0.1) #self.assert_almost_equal(tc, ) mustar = a2f.get_mustar_from_tc(tc) self.assert_almost_equal(mustar, 0.1) #self.assert_almost_equal(a2f.get_mcmillan_tc(mustar), tc) assert not ncfile.has_a2ftr assert ncfile.a2ftr_qcoarse is None assert ncfile.a2ftr_qintp is None assert ncfile.get_a2ftr_qsamp("qcoarse") is ncfile.a2ftr_qcoarse phdos_path = abidata.ref_file("al_161616q_PHDOS.nc") if self.has_matplotlib(): # Test A2f plot methods assert ncfile.a2f_qcoarse.plot(exchange_xy=True, fontsize=8, units="meV", show=False) assert ncfile.a2f_qcoarse.plot_with_lambda(show=False) assert ncfile.a2f_qcoarse.plot_tc_vs_mustar(show=False) assert ncfile.a2f_qintp.plot_a2(phdos_path, show=False) assert ncfile.a2f_qintp.plot_nuterms(show=False) assert ncfile.plot_a2f_interpol(show=False) # Test A2fFile plot methods. assert ncfile.plot(show=False) assert ncfile.plot_with_a2f(show=False) assert ncfile.plot_eph_strength(show=False) assert ncfile.plot_with_a2f(qsamp="qcoarse", show=False) assert ncfile.plot_with_a2f(phdos=phdos_path, show=False) if self.has_nbformat(): ncfile.write_notebook(nbpath=self.get_tmpname(text=True)) ncfile.close()
#!/usr/bin/env python """ This example shows how to generate an energy-dependent scissors operator by fitting the GW QPState corrections as function of the KS eigenvalues We then use the scissors operator to correct the KS band structure computed on a high symmetry k-path. Finally, the LDA and the QPState band structure are plotted with matplotlib. """ import abipy.data as abidata from abipy.abilab import abiopen, ElectronBandsPlotter # Get the quasiparticle results from the SIGRES.nc database. #sigma_file = abiopen(abidata.ref_file("tgw1_9o_DS4_SIGRES.nc")) sigma_file = abiopen(abidata.ref_file("si_g0w0ppm_nband30_SIGRES.nc")) #sigma_file.plot_qps_vs_e0() qplist_spin = sigma_file.qplist_spin # Construct the scissors operator domains = [[-10, 6.1], [6.1, 18]] scissors = qplist_spin[0].build_scissors(domains, bounds=None) # Read the KS band energies computed on the k-path ks_bands = abiopen(abidata.ref_file("si_nscf_GSR.nc")).ebands # Read the KS band energies computed on the Monkhorst-Pack (MP) mesh # and compute the DOS with the Gaussian method ks_mpbands = abiopen(abidata.ref_file("si_scf_GSR.nc")).ebands ks_dos = ks_mpbands.get_edos() # Apply the scissors operator first on the KS band structure # along the k-path then on the energies computed with the MP mesh.
def test_alas_elastic(self): """ Testing DDB containing also third order derivatives. """ self.skip_if_abinit_not_ge("8.9.3") with abilab.abiopen( abidata.ref_file( "refs/alas_elastic_dfpt/AlAs_elastic_DDB")) as ddb: assert ddb.has_strain_terms(select="at_least_one") assert ddb.has_strain_terms(select="all") assert ddb.has_internalstrain_terms(select="all") assert ddb.has_piezoelectric_terms(select="all") assert ddb.has_at_least_one_atomic_perturbation() # Get ElasticData by calling anaddb. e = ddb.anaget_elastic(verbose=2) assert e.params["elaflag"] == 3 assert e.params["piezoflag"] == 3 assert e.params["instrflag"] == 1 assert e.params["asr"] == 2 and e.params["chneut"] == 1 # Elastic tensors. self.assert_almost_equal(e.elastic_relaxed[0, 0, 0, 0], 122.23496623977118) assert e.elastic_clamped is not None assert e.elastic_stress_corr is None assert e.elastic_relaxed_fixed_D is None # Piezoelectric tensors. self.assert_almost_equal(e.piezo_relaxed[2, 2, 2], -0.041496005147475756) assert e.piezo_clamped is not None assert e.d_piezo_relaxed is None assert e.g_piezo_relaxed is None assert e.g_piezo_relaxed is None assert repr(e) assert str(e) assert e.to_string(verbose=2) assert e.structure.formula == "Al2 As2" assert e.elastic_relaxed._repr_html_() name_tensor_list = e.name_tensor_list(tensor_type="elastic") names = [nt[0] for nt in name_tensor_list] assert "elastic_relaxed" in names name_tensor_list = e.name_tensor_list(tensor_type="piezoelectric") names = [nt[0] for nt in name_tensor_list] assert "piezo_relaxed" in names edata_fit = e.fit_to_structure() assert edata_fit is not None edata_ieee = e.convert_to_ieee() assert edata_ieee is not None self.assertMSONable(e) df = e.get_elastic_tensor_dataframe(tensor_name="elastic_clamped", tol=1e-5) df = e.get_piezoelectric_tensor_dataframe( tensor_name="piezo_clamped", tol=1e-8) df = e.get_voigt_dataframe("elastic_relaxed", voigt_as_index=False, tol=1e-1) self.assert_almost_equal(df[(0, 0)][0], 122.23496623977118) df = e.get_elastic_properties_dataframe( tensor_names="elastic_relaxed", fit_to_structure=True)
def test_silicon_density(self): """Testing density object (spin unpolarized).""" si_den = Density.from_file(abidata.ref_file("si_DEN.nc")) repr(si_den) str(si_den) assert si_den.nspinor == 1 and si_den.nsppol == 1 and si_den.nspden == 1 assert si_den.is_collinear assert si_den.structure.formula == "Si2" assert si_den.mesh.shape == (18, 18, 18) assert si_den.is_density_like assert not si_den.is_potential_like self.assert_almost_equal(si_den.mesh.fft_g2r(si_den.datag), si_den.datar) # Read data directly from file. with FieldReader(abidata.ref_file("si_DEN.nc")) as r: nelect_file = r.read_value("number_of_electrons") same_si_den = r.read_field() assert np.all(same_si_den.datar == si_den.datar) ne = 8 assert ne == nelect_file self.assert_almost_equal(si_den.get_nelect(), ne) self.assert_almost_equal( si_den.total_rhor.sum() * si_den.structure.volume / si_den.mesh.size, ne) self.assert_almost_equal( si_den.total_rhog[0, 0, 0] * si_den.structure.volume, ne) totden = si_den.total_rhor_as_density() self.assert_equal(totden.datar.flatten(), si_den.total_rhor.flatten()) other = si_den - si_den assert other.nspden == si_den.nspden self.assert_equal(other.datar, 0) magfield = si_den.magnetization_field assert magfield.shape == si_den.mesh.shape self.assert_equal(magfield, 0) assert si_den.magnetization == 0 nup, ndown = si_den.nelect_updown assert nup == ndown self.assert_almost_equal(nup, ne / 2) self.assert_almost_equal(si_den.zeta, 0) df = si_den.integrate_in_spheres(rcut_symbol=None, out=True) assert "frac_coords" in df self.assert_almost_equal(df["ntot"].values, 2 * [2.010537]) self.assert_almost_equal(df["rsph_ang"].values, 2 * [1.11]) df = si_den.integrate_in_spheres(rcut_symbol=2, out=False) if self.has_matplotlib(): assert si_den.plot_line(0, 1, num=1000, show=False) assert si_den.plot_line([0, 0, 0], [1, 0, 0], num=1000, cartesian=True, show=False) # Export to chgcar and re-read it. chgcar_path = self.get_tmpname(text=True) chgcar = si_den.to_chgcar(filename=chgcar_path) assert hasattr(chgcar, "structure") assert not chgcar.is_spin_polarized poscar_path = self.get_tmpname(text=True) si_den.structure.to(fmt="poscar", filename=poscar_path) same_den = Density.from_chgcar_poscar(chgcar_path, poscar_path) self.assert_almost_equal(same_den.datar, si_den.datar) # Export data in xsf format. visu = si_den.export(".xsf") assert callable(visu) # Test CUBE files. tmp_cubefile = self.get_tmpname(text=True) si_den.export_to_cube(tmp_cubefile, spin="total") total_den = Density.from_cube(tmp_cubefile) assert total_den.structure == si_den.structure assert abs(total_den.get_nelect().sum() - ne) < 1e-3 # Test creation of AE core density. Use low parameters to reduce time rhoc = { "Si": core_density_from_file(os.path.join(abidata.pseudo_dir, "Si.fc")) } core_den_1 = Density.ae_core_density_on_mesh( si_den, si_den.structure, rhoc, maxr=1.5, method='get_sites_in_sphere', small_dist_mesh=(6, 6, 6)) core_den_2 = Density.ae_core_density_on_mesh( si_den, si_den.structure, rhoc, maxr=1.5, method='mesh3d_dist_gridpoints', small_dist_mesh=(6, 6, 6)) self.assertAlmostEquals(np.sum(core_den_1.datar) * si_den.mesh.dv, 20, delta=0.5) self.assertArrayAlmostEqual(core_den_1.datar, core_den_2.datar) with self.assertRaises(ValueError): Density.ae_core_density_on_mesh(si_den, si_den.structure, rhoc, maxr=1, nelec=20, tol=0.001, method='get_sites_in_sphere', small_dist_mesh=(2, 2, 2))
def test_silicon(self): """Test silicon space group.""" structure = Structure.from_file(abidata.ref_file("si_scf_WFK-etsf.nc")) self.assertTrue(structure.has_spacegroup) self.assertTrue(structure.is_symmorphic) self.serialize_with_pickle(structure, protocols=[-1]) spgrp = structure.spacegroup print("spgrp:\n", spgrp) #print("mult_tables:\n", spgrp.mult_table) # Classes cover the entire group. self.assertEqual(sum(len(cls) for cls in spgrp.groupby_class()), len(spgrp)) # Operation in the same class have the same trace and determinant. for cls in spgrp.groupby_class(): #print(cls) op0 = cls[0] ref_trace, ref_det = op0.trace, op0.det for op in cls[1:]: self.assertEqual(op.trace, ref_trace) self.assertEqual(op.det, ref_det) self.assertTrue(spgrp == spgrp) self.assertTrue(spgrp.spgid == 227) self.assertTrue(spgrp.has_timerev) self.assertTrue(len(spgrp) == 48 * 2) self.assertTrue(spgrp.num_spatial_symmetries == 48) self.assertTrue(spgrp.is_group()) # TODO #si_symrel = si_tnons = np.reshape(24 * [0, 0, 0, 0.25, 0.25, 0.25], (48, 3)) si_symafm = np.ones(48, dtype=np.int) self.assert_almost_equal(si_tnons, spgrp.tnons) self.assert_almost_equal(si_symafm, spgrp.symafm) for (idx, symmop) in enumerate(spgrp): self.assertTrue(symmop in spgrp) self.assertTrue(spgrp.count(symmop) == 1) self.assertTrue(spgrp.find(symmop) == idx) self.assertTrue(abs(symmop.det) == 1) for idx in range(len(spgrp) - 1): self.assertTrue(spgrp[idx] == spgrp[idx]) self.assertTrue(spgrp[idx] != spgrp[idx + 1]) for fmop in spgrp.fm_symmops: self.assertTrue(fmop.is_fm) ucell_coords = np.reshape([site.frac_coords for site in structure], (len(structure), 3)) err_msg = "" for site in structure: for symop in spgrp: rot_coords = symop.rotate_r(site.frac_coords, in_ucell=True) for atom_coords in ucell_coords: #print (atom_coords - rot_coords) if np.allclose(atom_coords, rot_coords): break else: err_msg += "Cannot find symmetrical image of %s\n" % str( rot_coords) self.assertFalse(err_msg)
#!/usr/bin/env python # # This example shows how plot the different contributions # to the electronic joint density of states of Silicon import abipy.data as abidata from abipy.abilab import abiopen # Extract the bands computed with the SCF cycle on a Monkhorst-Pack mesh. wfk_file = abiopen(abidata.ref_file("si_scf_WFK-etsf.nc")) ebands = wfk_file.ebands # Select the valence and conduction bands to include in the JDOS # Here we include valence bands from 0 to 3 and the first conduction band (4). vrange = range(0,4) crange = range(4,5) # Plot data. ebands.plot_ejdosvc(vrange, crange)
#!/usr/bin/env python r""" Density ======= This example shows how to analyze the electronic density stored in the DEN.nc file. """ from abipy.abilab import abiopen import abipy.data as abidata # Open the DEN.nc file ncfile = abiopen(abidata.ref_file("si_DEN.nc")) # The DEN file has a `Density`, a `Structure` and an `ElectronBands` object print(ncfile.structure) # To plot the KS eigenvalues. #ncfile.ebands.plot() density = ncfile.density print(density) # To visualize the total charge wih vesta #visu = density.visualize("vesta"); visu() # To plot the density along the line connecting # the first and the second in the structure: density.plot_line(point1=0, point2=1) # alternatively, one can define the line in terms of two points
def test_gruns_ncfile(self): """Testsing GrunsFile.""" with abilab.abiopen(abidata.ref_file("mg2si_GRUNS.nc")) as ncfile: repr(ncfile); str(ncfile) assert ncfile.structure.formula == "Mg2 Si1" assert ncfile.iv0 == 1 #assert len(ncfile.volumes) == 3 assert not ncfile.params d = ncfile.doses assert d is ncfile.doses assert "wmesh" in d assert len(ncfile.phbands_qpath_vol) == 3 assert d.qpoints.is_ibz assert ncfile.split_gruns assert ncfile.split_dwdq df = ncfile.to_dataframe() assert "grun" in df and "freq" in df assert ncfile.phdos self.assertAlmostEqual(ncfile.average_gruneisen(t=None, squared=True, limit_frequencies=None), 1.4206573918609795, places=5) self.assertAlmostEqual(ncfile.average_gruneisen(t=None, squared=False, limit_frequencies="debye"), 1.2121437911186166, places=5) self.assertAlmostEqual(ncfile.average_gruneisen(t=None, squared=False, limit_frequencies="acoustic"), 1.213016691881557, places=5) self.assertAlmostEqual(ncfile.thermal_conductivity_slack(squared=True, limit_frequencies=None), 14.553100876473687, places=5) self.assertAlmostEqual(ncfile.thermal_conductivity_slack(squared=True, limit_frequencies=None, t=300), 14.43141396698724, places=5) self.assertAlmostEqual(ncfile.debye_temp, 429.05702577371898, places=5) self.assertAlmostEqual(ncfile.acoustic_debye_temp, 297.49152615955893, places=5) ncfile.grun_vals_finite_differences(match_eigv=False) ncfile.gvals_qibz_finite_differences(match_eigv=False) if self.has_matplotlib(): assert ncfile.plot_doses(title="DOSes", show=False) assert ncfile.plot_doses(with_idos=False, xlims=None, show=False) # Arrow up for positive values, down for negative values. assert ncfile.plot_phbands_with_gruns(title="bands with gamma markers + DOSes", show=False) assert ncfile.plot_phbands_with_gruns(with_doses=None, gamma_fact=2, units="cm-1", show=False) assert ncfile.plot_phbands_with_gruns(fill_with="groupv", gamma_fact=2, units="cm-1", show=False) assert ncfile.plot_phbands_with_gruns(fill_with="gruns_fd", gamma_fact=2, units="cm-1", show=False) plotter = ncfile.get_plotter() assert plotter.combiboxplot(show=False) assert plotter.animate(show=False) assert ncfile.plot_gruns_scatter(units='cm-1', show=False) assert ncfile.plot_gruns_scatter(values="groupv", units='cm-1', show=False) assert ncfile.plot_gruns_scatter(values="gruns_fd", units='cm-1', show=False) assert ncfile.plot_gruns_bs(match_bands=True, show=False) assert ncfile.plot_gruns_bs(values="groupv", match_bands=False, show=False) assert ncfile.plot_gruns_bs(values="gruns_fd", match_bands=False, show=False) if self.has_nbformat(): assert ncfile.write_notebook(nbpath=self.get_tmpname(text=True))
def test_gsr_silicon(self): """spin unpolarized GSR file""" almost_equal = self.assertAlmostEqual with GsrFile(abidata.ref_file("si_scf_GSR.nc")) as gsr: assert gsr.basename == "si_scf_GSR.nc" assert gsr.relpath == os.path.relpath( abidata.ref_file("si_scf_GSR.nc")) assert gsr.filetype assert gsr.filestat() assert len(gsr.ncdump()) print(repr(gsr)) print(gsr) print(gsr.ebands) assert gsr.filepath == abidata.ref_file("si_scf_GSR.nc") assert gsr.nsppol == 1 assert gsr.mband == 8 and gsr.nband == 8 and gsr.nelect == 8 and len( gsr.kpoints) == 29 almost_equal(gsr.energy.to("Ha"), -8.86527676798556) almost_equal(gsr.energy_per_atom * len(gsr.structure), gsr.energy) # Test energy_terms eterm = gsr.energy_terms print(eterm) almost_equal(eterm.e_xc.to("Ha"), -3.51815936301812) almost_equal(eterm.e_nonlocalpsp.to("Ha"), 1.91660690901782) almost_equal(eterm.e_kinetic.to("Ha"), 2.96421325671218) almost_equal(eterm.e_fermie.to("Ha"), 0.205739364929368) # Forces and stress self.assert_almost_equal( gsr.cart_forces.to("Ha bohr^-1").flat, [ -1.14726679671674e-28, -3.76037290483622e-29, 5.65937773808884e-29, 1.14726679671674e-28, 3.76037290483622e-29, -5.65937773808884e-29 ]) almost_equal(gsr.max_force, 0) print(gsr.force_stats()) assert gsr.residm > 0 assert str(gsr.xc) == "LDA_XC_TETER93" #self.assert_almost_equal(gsr.cart_stress_tensor.flat, # Cartesian components of stress tensor (hartree/bohr^3) # sigma(1 1)= 1.77139311E-04 sigma(3 2)= 0.00000000E+00 # sigma(2 2)= 1.77139311E-04 sigma(3 1)= 0.00000000E+00 # sigma(3 3)= 1.77139311E-04 sigma(2 1)= 2.67294316E-15 almost_equal(gsr.pressure, -5.21162150) # Test as_dict pprint(gsr.as_dict()) #import json #with open("hello.json", "w") as fp: # json.dump(gsr.as_dict(), fp) #assert 0 # Test pymatgen computed_entries for inc_structure in (True, False): e = gsr.get_computed_entry(inc_structure=inc_structure) print(e) print(e.as_dict()) assert gsr.energy == e.energy if self.has_nbformat(): gsr.write_notebook(nbpath=self.get_tmpname(text=True))
#!/usr/bin/env python r""" Seaborn boxplot =============== This example shows how to use seaborn to draw a box plot showing the distributions of eigenvalues with respect to the band index. """ from abipy.abilab import abiopen import abipy.data as abidata # Open the file with energies computed with a homogeneous sampling # of the BZ and extract the band structure. with abiopen(abidata.ref_file("si_scf_GSR.nc")) as gsr: ebands = gsr.ebands import matplotlib.pyplot as plt # `swarm=True` to show the datapoints on top of the boxes ebands.boxplot(swarm=True) plt.show()
def test_utils(self): """Test utilities for the generation of Abinit inputs.""" # Test as_structure and from/to abivars si = Structure.as_structure(abidata.cif_file("si.cif")) assert si.formula == "Si2" assert si.abi_spacegroup is None and not si.has_abi_spacegroup assert "ntypat" in si.to(fmt="abivars") spgroup = si.spgset_abi_spacegroup(has_timerev=True) assert spgroup is not None assert si.has_abi_spacegroup assert si.abi_spacegroup.spgid == 227 with self.assertRaises(TypeError): Structure.as_structure({}) with self.assertRaises(TypeError): Structure.as_structure([]) si_wfk = Structure.as_structure(abidata.ref_file("si_scf_WFK.nc")) assert si_wfk.formula == "Si2" si_wfk.print_neighbors(radius=2.5) assert si_wfk.has_abi_spacegroup # Cannot change spacegroup with self.assertRaises(ValueError): si_wfk.spgset_abi_spacegroup(has_timerev=True) # TODO: Fix order of atoms in supercells. # Test __mul__, __rmul__ (should return Abipy structures) assert si_wfk == 1 * si_wfk supcell = si_wfk * [2, 2, 2] assert len(supcell) == 8 * len(si_wfk) and hasattr( supcell, "abi_string") si_abi = Structure.from_file( abidata.ref_file("refs/si_ebands/run.abi")) assert si_abi.formula == "Si2" self.assert_equal(si_abi.frac_coords, [[0, 0, 0], [0.25, 0.25, 0.25]]) si_abo = Structure.from_file( abidata.ref_file("refs/si_ebands/run.abo")) assert si_abo == si_abi assert "ntypat" in si_abi.to(fmt="abivars") znse = Structure.from_file( abidata.ref_file("refs/znse_phonons/ZnSe_hex_qpt_DDB")) assert len(znse) == 4 assert znse.formula == "Zn2 Se2" self.assert_almost_equal(znse.frac_coords.flat, [ 0.33333333333333, 0.66666666666667, 0.99962203020000, 0.66666666666667, 0.33333333333333, 0.49962203020000, 0.33333333333333, 0.66666666666667, 0.62537796980000, 0.66666666666667, 0.33333333333333, 0.12537796980000 ]) from abipy.core.structure import diff_structures diff_structures([si_abi, znse], headers=["si_abi", "znse"], fmt="abivars", mode="table") diff_structures([si_abi, znse], headers=["si_abi", "znse"], fmt="abivars", mode="diff") # From pickle file. import pickle tmp_path = self.get_tmpname(suffix=".pickle") with open(tmp_path, "wb") as fh: pickle.dump(znse, fh) same_znse = Structure.from_file(tmp_path) assert same_znse == znse same_znse = Structure.as_structure(tmp_path) assert same_znse == znse for fmt in ["abivars", "cif", "POSCAR", "json", "xsf", "qe"]: assert len(znse.convert(fmt=fmt)) > 0 oxi_znse = znse.get_oxi_state_decorated() assert len(oxi_znse.abi_string) from pymatgen.core.periodic_table import Specie assert Specie("Zn", 2) in oxi_znse.composition.elements assert Specie("Se", -2) in oxi_znse.composition.elements system = si.spget_lattice_type() assert system == "cubic" e = si.spget_equivalent_atoms(printout=True) assert len(e.irred_pos) == 1 self.assert_equal(e.eqmap[0], [0, 1]) for irr_pos in e.irred_pos: assert len(e.eqmap[irr_pos]) > 0 assert "equivalent_atoms" in e.spgdata if self.has_matplotlib(): assert si.plot_bz(show=False) assert si.plot_bz(pmg_path=False, show=False) assert si.plot_xrd(show=False) assert si.plot(show=False) if self.has_mayavi(): #assert si.vtkview(show=False) # Disabled due to (core dumped) on travis assert si.mayaview(show=False) assert si is Structure.as_structure(si) assert si == Structure.as_structure(si.to_abivars()) assert si == Structure.from_abivars(si.to_abivars()) assert len(si.abi_string) assert si.reciprocal_lattice == si.lattice.reciprocal_lattice kptbounds = si.calc_kptbounds() ksamp = si.calc_ksampling(nksmall=10) shiftk = [[0.5, 0.5, 0.5], [0.5, 0., 0.], [0., 0.5, 0.], [0., 0., 0.5]] self.assert_equal(si.calc_ngkpt(nksmall=2), [2, 2, 2]) self.assert_equal(si.calc_shiftk(), shiftk) self.assert_equal(ksamp.ngkpt, [10, 10, 10]) self.assert_equal(ksamp.shiftk, shiftk) si = Structure.from_mpid("mp-149") assert si.formula == "Si2" mgb2_cod = Structure.from_cod_id(1526507, primitive=True) assert mgb2_cod.formula == "Mg1 B2" assert mgb2_cod.spget_lattice_type() == "hexagonal" mgb2 = abidata.structure_from_ucell("MgB2") if self.has_ase(): mgb2.abi_primitive() assert [site.species_string for site in mgb2.get_sorted_structure_z()] == ["B", "B", "Mg"] s2inds = mgb2.get_symbol2indices() self.assert_equal(s2inds["Mg"], [0]) self.assert_equal(s2inds["B"], [1, 2]) s2coords = mgb2.get_symbol2coords() self.assert_equal(s2coords["Mg"], [[0, 0, 0]]) self.assert_equal(s2coords["B"], [[1 / 3, 2 / 3, 0.5], [2 / 3, 1 / 3, 0.5]]) # TODO: This part should be tested more carefully mgb2.abi_sanitize() mgb2.abi_sanitize(primitive_standard=True) mgb2.get_conventional_standard_structure() assert len(mgb2.abi_string) assert len(mgb2.spget_summary(verbose=10)) #print(structure._repr_html_()) self.serialize_with_pickle(mgb2) pseudos = abidata.pseudos("12mg.pspnc", "5b.pspnc") nv = mgb2.num_valence_electrons(pseudos) assert nv == 8 and isinstance(nv, int) assert mgb2.valence_electrons_per_atom(pseudos) == [2, 3, 3] self.assert_equal(mgb2.calc_shiftk(), [[0.0, 0.0, 0.5]]) bmol = Structure.boxed_molecule(pseudos, cart_coords=[[0, 0, 0], [5, 5, 5]], acell=[10, 10, 10]) self.assert_almost_equal(bmol.volume, (10 * bohr_to_ang)**3) # FIXME This is buggy #acell = np.array([10, 20, 30]) #batom = Structure.boxed_atom(abidata.pseudo("12mg.pspnc"), cart_coords=[1, 2, 3], acell=acell) #assert isinstance(batom, Structure) #assert len(batom.cart_coords) == 1 #self.assert_equal(batom.cart_coords[0], [1, 2, 3]) # Function to compute cubic a0 from primitive v0 (depends on struct_type) vol2a = { "fcc": lambda vol: (4 * vol)**(1 / 3.), "bcc": lambda vol: (2 * vol)**(1 / 3.), "zincblende": lambda vol: (4 * vol)**(1 / 3.), "rocksalt": lambda vol: (4 * vol)**(1 / 3.), "ABO3": lambda vol: vol**(1 / 3.), "hH": lambda vol: (4 * vol)**(1 / 3.), } a = 10 bcc_prim = Structure.bcc(a, ["Si"], primitive=True) assert len(bcc_prim) == 1 self.assert_almost_equal(a, vol2a["bcc"](bcc_prim.volume)) bcc_conv = Structure.bcc(a, ["Si"], primitive=False) assert len(bcc_conv) == 2 self.assert_almost_equal(a**3, bcc_conv.volume) fcc_prim = Structure.fcc(a, ["Si"], primitive=True) assert len(fcc_prim) == 1 self.assert_almost_equal(a, vol2a["fcc"](fcc_prim.volume)) fcc_conv = Structure.fcc(a, ["Si"], primitive=False) assert len(fcc_conv) == 4 self.assert_almost_equal(a**3, fcc_conv.volume) zns = Structure.zincblende(a / bohr_to_ang, ["Zn", "S"], units="bohr") self.assert_almost_equal(a, vol2a["zincblende"](zns.volume)) rock = Structure.rocksalt(a, ["Na", "Cl"]) assert len(rock) == 2 self.assert_almost_equal(a, vol2a["rocksalt"](rock.volume)) perov = Structure.ABO3(a, ["Ca", "Ti", "O", "O", "O"]) assert len(perov) == 5 self.assert_almost_equal(a**3, perov.volume) # Test notebook generation. if self.has_nbformat(): mgb2.write_notebook(nbpath=self.get_tmpname(text=True))
#!/usr/bin/env python r""" e-bands scatter3d ================= This example shows how to plot a particular "band" in 3D with matplotlib scatter3D. The color of the point gives the energy of the state wrt to the Fermi level. """ from abipy import abilab import abipy.data as abidata # Open the GSR file and extract the band structure. with abilab.abiopen(abidata.ref_file("ni_kpath_GSR.nc")) as ncfile: ncfile.ebands.plot_scatter3d(band=9, spin=0)
#!/usr/bin/env python r""" Potentials ========== This example shows how to plot the potentials stored in netcdf files. Use the input variables `prtpot`, `prtvha`, `prtvhxc`, `prtvxc` with `iomode 3` to produce these files at the end of the SCF-GS run. """ from abipy.abilab import abiopen import abipy.data as abidata # VKS = Hartree + XC potential + sum of local part of pseudos. with abiopen(abidata.ref_file("ni_666k_POT.nc")) as ncfile: vks = ncfile.vks #vks.plot_line(point1=[0, 0, 0], point2=[0, 4, 0], num=400, title="$V_{ks}(r)$") # Hartree potential. with abiopen(abidata.ref_file("ni_666k_VHA.nc")) as ncfile: vh = ncfile.vh vh.plot_line(point1=[0, 0, 0], point2=[0, 4, 0], num=400, title="$V_{hartree}(r)$") # XC potential. with abiopen(abidata.ref_file("ni_666k_VXC.nc")) as ncfile: vxc = ncfile.vxc
#!/usr/bin/env python r""" Effective masses ================ This example shows how to compute and plot the derivatives of the KS eigenvalues along a high symmetry path in K-space. """ from abipy.abilab import abiopen import abipy.data as abidata gsr_file = abiopen(abidata.ref_file("si_nscf_GSR.nc")) kpath = gsr_file.kpoints #print("ds", kpath.ds) #for vers in kpath.versors: # print("versors", vers) print(kpath) #print(kpath.lines) #branch = bands.get_branch(spin=0, band=3) #ders = kpath.finite_diff(branch, order=1) #ders = kpath.finite_diff(branch, order=2) #print("order2",ders) ebands = gsr_file.ebands xys = ebands.derivatives(spin=0, band=0, order=1) print("xys\n", xys) #xys = ebands.derivatives(spin=0, band=1, order=1)
def test_nickel_fatbands(self): """Testing Nickel fatbands with nsppol = 2 and prtdos 3.""" lmax = 2 elims = [-10, 2] fbnc_kpath = abilab.abiopen(abidata.ref_file("ni_kpath_FATBANDS.nc")) repr(fbnc_kpath) str(fbnc_kpath) assert fbnc_kpath.ebands.kpoints.is_path assert not fbnc_kpath.ebands.kpoints.is_ibz assert fbnc_kpath.prtdos == 3 assert fbnc_kpath.prtdosm == 1 assert fbnc_kpath.mbesslang == 5 assert fbnc_kpath.pawprtdos == 0 assert fbnc_kpath.usepaw == 0 assert fbnc_kpath.nsppol == 2 assert fbnc_kpath.nspden == 2 assert fbnc_kpath.nspinor == 1 #assert fbnc_kpath.nkpt == 78 #assert fbnc_kpath.mband == 8 assert fbnc_kpath.natsph_extra == 0 #assert not fbnc_kpath.ebands.has_metallic_scheme if self.has_matplotlib(): assert fbnc_kpath.plot_fatbands_typeview(ylims=elims, lmax=lmax, tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_lview(ylims=elims, lmax=lmax, tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_siteview(e0=None, view="inequivalent", fact=2.0, bdist=[1, 2, 3], show=False) if self.has_nbformat(): fbnc_kpath.write_notebook(nbpath=self.get_tmpname(text=True)) fbnc_kmesh = abilab.abiopen(abidata.ref_file("ni_666k_FATBANDS.nc")) repr(fbnc_kmesh) str(fbnc_kmesh) assert fbnc_kmesh.ebands.kpoints.is_ibz assert fbnc_kmesh.ebands.has_metallic_scheme assert fbnc_kmesh.prtdosm == 0 if self.has_matplotlib(): for combined_spins, stacked in itertools.product([True, False], [True, False]): assert fbnc_kmesh.plot_pjdos_typeview( xlims=elims, combined_spins=combined_spins, stacked=stacked, tight_layout=True, show=False) assert fbnc_kmesh.plot_pjdos_lview( xlims=elims, combined_spins=combined_spins, stacked=stacked, tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_with_pjdos(pjdosfile=fbnc_kmesh, ylims=elims, lmax=lmax, view="type", tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_with_pjdos(pjdosfile=fbnc_kmesh, ylims=elims, lmax=lmax, view="lview", tight_layout=True, show=False) # These calls should return None #assert fbnc_kpath.plot_fatbands_spinor() is None assert fbnc_kpath.plot_pjdos_lview() is None assert fbnc_kpath.plot_pawdos_terms() is None #assert fbnc_kpath.plot_pjdos_spinor() is None # TODO assert fbnc_kmesh.plot_fatbands_mview(iatom=0, show=False) is None assert fbnc_kpath.plot_fatbands_mview(iatom=0, lmax=2, fact=1.5, ylims=[-1.5, +1.0], blist=list(range(4, 10)), show=False) is not None fbnc_kpath.close() fbnc_kmesh.close()
def test_ni_density(self): """Testing density object (spin polarized, collinear).""" ni_den = Density.from_file(abidata.ref_file("ni_666k_DEN.nc")) repr(ni_den) str(ni_den) ni_den.to_string(verbose=1) self.assert_almost_equal( ni_den.mesh.vectors, pmgu.bohr_to_angstrom * np.reshape([ 0.0000000, 3.3259180, 3.3259180, 3.3259180, 0.0000000, 3.3259180, 3.3259180, 3.3259180, 0.0000000 ], (3, 3))) assert ni_den.nspinor == 1 and ni_den.nsppol == 2 and ni_den.nspden == 2 assert ni_den.is_collinear assert ni_den.structure.formula == "Ni1" assert ni_den.mesh.shape == (27, 27, 27) assert ni_den.is_density_like assert not ni_den.is_potential_like ne = 18 self.assert_almost_equal(ni_den.get_nelect(), ne) self.assert_almost_equal( ni_den.total_rhor.sum() * ni_den.structure.volume / ni_den.mesh.size, ne) self.assert_almost_equal( ni_den.total_rhog[0, 0, 0] * ni_den.structure.volume, ne) totden = ni_den.total_rhor_as_density() self.assert_equal(totden.datar.flatten(), ni_den.total_rhor.flatten()) self.assert_almost_equal(ni_den.mesh.fft_g2r(ni_den.datag), ni_den.datar) other = ni_den - ni_den assert other.nspden == ni_den.nspden self.assert_equal(other.datar, 0) magfield = ni_den.magnetization_field assert magfield.shape == ni_den.mesh.shape self.assert_equal(magfield, ni_den.datar[0] - ni_den.datar[1]) self.assert_almost_equal(ni_den.magnetization, 0.650144, decimal=5) nup, ndown = ni_den.nelect_updown self.assert_almost_equal(nup, 9.32507195) self.assert_almost_equal(ndown, 8.674928) self.assert_almost_equal(ni_den.zeta[3, 3, 3], 0.31311881970587324) df = ni_den.integrate_in_spheres(rcut_symbol=None, out=True) assert "frac_coords" in df self.assert_almost_equal(df["nup"].values, 8.9778673) self.assert_almost_equal(df["ndown"].values, 8.2989892) self.assert_almost_equal(df["mz"].values, 0.6788782) self.assert_almost_equal(df["rsph_ang"].values, 1.24) self.assert_almost_equal(df["nup"].values + df["ndown"].values, df["ntot"].values) if self.has_matplotlib(): assert ni_den.plot_line([0, 0, 0], [1, 1, 1], num=1000, show=False) assert ni_den.plot_line_neighbors( site_index=0, radius=1, num=50, max_nn=10) is None assert ni_den.plot_line_neighbors(site_index=0, radius=3, num=50, max_nn=10, show=False) # Export data in xsf format. visu = ni_den.export(".xsf") assert callable(visu) # Test CUBE files. tmp_cubefile = self.get_tmpname(text=True) ni_den.export_to_cube(tmp_cubefile, spin="total") total_den = Density.from_cube(tmp_cubefile) assert total_den.structure == ni_den.structure assert abs(total_den.get_nelect().sum() - ne) < 1e-3 # Export to chgcar and re-read it. chgcar_path = self.get_tmpname(text=True) chgcar = ni_den.to_chgcar(filename=chgcar_path) assert hasattr(chgcar, "structure") assert chgcar.is_spin_polarized poscar_path = self.get_tmpname(text=True) ni_den.structure.to(fmt="poscar", filename=poscar_path) same_den = Density.from_chgcar_poscar(chgcar_path, poscar_path) assert same_den.nspinor == 1 and same_den.nsppol == 2 and same_den.nspden == 2 self.assert_almost_equal(same_den.datar, ni_den.datar, decimal=5)
def test_gsr_robot(self): """Testing GSR robot""" from abipy import abilab gsr_ibz = abidata.ref_file("si_scf_GSR.nc") robot = abilab.GsrRobot() robot.add_file("gsr0", gsr_ibz) assert len(robot.abifiles) == 1 assert "gsr0" in robot.keys() assert "gsr0" in robot.labels assert robot.EXT == "GSR" repr(robot) str(robot) assert robot.to_string(verbose=2) # Cannot have same label with self.assertRaises(ValueError): robot.add_file("gsr0", gsr_ibz) assert len(robot) == 1 and not robot.exceptions robot.add_file("gsr1", abilab.abiopen(gsr_ibz)) assert len(robot) == 2 robot.show_files() assert not robot.has_different_structures() with self.assertRaises(AttributeError): robot.is_sortable("foobar", raise_exc=True) assert not robot.is_sortable("foobar") # Test different syntax. assert robot.is_sortable("nkpt") # gsr.nkpt assert robot.is_sortable("ebands.nkpt") # gsr.ebands.nkpt assert robot.is_sortable("ecut") # in gsr.params dfs = robot.get_structure_dataframes() assert dfs.lattice is not None assert dfs.coords is not None assert len(dfs.structures) == len(robot) assert len(robot.get_ebands_plotter(kselect="path")) == 0 filter_abifile = lambda gsr: gsr.ebands.kpoints.is_ibz assert len( robot.get_ebands_plotter(filter_abifile=filter_abifile)) == 2 ebands_plotter = robot.get_ebands_plotter() edos_plotter = robot.get_edos_plotter() if self.has_matplotlib(): assert ebands_plotter.gridplot(show=False) assert robot.combiplot_ebands(show=False) assert robot.gridplot_ebands(show=False) assert robot.boxplot_ebands(show=False) assert robot.combiboxplot_ebands(show=False) assert edos_plotter.gridplot(show=False) assert robot.combiplot_edos(show=False) assert robot.gridplot_edos(show=False) assert robot.plot_gsr_convergence(show=False) assert robot.plot_gsr_convergence(sortby="nkpt", hue="tsmear", show=False) y_vars = ["energy", "structure.lattice.a", "structure.volume"] assert robot.plot_convergence_items(y_vars, sortby="nkpt", hue="tsmear", show=False) assert robot.plot_egaps(show=False) assert robot.plot_egaps(sortby="nkpt", hue="tsmear") assert robot.gridplot_with_hue("structure.formula", show=False) # Get pandas dataframe. df = robot.get_dataframe() assert "energy" in df self.assert_equal(df["ecut"].values, 6.0) self.assert_almost_equal(df["energy"].values, -241.2364683) df_params = robot.get_params_dataframe() assert "nband" in df_params assert "alpha" in robot.get_lattice_dataframe() assert hasattr(robot.get_coords_dataframe(), "keys") eterms_df = robot.get_energyterms_dataframe(iref=0) assert "energy" in eterms_df assert "ecut" in eterms_df assert "nkpt" in eterms_df if self.has_matplotlib(): assert robot.plot_xy_with_hue(df, x="nkpt", y="pressure", hue="a", show=False) # Note: This is not a real EOS since we have a single volume. # But testing is better than not testing. r = robot.get_eos_fits_dataframe() assert hasattr(r, "fits") and hasattr(r, "dataframe") if self.has_matplotlib(): assert robot.gridplot_eos(show=False) if self.has_nbformat(): robot.write_notebook(nbpath=self.get_tmpname(text=True)) robot.close() # Test other class methods filepath = abidata.ref_file("si_scf_GSR.nc") robot = abilab.GsrRobot.from_dirs(os.path.dirname(filepath), abspath=True) assert len(robot) == 2 assert robot[filepath].filepath == filepath # Test from_dir_glob pattern = "%s/*/si_ebands/" % abidata.dirpath same_robot = abilab.GsrRobot.from_dir_glob(pattern, abspath=True) assert len(same_robot) == 2 assert set(robot.labels) == set(same_robot.labels) robot.close() same_robot.close()
def test_MgB2_fatbands(self): """Testing MgB2 fatbands with prtdos 3.""" fbnc_kpath = FatBandsFile(abidata.ref_file("mgb2_kpath_FATBANDS.nc")) repr(fbnc_kpath) str(fbnc_kpath) assert fbnc_kpath.to_string(verbose=2) assert fbnc_kpath.ebands.kpoints.is_path assert not fbnc_kpath.ebands.kpoints.is_ibz assert fbnc_kpath.prtdos == 3 assert fbnc_kpath.prtdosm == 0 assert fbnc_kpath.mbesslang == 5 assert fbnc_kpath.pawprtdos == 0 assert fbnc_kpath.usepaw == 0 assert fbnc_kpath.nsppol == 1 assert fbnc_kpath.nspden == 1 assert fbnc_kpath.nspinor == 1 assert fbnc_kpath.nkpt == 78 assert fbnc_kpath.mband == 8 assert fbnc_kpath.natsph_extra == 0 assert not fbnc_kpath.ebands.has_metallic_scheme assert fbnc_kpath.params["nkpt"] == 78 if self.has_matplotlib(): assert fbnc_kpath.plot_fatbands_typeview(tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_lview(tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_siteview(e0=None, view="inequivalent", fact=2.0, bdist=[1, 2, 3], show=False) if self.has_nbformat(): fbnc_kpath.write_notebook(nbpath=self.get_tmpname(text=True)) if self.has_panel(): assert hasattr(fbnc_kpath.get_panel(), "show") fbnc_kmesh = FatBandsFile( abidata.ref_file("mgb2_kmesh181818_FATBANDS.nc")) repr(fbnc_kmesh) str(fbnc_kmesh) assert fbnc_kmesh.ebands.kpoints.is_ibz assert fbnc_kmesh.ebands.has_metallic_scheme if self.has_matplotlib(): assert fbnc_kmesh.plot_pjdos_typeview(tight_layout=True, show=False) assert fbnc_kmesh.plot_pjdos_lview(tight_layout=True, stacked=True, show=False) assert fbnc_kmesh.plot_pjdos_lview(tight_layout=True, stacked=False, show=False) assert fbnc_kpath.plot_fatbands_with_pjdos(pjdosfile=fbnc_kmesh, view="type", tight_layout=True, show=False) assert fbnc_kpath.plot_fatbands_with_pjdos(pjdosfile=fbnc_kmesh, view="lview", tight_layout=True, show=False) assert fbnc_kpath.plot_spilling(e0=0, tight_layout=True, show=False) # These calls should return None #assert fbnc_kpath.plot_fatbands_spinor() is None assert fbnc_kpath.plot_pjdos_lview() is None assert fbnc_kpath.plot_pawdos_terms() is None #assert fbnc_kpath.plot_pjdos_spinor() is None assert fbnc_kpath.plot_fatbands_mview(iatom=0) is None fbnc_kpath.close() fbnc_kmesh.close()
def test_gsr_silicon(self): """spin unpolarized GSR file""" with GsrFile(abidata.ref_file("si_scf_GSR.nc")) as gsr: assert gsr.basename == "si_scf_GSR.nc" assert gsr.relpath == os.path.relpath( abidata.ref_file("si_scf_GSR.nc")) assert gsr.filetype assert gsr.filestat() assert len(gsr.ncdump()) repr(gsr) str(gsr) assert gsr.to_string(verbose=2) assert gsr.abinit_version == "8.0.6" str(gsr.ebands) assert gsr.filepath == abidata.ref_file("si_scf_GSR.nc") assert gsr.nsppol == 1 assert gsr.mband == 8 and gsr.nband == 8 and gsr.nelect == 8 and len( gsr.kpoints) == 29 assert gsr.mband == gsr.hdr.mband assert "nelect" in gsr.hdr and gsr.nelect == gsr.hdr.nelect self.assert_almost_equal(gsr.energy.to("Ha"), -8.86527676798556) self.assert_almost_equal(gsr.energy_per_atom * len(gsr.structure), gsr.energy) assert gsr.params["nband"] == 8 assert gsr.params["nkpt"] == 29 # Test energy_terms eterms = gsr.energy_terms repr(eterms) str(eterms) assert eterms.to_string(with_doc=True) self.assert_almost_equal(eterms.e_xc.to("Ha"), -3.51815936301812) self.assert_almost_equal(eterms.e_nonlocalpsp.to("Ha"), 1.91660690901782) self.assert_almost_equal(eterms.e_kinetic.to("Ha"), 2.96421325671218) self.assert_almost_equal(eterms.e_fermie.to("Ha"), 0.205739364929368) # Forces and stress self.assert_almost_equal( gsr.cart_forces.to("Ha bohr^-1").flat, [ -1.14726679671674e-28, -3.76037290483622e-29, 5.65937773808884e-29, 1.14726679671674e-28, 3.76037290483622e-29, -5.65937773808884e-29 ]) self.assert_almost_equal(gsr.max_force, 0) assert gsr.force_stats() assert gsr.residm > 0 assert str(gsr.xc) == "LDA_XC_TETER93" #self.assert_almost_equal(gsr.cart_stress_tensor.flat, # Cartesian components of stress tensor (hartree/bohr^3) # sigma(1 1)= 1.77139311E-04 sigma(3 2)= 0.00000000E+00 # sigma(2 2)= 1.77139311E-04 sigma(3 1)= 0.00000000E+00 # sigma(3 3)= 1.77139311E-04 sigma(2 1)= 2.67294316E-15 for i in range(3): self.assert_almost_equal(gsr.cart_stress_tensor[0, 0], 1.77139311E-04 * abu.HaBohr3_GPa) self.assert_almost_equal(gsr.pressure, -5.211617575719521) # Test pymatgen computed_entries for inc_structure in (True, False): e = gsr.get_computed_entry(inc_structure=inc_structure) str(e) d = e.as_dict() if inc_structure: assert "structure" in d assert d["energy"] == gsr.energy assert gsr.energy == e.energy if self.has_matplotlib(): assert gsr.plot_ebands(show=False) assert gsr.plot_ebands_with_edos(edos=gsr.get_edos(), show=False) if self.has_nbformat(): gsr.write_notebook(nbpath=self.get_tmpname(text=True))
#!/usr/bin/env python """ This example shows how to compute the DOS from the eigenvalues stored in the WFK file with the gaussian method. """ import abipy.data as abidata from abipy.abilab import abiopen # Open the wavefunction file computed with a homogeneous sampling of the BZ # and extract the band structure on the k-mesh. with abiopen(abidata.ref_file("si_scf_WFK.nc")) as gs_wfk: gs_ebands = gs_wfk.ebands # Compute the DOS with the Gaussian method (default) edos = gs_ebands.get_edos(method="gaussian", step=0.01, width=0.1) # Plot electron DOS and IDOS edos.plot(title="Silicon DOS") # Plot electron DOS and IDOS edos.plot_dos_idos(title="DOS and Integrated DOS")
#!/usr/bin/env python r""" Bethe-Salpeter ============== This example shows how to plot the macroscopic dielectric function (MDF) computed in the Bethe-Salpeter code. """ import abipy.data as abidata from abipy.abilab import abiopen # Open the MDF file produced in the tutorial. mdf_file = abiopen(abidata.ref_file("tbs_4o_DS2_MDF.nc")) # Plot the imaginary part of the macroscopic # dielectric function (EXC, RPA, GWRPA) between 2 and 5 eV. xlims = (2, 5) mdf_file.plot_mdfs( xlims=xlims, title="Si absorption spectrum: EXC vs RPA (averaged over small q-points)") # Plot the real part for the first q-point --> 0 mdf_file.plot_mdfs(cplx_mode="Re", qpoint=0, xlims=xlims, title="Real part for the first q-point: EXC vs RPA") # Plot the 6 different components of the macroscopic dielectric tensor tensor_exc = mdf_file.get_tensor("exc") tensor_exc.symmetrize(mdf_file.structure)
def test_abiview(self): """Testing abiview.py script""" env = self.get_env() runabo = abidata.ref_file("refs/gs_dfpt.abo") r = env.run(self.script, "abo", runabo, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) logpath = abidata.ref_file("refs/abinit.log") r = env.run(self.script, "log", logpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("refs/sic_relax_HIST.nc") r = env.run(self.script, "hist", ncpath, "--xdatcar", self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("si_nscf_GSR.nc") r = env.run(self.script, "ebands", ncpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) r = env.run(self.script, "ebands", ncpath, "--xmgrace", self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("si_scf_GSR.nc") r = env.run(self.script, "ebands", ncpath, "--bxsf", self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("mgb2_kpath_FATBANDS.nc") r = env.run(self.script, "fatbands", ncpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ddbpath = abidata.ref_file("refs/znse_phonons/ZnSe_hex_qpt_DDB") r = env.run(self.script, "ddb", ddbpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("ZnSe_hex_886.out_PHBST.nc") r = env.run(self.script, "phbands", ncpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) r = env.run(self.script, "phbands", ncpath, "--xmgrace", self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("ZnSe_hex_886.out_PHDOS.nc") r = env.run(self.script, "phdos", ncpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("mg2si_GRUNS.nc") r = env.run(self.script, "gruns", ncpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr) ncpath = abidata.ref_file("si_666_MDF.nc") r = env.run(self.script, "mdf", ncpath, self.loglevel, self.verbose, expect_stderr=self.expect_stderr)
def test_silicon_interpolation(self): """Testing interpolation of Si band energies with SKW method.""" from abipy.abilab import abiopen with abiopen(abidata.ref_file("si_scf_GSR.nc")) as gsr: # Extract data from GSR structure, ebands = gsr.structure, gsr.ebands kcoords = [k.frac_coords for k in ebands.kpoints] cell = (structure.lattice.matrix, structure.frac_coords, structure.atomic_numbers) # Get FM part of symmetry operations. abispg = structure.abi_spacegroup fm_symrel = [s for (s, afm) in zip(abispg.symrel, abispg.symafm) if afm == 1] # Build interpolator. lpratio, has_timrev = 5.0, True skw = SkwInterpolator(lpratio, kcoords, ebands.eigens, ebands.fermie, ebands.nelect, cell, fm_symrel, has_timrev, filter_params=None, verbose=1) repr(skw); print(skw) assert skw.occtype == "insulator" assert skw.use_cache assert skw.lpratio == lpratio assert skw.nsppol == 1 and skw.nkpt == 29 and skw.nband == 8 assert skw.ptg_nsym == 48 assert skw.nr == 145 and skw.rcut is None and skw.rsigma is None self.assert_almost_equal(skw.mae, 7.0e-11) assert skw.val_ib == 3 and isinstance(skw.val_ib, int) kmesh, is_shift = [8, 8, 8], None # Test interpolation routines (low-level API). k = skw.get_sampling(kmesh, is_shift) assert np.all(k.mesh == kmesh) and np.all(k.shift == 0) assert k.nbz == 8 ** 3 and k.nibz == 29 and k.weights.sum() == 1 assert len(k.bz2ibz) == k.nbz # interpolate energies at 3 new k-points new_kcoords = [(0, 0, 0), (0.1, 0, 0), (0.12, 0.13, 0.14)] new_eigens = skw.interp_kpts(new_kcoords).eigens assert new_eigens.shape == (skw.nsppol, len(new_kcoords), skw.nband) res1 = skw.interp_kpts(new_kcoords, dk1=True, dk2=False) print(res1.dedk) assert res1.dedk.shape == (skw.nsppol, len(new_kcoords), skw.nband, 3) # Group velocities at Gamma should be zero by symmetry. self.assert_almost_equal(res1.dedk[0, 0], 0.0) #assert 0 #res12 = skw.interp_kpts(new_kcoords, dk1=True, dk2=True) #print(res12.dedk2) # Test interpolation routines (high-level API). edos = skw.get_edos(kmesh, is_shift=None, method="gaussian", step=0.1, width=0.2, wmesh=None) jdos = skw.get_jdos_q0(kmesh, is_shift=None, method="gaussian", step=0.1, width=0.2, wmesh=None) #nest = skw.get_nesting_at_e0(qpoints, kmesh, e0, width=0.2, is_shift=None) # Test pickle tmpname = self.get_tmpname(text=True) skw.pickle_dump(tmpname) new = SkwInterpolator.pickle_load(tmpname) # Test plotting API. if self.has_matplotlib(): kmeshes = [[2, 2, 2], [4, 4, 4]] is_shift = None skw.plot_dos_vs_kmeshes(kmeshes, is_shift=is_shift, show=False) skw.plot_jdosq0_vs_kmeshes(kmeshes, is_shift=is_shift, show=False)
#!/usr/bin/env python """ This example shows how to compute the DOS and plot a band structure with DOS using two GSR files. """ from abipy.abilab import abiopen import abipy.data as abidata # Open the file with energies computed on a k-path in the BZ # and extract the band structure object. with abiopen(abidata.ref_file("si_nscf_GSR.nc")) as nscf_file: nscf_ebands = nscf_file.ebands # Open the file with energies computed with a homogeneous sampling of the BZ # and extract the band structure object. with abiopen(abidata.ref_file("si_scf_GSR.nc")) as gs_file: gs_ebands = gs_file.ebands # Compute the DOS with the Gaussian method (use default values for # the broadening and the step of the linear mesh. edos = gs_ebands.get_edos() # Plot bands and DOS. nscf_ebands.plot_with_edos(edos, e0=None) print("nscf_ebands.efermi", nscf_ebands.fermie) print("gs_ebands.efermi", gs_ebands.fermie)