def from_dir(cls, top, walk=True): """ This classmethod builds a robot by scanning all files located within directory `top`. Note that if walk is True, directories inside `top` are included as well. This method should be invoked with a concrete robot class, for example: robot = GsrRobot.from_dir(".") Args: top (str): Root directory """ top = os.path.abspath(top) from abipy.abilab import abiopen items = [] if walk: for dirpath, dirnames, filenames in os.walk(top): filenames = [f for f in filenames if f.endswith(cls.EXT + ".nc") or f.endswith(cls.EXT)] for f in filenames: ncfile = abiopen(os.path.join(dirpath, f)) if ncfile is not None: items.append((ncfile.filepath, ncfile)) else: filenames = [f for f in os.listdir(top) if f.endswith(cls.EXT + ".nc") or f.endswith(cls.EXT)] for f in filenames: ncfile = abiopen(os.path.join(top, f)) if ncfile is not None: items.append((ncfile.filepath, ncfile)) return cls(*items)
def _open_files_in_dir(cls, top, walk): """Open files in directory tree starting from `top`. Return list of Abinit files.""" if not os.path.isdir(top): raise ValueError("%s: no such directory" % str(top)) from abipy.abilab import abiopen items = [] if walk: for dirpath, dirnames, filenames in os.walk(top): filenames = [ f for f in filenames if cls.class_handles_filename(f) ] for f in filenames: abifile = abiopen(os.path.join(dirpath, f)) if abifile is not None: items.append((abifile.filepath, abifile)) else: filenames = [ f for f in os.listdir(top) if cls.class_handles_filename(f) ] for f in filenames: abifile = abiopen(os.path.join(top, f)) if abifile is not None: items.append((abifile.filepath, abifile)) return items
def test_coxp(self): """Test files based on the GaAs lobster test. Extracted from abinit calculation.""" # Test COHPCAR with abiopen(os.path.join(lobster_gaas_dir, "GaAs_COHPCAR.lobster.gz")) as cohp: repr(cohp); str(cohp) assert cohp.to_string(verbose=2) assert cohp.nsppol == 1 assert len(cohp.type_of_index) == 2 assert cohp.type_of_index[0] == "Ga" and cohp.type_of_index[1] == "As" assert cohp.cop_type == "cohp" self.assert_almost_equal(cohp.fermie, 2.29843, decimal=4) assert len(cohp.energies) == 401 assert (0, 1) in cohp.partial assert ("4s", "4p_x") in cohp.partial[(0, 1)] assert 0 in cohp.partial[(0, 1)][("4s", "4p_x")] assert len(cohp.partial[(0, 1)][("4s", "4p_x")][0]["single"]) == 401 self.assertAlmostEqual(cohp.partial[(0, 1)][("4s", "4p_x")][0]["single"][200], -0.02075) assert len(cohp.site_pairs_total) == 2 assert len(cohp.site_pairs_partial) == 2 self.assertAlmostEqual(cohp.functions_pair_lorbitals[(0, 1)][("4s", "4p")][0].values[200], -0.06225) self.assertAlmostEqual(cohp.functions_pair_morbitals[(0, 1)][("4s", "4p_x")][0].values[200], -0.02075) self.assertAlmostEqual(cohp.functions_pair[(0, 1)][0].values[200], -0.06124) #self.check_average(cohp) if self.has_matplotlib(): assert cohp.plot(title="default values", show=False) assert cohp.plot_site_pairs_total(from_site_index=[0, 1], what="single", exchange_xy=True, show=False) assert cohp.plot_site_pairs_partial(from_site_index=[0, 1], what="single", exchange_xy=True, show=False) assert cohp.plot_average_pairs(with_site_index=[0, 1], what="single", exchange_xy=True, show=False) #assert cohp.plot_with_ebands(ebands_kpath, show=False) if self.has_nbformat(): assert cohp.write_notebook(nbpath=self.get_tmpname(text=True)) # Test COOPCAR with abiopen(os.path.join(lobster_gaas_dir, "GaAs_COOPCAR.lobster.gz")) as coop: repr(coop); str(coop) assert coop.to_string(verbose=2) assert coop.nsppol == 1 assert len(coop.type_of_index) == 2 assert coop.type_of_index[0] == "Ga" and coop.type_of_index[1] == "As" assert coop.cop_type == "coop" assert len(coop.energies) == 401 assert (0, 1) in coop.partial assert ("4s", "4p_x") in coop.partial[(0, 1)] assert 0 in coop.partial[(0, 1)][("4s", "4p_x")] assert len(coop.partial[(0, 1)][("4s", "4p_x")][0]["single"]) == 401 self.assertAlmostEqual(coop.partial[(0, 1)][("4s", "4p_x")][0]["single"][200], 0.01466) #self.check_average(coop) if self.has_matplotlib(): assert coop.plot(title="default values", show=False) if self.has_nbformat(): assert coop.write_notebook(nbpath=self.get_tmpname(text=True))
def bsanddos(inputDos,inputBand,outputDos,outputBand,outputBoth,titleBS,titleDOS,show): ebands = abilab.abiopen(inputBand).ebands ebandsDos = abilab.abiopen(inputDos).ebands dos = ebandsDos.get_edos(); fig=dos.plot(title=titleDOS,show=show,savefig=outputBand) fig=ebands.plot(title=titleBS,show=show,savefig=outputDos) fig=ebands.plot_with_dos(dos,savefig=outputBoth,show=show)
def bsanddos(inputDos, inputBand, outputDos, outputBand, outputBoth, titleBS, titleDOS, show): ebands = abilab.abiopen(inputBand).ebands ebandsDos = abilab.abiopen(inputDos).ebands dos = ebandsDos.get_edos() fig = dos.plot(title=titleDOS, show=show, savefig=outputBand) fig = ebands.plot(title=titleBS, show=show, savefig=outputDos) fig = ebands.plot_with_dos(dos, savefig=outputBoth, show=show)
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 from_files(cls, filenames, labels=None, abspath=False): """ Build a Robot from a list of `filenames`. if labels is None, labels are automatically generated from absolute paths. Args: abspath: True if paths in index should be absolute. Default: Relative to `top`. """ filenames = list_strings(filenames) from abipy.abilab import abiopen filenames = [f for f in filenames if cls.class_handles_filename(f)] items = [] for i, f in enumerate(filenames): try: abifile = abiopen(f) except Exception as exc: cprint("Exception while opening file: `%s`" % str(f), "red") cprint(exc, "red") abifile = None if abifile is not None: label = abifile.filepath if labels is None else labels[i] items.append((label, abifile)) new = cls(*items) if labels is None and not abspath: new.trim_paths(start=None) return new
def abinp_abispg(options): """Call Abinit with chkprim = 0 to find space group.""" inp = build_abinit_input_from_file(options, chkprim=0, mem_test=0) r = inp.abivalidate() if r.retcode != 0: print(r.log_file, r.stderr_file) return r.retcode try: out = abilab.abiopen(r.output_file.path) except Exception as exc: print("Error while trying to parse output file:", r.output_file.path) print("Exception:\n", exc) return 1 #print(out) structure = out.initial_structure # Call spglib to get spacegroup if Abinit spacegroup is not available. # Return string with full information about crystalline structure i.e. # space group, point group, wyckoff positions, equivalent sites. print(structure.spget_summary(verbose=options.verbose)) if options.verbose: print(structure.abi_spacegroup.to_string(verbose=options.verbose)) return 0
def itest_g0w0_flow(fwp, tvars): """Test flow for G0W0 calculations.""" scf, nscf, scr, sig = make_g0w0_inputs(ngkpt=[2, 2, 2], tvars=tvars) flow = abilab.g0w0_flow(fwp.workdir, scf, nscf, scr, sig, manager=fwp.manager) # Will remove output files at run-time. flow.set_garbage_collector() flow.build_and_pickle_dump(abivalidate=True) for task in flow[0]: task.start_and_wait() flow.check_status() flow.show_status() assert all(work.finalized for work in flow) assert flow.all_ok scf_task = flow[0][0] nscf_task = flow[0][1] scr_task = flow[0][2] sig_task = flow[0][3] # Test garbage)_collector # The WFK|SCR file should have been removed because we call set_garbage_collector assert not scf_task.outdir.has_abiext("WFK") assert not nscf_task.outdir.has_abiext("WFK") assert not scr_task.outdir.has_abiext("SCR") assert not scr_task.outdir.has_abiext("SUS") # The sigma task should produce a SIGRES file. sigfile = sig_task.outdir.list_filepaths(wildcard="*SIGRES.nc")[0] assert sigfile with abilab.abiopen(sigfile) as sigres: assert sigres.nsppol == 1 # Test SigmaTask inspect method #if has_matplotlib #sig_task.inspect(show=False) # Test get_results for Sigma and Scr scr_task.get_results() sig_task.get_results() # Test SCR.nc file (this is optional) if scr_task.scr_path: with scr_task.open_scr() as scr: print(scr) assert len(scr.wpts) == 2 assert scr.nwre == 1 and scr.nwim == 1 for iq, qpoint in enumerate(scr.qpoints[:2]): print(qpoint) qpt, iqcheck = scr.reader.find_qpoint_fileindex(qpoint) assert iqcheck == iq em1 = scr.get_em1(qpoint) print(em1)
def test_lobsterdos(self): """Testing Lobster DOSCAR files.""" with abiopen(os.path.join(lobster_gaas_dir, "GaAs_DOSCAR.lobster.gz")) as ldos: repr(ldos) str(ldos) assert ldos.to_string(verbose=2) assert len(ldos.energies) == 401 assert ldos.nsppol == 1 assert ldos.nsites == 2 assert 1 in ldos.pdos assert "4p_x" in ldos.pdos[1] assert 0 in ldos.pdos[1]["4p_x"] self.assert_almost_equal(ldos.fermie, 2.29843, decimal=4) assert ldos.type_of_index[0] == "Ga" and ldos.type_of_index[ 1] == "As" self.assertAlmostEqual(ldos.pdos[1]["4p_x"][0][200], 0.02694) self.assertAlmostEqual(ldos.total_dos[0][200], 0.17824) self.check_average(ldos) if self.has_matplotlib(): assert ldos.plot(title="default values", show=False) assert ldos.plot_pdos_site(site_index=0, title="default values", show=False) assert ldos.plot_pdos_site(site_index=[0, 1], exchange_xy=True, title="default values", show=False) #assert cohp.plot_with_ebands(ebands_kpath, show=False) if self.has_nbformat(): assert ldos.write_notebook(nbpath=self.get_tmpname(text=True))
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_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 add_file(self, label, ncfile): if is_string(ncfile): from abipy.abilab import abiopen ncfile = abiopen(ncfile) self._do_close[ncfile.filepath] = True self._ncfiles[label] = ncfile
def on_value_change(change): """Callback""" clear_output() path = change["new"] #print(change) with abilab.abiopen(path) as abifile: print(abifile)
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_ddk_api(self): """Testing DDK API""" with abilab.abiopen(abidata.ref_file("gaas_444_dir1_DDK.nc")) as ddk: repr(ddk) str(ddk) assert ddk.to_string(verbose=2) assert ddk.structure.formula == "Ga1 As1" assert ddk.ebands.nsppol == 1 and ddk.ebands.nspden == 1 and ddk.ebands.nspinor == 1 assert ddk.ebands.nband == 20 assert ddk.idir == 1 and ddk.ipert == len(ddk.structure) + 1 assert ddk.kptopt == 2 ksamp = ddk.kpoints.ksampling self.assert_equal(ksamp.kptrlatt_orig.ravel(), [4, 0, 0, 0, 4, 0, 0, 0, 4]) self.assert_equal( ksamp.shifts_orig.ravel(), [0.5, 0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5]) assert ddk.kpoints.is_ibz ddk.kpoints.check_weights() assert np.all(ddk.hdr["qptn"] == 0) #assert ddk.xc == "LDA" assert ddk.params["nband"] == 20 if self.has_nbformat(): assert ddk.write_notebook(nbpath=self.get_tmpname(text=True))
def test_lobsterdos(self): """Testing Lobster DOSCAR files.""" with abiopen(os.path.join(lobster_gaas_dir, "GaAs_DOSCAR.lobster.gz")) as ldos: repr(ldos); str(ldos) assert ldos.to_string(verbose=2) assert len(ldos.energies) == 401 assert ldos.nsppol == 1 assert ldos.nsites == 2 assert 1 in ldos.pdos assert "4p_x" in ldos.pdos[1] assert 0 in ldos.pdos[1]["4p_x"] self.assert_almost_equal(ldos.fermie, 2.29843, decimal=4) assert ldos.type_of_index[0] == "Ga" and ldos.type_of_index[1] == "As" self.assertAlmostEqual(ldos.pdos[1]["4p_x"][0][200], 0.02694) self.assertAlmostEqual(ldos.total_dos[0][200], 0.17824) self.check_average(ldos) if self.has_matplotlib(): assert ldos.plot(title="default values", show=False) assert ldos.plot_pdos_site(site_index=0, title="default values", show=False) assert ldos.plot_pdos_site(site_index=[0, 1], exchange_xy=True, title="default values", show=False) #assert cohp.plot_with_ebands(ebands_kpath, show=False) if self.has_nbformat(): assert ldos.write_notebook(nbpath=self.get_tmpname(text=True))
def from_file(cls, filepath): """ Generate object from (SIGRES.nc) file. Main entry point for client code. """ from abipy.abilab import abiopen with abiopen(filepath) as ncfile: return cls(qps_spin=ncfile.qplist_spin, sigres_ebands=ncfile.ebands)
def add_file(self, label, abifile, filter_abifile=None): """ Add a file to the robot with the given label. Args: label: String used to identify the file (must be unique, ax exceptions is raised if label is already present. abifile: Specify the file to be added. Accepts strings (filepath) or abipy file-like objects. filter_abifile: Function that receives an ``abifile`` object and returns True if the file should be added to the plotter. """ if is_string(abifile): from abipy.abilab import abiopen abifile = abiopen(abifile) if filter_abifile is not None and not filter_abifile(abifile): abifile.close() return # Open file here --> have to close it. self._do_close[abifile.filepath] = True if label in self._abifiles: raise ValueError("label %s is already present!" % label) self._abifiles[label] = abifile
def test_plot_functions(self): """Testing plotting tools for phonons.""" if not self.has_matplotlib(): raise unittest.SkipTest("matplotlib missing") phbst_filename = abidata.ref_file("trf2_5.out_PHBST.nc") from abipy import abilab with abilab.abiopen(phbst_filename) as nc: phbands = nc.phbands phb_objects = [ phbands, phbst_filename, ] phdos_filename = abidata.ref_file("trf2_5.out_PHDOS.nc") phdos = PhdosFile(phdos_filename) phdos_objects = [ phdos, phdos_filename, ] fig = phbands_gridplot(phb_objects, titles=["phonons1", "phonons2"], phdos_objects=phdos_objects, show=False) assert fig is not None phdos.close()
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_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 add_file(self, filepath, label=None): """Add a filename to the plotter""" from abipy.abilab import abiopen sigres = abiopen(filepath) self._sigres_files[sigres.filepath] = sigres # TODO: Not used self._labels.append(label) # Initialize/check useful quantities. # # 1) Number of spins if not hasattr(self, "nsppol"): self.nsppol = sigres.nsppol if self.nsppol != sigres.nsppol: raise ValueError("Found two SIGRES files with different nsppol") # The set of k-points where GW corrections have been computed. if not hasattr(self, "computed_gwkpoints"): self.computed_gwkpoints = sigres.gwkpoints if self.computed_gwkpoints != sigres.gwkpoints: raise ValueError("Found two SIGRES files with different list of GW k-points.") #self.computed_gwkpoints = (self.computed_gwkpoints + sigres.gwkpoints).remove_duplicated() if not hasattr(self, "max_gwbstart"): self.max_gwbstart = sigres.max_gwbstart else: self.max_gwbstart = max(self.max_gwbstart, sigres.max_gwbstart) if not hasattr(self, "min_gwbstop"): self.min_gwbstop = sigres.min_gwbstop else: self.min_gwbstop = min(self.min_gwbstop, sigres.min_gwbstop)
def test_example03_silicon(self): """Parsing example02_silicon.wout with DISENTANGLE""" filepath = os.path.join(abidata.dirpath, "refs", "wannier90", "example03_silicon.wout") with abilab.abiopen(filepath) as wout: repr(wout); str(wout) assert wout.to_string(verbose=2) assert wout.version == "2.1.0+git" assert wout.structure.formula == "Si2" self.assert_almost_equal(wout.structure.frac_coords.ravel(), [-0.25000, 0.75000, -0.25000, 0.00000, 0.00000, 0.00000]) assert not wout.warnings for k in ("MAIN", "WANNIERISE", "DISENTANGLE"): assert k in wout.params_section assert wout.use_disentangle assert wout.nwan == 8 assert np.all(wout.grid_size == 4) assert len(wout.conv_df) == 6 + 1 assert wout.conv_df.O_D[1] == 0.1213986 and wout.conv_df.O_OD[1] == 2.7017701 assert wout.conv_df.O_D.values[-1] == 0.1054702 and wout.conv_df.O_OD.values[-1] == 2.5449106 # numpy array (nwan, nstep, ...) nstep = len(wout.conv_df.O_D) assert wout.wf_centers.shape == (wout.nwan, nstep, 3) self.assert_equal(wout.wf_centers[7, -1], [0.888643, 0.888652, 1.810090 ]) assert wout.wf_spreads.shape == (wout.nwan, nstep) self.assert_equal(wout.wf_spreads[7, -1], 1.81245236) if self.has_matplotlib(): assert wout.plot(show=False) assert wout.plot_centers_spread(show=False) if self.has_nbformat(): assert wout.write_notebook(nbpath=self.get_tmpname(text=True))
def abiview_log(options): """ Print WARNINGS/COMMENTS/ERRORS found in Abinit log file. """ with abilab.abiopen(options.filepath) as abo: print(abo.to_string(verbose=options.verbose)) return 0
def test_plot_functions(self): """Testing plotting tools for phonons.""" phbst_filename = abidata.ref_file("trf2_5.out_PHBST.nc") with abilab.abiopen(phbst_filename) as nc: phbands = nc.phbands phb_objects = [ phbands, phbst_filename, ] phdos_filename = abidata.ref_file("trf2_5.out_PHDOS.nc") phdos = PhdosFile(phdos_filename) phdos_objects = [ phdos, phdos_filename, ] if self.has_matplotlib(): assert phbands_gridplot(phb_objects, titles=["phonons1", "phonons2"], phdos_objects=phdos_objects, units="meV", show=False) phdos.close()
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_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_frohlich_zpr_flow(self): """Testing FrohlichZPRFlow""" # Read structure from DDB file. from abipy import abilab ddb_path = abidata.ref_file("refs/mgo_v8t57/mgo_zpr_t57o_DS3_DDB") with abilab.abiopen(ddb_path) as ddb: structure = ddb.structure pseudos = abidata.pseudos("Ca.psp8", "O.psp8") scf_input = abilab.AbinitInput(structure=structure, pseudos=pseudos) # Set other input variables. These quantities are system-depedent. # Here we use parameters similar to https://docs.abinit.org/tests/v8/Input/t57.in scf_input.set_vars( nband=12, nbdbuf=2, diemac=6, ecut=30, # Underconverged ecut. #ecut=15, nstep=100, tolvrs=1e-16, kptrlatt=[-2, 2, 2, # In cartesian coordinates, this grid is simple cubic 2, -2, 2, 2, 2, -2], ) workdir = self.mkdtemp() flow = FrohlichZPRFlow.from_scf_input(workdir, scf_input, ddb_node=ddb_path, ndivsm=2, tolwfr=1e-20, metadata={"mp_id": "mp-149"}) flow.allocate() flow.check_status() isok, checks = flow.abivalidate_inputs() assert isok
def test_example01_gaas(self): """Parsing example01_gaas.wout""" filepath = os.path.join(abidata.dirpath, "refs", "wannier90", "example01_gaas.wout") with abilab.abiopen(filepath) as wout: repr(wout); str(wout) assert wout.to_string(verbose=2) assert wout.version == "2.1.0+git" assert wout.structure.formula == "Ga1 As1" self.assert_almost_equal(wout.structure.frac_coords.ravel(), [0.00000, 0.00000, 0.00000, 0.25000, 0.25000, 0.25000]) assert not wout.warnings for k in ("MAIN", "WANNIERISE"): assert k in wout.params_section assert not wout.use_disentangle assert wout.nwan == 4 assert np.all(wout.grid_size == 2) assert len(wout.conv_df) == 20 + 1 assert wout.conv_df.O_D[0] == 0.0083198 and wout.conv_df.O_OD[0] == 0.5036294 assert wout.conv_df.O_D[20] == 0.0080300 and wout.conv_df.O_OD[20] == 0.5019880 # numpy array (nwan, nstep, ...) #natom = len(wout.structure) nstep = 21 assert wout.wf_centers.shape == (wout.nwan, nstep, 3) self.assert_equal(wout.wf_centers[1, 20], [-0.866253, 0.866253, 0.866253]) assert wout.wf_spreads.shape == (wout.nwan, nstep) self.assert_equal(wout.wf_spreads[1, 20], 1.11672024) if self.has_matplotlib(): assert wout.plot(show=False) assert wout.plot_centers_spread(show=False) if self.has_nbformat(): assert wout.write_notebook(nbpath=self.get_tmpname(text=True))
def abiview_ddb_ir(options): """ Compute infra-red spectrum from DDB. Plot results. """ asr = 2 chneut = 1 dipdip = 1 print(""" Computing phonon frequencies for infra-red spectrum with: asr = {asr}, chneut = {chneut}, dipdip = {dipdip} """.format(**locals())) with abilab.abiopen(options.filepath) as ddb: tgen = ddb.anaget_dielectric_tensor_generator(asr=asr, chneut=chneut, dipdip=dipdip, verbose=options.verbose) print(tgen.to_string(verbose=options.verbose)) gamma_ev = 1e-4 print( "Plotting dielectric tensor with constant phonon damping: %s (eV)" % gamma_ev) tgen.plot_all(gamma_ev=gamma_ev) return 0
def abiview_ddb_ifc(options): """ Visualize interatomic force constants in real space. """ asr = 2 chneut = 1 dipdip = 1 print(""" Computing interatomic force constants with asr = {asr}, chneut = {chneut}, dipdip = {dipdip} """.format(**locals())) with abilab.abiopen(options.filepath) as ddb: # Execute anaddb to compute the interatomic force constants. ifc = ddb.anaget_ifc(asr=asr, chneut=chneut, dipdip=dipdip) #print(ifc) with MplExpose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout) as e: e(ifc.plot_longitudinal_ifc(title="Longitudinal IFCs", show=False)) e( ifc.plot_longitudinal_ifc_short_range( title="Longitudinal IFCs short range", show=False)) e( ifc.plot_longitudinal_ifc_ewald( title="Longitudinal IFCs Ewald", show=False)) return 0
def __init__(self, parent, filepath, **kwargs): """ Args: parent: parent window filepath: Abinit output file. """ filepath = os.path.abspath(filepath) if "title" not in kwargs: kwargs["title"] = "Abinit Timer: %s" % os.path.basename(filepath) super(AbinitTimerFrame, self).__init__(parent, **kwargs) try: abifile = abiopen(filepath) self.timer_data = abifile.timer_data except Exception as exc: raise awx.Error(str(exc)) if not self.timer_data: raise awx.Error("%s does not contain a valid ABINIT TIMER section!" % filepath) self.BuildUi()
def itest_g0w0_flow(fwp, tvars): """Test flow for G0W0 calculations.""" scf, nscf, scr, sig = make_g0w0_inputs(ngkpt=[2, 2, 2], tvars=tvars) flow = abilab.g0w0_flow(fwp.workdir, scf, nscf, scr, sig, manager=fwp.manager) # Will remove output files at run-time. flow.set_cleanup_exts() flow.build_and_pickle_dump() for task in flow[0]: task.start_and_wait() flow.check_status() flow.show_status() assert all(work.finalized for work in flow) assert flow.all_ok scf_task = flow[0][0] nscf_task = flow[0][1] scr_task = flow[0][2] sig_task = flow[0][3] # Test set_cleanup_exts # The WFK|SCR file should have been removed because we call set_cleanup_exts assert not scf_task.outdir.has_abiext("WFK") assert not nscf_task.outdir.has_abiext("WFK") assert not scr_task.outdir.has_abiext("SCR") assert not scr_task.outdir.has_abiext("SUS") # The sigma task should produce a SIGRES file. sigfile = sig_task.outdir.list_filepaths(wildcard="*SIGRES.nc")[0] assert sigfile with abilab.abiopen(sigfile) as sigres: assert sigres.nsppol == 1
def test_readall(self): for path in abidata.SIGRES_NCFILES: with abilab.abiopen(path) as sigres: repr(sigres) str(sigres) assert sigres.to_string(verbose=2) assert len(sigres.structure)
def test_alas_with_third_order(self): """ Testing DDB containing also third order derivatives. """ with abilab.abiopen( abidata.ref_file("refs/alas_nl_dfpt/AlAs_nl_dte_DDB")) as ddb: repr(ddb) str(ddb) assert ddb.to_string(verbose=2) self.assert_almost_equal(ddb.total_energy.to("Ha"), -0.10085769246152e+02) assert ddb.cart_forces is not None stress = ddb.cart_stress_tensor # Ha/Bohr^3 from DDB ref_voigt = np.array([ -0.31110177329142E-05, -0.31110177329142E-05, -0.31110177329146E-05, 0.00000000000000E+00, 0.00000000000000E+00, 0.00000000000000E+00 ]) # AbiPy stress is in GPa self.assert_almost_equal(stress[0, 0], ref_voigt[0] * abu.HaBohr3_GPa) self.assert_almost_equal(stress[1, 1], ref_voigt[1] * abu.HaBohr3_GPa) self.assert_almost_equal(stress[2, 2], ref_voigt[2] * abu.HaBohr3_GPa) self.assert_almost_equal(stress[1, 2], ref_voigt[3] * abu.HaBohr3_GPa) self.assert_almost_equal(stress[0, 2], ref_voigt[4] * abu.HaBohr3_GPa) self.assert_almost_equal(stress[0, 1], ref_voigt[5] * abu.HaBohr3_GPa) for qpoint in ddb.qpoints: assert qpoint in ddb.computed_dynmat
def setUp(self): self.sigres = sigres = abilab.abiopen( abidata.ref_file("tgw1_9o_DS4_SIGRES.nc")) repr(self.sigres) str(self.sigres) assert self.sigres.to_string(verbose=2) self.qplist = sigres.get_qplist(spin=0, kpoint=sigres.gwkpoints[0])
def test_sigeph_interpolation(self): """Test interpolation and TdepElectronBands""" sigeph = abilab.abiopen( abidata.ref_file("diamond_444q_full_SIGEPH.nc")) # Test interpolation without KS bands. tdep_nopath = sigeph.interpolate(itemp_list=0) repr(tdep_nopath) str(tdep_nopath) assert tdep_nopath.to_string(verbose=2) assert tdep_nopath.ntemp == 1 #assert not tdep_nopath.has_kpath #assert not tdep_nopath.ks_ebands_kpath is None #assert not tdep_nopath.has_kmesh #assert not tdep_nopath.ks_ebands_kmesh is None same_tdep_nopath = tdep_nopath.__class__.pickle_load( tdep_nopath.pickle_dump()) if self.has_matplotlib(): assert tdep_nopath.plot_itemp(itemp=0, fontsize=8, show=False) assert tdep_nopath.plot_itemp_with_lws_vs_e0(itemp=0, fontsize=8, with_ratios=(3, 1), show=False) assert tdep_nopath.plot(show=False) assert tdep_nopath.plot_lws_vs_e0(itemp_list=[0, -1], show=False) assert tdep_nopath.get_ebands_plotter() #assert tdep_nopath.get_edos_plotter() is None # Test interpolation with KS bands. tdep = sigeph.interpolate(itemp_list=None, lpratio=5, ks_ebands_kpath=None, ks_ebands_kmesh=None, ks_degatol=1e-4, vertices_names=None, line_density=20, filter_params=None, only_corrections=False, verbose=0) repr(tdep) str(tdep) assert tdep.to_string(verbose=2) assert tdep_nopath.ntemp == 1 #assert not tdep_nopath.ks_ebands_kpath is None #assert tdep.has_kpath #assert not tdep_nopath.has_kmesh #assert not tdep_nopath.ks_ebands_kmesh is None if self.has_matplotlib(): assert tdep_nopath.plot_itemp(itemp=0, fontsize=8, show=False) assert tdep_nopath.plot_itemp_with_lws_vs_e0(itemp=0, fontsize=8, show=False) assert tdep_nopath.plot(show=False) assert tdep_nopath.plot_lws_vs_e0(itemp_list=[0, -1], show=False) assert tdep.get_ebands_plotter() #assert tdep.get_edos_plotter() is None sigeph.close()
def test_fermi_surface(self): """Testing Fermi surface tools.""" with abilab.abiopen(abidata.ref_file( "mgb2_kmesh181818_FATBANDS.nc")) as fbnc_kmesh: ebands = fbnc_kmesh.ebands str(ebands) ebands.to_bxsf(self.get_tmpname(text=True)) # Test Ebands3d eb3d = ebands.get_ebands3d() repr(eb3d) str(eb3d) assert eb3d.to_string(verbose=2) if self.has_matplotlib(): assert eb3d.plot_contour(band=4, spin=0, plane="xy", elevation=0, show=False) if self.has_skimage(): assert eb3d.plot_isosurfaces(e0="fermie", verbose=1, show=False) # Test Mayavi if self.has_mayavi(): assert eb3d.mvplot_isosurfaces(verbose=1, show=False)
def abiview_sigeph(options): """Plot e-ph self-energy. Requires SIGEPH.nc file.""" with abilab.abiopen(options.filepath) as abifile: print(abifile.to_string(verbose=options.verbose)) abifile.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) return 0
def abiview_a2f(options): """Plot Eliashberg function. Requires A2F.nc file.""" with abilab.abiopen(options.filepath) as abifile: print(abifile.to_string(verbose=options.verbose)) abifile.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) return 0
def abiview_gruns(options): """Plot Grunesein parameters. Requires GRUNS.nc file.""" with abilab.abiopen(options.filepath) as abifile: print(abifile.to_string(verbose=options.verbose)) abifile.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) return 0
def from_file(cls, filepath): """ Generate an instance of `AutomaticScissorsBuilder` from file. Main entry point for client code. """ from abipy.abilab import abiopen ncfile = abiopen(filepath) return cls(qps_spin=ncfile.qplist_spin, e_bands=ncfile.ebands)
def abiopen(self): """Dump the gridfs data to a temporary file and use `abiopen` to open the file.""" _, filepath = mkstemp(suffix='.' + self.abiext, text=self.abiform == "t") with open(filepath , "w" + self.abiform) as fh: fh.write(self.read()) return abilab.abiopen(filepath)
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 itest_htc_bandstructure(fwp, tvars): """Test band-structure calculations done with the HTC interface.""" structure = abilab.Structure.from_file(abidata.cif_file("si.cif")) scf_kppa = 20 nscf_nband = 6 ndivsm = 5 dos_kppa = 40 # TODO: Add this options because I don't like the kppa approach # I had to use it because it was the approach used in VaspIO #dos_ngkpt = [4,4,4] #dos_shiftk = [0.1, 0.2, 0.3] extra_abivars = dict( ecut=2, paral_kgb=tvars.paral_kgb, ) # Initialize the flow. flow = abilab.AbinitFlow(workdir=fwp.workdir, manager=fwp.manager) work = bandstructure(structure, abidata.pseudos("14si.pspnc"), scf_kppa, nscf_nband, ndivsm, spin_mode="unpolarized", smearing=None, dos_kppa=dos_kppa, **extra_abivars) flow.register_work(work) flow.allocate() flow.build_and_pickle_dump() fwp.scheduler.add_flow(flow) fwp.scheduler.start() assert fwp.scheduler.num_excs == 0 assert fwp.scheduler.nlaunch == 3 flow.show_status() assert flow.all_ok assert all(work.finalized for work in flow) # Test if GSR files are produced and are readable. for i, task in enumerate(work): gsr_path = task.outdir.list_filepaths(wildcard="*GSR.nc")[0] gsr = abilab.abiopen(gsr_path) print(gsr) assert gsr.nsppol == 1 assert gsr.structure == structure ebands = gsr.ebands # TODO: This does not work yet because GSR files do not contain # enough info to understand if we have a path or a mesh. #if i == 2: # Bandstructure case #assert ebands.has_bzpath #with pytest.raises(ebands.Error): # ebands.get_edos() if i == 3: # DOS case assert ebands.has_bzmesh gsr.bands.get_edos()