Ejemplo n.º 1
0
def h5diff(f1, f2, key=None, precision=1.e-6):
    """

    Modified version of triqs.utility.h5diff.h5diff
    key is the path of the data set to be compared: e.g., "dmft_out/Sigma_iw"

    """
    if key is None:
        h5diff_org(os.path.abspath(f1), os.path.abspath(f2), precision)
        return

    keys = key.split("/")
    h1 = HDFArchive(os.path.abspath(f1), 'r')
    h2 = HDFArchive(os.path.abspath(f2), 'r')

    for k in keys:
        h1 = h1[k]
        h2 = h2[k]

    compare(key, h1, h2, 0, precision)
    if failures:
        print('-' * 50, file=sys.stderr)
        print('-' * 20 + '  FAILED  ' + '-' * 20, file=sys.stderr)
        print('-' * 50, file=sys.stderr)
        for x in failures:
            print(x, file=sys.stderr)
            print('-' * 50, file=sys.stderr)
        raise RuntimeError("FAILED")
Ejemplo n.º 2
0
Archivo: archive.py Proyecto: hmenke/h5
    def test_archive_base(self):
        d = {'dbl' : 1.0, 'lst' : [1,[1],'a']}
        
        # === Write to archive
        with HDFArchive('hdf_archive2.h5','w', init = list(d.items())) as arch:
        
            arch['int'] = 100
            arch['arr'] = np.array([[1,2,3],[4,5,6]])
            arch['tpl'] = (2,[2],'b')
            arch['dct'] = { 'a':[10], 'b':20 }
            arch['nan'] = float('nan')
            arch['nanarr'] = np.array([np.nan, 1.0])
        
            arch.create_group('grp')
            grp = arch['grp']
            grp['int'] = 98
            grp['tpl'] = (3,[3],'c')
            grp['dct'] = { 'a':[30], 'b':40 }
        
        # === Read access
        with HDFArchive('hdf_archive2.h5','r') as arch:  
            dct = arch['dct']
            grp = arch['grp']
        
        # === Read/Write access
        with HDFArchive('hdf_archive2.h5','a') as arch:
        
            dct = arch['dct']
            dct['c'] = 'triqs'
            arch['dct'] = dct
        
            grp = arch['grp']
            dct = grp['dct']
            dct['c'] = 'qmc'
        
            grp['dct'] = dct
            grp['d'] = 700
            grp['x'] = 1.5
            grp['y'] = 'zzz'
        
        
        # === Final check
        arch = HDFArchive('hdf_archive2.h5','r')
        
        self.assertEqual( arch['dbl'] , 1.0 )
        
        self.assertEqual( arch['lst'] , [1,[1],'a'] )
        self.assertEqual( arch['int'] , 100 )
        assert_arrays_are_close( arch['arr'] , np.array([[1, 2, 3], [4, 5, 6]]) )
        self.assertEqual( arch['tpl'] , (2,[2],'b') )
        self.assertEqual( arch['dct'] , {'a':[10], 'b':20, 'c':'triqs'} )
        self.assertTrue( isnan(arch['nan']) )
        self.assertTrue( np.array_equal(np.isnan(arch['nanarr']), np.array([True, False])) )

        self.assertEqual( arch['grp']['int'] , 98 )
        self.assertEqual( arch['grp']['tpl'] , (3,[3],'c') )
        self.assertEqual( arch['grp']['dct'] , { 'a':[30], 'b':40, 'c':'qmc'} )
        self.assertEqual( arch['grp']['d'] , 700 )
        self.assertEqual( arch['grp']['x'] , 1.5 )
        self.assertEqual( arch['grp']['y'] , 'zzz' )
Ejemplo n.º 3
0
Archivo: archive.py Proyecto: hmenke/h5
    def test_hdf5_types(self):
        filename = 'h5archive.h5'

        p = dict(
            my_flag=True,
            my_int=1,
            my_long=1,
            my_float=1.,
            my_complex=1.j,
            my_string='foobar',
            my_string_unicode='foobar',
            my_ndarray_int=np.array([1]),
            my_ndarray_float=np.array([1.]),
            my_ndarray_complex=np.array([1.j]),
            )

        with HDFArchive(filename, 'w') as a:
            a['p'] = p

        with HDFArchive(filename, 'r') as a:
            p_ref = a['p']

        for key in list(p.keys()):
            print(key, type(p[key]), type(p_ref[key]))
            assert( type(p[key]) == type(p_ref[key]) )

            if type(p[key]) == np.ndarray:
                assert( p[key].dtype == p_ref[key].dtype )
                print('dtypes: ', p[key].dtype, p_ref[key].dtype)
Ejemplo n.º 4
0
    def test_TBLattice(self):

        tbl = TBLattice(units=self.units,
                        hoppings=self.hoppings,
                        orbital_positions=self.orbital_positions,
                        orbital_names=self.orbital_names)
        print(tbl)

        self.assertEqual(list(self.hoppings.keys()), list(tbl.hoppings.keys()))
        self.assertTrue(
            all(
                map(np.array_equal, self.hoppings.values(),
                    tbl.hoppings.values())))

        # Make sure manual BravaisLattice / TightBinding / BrillouinZone
        # construction yields same objects

        bl = BravaisLattice(self.units, self.orbital_positions,
                            self.orbital_names)
        bz = BrillouinZone(bl)
        tb = TightBinding(bl, self.hoppings)

        self.assertEqual(bl, tbl.bl)
        self.assertEqual(bz, tbl.bz)
        self.assertEqual(tb, tbl.tb)

        # Test H5 Read / Write

        with HDFArchive("tbl.h5", 'w') as arch:
            arch['tbl'] = tbl

        with HDFArchive("tbl.h5", 'r') as arch:
            tbl_read = arch['tbl']

        self.assertEqual(tbl, tbl_read)
Ejemplo n.º 5
0
    def test_hdf5_types(self):
        filename = 'h5archive.h5'

        # Test creation of softlinks
        with HDFArchive(filename, 'w') as a:
            a.create_group("group")
            a['data'] = 11
            a['group']['data'] = 22
            a.create_softlink('data', 'link')
            a.create_softlink('/group/data', '/group/link')

        with HDFArchive(filename, 'r') as a:
            link_data = a['link']
            link_group_data = a['group']['link']

        self.assertEqual(link_data, 11)
        self.assertEqual(link_group_data, 22)

        # Test overwriting of softlinks
        with HDFArchive(filename, 'a') as a:
            a['other data'] = 33
            a.create_softlink('other data', 'link')

        with HDFArchive(filename, 'r') as a:
            link_data = a['link']

        self.assertEqual(link_data, 33)

        # Test exception on overwriting of softlinks
        with HDFArchive(filename, 'a') as a:
            with self.assertRaises(RuntimeError):
                a.create_softlink('data', 'link', delete_if_exists=False)
Ejemplo n.º 6
0
    def test_storable(self):

        obj = Storable()
        obj.vec = [1, 2, 4, 5]
        obj.s = "some other string"

        with HDFArchive('h5_class.h5','w') as arch:
            arch['obj'] = obj

        with HDFArchive('h5_class.h5','r') as arch:
            obj_in = arch['obj']

        self.assertTrue(all(obj.vec == obj_in.vec))
        self.assertEqual(obj.s, obj_in.s)
Ejemplo n.º 7
0
    def generate_Hk_path(self, params):
        """
        Override the original method. It is assumed that H(k) data are already stored in seedname.h5.
        """

        # check h5 file
        with HDFArchive(self._seedname + '.h5', 'r') as f:
            if not 'dft_bands_input' in f:
                warn("  seedname.h5/dft_bands_input should be prepared in advance in lattice='external'")
                return None, None

            n_k = f["dft_bands_input"]["n_k"]

        # generate x values
        xk = []
        xnode = []
        file_kpath = "kpath.in"
        if not os.path.exists(file_kpath):
            warn("  '%s' not found" %file_kpath)
            return None, None
        with open(file_kpath, "r") as f:
            # -40 -40 40 80 2.31040 Z
            for line in f:
                array = line.split()
                assert len(array) >= 5
                x = float(array[4])
                xk.append(x)
                if len(array) >= 6:
                    xnode.append(XNode(x = x, label = array[5]))

        assert len(xk) == n_k
        return numpy.array(xk), xnode
Ejemplo n.º 8
0
    def set_group(self, grp):
        """
        return True if succeeded
        """
        if hasattr(self, 'data'):
            del self.data

        with HDFArchive(self.h5_file_in, 'r') as ar:
            if grp not in ar:
                return False
            ar = ar[grp]
            self.data = {key: ar[key] for key in list(ar.keys())}
        print("\n*** grp = " + grp)
        print(list(self.data.keys()))

        if 'n_k' in self.data:
            self.nk = self.data['n_k']
            print("n_k =", self.nk)

        if hasattr(self, '_max_n_orbitals'):
            del self._max_n_orbitals

        self.data_new = {}

        return True
Ejemplo n.º 9
0
Archivo: base.py Proyecto: FermiQ/DCore
def write_dft_bands_input_data(seedname,
                               params,
                               n_k,
                               kvec,
                               lattice_model,
                               bands_data='dft_bands_input'):
    """
    Write DFT band input data into a HDF5 file
    :param seedname:
    :param params: runtime parameters
    :param n_k:  Number of k points
    :param kvec:  2D array
    :param lattice_model: object of LatticeModel
    :return:  None
    """
    assert kvec.shape[0] == n_k

    hopping, n_orbitals, proj_mat = lattice_model.generate_dft_band_input_data(
        params, kvec)

    #
    # Output them into seedname.h5
    #
    with HDFArchive(seedname + '.h5', 'a') as f:
        if not (bands_data in f):
            f.create_group(bands_data)
        f[bands_data]['hopping'] = hopping
        f[bands_data]['n_k'] = n_k
        f[bands_data]['n_orbitals'] = n_orbitals
        f[bands_data]['proj_mat'] = proj_mat
    print('    Done')
Ejemplo n.º 10
0
    def generate_model_file(self):
        #
        #
        p = self._params
        seedname = self._params["model"]["seedname"]
        with open(seedname+'.inp', 'w') as f:
            _generate_w90_converter_input(self.nkdiv(), p, f)

        # Convert General-Hk to SumDFT-HDF5 format
        converter = Wannier90Converter(seedname=seedname)
        converter.convert_dft_input()

        if p["model"]["spin_orbit"]:
            with HDFArchive(seedname + '.h5', 'a') as f:
                f["dft_input"]["SP"] = 1
                f["dft_input"]["SO"] = 1

                corr_shells = f["dft_input"]["corr_shells"]
                for icor in range(p["model"]['ncor']):
                    corr_shells[icor]["SO"] = 1
                f["dft_input"]["corr_shells"] = corr_shells

                # Make projectors compatible with DCore's block structure
                # proj_mat (n_k, nb, n_corr, max_dim_sh, max_n_orb)
                proj_mat = f['dft_input']['proj_mat']
                n_k, nb, n_corr, max_dim_sh, max_n_orb = proj_mat.shape
                assert nb == 1
                # (n_k, nb, n_corr, orb, spin, orb, spin) => (n_k, nb, n_corr, spin, orb, spin, orb)
                assert max_dim_sh//2 > 0
                proj_mat = proj_mat.reshape((n_k, nb, n_corr, max_dim_sh//2, 2, max_n_orb//2, 2))
                proj_mat = proj_mat.transpose((0, 1, 2, 4, 3, 6, 5))
                proj_mat = proj_mat.reshape((n_k, 1, n_corr, max_dim_sh, max_n_orb))
                f['dft_input']['proj_mat'] = proj_mat
Ejemplo n.º 11
0
    def _get_results(self, group_prefix, n_data, orbital_symmetrize, dtype=float, stop_if_data_not_exist=True):
        """
        Read results with two spin-orbital indices from HDF5 file

        Returns
        -------
        numpy.ndarray of size (2*self.n_orb, 2*self.n_orb, n_data)

        """

        data_shape = (2*self.n_orb, 2*self.n_orb, n_data)

        array = numpy.zeros(data_shape, dtype=dtype)
        with HDFArchive('sim.h5', 'r') as f:
            results = f["simulation"]["results"]
            for i1, i2 in product(range(2*self.n_orb), repeat=2):
                group = "%s_%d_%d" % (group_prefix, i1, i2)
                if group in results:
                    array[i1, i2, :] = results[group]["mean"]["value"]
                    if orbital_symmetrize:  # Only i1>i2 is computed in CTQMC.
                        array[i2, i1, :] = array[i1, i2, :]
                elif stop_if_data_not_exist:
                    raise Exception("data does not exist in sim.h5/simulation/results/{}. alps_cthyb might be old.".format(group))


        # [(o1,s1), (o2,s2)] -> [o1, s1, o2, s2] -> [s1, o1, s2, o2] -> [(s1,o1), (s2,o2)]
        array = array.reshape((self.n_orb, 2, self.n_orb, 2, -1))\
                     .transpose((1, 0, 3, 2, 4))\
                     .reshape((2*self.n_orb, 2*self.n_orb, -1))
        return array
Ejemplo n.º 12
0
def calc_field(plot=True):

    filenames = glob.glob('data_pyed_h_field*.h5')

    out = ParameterCollection()
    d = ParameterCollection(data=[])
    h_vec, m_vec, m_ref_vec = [], [], []

    for filename in filenames:

        print('--> Loading:', filename)

        with HDFArchive(filename, 'r') as s:
            p = s['p']
            d.data.append(p)
            h_vec.append(p.h_field)

            m = 0.5 * (-p.G_tau['up'](p.beta) + p.G_tau['dn'](p.beta))
            m_vec.append(np.squeeze(m))

            m_ref_vec.append(p.magnetization)

            # Susceptibilit from quadratic expectation value
            if np.abs(p.h_field) < 1e-9:
                out.chi_exp = p.magnetization2 * 2 * p.beta

    h_vec, m_vec, m_ref_vec = np.array(h_vec), np.array(m_vec), np.array(
        m_ref_vec)
    sidx = np.argsort(h_vec)
    d.h_vec, d.m_vec, d.m_ref_vec = h_vec[sidx], m_vec[sidx], m_ref_vec[sidx]

    from scipy.interpolate import InterpolatedUnivariateSpline as IUS

    spl = IUS(d.h_vec, d.m_ref_vec)
    out.chi = -spl(0, nu=1)  # Linear response
    out.beta = p.beta

    print('beta, chi, chi_exp =', out.beta, out.chi, out.chi_exp)

    filename_out = 'data_pyed_extrap_h_field_beta%6.6f.h5' % out.beta
    with HDFArchive(filename_out, 'w') as s:
        s['field'] = out

    for key, value in list(out.dict().items()):
        setattr(d, key, value)

    if plot: plot_field(d)
Ejemplo n.º 13
0
def main(input_file, output_file):
    """
    Solve the impurity problem.
    """

    import time
    t_start = time.time()

    with HDFArchive(os.path.abspath(input_file), 'r') as h:
        rot = h['rot'] if 'rot' in h else None
        beta = h['beta']
        gf_struct = h['gf_struct']
        # convert a dict to a list of pairs [ (str,[int,...]), ...]
        gf_struct = [(k, list(v)) for k, v in gf_struct.items()]
        u_mat = h['u_mat']
        n_iw = h['n_iw']
        G0_iw = h['G0_iw']
        params = h['params']

    if rot is not None:
        raise RuntimeError("TRIQS/HubbardI interface does not support basis rotation!")

    h_int = make_h_int(u_mat, gf_struct)

    # Create a working horse
    S = Solver(beta, gf_struct, n_iw)
    S.G0_iw << G0_iw

    for k in params:
        # e.g. numpy.bool_ to bool
        params[k] = convert_to_built_in_scalar_type(params[k])

    S.solve(h_int=h_int, **params)

    # Retrieve results from the working horse
    Sigma_iw = S.Sigma_iw.copy()
    G_iw = S.G_iw.copy()

    if mpi.is_master_node():
        with HDFArchive(os.path.abspath(output_file), 'w') as h:
            h['Sigma_iw'] = Sigma_iw
            h['Gimp_iw'] = G_iw

    t_end = time.time()
    if mpi.is_master_node():
        print('TRIQS/hubbardI ran for {} seconds.'.format(t_end-t_start))
Ejemplo n.º 14
0
    def test_hk(self):
        self.proj_gr.orthogonalize()
        self.proj_gr.calc_hk(self.eigvals)

        testout = _rpath + 'hk.test.h5'
        with HDFArchive(testout, 'w') as h5test:
            h5test['hk'] = self.proj_gr.hk
        expected_file = _rpath + 'hk.ref.h5'
        self.assertH5FileEqual(testout, expected_file)
Ejemplo n.º 15
0
Archivo: archive.py Proyecto: hmenke/h5
    def test_hdf5_bool(self):

        # Write
        with HDFArchive('bool.h5','w') as arch:
            arch['t'] = True
            arch['f'] = False
            arch['i'] = 10

        with HDFArchive('bool.h5','r') as arch:
            t = arch['t']
            f = arch['f']
            i = arch['i']

        self.assertTrue(t)
        self.assertFalse(f)
        self.assertIs(type(t),bool)
        self.assertIs(type(f),bool)
        self.assertIs(type(i),int)
Ejemplo n.º 16
0
 def save_sparse_info(self, freqs):
     grp = self.args['sparse_grp']
     with HDFArchive(self.args['h5_file'], 'a') as f:
         if grp not in f:
             f.create_group(grp)
         # save all arguments in __init__ to re-instantiate
         f[grp]['args'] = self.args
         # save list of frequencies (sampling points)
         f[grp]['freqs'] = freqs
Ejemplo n.º 17
0
    def write_dft_band_input_data(self,
                                  params,
                                  kvec,
                                  bands_data='dft_bands_input'):
        """

        Returns
        -------
        hopping : complex
            k-dependent one-body Hamiltonian
        n_orbitals : integer
            Number of orbitals at each k. It does not depend on k
        proj_mat : complex
            Projection onto each correlated orbitals
        """

        n_k = kvec.shape[0]
        assert kvec.shape[1] == 3

        norb_sh = numpy.array(params['model']['norb_corr_sh'])

        assert len(norb_sh) == 1
        assert params['model']['ncor'] == 1

        #
        # Energy band
        #
        norb = norb_sh[0]
        dim_Hk = 2 * norb if params['model']['spin_orbit'] else norb
        n_spin = 1
        n_orbitals = numpy.ones((n_k, n_spin), dtype=int) * dim_Hk
        hopping = numpy.zeros((n_k, n_spin, dim_Hk, dim_Hk), complex)
        if params['model']['spin_orbit']:
            for ik in range(n_k):
                hopping[ik, 0, :, :] = self.Hk(kvec[ik])
        else:
            for ik in range(n_k):
                # Copy only the up component
                hopping[ik, 0, :, :] = self.Hk(kvec[ik])[0]

        #
        # proj_mat is (norb*norb) identities at each correlation shell
        #
        proj_mat = numpy.zeros([n_k, n_spin, 1, dim_Hk, dim_Hk], complex)
        proj_mat[:, :, 0, 0:dim_Hk, 0:dim_Hk] = numpy.identity(dim_Hk, complex)

        #
        # Output them into seedname.h5
        #
        with HDFArchive(params['model']['seedname'] + '.h5', 'a') as f:
            if not (bands_data in f):
                f.create_group(bands_data)
            f[bands_data]['hopping'] = hopping
            f[bands_data]['n_k'] = n_k
            f[bands_data]['n_orbitals'] = n_orbitals
            f[bands_data]['proj_mat'] = proj_mat
        print('    Done')
Ejemplo n.º 18
0
def __generate_local_potential(p):
    print("\n  @ Write the information of local potential")

    # str
    local_potential_matrix = p["model"]["local_potential_matrix"]
    local_potential_factor = p["model"]["local_potential_factor"]

    n_inequiv_shells = p["model"]['n_inequiv_shells']
    spin_orbit = p["model"]["spin_orbit"]

    # read parameters from DFT data
    skc = SumkDFTCompat(p["model"]["seedname"] + '.h5')

    assert skc.n_inequiv_shells == n_inequiv_shells

    corr_shells = skc.corr_shells
    dim_sh = [corr_shells[skc.inequiv_to_corr[ish]]['dim'] for ish in range(n_inequiv_shells)]

    # set factor
    try:
        fac = ast.literal_eval(local_potential_factor)
        if isinstance(fac, float) or isinstance(fac, int):
            fac = [float(fac)] * n_inequiv_shells
        elif isinstance(fac, list) or isinstance(fac, tuple):
            assert len(fac) == n_inequiv_shells
        else:
            raise Exception("local_potential_factor should be float or list of length %d" % n_inequiv_shells)
    except Exception as e:
        print("Error: local_potential_factor =", local_potential_factor)
        print(e)
        exit(1)

    # print factor
    print("fac =", fac)

    # set potential matrix
    pot = set_potential(local_potential_matrix, "local_potential_matrix", n_inequiv_shells, dim_sh, spin_orbit)

    for ish in range(n_inequiv_shells):
        pot[ish] *= fac[ish]

    # check if potential matrix is hermitian
    def is_hermitian(mat):
        return numpy.allclose(mat, mat.transpose().conj())
    try:
        for ish, pot_ish in enumerate(pot):
            for sp in range(pot_ish.shape[0]):
                assert is_hermitian(pot_ish[sp]), "potential matrix for ish={} sp={} is not hermitian".format(ish, sp)
    except AssertionError as e:
        print("Error:", e)
        exit(1)

    # write potential matrix
    with HDFArchive(p["model"]["seedname"] + '.h5', 'a') as f:
        f["DCore"]["LocalPotential"] = pot
    print("\n    Written to {0}".format(p["model"]["seedname"]+'.h5'))
Ejemplo n.º 19
0
def make_calc(beta=2.0, h_field=0.0):
    
    # ------------------------------------------------------------------
    # -- Hubbard atom with two bath sites, Hamiltonian

    p = ParameterCollection(
        beta = beta,
        h_field = h_field,
        U = 5.0,
        ntau = 40,
        niw = 15,
        )

    p.mu = 0.5*p.U
    
    # ------------------------------------------------------------------

    print('--> Solving SIAM with parameters')
    print(p)
    
    # ------------------------------------------------------------------

    up, do = 'up', 'dn'
    docc = c_dag(up,0) * c(up,0) * c_dag(do,0) * c(do,0)
    mA = c_dag(up,0) * c(up,0) - c_dag(do,0) * c(do,0)
    nA = c_dag(up,0) * c(up,0) + c_dag(do,0) * c(do,0)

    p.H = -p.mu * nA + p.U * docc + p.h_field * mA
    
    # ------------------------------------------------------------------

    fundamental_operators = [c(up,0), c(do,0)]
    
    ed = TriqsExactDiagonalization(p.H, fundamental_operators, p.beta)

    g_tau = GfImTime(beta=beta, statistic='Fermion', n_points=40, indices=[0])
    g_iw = GfImFreq(beta=beta, statistic='Fermion', n_points=10, indices=[0])

    p.G_tau = BlockGf(name_list=[up,do], block_list=[g_tau]*2, make_copies=True)
    p.G_iw = BlockGf(name_list=[up,do], block_list=[g_iw]*2, make_copies=True)
    
    ed.set_g2_tau(p.G_tau[up], c(up,0), c_dag(up,0))
    ed.set_g2_tau(p.G_tau[do], c(do,0), c_dag(do,0))

    ed.set_g2_iwn(p.G_iw[up], c(up,0), c_dag(up,0))
    ed.set_g2_iwn(p.G_iw[do], c(do,0), c_dag(do,0))

    p.magnetization = ed.get_expectation_value(0.5 * mA)
    p.magnetization2 = ed.get_expectation_value(0.25 * mA * mA)
    
    # ------------------------------------------------------------------
    # -- Store to hdf5
    
    filename = 'data_pyed_h_field_%4.4f.h5' % h_field
    with HDFArchive(filename,'w') as res:
        res['p'] = p
Ejemplo n.º 20
0
    def test_issue_multifile(self):

        # Open a file more than once and write to it
        with HDFArchive("multifile.h5", 'w') as arch:
            arch['i'] = 14

        with HDFArchive("multifile.h5", 'a') as arch:
            arch['d'] = 3.2

        # Open a file more than once and read from it
        with HDFArchive("multifile.h5", 'r') as arch:
            self.assertEqual(arch['i'], 14)
            self.assertEqual(arch['d'], 3.2)

        # Open a file more than once and write to it
        with HDFArchive("multifile.h5", 'a') as arch:
            arch['c'] = 1.2 + 3j

        with HDFArchive("multifile.h5", 'a') as arch:
            arch['s'] = "a string"

        # Open a file more than once and read from it
        with HDFArchive("multifile.h5", 'r') as arch:
            self.assertEqual(arch['c'], 1.2 + 3j)
            self.assertEqual(arch['s'], "a string")
Ejemplo n.º 21
0
def read_TarGZ_HDFArchive(filename):
    tar = tarfile.open(filename, "r:gz")
    f = tar.extractfile(tar.getmembers()[0])

    tmp = NamedTemporaryFile(delete=False)
    tmp.write(f.read())
    tmp.close()

    data = HDFArchive(tmp.name, 'r')

    os.remove(tmp.name)

    return data
Ejemplo n.º 22
0
def write_TarGZ_HDFArchive(filename, **kwargs):
    filename = filename.split('.')[0]
    filename_h5 = filename + '.h5'
    filename_tar = filename + '.tar.gz'

    with HDFArchive(filename_h5, 'w') as res:
        for key, value in list(kwargs.items()):
            res[key] = value

    with tarfile.open(filename_tar, 'w:gz') as tar:
        tar.add(filename_h5)

    os.remove(filename_h5)
Ejemplo n.º 23
0
Archivo: base.py Proyecto: FermiQ/DCore
    def solve(self, rot, mpirun_command, params_kw):

        params = copy.deepcopy(params_kw)

        # Write input parameters
        with HDFArchive(os.path.abspath('input.h5'), 'w') as h:
            h['beta'] = self.beta
            h['gf_struct'] = self.gf_struct
            h['u_mat'] = self.u_mat
            h['n_iw'] = self.n_iw
            if not rot is None:
                h['rot'] = rot
            h['G0_iw'] = self._G0_iw
            h['params'] = params

            if 'calc_Sigma_w' in params and params['calc_Sigma_w']:
                h['calc_Sigma_w'] = True
                for k in ['omega_min', 'omega_max', 'n_omega']:
                    h[k] = params[k]
            else:
                h['calc_Sigma_w'] = False

        # Run a working horse
        commands = [sys.executable, "-m", self._impl_module_name()]
        commands.append(os.path.abspath('./input.h5'))
        commands.append(os.path.abspath('./output.h5'))

        with open('./output', 'w') as output_file:
            launch_mpi_subprocesses(mpirun_command, commands, output_file)
        with open('./output', 'r') as output_file:
            for line in output_file:
                print(line)

        # Read results
        with HDFArchive(os.path.abspath('output.h5'), 'r') as h:
            self._Sigma_iw << h['Sigma_iw']
            self._Gimp_iw << h['Gimp_iw']
            if 'Sigma_w' in h:
                self._Sigma_w = h['Sigma_w']
Ejemplo n.º 24
0
    def __init__(self, params):
        super(ExternalModel, self).__init__(params)

        self._seedname = self._params["model"]["seedname"]
        h5_file = self._seedname+'.h5'

        # check if h5 file already exists
        try:
            assert os.path.exists(h5_file)
            with HDFArchive(h5_file, 'r') as ar:
                assert 'dft_input' in ar
        except:
            raise Exception("Prepare, in advance, '%s' file which stores DFT data in 'dft_input' subgroup" % h5_file)

        # set nkdiv
        self._nkdiv = set_nk(params["model"]["nk"],
                             params["model"]["nk0"],
                             params["model"]["nk1"],
                             params["model"]["nk2"])

        # Set [model][norb_inequiv_sh], which is necessary for generate_umat
        with HDFArchive(h5_file, 'r') as f:
            n_inequiv_shells = f["dft_input"]["n_inequiv_shells"]
            corr_shells = f["dft_input"]["corr_shells"]
            inequiv_to_corr = f["dft_input"]["inequiv_to_corr"]
            norb_inequiv_sh = [corr_shells[icsh]['dim'] for icsh in inequiv_to_corr]
            try:
                assert len(norb_inequiv_sh) == n_inequiv_shells
            except:
                print("ExternalModel.__init__: failed in setting 'norb_inequiv_sh'")
                print(" n_inequiv_shells =", n_inequiv_shells)
                print(" inequiv_to_corr =", inequiv_to_corr)
                print(" corr_shells =", corr_shells)
                print(" norb_inequiv_sh =", norb_inequiv_sh)
                exit(1)
            params['model']['norb_inequiv_sh'] = norb_inequiv_sh
Ejemplo n.º 25
0
    def change_dataset(self, *args):
        self.locked1 = True
        self.quantities = []
        if self.pickle_mode:
            with open(self.h5_file, 'r') as fi:
                self._result = _get_path(self.dataset.get(), pickle.load(fi))
        else:
            with HDFArchive(self.h5_file, 'r') as arx:
                self._result = _get_path(self.dataset.get(), arx)

        for function in dir(self._result):
            if not function.startswith("plot_"):
                continue
            # if there is an error with getting the data
            # we do not want to offer it in the menu
            try:
                getattr(self._result, function).original(self._result)
                self.quantities.append(function[5:])
            except Exception as e:
                print(e)
                pass

        if not hasattr(self._result, 'analyzer_results'):
            ar = []
        elif self._result.matrix_structure is not None and self._result.element_wise:
            m = product(*map(range, self._result.effective_matrix_structure))
            ar = [(i, self._get_ar_i(i)) for i in m]
        else:
            ar = [(None, self._result.analyzer_results)]
        for ia, a in ar:
            for key, analyzer in a.items():
                for function in dir(analyzer):
                    if not function.startswith("plot_"):
                        continue
                    # if there is an error with getting the data
                    # we do not want to offer it in the menu
                    try:
                        getattr(analyzer, function).\
                            original(analyzer, self._result, element=ia)
                        ky = key + ': ' + function[5:]
                        if ky not in self.quantities:
                            self.quantities.append(ky)
                    except:
                        pass

        self.update_quantity_ui()
        self.locked1 = False
        self.update_plot()
Ejemplo n.º 26
0
    def save(self, h5_file_out, grp):
        if self.h5_file_in == h5_file_out:
            # overwrite only updated components
            data_save = self.data_new
        else:
            # write all components
            data_save = dict(self.data)
            data_save.update(self.data_new)

        with HDFArchive(h5_file_out, 'a') as ar:
            if grp not in ar:
                ar.create_group(grp)
            ar = ar[grp]

            for key, d in list(data_save.items()):
                ar[key] = d
Ejemplo n.º 27
0
 def set_blockgf_from_h5(sigma, group):
     # swdata = numpy.zeros((2, self.n_orb, self.n_iw), dtype=complex)
     swdata = numpy.zeros((2*self.n_orb, self.n_iw), dtype=complex)
     with HDFArchive('sim.h5', 'r') as f:
         # for orb in range(self.n_orb):
         #     for spin in range(2):
         #         swdata_array = f[group][str(orb*2+spin)]["mean"]["value"]
         #         assert swdata_array.dtype == numpy.complex
         #         assert swdata_array.shape == (self.n_iw,)
         #         swdata[spin, orb, :] = swdata_array
         for i in range(2*self.n_orb):
             swdata_array = f[group][str(i)]["mean"]["value"]
             assert swdata_array.dtype == numpy.complex
             assert swdata_array.shape == (self.n_iw,)
             swdata[i, :] = swdata_array
     assign_from_numpy_array(sigma, swdata, self.block_names)
Ejemplo n.º 28
0
def calculate(d, temp, u, mu, path):
    n_loops = 20
    epsilon = d.eps
    rho = d.rho
    delta_eps = epsilon[1] - epsilon[0]
    n_bins = epsilon.size

    beta = 1. / temp
    s = Solver(beta=beta, gf_struct=[('up', [0]), ('down', [0])])
    g_temp = s.G0_iw.copy()
    g_temp.zero()
    for spin in ['up', 'down']:
        for i in range(
                n_bins
        ):  # Use local self energy and density of states create a new G
            g_temp['%s' % spin] += rho[i] * delta_eps * \
                                   inverse(iOmega_n + mu - epsilon[i])
    for block, g0 in s.G0_iw:  # dyson equations
        g0 << g_temp[block]
    for it in range(n_loops):  # num of loops
        if it > 0:  # No need for the first loop,already have a S.G0_iw
            g_temp.zero()
            for spin in ['up', 'down']:
                for i in range(
                        n_bins
                ):  # Use local self energy and density of states create a new G
                    g_temp['%s' % spin] += rho[i] * delta_eps * \
                                           inverse(iOmega_n + mu - epsilon[i] - s.Sigma_iw['%s' % spin])
            for block, g0 in s.G0_iw:  # dyson equations
                g0 << inverse(inverse(g_temp[block]) + s.Sigma_iw[block])
        s.solve(
            h_int=u * n('up', 0) * n('down', 0),  # Local Hamiltonian
            n_cycles=50000,  # Number of QMC cycles
            length_cycle=50,  # Length of one cycle
            n_warmup_cycles=10000,
            measure_density_matrix=True,  # Measure the reduced density matrix
            use_norm_as_weight=True)

    rho = s.density_matrix
    # Object containing eigensystem of the local Hamiltonian
    h_loc_diag = s.h_loc_diagonalization
    atomsnumbs = trace_rho_op(rho, n('up', 0) + n('down', 0), h_loc_diag)
    doubleocc = trace_rho_op(rho, n('up', 0) * n('down', 0), h_loc_diag)
    with HDFArchive(path + "/mu %.2f.h5" % mu) as A:
        A['N'] = atomsnumbs
        A['D'] = doubleocc
    return atomsnumbs, doubleocc
Ejemplo n.º 29
0
    def test_ortho_normion(self):
        self.proj_gr.normion = True
        self.proj_gr.orthogonalize()

        dens_mat, overl = self.proj_sh.density_matrix(self.el_struct)

        testout = _rpath + 'projortho_normion.test.h5'
        with HDFArchive(testout, 'w') as h5test:
            h5test['density_matrix'] = dens_mat
            h5test['overlap_matrix'] = overl

# FIXME: redundant
        self.assertEqual(overl[0, 0, ...], np.eye(5))
        self.assertEqual(overl[0, 1, ...], np.eye(5))

        expected_file = _rpath + 'projortho_normion.ref.h5'
        self.assertH5FileEqual(testout, expected_file)
Ejemplo n.º 30
0
def read_dft_input_data(file, subgrp, things_to_read):
    """

    Small version of SumkDFT.read_input_from_hdf()
    Read DFT data from a HDF file and return the data as a dict.

    """

    values = {}
    with HDFArchive(file, 'r') as ar:
        if not subgrp in ar:
            raise RuntimeError("subrp " + subgrp + "does not exist in " +
                               file + "!")
        # first read the necessary things:
        for it in things_to_read:
            values[it] = ar[subgrp][it]

    return values