def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) assert len(abilab.dir2abifiles(top=abidata.dirpath, recurse=False)) == 1 with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") import pandas df = pandas.DataFrame({"a": [1, 2], "b": [3, 4]}) abilab.print_dataframe(df, title="foo") d = abilab.software_stack() assert d assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3() assert not abilab.in_notebook() abilab.enable_notebook(with_seaborn=True) assert abilab.in_notebook() abilab.disable_notebook() assert not abilab.in_notebook()
def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) assert len(abilab.dir2abifiles(top=abidata.dirpath, recurse=False)) == 1 with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") import pandas df = pandas.DataFrame({"a": [1, 2], "b": [3, 4]}) abilab.print_dataframe(df, title="foo") d = abilab.software_stack() assert d assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3() assert not abilab.in_notebook() abilab.enable_notebook(with_seaborn=True) assert abilab.in_notebook() abilab.disable_notebook() assert not abilab.in_notebook()
def abicomp_xrd(options): """ Compare X-ray diffraction plots (requires FILES with structure). """ if len(options.paths) < 2: print("You need more than one structure to compare!") return 1 structures = [abilab.Structure.from_file(p) for p in options.paths] dfs = abilab.dataframes_from_structures( structures, index=[os.path.relpath(p) for p in options.paths]) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") if options.verbose: abilab.print_dataframe( dfs.coords, title="Atomic positions (columns give the site index):") from pymatgen.analysis.diffraction.xrd import XRDCalculator two_theta_range = tuple(float(t) for t in options.two_theta_range) xrd = XRDCalculator(wavelength=options.wavelength, symprec=options.symprec) xrd.plot_structures(structures, two_theta_range=two_theta_range, fontsize=6, annotate_peaks=not options.no_annotate_peaks, tight_layout=True) return 0
def abicomp_phbands(options): """ Plot phonon bands on a grid. """ paths = options.paths plotter = abilab.PhononBandsPlotter(key_phbands=[(os.path.relpath(p), p) for p in paths]) if options.ipython: import IPython IPython.embed(header=str(plotter) + "\n\nType `plotter` in the terminal and use <TAB> to list its methods", plotter=plotter) elif options.notebook: plotter.make_and_open_notebook(foreground=options.foreground) else: # Print pandas Dataframe. frame = plotter.get_phbands_frame() abilab.print_dataframe(frame) # Optionally, print info on gaps and their location if not options.verbose: print("\nUse --verbose for more information") else: for phbands in plotter.phbands_list: print(phbands) # Here I select the plot method to call. if options.plot_mode != "None": plotfunc = getattr(plotter, options.plot_mode, None) if plotfunc is None: raise ValueError("Don't know how to handle plot_mode: %s" % options.plot_mode) plotfunc() return 0
def abicomp_ebands(options): """ Plot electron bands on a grid. """ paths, e0 = options.paths, options.e0 plotter = abilab.ElectronBandsPlotter(key_ebands=[(os.path.relpath(p), p) for p in paths]) if options.ipython: import IPython IPython.embed(header=str(plotter) + "\n\nType `plotter` in the terminal and use <TAB> to list its methods", plotter=plotter) elif options.notebook: plotter.make_and_open_notebook(foreground=options.foreground) else: # Print pandas Dataframe. frame = plotter.get_ebands_frame() abilab.print_dataframe(frame) # Optionally, print info on gaps and their location if not options.verbose: print("\nUse --verbose for more information") else: for ebands in plotter.ebands_list: print(ebands) # Here I select the plot method to call. if options.plot_mode != "None": plotfunc = getattr(plotter, options.plot_mode, None) if plotfunc is None: raise ValueError("Don't know how to handle plot_mode: %s" % options.plot_mode) plotfunc(e0=e0) return 0
def abiview_ddb_vs(options): """ Compute speed of sound by fitting phonon frequencies along selected directions. """ num_points = 20 asr = 2 chneut = 1 dipdip = 1 print(""" Computing phonon frequencies for linear least-squares with: num_points= {num_points}, asr = {asr}, chneut = {chneut}, dipdip = {dipdip} """.format(**locals())) print("Invoking anaddb ... ") sv = abilab.SoundVelocity.from_ddb(options.filepath, num_points=num_points, asr=asr, chneut=chneut, dipdip=dipdip, verbose=options.verbose) #print("Calculation completed.\nResults available in", os.path.dirname(phbst_file.filepath)) df = sv.get_dataframe() abilab.print_dataframe(df, title="Speed of sound for different directions:") df_to_clipboard(options, df) sv.plot() return 0
def abicomp_pseudos(options): """"Compare multiple pseudos Print table to terminal.""" # Make sure entries in index are unique. index = [os.path.basename(p) for p in options.paths] if len(index) != len(set(index)): index = [os.path.relpath(p) for p in options.paths] df = dataframe_from_pseudos(options.paths, index=index) abilab.print_dataframe(df, sortby="Z_val") return 0
def abicomp_structure(options): """ Compare crystalline structures. Use `--group` to compare for similarity." """ if options.group: return compare_structures(options) paths = options.paths index = [os.path.relpath(p) for p in paths] if options.notebook: import nbformat nbv = nbformat.v4 nb = nbv.new_notebook() nb.cells.extend([ nbv.new_code_cell("""\ from __future__ import print_function, division, unicode_literals, absolute_import import sys import os %matplotlib notebook from IPython.display import display from abipy import abilab"""), nbv.new_code_cell("dfs = abilab.dataframes_from_structures(%s, index=%s)" % (paths, index)), # Analyze dataframes. nbv.new_code_cell("dfs.lattice"), nbv.new_code_cell("dfs.coords"), nbv.new_code_cell("# for structure in dfs.structures: display(structure)"), ]) import io, tempfile # os, _, nbpath = tempfile.mkstemp(prefix="abinb_", suffix='.ipynb', dir=os.getcwd(), text=True) # Write notebook import nbformat with io.open(nbpath, 'wt', encoding="utf8") as fh: nbformat.write(nb, fh) cmd = "jupyter notebook %s" % nbpath return os.system(cmd) dfs = abilab.dataframes_from_structures(paths, index=index) if options.ipython: import IPython IPython.embed(header="Type `dfs` in the terminal and use <TAB> to list its methods", dfs=dfs) else: print("File list:") for i, p in enumerate(paths): print("%d %s" % (i, p)) print() abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") if options.verbose: abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):") return 0
def abicomp_structure(options): """ Compare crystalline structures. Use `--group` to compare for similarity. """ if options.group: return compare_structures(options) paths = options.paths index = [os.path.relpath(p) for p in paths] if options.notebook: import nbformat nbv = nbformat.v4 nb = nbv.new_notebook() nb.cells.extend([ nbv.new_code_cell("""\ from __future__ import print_function, division, unicode_literals, absolute_import import sys import os %matplotlib notebook from IPython.display import display from abipy import abilab"""), nbv.new_code_cell("dfs = abilab.dataframes_from_structures(%s, index=%s)" % (paths, index)), # Analyze dataframes. nbv.new_code_cell("dfs.lattice"), nbv.new_code_cell("dfs.coords"), nbv.new_code_cell("# for structure in dfs.structures: display(structure)"), ]) import io, tempfile # os, _, nbpath = tempfile.mkstemp(prefix="abinb_", suffix='.ipynb', dir=os.getcwd(), text=True) # Write notebook import nbformat with io.open(nbpath, 'wt', encoding="utf8") as fh: nbformat.write(nb, fh) cmd = "jupyter notebook %s" % nbpath return os.system(cmd) dfs = abilab.dataframes_from_structures(paths, index=index) if options.ipython: import IPython IPython.embed(header="Type `dfs` in the terminal and use <TAB> to list its methods", dfs=dfs) else: print("File list:") for i, p in enumerate(paths): print("%d %s" % (i, p)) print() abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") if options.verbose: abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):") return 0
def _compare_with_database(options): structures = [abilab.Structure.from_file(p) for p in options.paths] dbname = { "mp_structure": "materials project", "cod_structure": "COD" }[options.command] if options.command == "mp_structure": mpres = [ abilab.mp_search(struct.composition.formula) for struct in structures ] elif options.command == "cod_structure": mpres = [ abilab.cod_search(struct.composition.formula) for struct in structures ] else: raise NotImplementedError(str(options.command)) # Filter by spglib space group number. if getattr(options, "same_spgnum", False): spgnums = [struct.get_space_group_info()[1] for struct in structures] mpres = [ r.filter_by_spgnum(spgnum) for spgnum, r in zip(spgnums, mpres) ] retcode = 0 for this_structure, r in zip(structures, mpres): if r.structures: if options.notebook: new = r.add_entry(this_structure, "this") retcode += new.make_and_open_notebook( foreground=options.foreground) else: print() dfs = abilab.dataframes_from_structures(r.structures + [this_structure], index=r.ids + ["this"]) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:", sortby="spglib_num") if options.verbose: abilab.print_dataframe( dfs.coords, title="Atomic positions (columns give the site index):" ) else: print("Use --verbose to print atomic positions.") print() else: print("Couldn't find %s database entries with formula `%s`" % (dbname, this_structure.composition.formula)) retcode += 1 return retcode
def test_abilab(self): """Testing abilab""" abilab.abiopen_ext2class_table() assert abilab.abifile_subclass_from_filename("GSR.nc") is not None assert len(abilab.dir2abifiles(top=abidata.dirpath)) assert len(abilab.dir2abifiles(top=abidata.dirpath, recurse=False)) == 1 with self.assertRaises(ValueError): abilab.abifile_subclass_from_filename("foobar") assert abilab.isabifile("foo_GSR.nc") assert not abilab.isabifile("foobar") import pandas df = pandas.DataFrame({"a": [1, 2], "b": [3, 4]}) abilab.print_dataframe(df, title="foo") d = abilab.software_stack() assert d filepath = self.get_tmpname(text=True, suffix=".json") data = {"foo": "bar"} abilab.mjson_write(data, filepath, indent=4) data = abilab.mjson_load(filepath) assert data["foo"] == "bar" same_data = abilab.mjson_loads(json.dumps(data)) assert len(same_data) == len(data) assert same_data["foo"] == data["foo"] assert not abilab.abicheck(verbose=1) abilab.abipy_logo1() abilab.abipy_logo2() abilab.abipy_logo3() assert not abilab.in_notebook() abilab.enable_notebook(with_seaborn=True) assert abilab.in_notebook() abilab.disable_notebook() assert not abilab.in_notebook() assert abilab.install_config_files(workdir=self.mkdtemp()) == 0
def abicomp_xrd(options): """ Compare X-ray diffraction plots (requires FILES with structure). """ if len(options.paths) < 2: print("You need more than one structure to compare!") return 1 structures = [abilab.Structure.from_file(p) for p in options.paths] dfs = abilab.dataframes_from_structures(structures, index=[os.path.relpath(p) for p in options.paths]) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") if options.verbose: abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):") from pymatgen.analysis.diffraction.xrd import XRDCalculator two_theta_range = tuple(float(t) for t in options.two_theta_range) xrd = XRDCalculator(wavelength=options.wavelength, symprec=options.symprec) xrd.plot_structures(structures, two_theta_range=two_theta_range, fontsize=6, annotate_peaks=not options.no_annotate_peaks, tight_layout=True) return 0
def abicomp_spg(options): """ Compare the space group found by Abinit with the spglib results for a set of crystalline structure(s) read from FILE(s). """ try: structures = [abilab.Structure.from_file(p) for p in options.paths] except Exception as ex: print("Error reading structures from files. Are they in the right format?") print(str(ex)) return 1 # Remove disordered structures. structures = remove_disordered(structures, options.paths) rows, index = [], [] symprec, angle_tolerance = options.symprec, options.angle_tolerance for structure in structures: index.append(structure.formula) # Call Abinit row = structure.abiget_spginfo(tolsym=options.tolsym, pre="abi_") # Call spglib. spglib_symbol, spglib_number = structure.get_space_group_info(symprec=symprec, angle_tolerance=angle_tolerance) spglib_lattice_type = structure.spget_lattice_type(symprec=symprec, angle_tolerance=angle_tolerance) row.update(spglib_symbol=spglib_symbol, spglib_number=spglib_number, spglib_lattice=spglib_lattice_type) rows.append(row) import pandas as pd df = pd.DataFrame(rows, index=index, columns=list(rows[0].keys()) if rows else None) print("Spglib options: symprec=", options.symprec, "angle_tolerance=", options.angle_tolerance) print("Abinit options: tolsym=", options.tolsym) print("") abilab.print_dataframe(df, title="Spacegroup found by Abinit and Spglib:") df_to_clipboard(options, df) return 0
def _compare_with_database(options): structures = [abilab.Structure.from_file(p) for p in options.paths] dbname = {"mp_structure": "materials project", "cod_structure": "COD"}[options.command] if options.command == "mp_structure": mpres = [abilab.mp_search(struct.composition.formula) for struct in structures] elif options.command == "cod_structure": mpres = [abilab.cod_search(struct.composition.formula) for struct in structures] else: raise NotImplementedError(str(options.command)) # Filter by spglib space group number. if getattr(options, "same_spgnum", False): spgnums = [struct.get_space_group_info()[1] for struct in structures] mpres = [r.filter_by_spgnum(spgnum) for spgnum, r in zip(spgnums, mpres)] retcode = 0 for this_structure, r in zip(structures, mpres): if r.structures: if options.notebook: new = r.add_entry(this_structure, "this") retcode += new.make_and_open_notebook(foreground=options.foreground) else: print() dfs = abilab.dataframes_from_structures(r.structures + [this_structure], index=r.ids + ["this"]) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:", sortby="spglib_num") if options.verbose: abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):") else: print("Use --verbose to print atomic positions.") print() else: print("Couldn't find %s database entries with formula `%s`" % (dbname, this_structure.composition.formula)) retcode += 1 return retcode
def main(): def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(get_epilog()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) parser = get_parser(with_epilog=True) # Parse command line. try: options = parser.parse_args() except Exception as exc: show_examples_and_exit(error_code=1) if not options.command: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) if options.verbose > 2: print(options) if options.command == "spglib": structure = abilab.Structure.from_file(options.filepath) print(structure.spget_summary(symprec=options.symprec, angle_tolerance=options.angle_tolerance, verbose=options.verbose)) #remove_equivalent_atoms(structure) elif options.command == "abispg": structure = abilab.Structure.from_file(options.filepath) check_ordered_structure(structure) spgrp = structure.abi_spacegroup if spgrp is not None: print(structure.spget_summary(verbose=options.verbose)) else: # Here we compare Abinit wrt spglib. If spgrp is None, we create a temporary # task to run the code in dry-run mode. print("FILE does not contain Abinit symmetry operations.") print("Calling Abinit in --dry-run mode with chkprim = 0 to get space group.") from abipy.data.hgh_pseudos import HGH_TABLE gsinp = factories.gs_input(structure, HGH_TABLE, spin_mode="unpolarized") gsinp["chkprim"] = 0 abistructure = gsinp.abiget_spacegroup(tolsym=options.tolsym) print(abistructure.spget_summary(verbose=options.verbose)) diff_structures([structure, abistructure], mode=options.diff_mode, headers=["Input structure", "After Abinit symmetrization"], fmt="abivars") # Save file. save_structure(abistructure, options) elif options.command == "convert": fmt = options.format if fmt == "cif" and options.filepath.endswith(".cif"): fmt = "abivars" print(abilab.Structure.from_file(options.filepath).convert(fmt=fmt)) elif options.command == "supercell": structure = abilab.Structure.from_file(options.filepath) options.scaling_matrix = np.array(options.scaling_matrix) if len(options.scaling_matrix) == 9: options.scaling_matrix.shape = (3, 3) if options.verbose: print("scaling matrix: ", options.scaling_matrix) supcell = structure * options.scaling_matrix #supcell = structure.make_supercell(scaling_matrix, to_unit_cell=True) print(supcell.convert(fmt=options.format)) elif options.command == "abisanitize": print("\nCalling abi_sanitize to get a new structure in which:") print(" * Structure is refined.") print(" * Reduced to primitive settings.") print(" * Lattice vectors are exchanged if the triple product is negative\n") structure = abilab.Structure.from_file(options.filepath) sanitized = structure.abi_sanitize(symprec=options.symprec, angle_tolerance=options.angle_tolerance, primitive=not options.no_primitive, primitive_standard=options.primitive_standard) index = [options.filepath, "abisanitized"] dfs = abilab.dataframes_from_structures([structure, sanitized], index=index, with_spglib=True) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):") if not options.verbose: print("\nUse -v for more info") #print(sanitized.convert(fmt="cif")) else: #print("\nDifference between structures:") if len(structure) == len(sanitized): table = [] for line1, line2 in zip(str(structure).splitlines(), str(sanitized).splitlines()): table.append([line1, line2]) print(str(tabulate(table, headers=["Initial structure", "Abisanitized"]))) else: print("\nInitial structure:") print(structure) print("\nabisanitized structure:") print(sanitized) # Save file. save_structure(sanitized, options) elif options.command == "irefine": structure = abilab.Structure.from_file(options.filepath) sanitized = structure.copy() symprec, angle_tolerance = options.symprec, options.angle_tolerance print("Calling abi_sanitize with increasing tolerances to reach target space group:", options.target_spgnum) print("Using symprec_step: ", options.symprec_step, ", angle_tolerance_step:", options.angle_tolerance_step, "ntrial", options.ntrial) itrial = 0 while itrial < options.ntrial: print(">>> Trying with symprec: %s, angle_tolerance: %s" % (symprec, angle_tolerance)) sanitized = sanitized.abi_sanitize(symprec=symprec, angle_tolerance=angle_tolerance, primitive=not options.no_primitive, primitive_standard=options.primitive_standard) spg_symb, spg_num = sanitized.get_space_group_info(symprec=symprec, angle_tolerance=angle_tolerance) print(">>> Space-group number:", spg_symb, ", symbol:", spg_num, "for trial:", itrial) if spg_num == options.target_spgnum: print(2 * "\n", "# Final structure with space group number:", spg_symb, ", symbol:", spg_num, 2 *"\n") print(sanitized.convert(fmt="cif")) break # Increment counter and tols. itrial += 1 symprec += options.symprec_step angle_tolerance += options.angle_tolerance_step else: print("Cannot find space group number:", options.target_spgnum, "after", options.ntrial, "iterations") return 1 # Save file. #save_structure(sanitized, options) elif options.command == "conventional": print("\nCalling get_conventional_standard_structure to get conventional structure:") print("The standards are defined in Setyawan, W., & Curtarolo, S. (2010). ") print("High-throughput electronic band structure calculations: Challenges and tools. ") print("Computational Materials Science, 49(2), 299-312. doi:10.1016/j.commatsci.2010.05.010\n") structure = abilab.Structure.from_file(options.filepath) conv = structure.get_conventional_standard_structure(international_monoclinic=True, symprec=options.symprec, angle_tolerance=options.angle_tolerance) index = [options.filepath, "conventional"] dfs = abilab.dataframes_from_structures([structure, conv], index=index, with_spglib=True) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") if options.verbose: abilab.print_dataframe(dfs.coords, title="Atomic positions (columns give the site index):") if not options.verbose: print("\nUse -v for more info") else: #print("\nDifference between structures:") if len(structure) == len(conv): table = [] for line1, line2 in zip(str(structure).splitlines(), str(conv).splitlines()): table.append([line1, line2]) print(str(tabulate(table, headers=["Initial structure", "Conventional"]))) else: print("\nInitial structure:\n", structure) print("\nConventional structure:\n", conv) # Save file. save_structure(conv, options) elif options.command == "neighbors": abilab.Structure.from_file(options.filepath).print_neighbors(radius=options.radius) elif options.command == "interpolate": initial_structure = abilab.Structure.from_file(options.filepaths[0]) end_structure = abilab.Structure.from_file(options.filepaths[1]) structures = initial_structure.interpolate(end_structure, nimages=options.nimages, interpolate_lattices=False, pbc=True, autosort_tol=options.autosort_tol) structures = list(map(abilab.Structure.as_structure, structures)) for i, s in enumerate(structures): print(marquee("Structure #%d" % i, mark="=")) print(s.convert(fmt=options.format)) print(" ") elif options.command == "xrd": structure = abilab.Structure.from_file(options.filepath) two_theta_range = tuple(float(t) for t in options.two_theta_range) structure.plot_xrd(wavelength=options.wavelength, two_theta_range=two_theta_range, symprec=options.symprec, annotate_peaks=not options.no_annotate_peaks) elif options.command == "oxistate": print(abilab.Structure.from_file(options.filepath).get_oxi_state_decorated()) elif options.command == "ipython": structure = abilab.Structure.from_file(options.filepath) print("Invoking Ipython, `structure` object will be available in the Ipython terminal") import IPython IPython.start_ipython(argv=[], user_ns={"structure": structure}) elif options.command == "notebook": structure = abilab.Structure.from_file(options.filepath) structure.make_and_open_notebook(nbpath=None, foreground=options.foreground) elif options.command == "visualize": structure = abilab.Structure.from_file(options.filepath) print(structure) print("Visualizing structure with:", options.appname) structure.visualize(appname=options.appname) elif options.command == "kpath": structure = abilab.Structure.from_file(options.filepath) print(structure.get_kpath_input_string(fmt=options.format, line_density=10)) elif options.command == "bz": abilab.Structure.from_file(options.filepath).plot_bz() elif options.command == "ngkpt": d = abilab.Structure.from_file(options.filepath).calc_ksampling(options.nksmall) print("ngkpt %d %d %d" % (d.ngkpt[0], d.ngkpt[1], d.ngkpt[2])) print("nshiftk ", len(d.shiftk), "\nshiftk") for s in d.shiftk: print(" %s %s %s" % (s[0], s[1], s[2])) elif options.command == "ktables": structure = abilab.Structure.from_file(options.filepath) k = Ktables(structure, options.mesh, options.is_shift, not options.no_time_reversal) print(k) print("") print("NB: These results are obtained by calling spglib with the structure read from file.") print("The k-points might differ from the ones expected by Abinit, especially if the space groups differ.") if not options.verbose: print("\nUse -v to obtain the BZ --> IBZ mapping.") else: print() k.print_bz2ibz() elif options.command == "abikmesh": structure = abilab.Structure.from_file(options.filepath) if options.kppa is None and options.ngkpt is None: raise ValueError("Either ngkpt or kppa must be provided") if options.kppa is not None: print("Calling Abinit to compute the IBZ with kppa:", options.kppa, "and shiftk:", options.shiftk) ibz = IrredZone.from_kppa(structure, options.kppa, options.shiftk, kptopt=options.kptopt, verbose=options.verbose) else: print("Calling Abinit to compute the IBZ with ngkpt:", options.ngkpt, "and shiftk:", options.shiftk) ibz = IrredZone.from_ngkpt(structure, options.ngkpt, options.shiftk, kptopt=options.kptopt, verbose=options.verbose) print(ibz.to_string(verbose=options.verbose)) #elif options.command == "kmesh_jhu": # structure = abilab.Structure.from_file(options.filepath) # ksampling = structure.ksampling_from_jhudb(kppra=1000) # #print(ksampling) elif options.command == "lgk": structure = abilab.Structure.from_file(options.filepath) spgrp = structure.abi_spacegroup if spgrp is None: cprint("Your file does not contain Abinit symmetry operations.", "yellow") cprint("Will call spglib to obtain the space group (assuming time-reversal: %s)" % (not options.no_time_reversal), "yellow") spgrp = AbinitSpaceGroup.from_structure(structure, has_timerev=not options.no_time_reversal, symprec=options.symprec, angle_tolerance=options.angle_tolerance) print() print(marquee("Structure", mark="=")) print(structure.spget_summary(verbose=options.verbose)) print("\n") print(marquee("Little Group", mark="=")) ltk = spgrp.find_little_group(kpoint=options.kpoint) print(ltk.to_string(verbose=options.verbose)) elif options.command == "kstar": structure = abilab.Structure.from_file(options.filepath) # Call spglib to get spacegroup if Abinit spacegroup is not available. if structure.abi_spacegroup is None: structure.spgset_abi_spacegroup(has_timerev=not options.no_time_reversal) kpoint = Kpoint(options.kpoint, structure.reciprocal_lattice) kstar = kpoint.compute_star(structure.abi_spacegroup, wrap_tows=True) print("Found %s points in the star of %s\n" % (len(kstar), repr(kpoint))) for k in kstar: print(4 * " ", repr(k)) elif options.command == "keq": structure = abilab.Structure.from_file(options.filepath) # Call spglib to get spacegroup if Abinit spacegroup is not available. if structure.abi_spacegroup is None: structure.spgset_abi_spacegroup(has_timerev=not options.no_time_reversal) k1, k2 = options.kpoints[:3], options.kpoints[3:6] k1tab = structure.abi_spacegroup.symeq(k1, k2) if k1tab.isym != -1: print("\nk1:", k1, "and k2:", k2, "are symmetry equivalent k-points\n") print("Related by the symmetry operation (reduced coords):\n", k1tab.op) print("With umklapp vector Go = TO(k1) - k2 =", k1tab.g0) else: print(k1, "and", k2, "are NOT symmetry equivalent") elif options.command == "mp_id": # Get the Structure corresponding to material_id. structure = abilab.Structure.from_mpid(options.mpid, final=True, api_key=options.mapi_key, endpoint=options.endpoint) # Convert to format and print it. print(structure.convert(fmt=options.format)) elif options.command == "mp_match": mp = abilab.mp_match_structure(options.filepath) if not mp.structures: cprint("No structure found in database", "yellow") return 1 if options.notebook: return mp.make_and_open_notebook(foreground=options.foreground) else: mp.print_results(fmt=options.format, verbose=options.verbose) if options.browser: mp.open_browser(limit=None if options.verbose == 2 else 10) elif options.command == "mp_search": mp = abilab.mp_search(options.chemsys_formula_id) if not mp.structures: cprint("No structure found in Materials Project database", "yellow") return 1 if options.select_spgnum: mp = mp.filter_by_spgnum(options.select_spgnum) if options.notebook: return mp.make_and_open_notebook(foreground=options.foreground) else: mp.print_results(fmt=options.format, verbose=options.verbose) if options.browser: mp.open_browser(limit=None if options.verbose == 2 else 10) elif options.command == "mp_pd": if os.path.exists(options.file_or_elements): structure = abilab.Structure.from_file(options.file_or_elements) elements = structure.symbol_set else: elements = options.file_or_elements.split("-") if options.verbose > 1: print("Building phase-diagram for elements:", elements) with abilab.restapi.get_mprester(api_key=options.mapi_key, endpoint=options.endpoint) as rest: pdr = rest.get_phasediagram_results(elements) pdr.print_dataframes(verbose=options.verbose) pdr.plot(show_unstable=options.show_unstable) elif options.command == "cod_search": cod = abilab.cod_search(options.formula, primitive=options.primitive) if not cod.structures: cprint("No structure found in COD database", "yellow") return 1 if options.select_spgnum: cod = cod.filter_by_spgnum(options.select_spgnum) if options.notebook: return cod.make_and_open_notebook(foreground=options.foreground) else: cod.print_results(fmt=options.format, verbose=options.verbose) elif options.command == "cod_id": # Get the Structure from COD structure = abilab.Structure.from_cod_id(options.cod_identifier, primitive=options.primitive) # Convert to format and print it. print(structure.convert(fmt=options.format)) elif options.command == "animate": filepath = options.filepath if any(filepath.endswith(ext) for ext in ("HIST", "HIST.nc")): with abilab.abiopen(filepath) as hist: structures = hist.structures elif "XDATCAR" in filepath: structures = Xdatcar(filepath).structures if not structures: raise RuntimeError("Your Xdatcar contains only one structure. Due to a bug " "in the pymatgen routine, your structures won't be parsed correctly" "Solution: Add another structure at the end of the file.") else: raise ValueError("Don't know how to handle file %s" % filepath) xsf_write_structure(sys.stdout, structures) else: raise ValueError("Unsupported command: %s" % options.command) return 0
def test_from_ddb(self): """Testing MsqDos from DDB file.""" self.skip_if_abinit_not_ge("8.11.0") filepath = os.path.join(abidata.dirpath, "refs", "mp-7000_DDB.bz2") with abilab.abiopen(filepath) as ddb: phbst_file, phdos_file = ddb.anaget_phbst_and_phdos_files(nqsmall=2, ndivsm=1, mpi_procs=2) msqd_dos = phdos_file.msqd_dos # Read indsym from file and convert from F to C indsym = phdos_file.reader.read_value("indsym") indsym[:, :, 3] -= 1 phbst_file.close() phdos_file.close() repr(msqd_dos); str(msqd_dos) assert msqd_dos.to_string(verbose=2) for fmt in ("cartesian", "cif", "ustar", "beta"): #, "B"): df = msqd_dos.get_dataframe(temp=100, view="all", select_symbols="Si", fmt=fmt) abilab.print_dataframe(df, title="Format: %s" % fmt) # Equivalent atoms should have same determinant. df = msqd_dos.get_dataframe(temp=300, view="all", fmt="cartesian") for _, group in df.groupby(by="element"): self.assert_almost_equal(group["determinant"].values, group["determinant"].values[0]) # Compare Abinit indsym with AbiPy version. abispg = msqd_dos.structure.abi_spacegroup abipy_indsym = indsym_from_symrel(abispg.symrel, abispg.tnons, msqd_dos.structure, tolsym=1e-8) assert np.all(abipy_indsym == indsym) assert np.all(abipy_indsym == msqd_dos.structure.indsym) cif_string = msqd_dos.get_cif_string(temp=300) print("cif_string:\n", cif_string) self.assertMultiLineEqual(cif_string, """\ # generated using pymatgen data_SiO2 _symmetry_space_group_name_H-M 'P 1' _cell_length_a 4.94990566 _cell_length_b 4.94990566 _cell_length_c 5.44089660 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 120.00000000 _symmetry_Int_Tables_number 1 _chemical_formula_structural SiO2 _chemical_formula_sum 'Si3 O6' _cell_volume 115.45026881 _cell_formula_units_Z 3 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_occupancy Si Si0 1 0.52885459 0.00000000 0.83333333 1 Si Si1 1 0.47114541 0.47114541 0.50000000 1 Si Si2 1 0.00000000 0.52885459 0.16666667 1 O O3 1 0.41316747 0.14770576 0.62024227 1 O O4 1 0.85229424 0.26546172 0.95357560 1 O O5 1 0.73453828 0.58683253 0.28690893 1 O O6 1 0.26546172 0.85229424 0.04642440 1 O O7 1 0.14770576 0.41316747 0.37975773 1 O O8 1 0.58683253 0.73453828 0.71309107 1 loop_ _atom_site_aniso_label _atom_site_aniso_U_11 _atom_site_aniso_U_22 _atom_site_aniso_U_33 _atom_site_aniso_U_23 _atom_site_aniso_U_13 _atom_site_aniso_U_12 Si0 0.00850 0.00695 0.00611 -0.00019 -0.00009 0.00348 Si1 0.00850 0.00850 0.00611 0.00009 -0.00009 0.00502 Si2 0.00695 0.00850 0.00611 0.00009 0.00019 0.00348 O3 0.01916 0.01120 0.01353 0.00249 -0.00411 0.00762 O4 0.01120 0.01512 0.01353 -0.00660 -0.00249 0.00358 O5 0.01512 0.01916 0.01353 0.00411 0.00660 0.01153 O6 0.01512 0.01120 0.01353 0.00249 0.00660 0.00358 O7 0.01120 0.01916 0.01353 0.00411 -0.00249 0.00762 O8 0.01916 0.01512 0.01353 -0.00660 -0.00411 0.01153""") # Write CIF file with U_cif tensor filepath = msqd_dos.write_cif_file(filepath=None, temp=300) assert filepath.endswith(".cif") same_structure = abilab.abiopen(filepath) assert same_structure.formula == msqd_dos.structure.formula assert len(same_structure) == len(msqd_dos.structure) # NB: lattice.matrix and cart_coords are not necessarily the # same when we read the structure from CIF because the lattice # is initialized from_angles_and_lenghts #self.assert_almost_equal(same_structure.lattice.matrix, msqd_dos.structure.lattice.matrix) for s1, s2 in zip(same_structure, msqd_dos.structure): assert s1.specie.symbol == s2.specie.symbol self.assert_almost_equal(s1.frac_coords, s2.frac_coords, decimal=5) #self.assert_almost_equal(s1.coords, s2.coords, decimal=5) maxerr = msqd_dos.check_site_symmetries(temp=300, verbose=1) assert maxerr < 1e-10 # Get dict with results and try to encode with MontyEncoder jdoc = msqd_dos.get_json_doc(tstart=10, tstop=10, num=1) from monty.json import json, MontyEncoder assert json.dumps(jdoc, cls=MontyEncoder) if self.has_matplotlib(): assert msqd_dos.plot(show=False) assert msqd_dos.plot(view="all", show=False) assert msqd_dos.plot_tensor(show=False) assert msqd_dos.plot_tensor(view="all", show=False) assert msqd_dos.plot_uiso(show=False) assert msqd_dos.plot_uiso(view="all", show=False) assert msqd_dos.plot_uiso(view="all", what="vel", show=False)
def _invoke_robot(options): """ Analyze multiple files with a robot. Support list of files and/or list of directories passed on the CLI.. By default, the script with call `robot.to_string(options.verbose)` to print info to terminal. For finer control, use --ipy to start an ipython console to interact with the robot directly or --nb to generate a jupyter notebook. """ robot_cls = abilab.Robot.class_for_ext(options.command.upper()) # To define an Help action # http://stackoverflow.com/questions/20094215/argparse-subparser-monolithic-help-output?rq=1 paths = options.paths #print(paths) if os.path.isdir(paths[0]): # Assume directory. robot = robot_cls.from_dir(top=paths[0], walk=not options.no_walk) else: # Assume file. robot = robot_cls.from_files([paths[0]]) if len(paths) > 1: # Handle multiple arguments. Could be either other directories or files. for p in paths[1:]: if os.path.isdir(p): robot.scan_dir(top=p, walk=not options.no_walk) elif os.path.isfile(p): robot.add_file(os.path.abspath(p), p) else: cprint("Ignoring %s. Neither file or directory." % str(p), "red") if len(robot) == 0: cprint("Warning: robot is empty. No file found", "red") return 1 if options.notebook: robot.make_and_open_notebook(foreground=options.foreground) elif options.print or options.expose: robot.trim_paths() #df = robot.get_params_dataframe() #abilab.print_dataframe(df, title="Output of robot.get_params_dataframe():") # Print dataframe if robot provides get_dataframe method. if hasattr(robot, "get_dataframe"): try: df = robot.get_dataframe() abilab.print_dataframe( df, title="Output of robot.get_dataframe():") except Exception as exc: cprint( "Exception:\n%s\n\nwhile invoking get_dataframe. Falling back to to_string" % str(exc), "red") print(robot.to_string(verbose=options.verbose)) else: cprint( "%s does not provide `get_dataframe` method. Using `to_string`" % (robot.__class__.__name__), "yellow") print(robot.to_string(verbose=options.verbose)) if not options.verbose: print("\nUse --verbose for more information") if options.expose and hasattr(robot, "expose"): robot.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) #elif options.ipython: else: import IPython robot.trim_paths() IPython.embed( header=repr(robot) + "\n\nType `robot` in the terminal and use <TAB> to list its methods", robot=robot) return 0
filepath = os.path.join(abidata.dirpath, "refs", "mp-7000_DDB.bz2") ddb = abilab.abiopen(filepath) # Invoke anaddb to compute phonon bands and dos. #dos_method = "gaussian" dos_method = "tetra" phbst_file, phdos_file = ddb.anaget_phbst_and_phdos_files(nqsmall=4, dos_method=dos_method, ndivsm=1, mpi_procs=2) # Extract msqd_dos msqd_dos = phdos_file.msqd_dos #print(msqd_dos) #for fmt in ("cartesian", "cif", "ustar", "beta", "B"): for fmt in ("cartesian", "cif"): df = msqd_dos.get_dataframe(temp=300, view="all", fmt=fmt) abilab.print_dataframe(df, title="Format: %s" % fmt) # Plot generalized phonon DOS for each inequivalent atom in the unit cell. msqd_dos.plot() # Plot tensor(T) for each inequivalent atom. msqd_dos.plot_tensor() msqd_dos.plot_uiso() # To save the structure and the U tensor at T=300K in CIF format, use: #msqd_dos.write_cif_file("DW.cif", temp=300) # To visualize the thermal ellipsoids with Vesta, use: #msqd_dos.vesta_open(temp=300)
def _invoke_robot(options): """ Analyze multiple files with a robot. Support list of files and/or list of directories passed on the CLI.. By default, the script with call `robot.to_string(options.verbose)` to print info to terminal. For finer control, use --ipy to start an ipython console to interact with the robot directly or --nb to generate a jupyter notebook. """ robot_cls = abilab.Robot.class_for_ext(options.command.upper()) # To define an Help action # http://stackoverflow.com/questions/20094215/argparse-subparser-monolithic-help-output?rq=1 paths = options.paths if options.verbose > 1: print("In _invoke_robot with paths", paths) if os.path.isdir(paths[0]): # Assume directory. robot = robot_cls.from_dir(top=paths[0], walk=not options.no_walk) else: # Assume file. robot = robot_cls.from_files([paths[0]]) if len(paths) > 1: # Handle multiple arguments. Could be either other directories or files. for p in paths[1:]: if os.path.isdir(p): robot.scan_dir(top=p, walk=not options.no_walk) elif os.path.isfile(p): robot.add_file(os.path.abspath(p), p) else: cprint("Ignoring %s. Neither file or directory." % str(p), "red") if len(robot) == 0: cprint("Warning: robot is empty. No file found", "red") return 1 if options.notebook: robot.make_and_open_notebook(foreground=options.foreground) elif options.print or options.expose: robot.trim_paths() # Print dataframe if robot provides get_dataframe method. if hasattr(robot, "get_dataframe"): try: df = robot.get_dataframe() abilab.print_dataframe(df, title="Output of robot.get_dataframe():") df_to_clipboard(options, df) except Exception as exc: cprint("Exception:\n%s\n\nwhile invoking get_dataframe. Falling back to to_string" % str(exc), "red") print(robot.to_string(verbose=options.verbose)) else: cprint("%s does not provide `get_dataframe` method. Using `to_string`" % ( robot.__class__.__name__), "yellow") print(robot.to_string(verbose=options.verbose)) if not options.verbose: print("\nUse --verbose for more information") if options.expose and hasattr(robot, "expose"): robot.expose(slide_mode=options.slide_mode, slide_timeout=options.slide_timeout, verbose=options.verbose) #elif options.ipython: else: import IPython robot.trim_paths() IPython.embed(header=repr(robot) + "\n\nType `robot` in the terminal and use <TAB> to list its methods", robot=robot) return 0
def main(): def show_examples_and_exit(err_msg=None, error_code=1): """Display the usage of the script.""" sys.stderr.write(get_epilog()) if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n") sys.exit(error_code) parser = get_parser(with_epilog=True) # Parse command line. try: options = parser.parse_args() except Exception as exc: show_examples_and_exit(error_code=1) if not options.command: show_examples_and_exit(error_code=1) # loglevel is bound to the string value obtained from the command line argument. # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug import logging numeric_level = getattr(logging, options.loglevel.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % options.loglevel) logging.basicConfig(level=numeric_level) if options.verbose > 2: print(options) if options.command == "spglib": structure = abilab.Structure.from_file(options.filepath) print( structure.spget_summary(symprec=options.symprec, angle_tolerance=options.angle_tolerance, verbose=options.verbose)) #remove_equivalent_atoms(structure) elif options.command == "abispg": structure = abilab.Structure.from_file(options.filepath) spgrp = structure.abi_spacegroup if spgrp is not None: print(structure.spget_summary(verbose=options.verbose)) else: # Here we compare Abinit wrt spglib. If spgrp is None, we create a temporary # task to run the code in dry-run mode. print("FILE does not contain Abinit symmetry operations.") print( "Calling Abinit in --dry-run mode with chkprim = 0 to get space group." ) from abipy.data.hgh_pseudos import HGH_TABLE gsinp = factories.gs_input(structure, HGH_TABLE, spin_mode="unpolarized") gsinp["chkprim"] = 0 abistructure = gsinp.abiget_spacegroup(tolsym=options.tolsym) print(abistructure.spget_summary(verbose=options.verbose)) diff_structures( [structure, abistructure], mode=options.diff_mode, headers=["Input structure", "After Abinit symmetrization"], fmt="abivars") # Save file. save_structure(abistructure, options) elif options.command == "convert": fmt = options.format if fmt == "cif" and options.filepath.endswith(".cif"): fmt = "abivars" print(abilab.Structure.from_file(options.filepath).convert(fmt=fmt)) elif options.command == "supercell": structure = abilab.Structure.from_file(options.filepath) options.scaling_matrix = np.array(options.scaling_matrix) if len(options.scaling_matrix) == 9: options.scaling_matrix.shape = (3, 3) if options.verbose: print("scaling matrix: ", options.scaling_matrix) supcell = structure * options.scaling_matrix #supcell = structure.make_supercell(scaling_matrix, to_unit_cell=True) print(supcell.convert(fmt=options.format)) elif options.command == "abisanitize": print("\nCalling abi_sanitize to get a new structure in which:") print(" * Structure is refined.") print(" * Reduced to primitive settings.") print( " * Lattice vectors are exchanged if the triple product is negative\n" ) structure = abilab.Structure.from_file(options.filepath) sanitized = structure.abi_sanitize( symprec=options.symprec, angle_tolerance=options.angle_tolerance, primitive=not options.no_primitive, primitive_standard=options.primitive_standard) index = [options.filepath, "abisanitized"] dfs = abilab.dataframes_from_structures([structure, sanitized], index=index, with_spglib=True) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") abilab.print_dataframe( dfs.coords, title="Atomic positions (columns give the site index):") if not options.verbose: print("\nUse -v for more info") #print(sanitized.convert(fmt="cif")) else: #print("\nDifference between structures:") if len(structure) == len(sanitized): table = [] for line1, line2 in zip( str(structure).splitlines(), str(sanitized).splitlines()): table.append([line1, line2]) print( str( tabulate(table, headers=["Initial structure", "Abisanitized"]))) else: print("\nInitial structure:") print(structure) print("\nabisanitized structure:") print(sanitized) # Save file. save_structure(sanitized, options) elif options.command == "irefine": structure = abilab.Structure.from_file(options.filepath) sanitized = structure.copy() symprec, angle_tolerance = options.symprec, options.angle_tolerance print( "Calling abi_sanitize with increasing tolerances to reach target space group:", options.target_spgnum) print("Using symprec_step: ", options.symprec_step, ", angle_tolerance_step:", options.angle_tolerance_step, "ntrial", options.ntrial) itrial = 0 while itrial < options.ntrial: print(">>> Trying with symprec: %s, angle_tolerance: %s" % (symprec, angle_tolerance)) sanitized = sanitized.abi_sanitize( symprec=symprec, angle_tolerance=angle_tolerance, primitive=not options.no_primitive, primitive_standard=options.primitive_standard) spg_symb, spg_num = sanitized.get_space_group_info( symprec=symprec, angle_tolerance=angle_tolerance) print(">>> Space-group number:", spg_symb, ", symbol:", spg_num, "for trial:", itrial) if spg_num == options.target_spgnum: print(2 * "\n", "# Final structure with space group number:", spg_symb, ", symbol:", spg_num, 2 * "\n") print(sanitized.convert(fmt="cif")) break # Increment counter and tols. itrial += 1 symprec += options.symprec_step angle_tolerance += options.angle_tolerance_step else: print("Cannot find space group number:", options.target_spgnum, "after", options.ntrial, "iterations") return 1 # Save file. #save_structure(sanitized, options) elif options.command == "conventional": print( "\nCalling get_conventional_standard_structure to get conventional structure:" ) print( "The standards are defined in Setyawan, W., & Curtarolo, S. (2010). " ) print( "High-throughput electronic band structure calculations: Challenges and tools. " ) print( "Computational Materials Science, 49(2), 299-312. doi:10.1016/j.commatsci.2010.05.010\n" ) structure = abilab.Structure.from_file(options.filepath) conv = structure.get_conventional_standard_structure( international_monoclinic=True, symprec=options.symprec, angle_tolerance=options.angle_tolerance) index = [options.filepath, "conventional"] dfs = abilab.dataframes_from_structures([structure, conv], index=index, with_spglib=True) abilab.print_dataframe(dfs.lattice, title="Lattice parameters:") if options.verbose: abilab.print_dataframe( dfs.coords, title="Atomic positions (columns give the site index):") if not options.verbose: print("\nUse -v for more info") else: #print("\nDifference between structures:") if len(structure) == len(conv): table = [] for line1, line2 in zip( str(structure).splitlines(), str(conv).splitlines()): table.append([line1, line2]) print( str( tabulate(table, headers=["Initial structure", "Conventional"]))) else: print("\nInitial structure:\n", structure) print("\nConventional structure:\n", conv) # Save file. save_structure(conv, options) elif options.command == "neighbors": abilab.Structure.from_file( options.filepath).print_neighbors(radius=options.radius) elif options.command == "interpolate": initial_structure = abilab.Structure.from_file(options.filepaths[0]) end_structure = abilab.Structure.from_file(options.filepaths[1]) structures = initial_structure.interpolate( end_structure, nimages=options.nimages, interpolate_lattices=False, pbc=True, autosort_tol=options.autosort_tol) structures = list(map(abilab.Structure.as_structure, structures)) for i, s in enumerate(structures): print(marquee("Structure #%d" % i, mark="=")) print(s.convert(fmt=options.format)) print(" ") elif options.command == "xrd": structure = abilab.Structure.from_file(options.filepath) two_theta_range = tuple(float(t) for t in options.two_theta_range) structure.plot_xrd(wavelength=options.wavelength, two_theta_range=two_theta_range, symprec=options.symprec, annotate_peaks=not options.no_annotate_peaks) elif options.command == "oxistate": print( abilab.Structure.from_file( options.filepath).get_oxi_state_decorated()) elif options.command == "ipython": structure = abilab.Structure.from_file(options.filepath) print( "Invoking Ipython, `structure` object will be available in the Ipython terminal" ) import IPython IPython.start_ipython(argv=[], user_ns={"structure": structure}) elif options.command == "notebook": structure = abilab.Structure.from_file(options.filepath) structure.make_and_open_notebook(nbpath=None, foreground=options.foreground) elif options.command == "visualize": structure = abilab.Structure.from_file(options.filepath) print(structure) print("Visualizing structure with:", options.appname) structure.visualize(appname=options.appname) elif options.command == "kpath": structure = abilab.Structure.from_file(options.filepath) print("# Abinit Structure") print(structure.abi_string) print("\n# K-path in reduced coordinates:") print("# tolwfr 1e-20 iscf -2 getden ??") print(" ndivsm 10") print(" kptopt", -(len(structure.hsym_kpoints) - 1)) print(" kptbounds") for k in structure.hsym_kpoints: print(" %+.5f %+.5f %+.5f" % tuple(k.frac_coords), "#", k.name) elif options.command == "bz": abilab.Structure.from_file(options.filepath).plot_bz() elif options.command == "ngkpt": d = abilab.Structure.from_file(options.filepath).calc_ksampling( options.nksmall) print("ngkpt %d %d %d" % (d.ngkpt[0], d.ngkpt[1], d.ngkpt[2])) print("nshiftk ", len(d.shiftk), "\nshiftk") for s in d.shiftk: print(" %s %s %s" % (s[0], s[1], s[2])) elif options.command == "ktables": structure = abilab.Structure.from_file(options.filepath) k = Ktables(structure, options.mesh, options.is_shift, not options.no_time_reversal) print(k) print("") print( "NB: These results are obtained by calling spglib with the structure read from file." ) print( "The k-points might differ from the ones expected by Abinit, especially if the space groups differ." ) if not options.verbose: print("\nUse -v to obtain the BZ --> IBZ mapping.") else: print() k.print_bz2ibz() elif options.command == "abikmesh": structure = abilab.Structure.from_file(options.filepath) from abipy.data.hgh_pseudos import HGH_TABLE gsinp = factories.gs_input(structure, HGH_TABLE, spin_mode="unpolarized", kppa=options.kppa) if options.kppa is not None: print("Calling Abinit to compute the IBZ with kppa:", options.kppa, "and shiftk:", options.shiftk) options.ngkpt = None else: print("Calling Abinit to compute the IBZ with ngkpt:", options.ngkpt, "and shiftk", options.shiftk) ibz = gsinp.abiget_ibz(ngkpt=options.ngkpt, shiftk=options.shiftk, kptopt=options.kptopt) if options.verbose: print(gsinp) print("Found %d points in the IBZ:" % len(ibz.points)) for i, (k, w) in enumerate(zip(ibz.points, ibz.weights)): print("%6d) [%+.3f, %+.3f, %+.3f] weight=%.3f" % (i, k[0], k[1], k[2], w)) #elif options.command == "kmesh_jhu": # structure = abilab.Structure.from_file(options.filepath) # ksampling = structure.ksampling_from_jhudb(kppra=1000) # #print(ksampling) elif options.command == "lgk": structure = abilab.Structure.from_file(options.filepath) spgrp = structure.abi_spacegroup if spgrp is None: cprint("Your file does not contain Abinit symmetry operations.", "yellow") cprint( "Will call spglib to obtain the space group (assuming time-reversal: %s)" % (not options.no_time_reversal), "yellow") spgrp = AbinitSpaceGroup.from_structure( structure, has_timerev=not options.no_time_reversal, symprec=options.symprec, angle_tolerance=options.angle_tolerance) print() print(marquee("Structure", mark="=")) print(structure.spget_summary(verbose=options.verbose)) print("\n") print(marquee("Little Group", mark="=")) ltk = spgrp.find_little_group(kpoint=options.kpoint) print(ltk.to_string(verbose=options.verbose)) elif options.command == "kstar": structure = abilab.Structure.from_file(options.filepath) # TODO #kstar = structure.get_star_kpoint(options.kpoint, has_timerev=not options.no_time_reversal) # Call spglib to get spacegroup if Abinit spacegroup is not available. if structure.abi_spacegroup is None: structure.spgset_abi_spacegroup( has_timerev=not options.no_time_reversal) kpoint = Kpoint(options.kpoint, structure.reciprocal_lattice) kstar = kpoint.compute_star(structure.abi_spacegroup, wrap_tows=True) print("Found %s points in the star of %s\n" % (len(kstar), repr(kpoint))) for k in kstar: print(4 * " ", repr(k)) elif options.command == "mp_id": # Get the Structure corresponding to material_id. structure = abilab.Structure.from_mpid(options.mpid, final=True, api_key=options.mapi_key, endpoint=options.endpoint) # Convert to format and print it. print(structure.convert(fmt=options.format)) elif options.command == "mp_match": mp = abilab.mp_match_structure(options.filepath) if not mp.structures: cprint("No structure found in database", "yellow") return 1 if options.notebook: return mp.make_and_open_notebook(foreground=options.foreground) else: mp.print_results(fmt=options.format, verbose=options.verbose) if options.browser: mp.open_browser(limit=None if options.verbose == 2 else 10) elif options.command == "mp_search": mp = abilab.mp_search(options.chemsys_formula_id) if not mp.structures: cprint("No structure found in Materials Project database", "yellow") return 1 if options.select_spgnum: mp = mp.filter_by_spgnum(options.select_spgnum) if options.notebook: return mp.make_and_open_notebook(foreground=options.foreground) else: mp.print_results(fmt=options.format, verbose=options.verbose) if options.browser: mp.open_browser(limit=None if options.verbose == 2 else 10) elif options.command == "mp_pd": if os.path.exists(options.file_or_elements): structure = abilab.Structure.from_file(options.file_or_elements) elements = structure.symbol_set else: elements = options.file_or_elements.split("-") if options.verbose > 1: print("Building phase-diagram for elements:", elements) with abilab.restapi.get_mprester(api_key=options.mapi_key, endpoint=options.endpoint) as rest: pdr = rest.get_phasediagram_results(elements) pdr.print_dataframes(verbose=options.verbose) pdr.plot(show_unstable=options.show_unstable) elif options.command == "cod_search": cod = abilab.cod_search(options.formula, primitive=options.primitive) if not cod.structures: cprint("No structure found in COD database", "yellow") return 1 if options.select_spgnum: cod = cod.filter_by_spgnum(options.select_spgnum) if options.notebook: return cod.make_and_open_notebook(foreground=options.foreground) else: cod.print_results(fmt=options.format, verbose=options.verbose) elif options.command == "cod_id": # Get the Structure from COD structure = abilab.Structure.from_cod_id(options.cod_identifier, primitive=options.primitive) # Convert to format and print it. print(structure.convert(fmt=options.format)) elif options.command == "animate": filepath = options.filepath if any(filepath.endswith(ext) for ext in ("HIST", "HIST.nc")): with abilab.abiopen(filepath) as hist: structures = hist.structures elif "XDATCAR" in filepath: structures = Xdatcar(filepath).structures if not structures: raise RuntimeError( "Your Xdatcar contains only one structure. Due to a bug " "in the pymatgen routine, your structures won't be parsed correctly" "Solution: Add another structure at the end of the file.") else: raise ValueError("Don't know how to handle file %s" % filepath) xsf_write_structure(sys.stdout, structures) else: raise ValueError("Unsupported command: %s" % options.command) return 0