def from_file(cls, filepath): """Create the object from a netcdf_ file.""" with ETSF_Reader(filepath) as r: try: structure = r.read_structure() atoms_indices = r.read_value("ifc_atoms_indices") - 1 neighbours_indices = r.read_value("ifc_neighbours_indices") - 1 distances = r.read_value("ifc_distances") ifc_cart_coord = r.read_value("ifc_matrix_cart_coord") ifc_cart_coord_short_range = r.read_value( "ifc_matrix_cart_coord_short_range", default=None) local_vectors = r.read_value("ifc_local_vectors", default=None) # The following are set to None by default to keep backward # compatibility with anaddb.nc files generated by versions of abinit<9.2 atoms_cart_coord = r.read_value("ifc_atoms_cart_coord", default=None) ifc_weights = r.read_value("ifc_weights", default=None) except Exception: import traceback msg = traceback.format_exc() msg += ( "Error while trying to read IFCs from file.\n" "Verify that the required variables are used in anaddb: ifcflag, natifc, atifc, ifcout\n" ) raise ValueError(msg) return cls(structure=structure, atoms_indices=atoms_indices, neighbours_indices=neighbours_indices, ifc_cart_coord=ifc_cart_coord, ifc_cart_coord_short_range=ifc_cart_coord_short_range, local_vectors=local_vectors, distances=distances, atoms_cart_coord=atoms_cart_coord, ifc_weights=ifc_weights)
def anaget_emacro_and_becs(self, chneut=1, workdir=None, manager=None, verbose=0): """ Call anaddb to compute the macroscopic dielectric tensor and the Born effective charges. Args: chneut: Anaddb input variable. See official documentation. manager: :class:`TaskManager` object. If None, the object is initialized from the configuration file verbose: verbosity level. Set it to a value > 0 to get more information Return: emacro, becs """ inp = AnaddbInput(self.structure, anaddb_kwargs={"chneut": chneut}) task = AnaddbTask.temp_shell_task(inp, ddb_node=self.filepath, workdir=workdir, manager=manager) if verbose: print("ANADDB INPUT:\n", inp) print("workdir:", task.workdir) # Run the task here. task.start_and_wait(autoparal=False) report = task.get_event_report() if not report.run_completed: raise self.AnaddbError(task=task, report=report) # Read data from the netcdf output file produced by anaddb. with ETSF_Reader(os.path.join(task.workdir, "anaddb.nc")) as r: structure = r.read_structure() emacro = Tensor.from_cartesian_tensor(r.read_value("emacro_cart"), structure.lattice, space="r"), becs = Becs(r.read_value("becs_cart"), structure, chneut=inp["chneut"], order="f") return emacro, becs
def from_file(cls, filepath): """ Reads the non analytical directions, frequencies and displacements from the anaddb.nc file specified. Non existence of displacements is accepted for compatibility with abinit 8.0.6 Raises an error if the other values are not present in anaddb.nc. """ with ETSF_Reader(filepath) as r: directions = r.read_value("non_analytical_directions") phfreq = r.read_value("non_analytical_phonon_modes") # need a default as the first abinit version including IFCs in the netcdf doesn't have this attribute phdispl_cart = r.read_value("non_analytical_phdispl_cart", cmode="c", default=None) structure = r.read_structure() amu_list = r.read_value("atomic_mass_units", default=None) if amu_list is not None: # ntypat arrays atomic_numbers = r.read_value("atomic_numbers") amu = {at: a for at, a in zip(atomic_numbers, amu_list)} else: amu = None return cls(structure=structure, directions=directions, phfreqs=phfreq, phdispl_cart=phdispl_cart, amu=amu)
def __init__(self, filepath): super().__init__(filepath) self.reader = r = ETSF_Reader(filepath) # Read dimensions. self.nfft = r.read_dimvalue("nfft") self.nspden = r.read_dimvalue("nspden") self.natom3 = len(self.structure) * 3 self.symv1scf = r.read_value("symv1scf")
def __init__(self, filepath): super().__init__(filepath) self.reader = r = ETSF_Reader(filepath) self.has_zeff = bool(r.read_value("has_zeff")) self.has_dielt = bool(r.read_value("has_dielt")) self.has_quadrupoles = bool(r.read_value("has_quadrupoles")) self.dvdb_add_lr = r.read_value("dvdb_add_lr") self.symv1 = bool(r.read_value("symv1"))
def __init__(self, filepath): super().__init__(filepath) self.reader = r = ETSF_Reader(filepath) # Read medadata self.has_zeff = bool(r.read_value("has_zeff")) self.has_dielt = bool(r.read_value("has_dielt")) self.has_quadrupoles = bool(r.read_value("has_quadrupoles")) self.has_efield = bool(r.read_value("has_efield", default=False)) self.dvdb_add_lr = r.read_value("dvdb_add_lr") self.symv1scf = r.read_value("symv1scf") self.interpolated = bool(r.read_value("interpolated")) self.qdamp = r.read_value("qdamp")
def OnAddLoTo(self, event): """Add LO-TO splitting data to the phbands in the active tab""" dialog = wx.FileDialog(self, message="Choose an anaddb.nc file", defaultDir=os.getcwd(), wildcard="Netcdf files (*.nc)|*.nc", style=wx.OPEN | wx.CHANGE_DIR) if dialog.ShowModal() == wx.ID_CANCEL: return with ETSF_Reader(dialog.GetPath()) as r: directions = r.read_value("non_analytical_directions") non_anal_phfreq = r.read_value("non_analytical_phonon_modes") self.phbands.non_anal_directions = directions self.phbands.non_anal_phfreqs = non_anal_phfreq
def from_file(cls, filepath): """ Creates the tensor from a anaddb.nc netcdf file containing ``dchide``. This requires to run anaddb with ``tnlflag`` > 0 """ with ETSF_Reader(filepath) as reader: try: return cls(reader.read_value("dchide")) except Exception as exc: import traceback msg = traceback.format_exc() msg += ("Error while trying to read from file.\n" "Verify that nlflag > 0 in anaddb\n") raise ValueError(msg)
def __init__(self, filepath): super().__init__(filepath) self.reader = r = ETSF_Reader(filepath) # Read dimensions. self.nfft = r.read_dimvalue("nfft") self.nspden = r.read_dimvalue("nspden") self.natom3 = len(self.structure) * 3 self.method = r.read_value("method") assert self.method == 0 self.ngqpt = r.read_value("ngqpt") self.rpt = r.read_value("rpt") self.nrpt = len(self.rpt) # FFT mesh. self.ngfft = r.read_value("ngfft")
def from_file(cls, filepath): """ Create the object from an anaddb.nc netcdf file. Args: filepath: path to the netcdf file. Returns: An instance of Raman. """ with ETSF_Reader(filepath) as r: try: susceptibility = r.read_value("raman_sus").T phfreqs = r.read_value("gamma_phonon_modes") non_anal_susceptibility = r.read_value( "non_analytical_raman_sus", default=None) if non_anal_susceptibility is not None: non_anal_susceptibility = non_anal_susceptibility.T non_anal_phfreqs = r.read_value("non_analytical_phonon_modes", default=None) non_anal_directions = r.read_value("non_analytical_directions", default=None) except Exception: import traceback msg = traceback.format_exc() msg += ( "Error while trying to read Raman from file.\n" "Verify that the required variables are used in anaddb: nlflag\n" ) raise ValueError(msg) return cls(susceptibility=susceptibility, phfreqs=phfreqs, non_anal_susceptibility=non_anal_susceptibility, non_anal_phfreqs=non_anal_phfreqs, non_anal_directions=non_anal_directions)
def __init__(self, filepath): super(AbinitNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) self._structure = self.reader.read_structure()
class AnaddbNcFile(AbinitNcFile, Has_Structure, NotebookWriter): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure |Structure| object. .. attribute:: epsinf Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs. .. rubric:: Inheritance Diagram .. inheritance-diagram:: AnaddbNcFile """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super(AnaddbNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) def close(self): self.reader.close() @lazy_property def structure(self): return self.reader.read_structure() @lazy_property def params(self): # -666 to support old anaddb.nc files without metadata return OrderedDict([ ("asr", int(self.reader.read_value("asr", default=-666))), ("chneut", int(self.reader.read_value("chneut", default=-666))), ("dipdip", int(self.reader.read_value("dipdip", default=-666))), ("symdynmat", int(self.reader.read_value("symdynmat", default=-666))), ]) def __str__(self): return self.to_string() def to_string(self, verbose=0): """ String representation Args: verbose: verbosity level. """ lines = []; app = lines.append app(marquee("File Info", mark="=")) app(self.filestat(as_string=True)) app("") app(self.structure.to_string(verbose=verbose, title="Structure")) import json app(marquee("Parameters", mark="=")) app(json.dumps(self.params, indent=2, sort_keys=True)) app("") if self.has_elastic_data: app("") df = self.elastic_data.get_average_elastic_dataframe(tensor="elastic_relaxed") if not df.empty: app(marquee("Averaged elastic properties (relaxed ions)", mark="=")) app(df.to_string(index=False)) app("") df = self.elastic_data.get_elast_properties_dataframe() if not df.empty: app(marquee("Averaged elastic properties (relaxed ions)", mark="=")) app(df.T.to_string(index=True)) if verbose: df = self.elastic_data.get_voigt_dataframe() app(df.T.to_string()) tol = 1e-3 if self.epsinf is not None: app("Electronic dielectric tensor (eps_inf) in Cartesian coordinates. Set to zero below %.2e." % tol) app(self.epsinf.get_dataframe(tol=tol).to_string()) app("") if self.eps0 is not None: app("Zero-frequency dielectric tensor (eps_zero) in Cartesian coordinates. Set to zero below %.2e." % tol) app(self.eps0.get_dataframe(tol=tol).to_string()) app("") #if self.becs is not None: if self.dchide is not None: app("Non-linear optical susceptibility tensor.") app(str(self.dchide)) app("") if self.dchidt is not None: app("First-order change in the linear dielectric susceptibility.") app(str(self.dchidt)) app("") #if self.has_piezoelectric_data: # df = self.elastic_data.get_piezoelectric_dataframe() return "\n".join(lines) @lazy_property def epsinf(self): """ Macroscopic electronic |DielectricTensor| in Cartesian coordinates (a.k.a. epsilon_infinity) None if the file does not contain this information. """ try: return DielectricTensor(self.reader.read_value("emacro_cart").T.copy()) except Exception as exc: #print(exc, "Returning None", sep="\n") return None # FIXME To maintain backward compatibility @property def emacro(self): msg = "emacro is deprecated. It will removed in abipy 0.8. Use epsinf" warnings.simplefilter('default') warnings.warn(msg, DeprecationWarning, stacklevel=2) return self.epsinf @lazy_property def eps0(self): """ Relaxed ion macroscopic |DielectricTensor| in Cartesian coordinates (a.k.a. epsilon_zero) None if the file does not contain this information. """ try: return DielectricTensor(self.reader.read_value("emacro_cart_rlx").T.copy()) except Exception as exc: #print(exc, "Requires dieflag > 0", "Returning None", sep="\n") return None # FIXME To maintain backward compatibility @property def emacro_rlx(self): msg = "emacro_rlx is deprecated and will removed in abipy 0.8. Use epsinf" warnings.simplefilter('default') warnings.warn(msg, DeprecationWarning, stacklevel=2) return self.eps0 @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ chneut = self.params["chneut"] try: return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: #print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ``ifcflag``, ``natifc``, ``atifc``, ``ifcout``. Return None, if the netcdf_ file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: #print(exc) #cprint("Interatomic force constants have not been calculated. Returning None", "red") return None @lazy_property def dchide(self): """ Non-linear optical susceptibility tensor. Returns a :class:`NLOpticalSusceptibilityTensor` or None if the file does not contain this information. """ try: return NLOpticalSusceptibilityTensor(self.reader.read_value("dchide")) except Exception as exc: #print(exc, "Requires nlflag > 0", "Returning None", sep="\n") return None @lazy_property def dchidt(self): """ First-order change in the linear dielectric susceptibility. Returns a list of lists of 3x3 Tensor object with shape (number of atoms, 3). The [i][j] element of the list contains the Tensor representing the change due to the displacement of the ith atom in the jth direction. None if the file does not contain this information. """ try: a = self.reader.read_value("dchidt").T.copy() except Exception as exc: #print(exc, "Requires 0 < nlflag < 3", "Returning None", sep="\n") return None dchidt = [] for i in a: d = [] for j in i: d.append(Tensor(j)) dchidt.append(d) return dchidt @lazy_property def oscillator_strength(self): """ A complex |numpy-array| containing the oscillator strengths with shape [number of phonon modes, 3, 3], in a.u. (1 a.u.=253.2638413 m3/s2). None if the file does not contain this information. """ try: carr = self.reader.read_value("oscillator_strength", cmode="c") carr = carr.transpose((0, 2, 1)).copy() return carr except Exception as exc: #print(exc, "Oscillator strengths require dieflag == 1, 3 or 4", "Returning None", sep="\n") return None @lazy_property def has_elastic_data(self): """True if elastic tensors have been computed.""" return self.reader.read_value("elaflag", default=0) != 0 @lazy_property def has_piezoelectric_data(self): """True if piezoelectric tensors have been computed.""" return self.reader.read_value("piezoflag", default=0) != 0 @lazy_property def elastic_data(self): """ Container with the different (piezo)elastic tensors computed by anaddb. stored in pymatgen tensor objects. """ return ElasticData.from_ncreader(self.reader) def yield_figs(self, **kwargs): # pragma: no cover """ This function *generates* a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results. """ yield None def write_notebook(self, nbpath=None): """ Write an jupyter_ notebook to nbpath. If ``nbpath`` is None, a temporay file in the current working directory is created. Return path to the notebook. """ nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=None) nb.cells.extend([ nbv.new_code_cell("ananc = abilab.abiopen('%s')" % self.filepath), nbv.new_code_cell("print(ananc)"), ]) return self._write_nb_nbpath(nb, nbpath)
class AnaddbNcFile(AbinitNcFile, Has_Structure): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure Structure object. .. attribute:: emacro Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs, """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super(AbinitNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) self._structure = self.reader.read_structure() def close(self): self.reader.close() @property def structure(self): return self._structure @lazy_property def emacro(self): """ Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor( self.reader.read_value("emacro_cart"), self.structure.lattice, space="r"), except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ try: chneut = -666 # TODO: anaddb.nc should contain the input file. return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ifcflag, natifc, atifc, ifcout Return None, if the netcdf file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: print(exc, "Returning None", sep="\n") return None
def from_file(cls, path): """Initialize the object from the data stored in a netcdf file.""" with ETSF_Reader(path) as r: mesh = r.get_a2fmesh() values = r.get_a2fvalues() return cls(mesh, values)
def __init__(self, filepath): super(AnaddbNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath)
class AnaddbNcFile(AbinitNcFile, Has_Structure): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure Structure object. .. attribute:: emacro Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs, """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super(AbinitNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) self._structure = self.reader.read_structure() def close(self): self.reader.close() @property def structure(self): return self._structure @lazy_property def emacro(self): """ Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor(self.reader.read_value("emacro_cart"), self.structure.lattice, space="r"), except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ try: chneut = -666 # TODO: anaddb.nc should contain the input file. return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ifcflag, natifc, atifc, ifcout Return None, if the netcdf file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: print(exc, "Returning None", sep="\n") return None
class AnaddbNcFile(AbinitNcFile, Has_Structure, NotebookWriter): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure |Structure| object. .. attribute:: emacro Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs. .. rubric:: Inheritance Diagram .. inheritance-diagram:: AnaddbNcFile """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super(AnaddbNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) self._structure = self.reader.read_structure() def close(self): self.reader.close() @lazy_property def params(self): return {} def __str__(self): return self.to_string() def to_string(self, verbose=0): """ String representation Args: verbose: verbosity level. """ lines = []; app = lines.append app(marquee("File Info", mark="=")) app(self.filestat(as_string=True)) app("") app(self.structure.to_string(verbose=verbose, title="Structure")) return "\n".join(lines) @property def structure(self): return self._structure @lazy_property def emacro(self): """ Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor(self.reader.read_value("emacro_cart"), self.structure.lattice, space="r") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def emacro_rlx(self): """ Relaxed ion Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor(self.reader.read_value("emacro_cart_rlx"), self.structure.lattice, space="r") except Exception as exc: print(exc, "Requires dieflag > 0", "Returning None", sep="\n") return None @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ try: chneut = -666 # TODO: anaddb.nc should contain the input file. return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ``ifcflag``, ``natifc``, ``atifc``, ``ifcout``. Return None, if the netcdf_ file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: print(exc) cprint("Interatomic force constants have not been calculated. Returning None", "red") return None @lazy_property def dchide(self): """ Non-linear optical susceptibility tensor. Returns a :class:`NLOpticalSusceptibilityTensor` or None if the file does not contain this information. """ try: return NLOpticalSusceptibilityTensor(self.reader.read_value("dchide")) except Exception as exc: print(exc, "Requires nlflag > 0", "Returning None", sep="\n") return None @lazy_property def dchidt(self): """ First-order change in the linear dielectric susceptibility. Returns a list of lists of 3x3 Tensor object with shape (number of atoms, 3). The [i][j] element of the list contains the Tensor representing the change due to the displacement of the ith atom in the jth direction. None if the file does not contain this information. """ try: a = self.reader.read_value("dchidt").T dchidt = [] for i in a: d = [] for j in i: d.append(Tensor.from_cartesian_tensor(j, self.structure.lattice, space="r")) dchidt.append(d) return dchidt except Exception as exc: print(exc, "Requires 0 < nlflag < 3", "Returning None", sep="\n") return None @lazy_property def oscillator_strength(self): """ A complex |numpy-array| containing the oscillator strengths with shape (number of phonon modes, 3, 3), in a.u. (1 a.u.=253.2638413 m3/s2). None if the file does not contain this information. """ try: return self.reader.read_value("oscillator_strength", cmode="c") except Exception as exc: print(exc, "Oscillator strengths require dieflag == 1, 3 or 4", "Returning None", sep="\n") raise return None def write_notebook(self, nbpath=None): """ Write an jupyter_ notebook to nbpath. If ``nbpath`` is None, a temporay file in the current working directory is created. Return path to the notebook. """ nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=None) nb.cells.extend([ nbv.new_code_cell("ananc = abilab.abiopen('%s')" % self.filepath), nbv.new_code_cell("print(ananc)"), ]) return self._write_nb_nbpath(nb, nbpath)
def __init__(self, filepath): super().__init__(filepath) self.reader = ETSF_Reader(filepath)
class AnaddbNcFile(AbinitNcFile, Has_Structure, NotebookWriter): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure |Structure| object. .. attribute:: epsinf Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs. .. rubric:: Inheritance Diagram .. inheritance-diagram:: AnaddbNcFile """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super().__init__(filepath) self.reader = ETSF_Reader(filepath) def close(self): self.reader.close() @lazy_property def structure(self): return self.reader.read_structure() @lazy_property def params(self): # -666 to support old anaddb.nc files without metadata return OrderedDict([ ("asr", int(self.reader.read_value("asr", default=-666))), ("chneut", int(self.reader.read_value("chneut", default=-666))), ("dipdip", int(self.reader.read_value("dipdip", default=-666))), ("symdynmat", int(self.reader.read_value("symdynmat", default=-666))), ]) def __str__(self): return self.to_string() def to_string(self, verbose=0): """ String representation Args: verbose: verbosity level. """ lines = [] app = lines.append app(marquee("File Info", mark="=")) app(self.filestat(as_string=True)) app("") app(self.structure.to_string(verbose=verbose, title="Structure")) import json app(marquee("Parameters", mark="=")) app(json.dumps(self.params, indent=2, sort_keys=True)) app("") if self.has_elastic_data: app("") df = self.elastic_data.get_average_elastic_dataframe( tensor="elastic_relaxed") if not df.empty: app( marquee("Averaged elastic properties (relaxed ions)", mark="=")) app(df.to_string(index=False)) app("") df = self.elastic_data.get_elast_properties_dataframe() if not df.empty: app( marquee("Averaged elastic properties (relaxed ions)", mark="=")) app(df.T.to_string(index=True)) if verbose: df = self.elastic_data.get_voigt_dataframe() app(df.T.to_string()) tol = 1e-3 if self.epsinf is not None: app("Electronic dielectric tensor (eps_inf) in Cartesian coordinates. Set to zero below %.2e." % tol) app(self.epsinf.get_dataframe(tol=tol).to_string()) app("") if self.eps0 is not None: app("Zero-frequency dielectric tensor (eps_zero) in Cartesian coordinates. Set to zero below %.2e." % tol) app(self.eps0.get_dataframe(tol=tol).to_string()) app("") #if self.becs is not None: if self.dchide is not None: app("Non-linear optical susceptibility tensor.") app(str(self.dchide)) app("") if self.dchidt is not None: app("First-order change in the linear dielectric susceptibility.") app(str(self.dchidt)) app("") #if self.has_piezoelectric_data: # df = self.elastic_data.get_piezoelectric_dataframe() return "\n".join(lines) @lazy_property def epsinf(self): """ Macroscopic electronic |DielectricTensor| in Cartesian coordinates (a.k.a. epsilon_infinity) None if the file does not contain this information. """ try: return DielectricTensor( self.reader.read_value("emacro_cart").T.copy()) except Exception as exc: #print(exc, "Returning None", sep="\n") return None # FIXME To maintain backward compatibility @property def emacro(self): msg = "emacro is deprecated. It will removed in abipy 0.8. Use epsinf" warnings.simplefilter('default') warnings.warn(msg, DeprecationWarning, stacklevel=2) return self.epsinf @lazy_property def eps0(self): """ Relaxed ion macroscopic |DielectricTensor| in Cartesian coordinates (a.k.a. epsilon_zero) None if the file does not contain this information. """ try: return DielectricTensor( self.reader.read_value("emacro_cart_rlx").T.copy()) except Exception as exc: #print(exc, "Requires dieflag > 0", "Returning None", sep="\n") return None # FIXME To maintain backward compatibility @property def emacro_rlx(self): msg = "emacro_rlx is deprecated and will removed in abipy 0.8. Use eps0" warnings.simplefilter('default') warnings.warn(msg, DeprecationWarning, stacklevel=2) return self.eps0 @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ chneut = self.params["chneut"] try: return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: #print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ``ifcflag``, ``natifc``, ``atifc``, ``ifcout``. Return None, if the netcdf_ file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: cprint( "Interatomic force constants have not been calculated. Returning None", "red") return None @lazy_property def dchide(self): """ Non-linear optical susceptibility tensor. Returns a :class:`NLOpticalSusceptibilityTensor` or None if the file does not contain this information. """ try: return NLOpticalSusceptibilityTensor( self.reader.read_value("dchide")) except Exception as exc: #print(exc, "Requires nlflag > 0", "Returning None", sep="\n") return None @lazy_property def dchidt(self): """ First-order change in the linear dielectric susceptibility. Returns a list of lists of 3x3 Tensor object with shape (number of atoms, 3). The [i][j] element of the list contains the Tensor representing the change due to the displacement of the ith atom in the jth direction. None if the file does not contain this information. """ try: a = self.reader.read_value("dchidt").T.copy() except Exception as exc: #print(exc, "Requires 0 < nlflag < 3", "Returning None", sep="\n") return None dchidt = [] for i in a: d = [] for j in i: d.append(Tensor(j)) dchidt.append(d) return dchidt @lazy_property def oscillator_strength(self): """ A complex |numpy-array| containing the oscillator strengths with shape [number of phonon modes, 3, 3], in a.u. (1 a.u.=253.2638413 m3/s2). None if the file does not contain this information. """ try: carr = self.reader.read_value("oscillator_strength", cmode="c") carr = carr.transpose((0, 2, 1)).copy() return carr except Exception as exc: #print(exc, "Oscillator strengths require dieflag == 1, 3 or 4", "Returning None", sep="\n") return None @lazy_property def has_elastic_data(self): """True if elastic tensors have been computed.""" return self.reader.read_value("elaflag", default=0) != 0 @lazy_property def has_piezoelectric_data(self): """True if piezoelectric tensors have been computed.""" return self.reader.read_value("piezoflag", default=0) != 0 @lazy_property def elastic_data(self): """ Container with the different (piezo)elastic tensors computed by anaddb. stored in pymatgen tensor objects. """ return ElasticData.from_ncreader(self.reader) @lazy_property def amu(self): """ Dictionary with atomic_number as keys and the atomic massu units as values. """ amu_list = self.reader.read_value("atomic_mass_units", default=None) if amu_list is not None: atomic_numbers = self.reader.read_value("atomic_numbers") amu = {at: a for at, a in zip(atomic_numbers, amu_list)} else: amu = None return amu def yield_figs(self, **kwargs): # pragma: no cover """ This function *generates* a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results. """ yield None def write_notebook(self, nbpath=None): """ Write an jupyter_ notebook to nbpath. If ``nbpath`` is None, a temporay file in the current working directory is created. Return path to the notebook. """ nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=None) nb.cells.extend([ nbv.new_code_cell("ananc = abilab.abiopen('%s')" % self.filepath), nbv.new_code_cell("print(ananc)"), ]) return self._write_nb_nbpath(nb, nbpath)
class AnaddbNcFile(AbinitNcFile, Has_Structure, NotebookWriter): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure |Structure| object. .. attribute:: emacro Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs. .. rubric:: Inheritance Diagram .. inheritance-diagram:: AnaddbNcFile """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super(AnaddbNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) self._structure = self.reader.read_structure() def close(self): self.reader.close() @lazy_property def params(self): return {} def __str__(self): return self.to_string() def to_string(self, verbose=0): """ String representation Args: verbose: verbosity level. """ lines = [] app = lines.append app(marquee("File Info", mark="=")) app(self.filestat(as_string=True)) app("") app(self.structure.to_string(verbose=verbose, title="Structure")) return "\n".join(lines) @property def structure(self): return self._structure @lazy_property def emacro(self): """ Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor( self.reader.read_value("emacro_cart"), self.structure.lattice, space="r") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def emacro_rlx(self): """ Relaxed ion Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor( self.reader.read_value("emacro_cart_rlx"), self.structure.lattice, space="r") except Exception as exc: print(exc, "Requires dieflag > 0", "Returning None", sep="\n") return None @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ try: chneut = -666 # TODO: anaddb.nc should contain the input file. return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ``ifcflag``, ``natifc``, ``atifc``, ``ifcout``. Return None, if the netcdf_ file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: print(exc) cprint( "Interatomic force constants have not been calculated. Returning None", "red") return None @lazy_property def dchide(self): """ Non-linear optical susceptibility tensor. Returns a :class:`NLOpticalSusceptibilityTensor` or None if the file does not contain this information. """ try: return NLOpticalSusceptibilityTensor( self.reader.read_value("dchide")) except Exception as exc: print(exc, "Requires nlflag > 0", "Returning None", sep="\n") return None @lazy_property def dchidt(self): """ First-order change in the linear dielectric susceptibility. Returns a list of lists of 3x3 Tensor object with shape (number of atoms, 3). The [i][j] element of the list contains the Tensor representing the change due to the displacement of the ith atom in the jth direction. None if the file does not contain this information. """ try: a = self.reader.read_value("dchidt").T dchidt = [] for i in a: d = [] for j in i: d.append( Tensor.from_cartesian_tensor(j, self.structure.lattice, space="r")) dchidt.append(d) return dchidt except Exception as exc: print(exc, "Requires 0 < nlflag < 3", "Returning None", sep="\n") return None @lazy_property def oscillator_strength(self): """ A complex |numpy-array| containing the oscillator strengths with shape (number of phonon modes, 3, 3), in a.u. (1 a.u.=253.2638413 m3/s2). None if the file does not contain this information. """ try: return self.reader.read_value("oscillator_strength", cmode="c") except Exception as exc: print(exc, "Oscillator strengths require dieflag == 1, 3 or 4", "Returning None", sep="\n") raise return None def write_notebook(self, nbpath=None): """ Write an jupyter_ notebook to nbpath. If ``nbpath`` is None, a temporay file in the current working directory is created. Return path to the notebook. """ nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=None) nb.cells.extend([ nbv.new_code_cell("ananc = abilab.abiopen('%s')" % self.filepath), nbv.new_code_cell("print(ananc)"), ]) return self._write_nb_nbpath(nb, nbpath)
class AnaddbNcFile(AbinitNcFile, Has_Structure, NotebookWriter): """ AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with `abiopen("anaddb.nc")`. .. attribute:: structure Structure object. .. attribute:: emacro Macroscopic dielectric tensor. None if the file does not contain this information. .. attribute:: becs Born effective charges. None if the file does not contain this inf .. attribute:: ifc :class:`InteratomicForceConstants` object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs, """ @classmethod def from_file(cls, filepath): """Initialize the object from file.""" return cls(filepath) def __init__(self, filepath): super(AbinitNcFile, self).__init__(filepath) self.reader = ETSF_Reader(filepath) self._structure = self.reader.read_structure() def close(self): self.reader.close() @property def structure(self): return self._structure @lazy_property def emacro(self): """ Macroscopic dielectric tensor. None if the file does not contain this information. """ try: return Tensor.from_cartesian_tensor( self.reader.read_value("emacro_cart"), self.structure.lattice, space="r"), except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def becs(self): """ Born effective charges. None if the file does not contain this information. """ try: chneut = -666 # TODO: anaddb.nc should contain the input file. return Becs(self.reader.read_value("becs_cart"), self.structure, chneut=chneut, order="f") except Exception as exc: print(exc, "Returning None", sep="\n") return None @lazy_property def ifc(self): """ The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ifcflag, natifc, atifc, ifcout Return None, if the netcdf file does not contain the IFCs, """ try: return InteratomicForceConstants.from_file(self.filepath) except Exception as exc: print(exc) cprint( "Interatomic force constants have not been calculated. Returning None", "red") return None def write_notebook(self, nbpath=None): """ Write an ipython notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook. """ nbformat, nbv, nb = self.get_nbformat_nbv_nb(title=None) nb.cells.extend([ nbv.new_code_cell("ananc = abilab.abiopen('%s')" % self.filepath), nbv.new_code_cell("print(ananc)"), ]) return self._write_nb_nbpath(nb, nbpath)