Beispiel #1
0
    def export_unk(self, spin=0, ngrid=None):
        '''
        Export the periodic part of BF in a real space grid for plotting with wannier90
        '''

        from scipy.io import FortranFile
        if spin == 0:
            spin_str = '.1'
        else:
            spin_str = '.2'

        if ngrid is None:
            ngrid = self.ngrid.copy()
        else:
            ngrid = np.array(ngrid, dtype=np.int64)
            assert ngrid.shape[0] == 3, 'Wrong syntax for ngrid'
            assert np.alltrue(ngrid >= self.ngrid), "Minium FT grid size: (%d, %d, %d)" % \
                    (self.ngrid[0], self.ngrid[1], self.ngrid[2])

        for kpt in range(self.nkpts):
            unk_file = FortranFile('UNK' + "%05d" % (kpt + 1) + spin_str, 'w')
            unk_file.write_record(
                np.asarray(
                    [ngrid[0], ngrid[1], ngrid[2], kpt + 1, self.nbands],
                    dtype=np.int32))
            for band in range(self.nbands):
                unk = self.get_unk(spin=spin,
                                   kpt=kpt + 1,
                                   band=band + 1,
                                   ngrid=ngrid,
                                   norm=False,
                                   norm_c=False)
                unk = unk.T.flatten()
                unk_file.write_record(unk)
            unk_file.close()
Beispiel #2
0
def read_fortFFT(file=None):
    ''' Read FFT grid from fortran output and return delta[i_k,j_k,l_k]
    '''
    f = FortranFile(file, 'r')
    Ngrid = f.read_ints(dtype=np.int32)[0]
    delt = f.read_reals(dtype=np.complex64)
    delt = np.reshape(delt, (Ngrid / 2 + 1, Ngrid, Ngrid), order='F')

    # reflect half field
    delta = np.zeros((Ngrid, Ngrid, Ngrid), dtype=np.complex64)
    # i = 0 - Ngrid // 2 (confirmed correct)
    delta[:Ngrid // 2 + 1, :, :] = delt[:, :, :]

    # i = Ngrid // 2 - Ngrid (confirmed corect)
    delta[:Ngrid // 2:-1, Ngrid:0:-1,
          Ngrid:0:-1] = np.conj(delt[1:Ngrid // 2, 1:Ngrid, 1:Ngrid])
    delta[:Ngrid // 2:-1, Ngrid:0:-1, 0] = np.conj(delt[1:Ngrid // 2, 1:Ngrid,
                                                        0])
    delta[:Ngrid // 2:-1, 0, Ngrid:0:-1] = np.conj(delt[1:Ngrid // 2, 0,
                                                        1:Ngrid])
    # reflect the x-axis
    delta[:Ngrid // 2:-1, 0, 0] = np.conj(delt[1:Ngrid // 2, 0, 0])

    hg = Ngrid // 2
    delta[hg, 0, 0] = np.real(delt[hg, 0, 0])
    delta[0, hg, 0] = np.real(delt[0, hg, 0])
    delta[0, 0, hg] = np.real(delt[0, 0, hg])
    delta[0, hg, hg] = np.real(delt[0, hg, hg])
    delta[hg, 0, hg] = np.real(delt[hg, 0, hg])
    delta[hg, hg, 0] = np.real(delt[hg, hg, 0])
    delta[hg, hg, hg] = np.real(delt[hg, hg, hg])
    return delta
Beispiel #3
0
def test_fortran_eof_multidimensional(tmpdir):
    filename = path.join(str(tmpdir), "scratch")
    n, m, q = 3, 5, 7
    dt = np.dtype([("field", np.float, (n, m))])
    a = np.zeros(q, dtype=dt)
    with FortranFile(filename, 'w') as f:
        f.write_record(a[0])
        f.write_record(a)
        f.write_record(a)
    with open(filename, "ab") as f:
        f.truncate(path.getsize(filename)-20)
    with FortranFile(filename, 'r') as f:
        assert len(f.read_record(dtype=dt)) == 1
        assert len(f.read_record(dtype=dt)) == q
        with pytest.raises(FortranFormattingError):
            f.read_record(dtype=dt)
    def get_inverse_covmat(self, spectra):
        '''
        high ell TT, TE and EE
        from Planck plik-lite datafile
        '''
        f = FortranFile(self.cov_file, 'r')
        covmat = f.read_reals(dtype=float).reshape((self.nbin_hi,self.nbin_hi))
        f.close()

        for i in range(self.nbin_hi):
            for j in range(i,self.nbin_hi):
                covmat[i,j] = covmat[j,i]

        if spectra=='TT':
            #select relevant covmat for temperature only
            bin_no=self.nbintt_hi
            start=0
            end=start+bin_no
            cov=covmat[start:end, start:end]
        else: #TTTEEE
            bin_no=self.nbin_hi
            cov=covmat

        #invert high ell covariance matrix (cholesky decomposition should be faster)
        fisher=scipy.linalg.cho_solve(scipy.linalg.cho_factor(cov), np.identity(bin_no))
        fisher=fisher.transpose()

        return fisher
Beispiel #5
0
    def __init__(self, resroot, filename="LUM_SF.bin", NT_TOT=107, NBMU=51):
        """ Filename defined by -OSOAA.ResFile.vsZ:
            This optional file provides the radiance field (I,Q,U) versus
            the altitude or depth, for the given relative azimuth angle
            (-OSOAA.View.Phi) and for the given viewing zenith angle
            (-OSOAA.View.VZA).
            resroot     OSOAA results root directory.
            filename    Filename to look for the results.
            I           I Stokes parameters Fourier components. The array
                        is I(LEVEL;WAVE_NUMBER)
            Q           Q Stokes parameters Fourier components. The array
                        is Q(LEVEL;WAVE_NUMBER)
            U           U Stokes parameters Fourier components. The array
                        is U(LEVEL;WAVE_NUMBER)
            """
        # We read the fortran binary file
        with FortranFile(resroot + "/Advanced_outputs/" + filename,
                         "r") as file:
            tmp = file.read_reals()

        # Reshape the array into 3 array for I, Q and U
        tmp = tmp.reshape(3, int(tmp.size / 3))
        Itmp = tmp[0, :]
        Qtmp = tmp[1, :]
        Utmp = tmp[2, :]

        # We reshape the array for the number of levels
        Itmp = Itmp.reshape(int(Itmp.size / (NT_TOT + 1)), NT_TOT + 1)
        Qtmp = Qtmp.reshape(int(Qtmp.size / (NT_TOT + 1)), NT_TOT + 1)
        Utmp = Utmp.reshape(int(Utmp.size / (NT_TOT + 1)), NT_TOT + 1)

        # We transpose the result to get and array of ARRAY[LEVEL:ANGLE]
        self.I = Itmp.transpose()
        self.Q = Qtmp.transpose()
        self.U = Utmp.transpose()
Beispiel #6
0
    def from_file(self, fname):
        with FortranFile(fname, 'r') as f:
            self.header = ''.join(map(str, f.read_record('c')))
            self.nbnds = f.read_ints()[0]
            self.nbnds_excl = f.read_ints()[0]
            self.bands_excl = f.read_ints()
            self.dlv = f.read_reals().reshape((3, 3), order='F')
            self.rlv = f.read_reals().reshape((3, 3), order='F')
            self.nkpts = f.read_ints()[0]
            self.grid_dims = f.read_ints()
            self.kpoints = f.read_reals().reshape((-1, 3))
            self.nntot = f.read_ints()[0]
            self.nwann = f.read_ints()[0]
            self.chkpt = f.read_record('c')
            self.disentanglement = bool(f.read_ints()[0])

            if self.disentanglement:
                self.omega_invariant = f.read_reals()[0]
                self.windows = f.read_ints().reshape((self.nbnds, self.nkpts),
                                                     order='F').transpose
                f.read_ints()
                self.umat_opt = np.transpose(
                    f.read_reals().view(complex).reshape(
                        (self.nbnds, self.nwann, self.nkpts), order='F'),
                    axes=(2, 0, 1))

            self.umat = np.transpose(f.read_reals().view(complex).reshape(
                (self.nwann, self.nwann, self.nkpts), order='F'),
                                     axes=(2, 0, 1))
            self.mmat = np.transpose(f.read_reals().view(complex).reshape(
                (self.nwann, self.nwann, self.nntot, self.nkpts), order='F'),
                                     axes=(3, 2, 0, 1))
            self.wannier_centers = f.read_reals().reshape((-1, 3))
            self.wannier_spreads = f.read_reals()
Beispiel #7
0
def readf(df):
    f = FortranFile(df, 'r')
    s = f.read_reals()

    nk = 100
    ne = 500
    nz_sc = 4
    nlay = 4 * nz_sc
    # in fortran, the array is a x b but in python, it is b x a

    s = s.reshape(((ne, (nk) * nz_sc + 1, nlay, 3)))
    ii = range(0, nlay // 2, 4)
    sall = np.zeros((len(ii), s.shape[0]))

    fig, ax = plt.subplots(1, 2, figsize=(6, 6))
    for ct, i in enumerate(ii):

        sc = ax[ct].imshow(s[:, :, i, 2],
                           aspect='auto',
                           origin='lower',
                           interpolation='bilinear',
                           vmax=0.018,
                           cmap='jet',
                           extent=(0, 1, 0, emax))

        ax[0].set_ylabel('Frequency [THz]')
        ##ax[1].plot(np.sum(s[:,:,i,2],axis=1),np.arange(s.shape[0]))
        ##ax[1].set_xlim([0,3])
        ##ax[1].set_ylim([0,s.shape[0]])
        #plt.savefig('test.png',dpi=300)
        sall[ct, :] = np.sum(s[:, :, i, 2], axis=1)

    plt.colorbar(sc)
    return sall, emax * np.arange(s.shape[0])
Beispiel #8
0
def get_nframes(dcdfilename):
    """
    Get the number of frames in the dcd file
    """
    with FortranFile(dcdfilename, 'r') as f:
        nframes = f.read_ints()[1]
    return nframes
Beispiel #9
0
    def readKernel(self):
        '''
        Read the EDKS Kernel and stores it in {self}

        Returns:
            * None
        '''

        # Show me
        if self.verbose:
            print('Read Kernel file {}'.format(self.kernel))

        # Open the file
        fedks = FortranFile(self.kernel, 'r')

        # Read
        kernel = fedks.read_reals(np.float32).reshape(
            (self.ndepth * self.ndista, 12))

        # Save
        self.depths = kernel[:, 0]
        self.distas = kernel[:, 1]
        self.zrtdsx = kernel[:, 2:]

        # CLose file
        fedks.close()
Beispiel #10
0
def getgrid(DIR=' '):

    global t_max, dt, nx, ny, nz, xb, yb, zb, xc, yc, zc, \
              alpha, rho_bcc, rho_bbb, rho_ccb, rho_cbc

    if DIR == ' ':
        filename = 'Data/grid.dat'
    else:
        filename = DIR + 'grid.dat'

    file = FortranFile(filename, 'r')

    t_max = file.read_reals(float)[0]
    dt = file.read_reals(float)[0]
    nx = file.read_ints(np.int32)[0]
    ny = file.read_ints(np.int32)[0]
    nz = file.read_ints(np.int32)[0]
    xb = file.read_reals(float)
    yb = file.read_reals(float)
    zb = file.read_reals(float)
    xc = file.read_reals(float)
    yc = file.read_reals(float)
    zc = file.read_reals(float)
    alpha = file.read_reals(float)[0]
    rho_bcc = file.read_reals(float).reshape((nz + 2, ny + 2, nx + 1),
                                             order="F")
    rho_bbb = file.read_reals(float).reshape((nz + 2, ny + 2, nx + 1),
                                             order="F")
    rho_ccb = file.read_reals(float).reshape((nz + 2, ny + 2, nx), order="F")
    rho_cbc = file.read_reals(float).reshape((nz + 2, ny + 2, nx), order="F")
Beispiel #11
0
    def from_file(filename: str) -> object:
        """
        Reads the UNK data from file.

        Args:
            filename (str): path to UNK file to read

        Returns:
            Unk object
        """
        input_data = []
        with FortranFile(filename, "r") as f:
            *ng, ik, nbnd = f.read_ints()
            for _ in range(nbnd):
                input_data.append(
                    # when reshaping need to specify ordering as fortran
                    f.read_record(np.complex128).reshape(ng, order="F"))
            try:
                for _ in range(nbnd):
                    input_data.append(
                        f.read_record(np.complex128).reshape(ng, order="F"))
                is_noncollinear = True
            except FortranEOFError:
                is_noncollinear = False

        # mypy made me create an extra variable here >:(
        data = np.array(input_data, dtype=np.complex128)

        # spinors are interwoven, need to separate them
        if is_noncollinear:
            temp_data = np.empty((nbnd, 2, *ng), dtype=np.complex128)
            temp_data[:, 0, :, :, :] = data[::2, :, :, :]
            temp_data[:, 1, :, :, :] = data[1::2, :, :, :]
            return Unk(ik, temp_data)
        return Unk(ik, data)
Beispiel #12
0
    def export_unk(self, grid=[50, 50, 50]):
        '''
        Export the periodic part of BF in a real space grid for plotting with wannier90
        '''

        from scipy.io import FortranFile
        grids_coor = general_grid(self.cell, grid)

        for k_id in range(self.num_kpts_loc):
            kpt = self.cell.get_abs_kpts(self.kpt_latt_loc[k_id])
            ao = numint.eval_ao(self.cell, grids_coor, kpt=kpt)
            u_ao = np.einsum('x,xi->xi',
                             np.exp(-1j * np.dot(grids_coor, kpt)),
                             ao,
                             optimize=True)
            unk_file = FortranFile('UNK0000' + str(k_id + 1) + '.1', 'w')
            unk_file.write_record(
                np.asarray(
                    [grid[0], grid[1], grid[2], k_id + 1, self.num_bands_loc],
                    dtype=np.int32))
            mo_included = np.dot(
                self.U[k_id],
                self.mo_coeff_kpts[k_id])[:, self.band_included_list]
            u_mo = np.einsum('xi,in->xn', u_ao, mo_included, optimize=True)
            for band in range(len(self.band_included_list)):
                unk_file.write_record(
                    np.asarray(u_mo[:, band], dtype=np.complex))
            unk_file.close()
Beispiel #13
0
def getstep(filenumber, DIR=' '):
    if DIR == ' ':
        filename = 'Data/step' '{:03d}'.format(filenumber) + '.dat'
    else:
        filename = DIR + 'step' + '{:03d}'.format(filenumber) + '.dat'
    file = FortranFile(filename, 'r')
    return file.read_ints(np.int32)[0]
Beispiel #14
0
def fits_to_unformatted(
  input_filename, output_filename, omega_m
):
  # define cosmology
  cosmo = Cosmology(omega_m=omega_m)

  # open fits file
  with fits.open(input_filename) as hdul:
    cat = hdul[1].data

  # convert redshifts to distances
  dist = cosmo.ComovingDistance(cat['Z'])
  x = dist * np.sin(cat['DEC'] * np.pi / 180) * np.cos(cat['RA'] * np.pi / 180)
  y = dist * np.sin(cat['DEC'] * np.pi / 180) * np.sin(cat['RA'] * np.pi / 180)
  z = dist * np.cos(cat['DEC'] * np.pi / 180)

  # write result to output file
  cout = np.c_[x, y, z]
  nrows, ncols = np.shape(cout)
  f = FortranFile(output_filename, 'w')
  nrows, ncols = np.shape(cout)
  f.write_record(nrows)
  f.write_record(ncols)
  f.write_record(cout)
  f.close()
Beispiel #15
0
def test_fortranfiles_write():
    for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
        m = re.search('fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
        if not m:
            raise RuntimeError("Couldn't match %s filename to regex" %
                               filename)
        dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))

        counter = 0
        data = np.zeros(dims, dtype=m.group(1))
        for k in range(dims[2]):
            for j in range(dims[1]):
                for i in range(dims[0]):
                    data[i, j, k] = counter
                    counter += 1
        tmpdir = tempfile.mkdtemp()
        try:
            testFile = path.join(tmpdir, path.basename(filename))
            f = FortranFile(testFile, 'w', '<u4')
            f.write_record(data)
            f.close()
            originalfile = open(filename, 'rb')
            newfile = open(testFile, 'rb')
            assert_equal(originalfile.read(), newfile.read(), err_msg=filename)
            originalfile.close()
            newfile.close()
        finally:
            shutil.rmtree(tmpdir)
Beispiel #16
0
    def export_unk(self, grid=[50, 50, 50]):
        '''
        Export the periodic part of BF in a real space grid for plotting with wannier90
        '''

        from scipy.io import FortranFile
        grids_coor, weights = periodic_grid(self.cell, grid, order='F')

        for k_id in range(self.num_kpts_loc):
            spin = '.1'
            if self.spin_up != None and self.spin_up == False: spin = '.2'
            kpt = self.cell.get_abs_kpts(self.kpt_latt_loc[k_id])
            ao = numint.eval_ao(self.cell, grids_coor, kpt=kpt)
            u_ao = np.einsum('x,xi->xi',
                             np.exp(-1j * np.dot(grids_coor, kpt)),
                             ao,
                             optimize=True)
            unk_file = FortranFile('UNK' + "%05d" % (k_id + 1) + spin, 'w')
            unk_file.write_record(
                np.asarray(
                    [grid[0], grid[1], grid[2], k_id + 1, self.num_bands_loc],
                    dtype=np.int32))
            mo_included = self.mo_coeff_kpts[k_id][:, self.band_included_list]
            u_mo = np.einsum('xi,in->xn', u_ao, mo_included, optimize=True)
            for band in range(len(self.band_included_list)):
                unk_file.write_record(
                    np.asarray(u_mo[:, band], dtype=np.complex128))
            unk_file.close()
Beispiel #17
0
    def __init__(self, seedname='wannier90', formatted=False, suffix='sHu'):
        print("----------\n  {0}   \n---------".format(suffix))

        if formatted:
            f_sXu_in = open(seedname + "." + suffix, 'r')
            header = f_sXu_in.readline().strip()
            NB, NK, NNB = (int(x) for x in f_sXu_in.readline().split())
        else:
            f_sXu_in = FortranFile(seedname + "." + suffix, 'r')
            header = readstr(f_sXu_in)
            NB, NK, NNB = f_sXu_in.read_record('i4')

        print("reading {}.{} : <{}>".format(seedname, suffix, header))

        self.data = np.zeros((NK, NNB, NB, NB, 3), dtype=complex)

        for ik in range(NK):
            #            print ("k-point {} of {}".format( ik+1,NK))
            for ib2 in range(NNB):
                for ipol in range(3):
                    tmp = f_sXu_in.read_record('f8').reshape(
                        (2, NB, NB), order='F').transpose(2, 1, 0)
                    self.data[ik, ib2, :, :,
                              ipol] = tmp[:, :, 0] + 1j * tmp[:, :, 1]
        print("----------\n {0} OK  \n---------\n".format(suffix))
        f_sXu_in.close()
Beispiel #18
0
 def read_patch(self, file, verbose=0):
     ''' Read particles in a patch '''
     name = file + '.peb'
     f = FortranFile(name, 'rb')
     fmt = f.readInts()
     if verbose > 2:
         print('ioformat:', fmt[0])
     dim = f.readInts()
     dim = dim[0:2]
     a = f.readReals()
     a = a.reshape(dim[1], dim[0]).transpose()
     idv = f.readInts()
     idx = idv[0:dim[0]]
     f.close()
     dict = {}
     for i in range(size(idx)):
         id = idx[i]
         dict[id] = {
             'p': a[i, 0:3],
             'v': a[i, 0:3],
             't': a[i, 6],
             's': a[i, 7],
             'w': a[i, 8]
         }
     return idx, dict
Beispiel #19
0
    def __read_phiaver(self,
                       datadir,
                       variables,
                       aver_file_name,
                       n_vars,
                       var_index,
                       iter_list,
                       precision='f',
                       l_h5=False):
        """
        Read the PHIAVG file
        Return the time, cylindrical r and z and raw data.
        """

        import os
        import numpy as np
        from scipy.io import FortranFile
        from pencil import read

        # Read the data
        if l_h5:
            import h5py
            #
            # Not implemented
            #
        else:
            glob_dim = read.dim(datadir)
            nu = glob_dim.nx / 2
            nv = glob_dim.nz

            dim = read.dim(datadir)
            if dim.precision == 'S':
                read_precision = np.float32
            if dim.precision == 'D':
                read_precision = np.float64

            # Prepare the raw data.
            raw_data = []
            t = []

            # Read records
            #path=os.path.join(datadir, aver_file_name)
            #print(path)
            file_id = FortranFile(os.path.join(datadir, aver_file_name))

            data1 = file_id.read_record(dtype='i4')
            nr_phiavg = data1[0]
            nz_phiavg = data1[1]
            nvars = data1[2]
            nprocz = data1[3]

            data2 = file_id.read_record(dtype=read_precision).astype(precision)
            t = data2[0]
            r_cyl = data2[1:nr_phiavg + 1]
            z_cyl = data2[nr_phiavg + 1:nr_phiavg + nz_phiavg + 1]

            data3 = file_id.read_record(dtype=read_precision).astype(precision)
            raw_data = data3.reshape(nvars, nz_phiavg, nr_phiavg)

            return t, r_cyl, z_cyl, raw_data
Beispiel #20
0
def read_fortran_file(filename: Union[str, Path]) -> np.ndarray:
    with FortranFile(str(filename), 'r') as f:
        [t, gamma] = f.read_reals('f4')
        [nx, ny, nvar, nstep] = f.read_ints('i')
        dat = f.read_reals('f4')
    dat = np.array(dat)
    return dat.reshape(nvar, ny, nx)
Beispiel #21
0
def siesta_read_coefficients(filename, debug=0):
    """
    This routine reads siesta eigenvectors from MyM.WFSX binary
    using the FortranFile magical binary reader
    and returns an array with the following dimensions:
    1) the k-point index
    2) the spin index
    3) the state index (nwflist)
    4) the coefficient for each basis set index (nuotot)
    
    """

    f = FortranFile("%s.WFSX" % filename)
    nk, gamma = f.read_ints()
    if debug: print "nk, gamma  = ", nk, gamma
    nspin = int(f.read_ints())
    if debug: print "nspin =", nspin
    nuotot = int(f.read_ints())
    if debug: print "nuotot =", nuotot
    bla = f.read_record([('orbital_pos', 'i4'), ('b', '20S'), ('c', 'i4'),
                         ('d', 'i4'), ('e', '20S')])
    orbital_pos = np.array(bla['orbital_pos'] - 1, dtype=np.int)
    psi = np.zeros((nk, nspin, nuotot, nuotot))
    psi = psi + 0j
    #separate condition for gamma point since the array is real
    if bool(gamma) == True:
        for iispin in range(1, nspin + 1):  #for each spin
            f.read_record('f')
            ispin = int(f.read_ints())
            nwflist = int(f.read_ints())
            for iw in range(1, nwflist + 1):
                # for each state (nwflist = total number of states)
                indwf = f.read_ints()
                # we first read the energy of the state
                energy = f.read_reals('d')
                # and all the orbital coefficients
                read_psi = f.read_reals('f')
            read_psi = np.reshape(read_psi, (nuotot, 1))
            psi[0, iispin - 1, iw - 1, :] = read_psi[:, 0]
    else:
        for iik in range(1, nk + 1):  #for each k-point
            for iispin in range(1, nspin + 1):  #for each spin
                f.read_record('f')
                ispin = int(f.read_ints())
                nwflist = int(f.read_ints())
                for iw in range(1, nwflist + 1):
                    # for each state (nwflist = total number of states)
                    indwf = f.read_ints()
                    # we first read the energy of the state
                    energy = f.read_reals('d')
                    # and all the orbital coefficients (real value, followed by the imaginary value
                    read_psi = f.read_reals('f')
                    if debug:
                        print "nutot", nuotot, 'len(read_psi)', len(read_psi)
                    read_psi = np.reshape(read_psi, (nuotot, 2))  # reshape it
                    # and make a row of complex numbers
                    psi[iik - 1, iispin - 1,
                        iw - 1, :] = read_psi[:, 0] + 1j * read_psi[:, 1]
    return psi, orbital_pos
Beispiel #22
0
    def get_circumcentres(self, radius_limit=1000):
        '''
        Find the centre of the circumspheres
        associated to an input catalogue of
        tetrahedra.
        '''

        print('Finding circumcentres of tetrahedra...')
        vertices = self.delaunay_triangulation()
        cenx, ceny, cenz, r = [], [], [], []

        sing = 0
        for tetra in vertices:
            x0, x1, x2, x3 = tetra
            A = []
            B = []
            A.append((x1 - x0).T)
            A.append((x2 - x0).T)
            A.append((x3 - x0).T)
            A = np.asarray(A)
            B = np.sum(A**2, axis=1)
            B = np.asarray(B)
            try:
                C = np.linalg.inv(A).dot(B)
            except:
                sing += 1
                continue
            centre = x0 + 0.5 * C
            radius = 0.5 * np.sqrt(np.sum(C**2))
            if radius < radius_limit:
                cenx.append(centre[0])
                ceny.append(centre[1])
                cenz.append(centre[2])
                r.append(radius)

        print('{} singular matrices found.'.format(sing))

        cenx = np.asarray(cenx)
        ceny = np.asarray(ceny)
        cenz = np.asarray(cenz)

        cenx = cenx.reshape(len(cenx), 1)
        ceny = ceny.reshape(len(ceny), 1)
        cenz = cenz.reshape(len(cenz), 1)

        cout = np.hstack([cenx, ceny, cenz])

        print('{} centres found.'.format(len(cout)))

        f = FortranFile(self.centres_file, 'w')
        nrows, ncols = np.shape(cout)
        f.write_record(nrows)
        f.write_record(ncols)
        f.write_record(cout)
        f.close()

        self.centres = cout

        return
Beispiel #23
0
    def __init__(self, seedname):
        seedname = seedname.strip()
        FIN = FortranFile(seedname + '.chk', 'r')
        readint = lambda: FIN.read_record('i4')
        readfloat = lambda: FIN.read_record('f8')

        def readcomplex():
            a = readfloat()
            return a[::2] + 1j * a[1::2]

        print('Reading restart information from file ' + seedname + '.chk :')
        self.comment = readstr(FIN)
        self.num_bands = readint()[0]
        num_exclude_bands = readint()[0]
        self.exclude_bands = readint()
        assert len(self.exclude_bands) == num_exclude_bands
        self.real_lattice = readfloat().reshape((3, 3), order='F')
        self.recip_lattice = readfloat().reshape((3, 3), order='F')
        assert np.linalg.norm(
            self.real_lattice.dot(self.recip_lattice.T) /
            (2 * np.pi) - np.eye(3)) < 1e-14
        self.num_kpts = readint()[0]
        self.mp_grid = readint()
        assert len(self.mp_grid) == 3
        assert self.num_kpts == np.prod(self.mp_grid)
        self.kpt_latt = readfloat().reshape((self.num_kpts, 3))
        self.nntot = readint()[0]
        self.num_wann = readint()[0]
        self.checkpoint = readstr(FIN)
        self.have_disentangled = bool(readint()[0])
        if self.have_disentangled:
            self.omega_invariant = readfloat()[0]
            lwindow = np.array(readint().reshape(
                (self.num_kpts, self.num_bands)),
                               dtype=bool)
            ndimwin = readint()
            u_matrix_opt = readcomplex().reshape(
                (self.num_kpts, self.num_wann, self.num_bands))
            self.win_min = np.array(
                [np.where(lwin)[0].min() for lwin in lwindow])
            self.win_max = np.array(
                [wm + nd for wm, nd in zip(self.win_min, ndimwin)])
        else:
            self.win_min = np.array([0] * self.num_kpts)
            self.win_max = np.array([self.num_wann] * self.num_kpts)

        u_matrix = readcomplex().reshape(
            (self.num_kpts, self.num_wann, self.num_wann))
        m_matrix = readcomplex().reshape(
            (self.num_kpts, self.nntot, self.num_wann, self.num_wann))
        if self.have_disentangled:
            self.v_matrix = [
                u.dot(u_opt[:, :nd])
                for u, u_opt, nd in zip(u_matrix, u_matrix_opt, ndimwin)
            ]
        else:
            self.v_matrix = [u for u in u_matrix]
        self.wannier_centres = readfloat().reshape((self.num_wann, 3))
        self.wannier_spreads = readfloat().reshape((self.num_wann))
Beispiel #24
0
def test_fortranfiles_mixed_record():
    filename = path.join(DATA_PATH, "fortran-mixed.dat")
    f = FortranFile(filename, 'r', '<u4')
    record = f.read_record('<i4,<f4,<i8,(2)<f8')
    assert_equal(record['f0'][0], 1)
    assert_allclose(record['f1'][0], 2.3)
    assert_equal(record['f2'][0], 4)
    assert_allclose(record['f3'][0], [5.6, 7.8])
Beispiel #25
0
 def applicable(cls, filename: Path) -> bool:
     _, u4_type = dtypes(config.input_endianness)
     try:
         with FortranFile(filename, 'r', header_dtype=u4_type) as f:
             assert f._read_size() == 6 * 4
         return True
     except:
         return False
Beispiel #26
0
def getErrors(kind):

    index = np.s_[:, :, 0] if kind == 'phi' else np.s_[:, :, :]

    with FortranFile('src/10pinreference_{}.bin'.format(kind), 'r') as f:
        ref = f.read_reals(dtype=np.float).reshape(280, -1, 8)[index]

    full_err = []
    mox_err = []
    uo2_err = []
    comp_err = []

    for i in range(85):
        with FortranFile(
                'klt_full_7/10pin_dgm_7g_full_{}_{}.bin'.format(i + 1, kind),
                'r') as f:
            full_err.append(
                computeError(
                    ref,
                    f.read_reals(dtype=np.float).reshape(280, -1, 8)[index]))
        with FortranFile(
                'klt_mox_7/10pin_dgm_7g_mox_{}_{}.bin'.format(i + 1, kind),
                'r') as f:
            mox_err.append(
                computeError(
                    ref,
                    f.read_reals(dtype=np.float).reshape(280, -1, 8)[index]))
        with FortranFile(
                'klt_uo2_7/10pin_dgm_7g_uo2_{}_{}.bin'.format(i + 1, kind),
                'r') as f:
            uo2_err.append(
                computeError(
                    ref,
                    f.read_reals(dtype=np.float).reshape(280, -1, 8)[index]))
        with FortranFile(
                'klt_combine_7/10pin_dgm_7g_combine_{}_{}.bin'.format(
                    i + 1, kind), 'r') as f:
            comp_err.append(
                computeError(
                    ref,
                    f.read_reals(dtype=np.float).reshape(280, -1, 8)[index]))

    np.savetxt('full_err_{}'.format(kind), np.array(full_err))
    np.savetxt('mox_err_{}'.format(kind), np.array(mox_err))
    np.savetxt('uo2_err_{}'.format(kind), np.array(uo2_err))
    np.savetxt('comp_err_{}'.format(kind), np.array(comp_err))
Beispiel #27
0
 def __init__(self, filename, itype, newResults=[]):
     self.mesh = Mesh()
     self.newResults = newResults
     #    print(self.newResults)
     self.filename = filename
     self.itype = itype
     self.intType = 'i4'
     self.f = FortranFile(filename)
     try:
         self.defGeneralVars()
     except ValueError:
         self.f.close()
         self.f = FortranFile(filename)
         self.intType = 'i8'
         self.defGeneralVars()
     self.readGeom()
     self.getTypeAndNnodePerElement()
Beispiel #28
0
def writef90map(fname, d1):
    """
    Save data to a fortran file
    """
    f = FortranFile(fname, 'w')
    #f.write_record(np.int16(dim))
    f.write_record(np.float64(d1))
    f.close()
Beispiel #29
0
def read_fortran_bin(fname):
    ff = FortranFile(fname)
    data = []
    while True:
        try:
            data.append(ff.read_reals(dtype=np.float64))
        except:
            break
    return np.array(data)
Beispiel #30
0
def read(self,
         name,
         tracdir,
         tracfile,
         varnames,
         dates,
         interpol_flx=False,
         **kwargs):
    """Get fluxes from pre-computed fluxes and load them into a pycif
    variables

    Args:
        self: the model Plugin
        name: the name of the component
        tracdir, tracfile: flux directory and file format
        dates: list of dates to extract
        interpol_flx (bool): if True, interpolates fluxes at time t from
        values of surrounding available files

    """

    list_file_flx = [dd.strftime(tracfile) for dd in dates]

    trcr_dates = []
    trcr_flx = []
    trcr_flx_tl = []
    for dd, file_flx in zip(dates, list_file_flx):
        # Read binary file
        data = []

        with FortranFile("{}/{}".format(tracdir, file_flx)) as f:
            while True:
                try:
                    data.append(f.read_reals())

                except BaseException:
                    info("End of file {}".format(file_flx))
                    break

        # Reshape file
        nlon = self.domain.nlon
        nlat = self.domain.nlat

        data = np.array(data)

        flx = data[:, 0].reshape((-1, nlat, nlon))
        flx_tl = data[:, 1].reshape((-1, nlat, nlon))

        trcr_flx.append(flx)
        trcr_flx_tl.append(flx_tl)
        trcr_dates.extend(list(pd.date_range(dd, freq="D", periods=len(flx))))

    xmod = xr.DataArray(trcr_flx[0],
                        coords={"time": trcr_dates},
                        dims=("time", "lat", "lon"))

    return xmod