Exemple #1
0
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)
Exemple #2
0
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
Exemple #3
0
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)
Exemple #4
0
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
Exemple #5
0
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)
Exemple #6
0
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)
Exemple #7
0
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)