def __init_espresso(self, prefix, ik, IBstart, IBend, Ecut, Ecut0, kptxml, thresh=1e-4): self.K = np.array(kptxml.find("k_point").text.split(), dtype=float) eigen = np.array(kptxml.find("eigenvalues").text.split(), dtype=float) self.Energy = eigen[IBstart:IBend] * Hartree_eV try: self.upper = eigen[IBend] * Hartree_eV except: self.upper = np.NaN npw = int(kptxml.find("npw").text) # kg= np.random.randint(100,size=(npw,3))-50 npwtot = npw * (2 if self.spinor else 1) CG = np.zeros((IBend - IBstart, npwtot), dtype=complex) try: fWFC = FF("{}.save/WFC{}.dat".format(prefix, ik + 1), "r") except FileNotFoundError: fWFC = FF("{}.save/wfc{}.dat".format(prefix, ik + 1), "r") rec = record_abinit(fWFC, 'i4,3f8,i4,i4,f8')[0] # print ('rec=',rec) ik, xk, ispin, gamma_only, scalef = rec # xk/=bohr # xk=xk.dot(np.linalg.inv(RecLattice)) rec = record_abinit(fWFC, '4i4') # print ('rec=',rec) ngw, igwx, npol, nbnd = rec rec = record_abinit(fWFC, '(3,3)f8') # print ('rec=',rec) B = np.array(rec) # print (np.mean(B/RecLattice)) self.K = xk.dot(np.linalg.inv(B)) rec = record_abinit(fWFC, '({},3)i4'.format(igwx)) # print ('rec=',rec) kg = np.array(rec) # print (np.mean(B/RecLattice)) # print ("k-point {0}: {1}/{2}={3}".format(ik, self.K,xk,self.K/xk)) # print ("k-point {0}: {1}".format(ik,self.K )) for ib in range(IBend): cg_tmp = record_abinit(fWFC, '{}f8'.format(npwtot * 2)) if ib >= IBstart: CG[ib - IBstart] = cg_tmp[0::2] + 1.j * cg_tmp[1::2] return self.__sortIG(kg, self.K, CG, B, Ecut0, Ecut, thresh=thresh)
def __getMat(self, suffix): f = FF(self.seedname + "_" + suffix + "_R" + (".dat" if self.old_format else "")) MM_R = np.array([[ np.array(f.read_record('2f8'), dtype=float) for m in range(self.num_wann) ] for n in range(self.num_wann)]) MM_R = MM_R[:, :, :, 0] + 1j * MM_R[:, :, :, 1] f.close() ncomp = MM_R.shape[2] / self.nRvec0 if ncomp == 1: result = MM_R / self.Ndegen[None, None, :] elif ncomp == 3: result = MM_R.reshape( self.num_wann, self.num_wann, 3, self.nRvec0).transpose( 0, 1, 3, 2) / self.Ndegen[None, None, :, None] elif ncomp == 9: result = MM_R.reshape( self.num_wann, self.num_wann, 3, 3, self.nRvec0).transpose( 0, 1, 4, 3, 2) / self.Ndegen[None, None, :, None, None] else: raise RuntimeError( "in __getMat: invalid ncomp : {0}".format(ncomp)) if self.ws_map is None: return result else: return self.ws_map(result)
def read_one_cpu(output): f = FF(output) ncpu = f.read_ints() ndim = f.read_ints() npart = f.read_ints() localseed = f.read_ints() nstart_tot = f.read_ints() mstar_tot = f.read_ints() mstart_lost = f.read_ints() nsink = f.read_ints() x = np.zeros((ndim, npart), dtype=float) v = np.zeros((ndim, npart), dtype=float) m = np.zeros((npart), dtype=float) ind = np.zeros((npart), dtype=int) for dim in range(ndim): x[dim] = f.read_reals() for dim in range(ndim): v[dim] = f.read_reals() m = f.read_reals() ind = f.read_ints() lvl = f.read_ints() try: tp = f.read_reals() Z = f.read_reals() except TypeError: tp = np.zeros((npart)) Z = np.zeros((npart)) return ind, ndim, npart, x, v, m, lvl, tp, Z
def __init__(self, normalcar='NormalCAR', wavecar='WAVECAR'): """ Initialize the class with supplied file name (including path) Only the records untile projector coefficients are read for initialize projector coefficients will only be read when explicitly invoked. Args: fnm (optional): NormalCAR filename (including path) Returns: None Raise: IOError if encounter problems reading NormalCAR ValueError if inconsistent record/info read Note: All 'private' members or attributes (starts with single underline) have names following the nice VASP style... with each has a corresponding a callable getXXX() method, where XXX might be easily understood... """ self._normalcar = normalcar self._wavecar = wavecar try: self._fh = FF(self._normalcar, 'r') except: raise IOError("Failed to open NormalCAR file: {}".format( self._fnm)) # rec 1 self._LMDIM, self._NIONS, self._NRSPINORS = FF.read_ints(self._fh) # rec 2 self._CQIJ = FF.read_reals(self._fh) dump = self._LMDIM * self._LMDIM * self._NIONS * self._NRSPINORS if len(self._CQIJ) != dump: raise ValueError( "Inconsistent dimension for CQIJ:\n" "\t# floats intend to read: {}\n\t# floats in this record". format(dump, len(self._CQIJ))) self._CQIJ = self._CQIJ.reshape( [self._LMDIM, self._LMDIM, self._NIONS, self._NRSPINORS], order='F') del dump # rec 3 self._NPROD, self._NPRO, self._NTYP = FF.read_ints(self._fh) # rec 4 ... 3 + NTypes self._LMMAX = [] for i in range(self._NTYP): self._LMMAX.append(FF.read_ints(self._fh)) self._LMMAX = np.array(self._LMMAX) self._NPROJ = np.sum(self._LMMAX[:, 0] * self._LMMAX[:, 1]) # read wavefunction stuff, number of kpts and bands _WC = wf.WAVECAR(self._wavecar) self._NK = _WC.getNKpts() self._NB = _WC.getNBands()
def test_halo_particle_ids(halos): with FF(halos._fname, mode="r") as f: for halo_id in range(1, len(halos) + 1): # Manually read the particle ids and make sure pynbody is reading them as it should f._fp.seek(halos[halo_id].properties["file_offset"]) f.read_ints() # number of particles expected_members = f.read_ints("i") # halo members np.testing.assert_equal(expected_members, halos[halo_id].properties["members"])
def __init_wannier(self, NBin, IBstart, IBend, Ecut, kpt, eigenval, thresh=1e-4): self.K = np.array(kpt, dtype=float) self.Energy = eigenval[IBstart:IBend] fname = "UNK{:05d}.{}".format(self.ik0, 'NC' if self.spinor else "1") fUNK = FF(fname, "r") ngx, ngy, ngz, ik, nbnd = record_abinit(fUNK, 'i4,i4,i4,i4,i4')[0] ngtot = ngx * ngy * ngz if ik != self.ik0: raise RuntimeError( "file {} contains point number {}, expected {}".format( fname, ik, self.ik0)) if nbnd != NBin: raise RuntimeError( "file {} contains {} bands , expected {}".format( fname, nbnd, NBin)) nspinor = 2 if self.spinor else 1 try: self.upper = eigenval[IBend] except: self.upper = np.NaN ig = calc_gvectors(self.K, self.RecLattice, Ecut, spinor=self.spinor, nplanemax=np.max([ngx, ngy, ngz]) // 2) selectG = tuple(ig[0:3]) def _readWF_1(skip=False): cg_tmp = record_abinit(fUNK, '{}f8'.format(ngtot * 2)) if skip: return np.array([0], dtype=complex) cg_tmp = (cg_tmp[0::2] + 1.j * cg_tmp[1::2]).reshape( (ngx, ngy, ngz), order='F') cg_tmp = np.fft.fftn(cg_tmp) return cg_tmp[selectG] def _readWF(skip=False): return np.hstack([_readWF_1(skip) for i in range(nspinor)]) for ib in range(IBstart): _readWF(skip=True) WF = np.array([_readWF(skip=False) for ib in range(IBend - IBstart)]) return WF, ig
def write_mock_clus(vx, vy, vz, it, digits=5, path=''): with FF(os.path.join(path, masclet.read_masclet.filename(it, 'b', digits)), 'w') as clus: clus.write_record(np.array([it, 0, 0, 0]).astype('i4')) #first line # base level clus.write_record(np.array([0]).astype('i4')) clus.write_record(vx[0].T.astype('f4')) clus.write_record(vy[0].T.astype('f4')) clus.write_record(vz[0].T.astype('f4')) for i in range(6): clus.write_record(np.array([0]).astype('i4')) # refinement levels for vxi, vyi, vzi in zip(vx[1:], vy[1:], vz[1:]): clus.write_record(np.array([0]).astype('i4')) clus.write_record(vxi.T.astype('f4')) clus.write_record(vyi.T.astype('f4')) clus.write_record(vzi.T.astype('f4')) for i in range(7): clus.write_record(np.array([0]).astype('i4'))
def read(fname: PathType) -> IOResult: """Read a grafic file. Parameters ---------- fname : str, filename """ try: aexp = float(fname.split("-")[-1].replace(".dat", "")) except ValueError: aexp = 1 with FF(fname, "r") as f: N1, N2, N3, qq, Xc1, Xc2, Xc3, Omega_m, Omega_c, Omega_l, H = f.read_record( *["i"] * 3, *["f"] * 8 ) Lbox = qq * Xc1 * H / 100 Lbox /= 1000 # Gpc Lbox = float(Lbox) N1, N2, N3 = (int(_) for _ in (N1, N2, N3)) Xc = np.stack((Xc1, Xc2, Xc3)).flatten() dens = np.zeros((N1, N2, N3), dtype="f") for i in range(N1): dens[i] = f.read_reals("f").reshape(N2, N3) return IOResult( data=dict(rho=dens), metadata=dict( Lbox=Lbox, Omega_m=Omega_m, Omega_c=Omega_c, Omega_l=Omega_l, Xc=Xc, aexp=aexp, N=N1, ), )
def __init__(self, fname): self.fWFK = FF(fname, "r") fWFK = self.fWFK record = fWFK.read_record('a6,2i4') # print (record) stdout.flush() codsvn = record[0][0].decode('ascii') headform, fform = record[0][1] defversion = '8.6.3 ' if not (codsvn == defversion): print("WARNING, the version {0} of abinit is not {1}".format( codsvn, defversion)) if headform < 80: raise ValueError( "Head form {0}<80 is not supported".format(headform)) record = fWFK.read_record('18i4,19f8,4i4')[0] # write(unit=header) codvsn,headform,fform # write(unit=header) bantot,date,intxc,ixc,natom,ngfft(1:3),& # & nkpt,nspden,nspinor,nsppol,nsym,npsp,ntypat,occopt,pertcase,usepaw,& # & ecut,ecutdg,ecutsm,ecut_eff,qptn(1:3),rprimd(1:3,1:3),stmbias,tphysel,tsmear,usewvl, #hdr%nshiftk_orig, hdr%nshiftk, hdr%mband # print (record) self.rprimd = record[1][7:16].reshape((3, 3)) # print (self.rprimd) self.ecut = record[1][0] * Hartree_eV print("ecut={0} eV".format(self.ecut)) stdout.flush() bandtot, self.natom, self.nkpt, nsym, npsp, nsppol, ntypat, self.usepaw, nspinor = np.array( record[0])[[0, 4, 8, 12, 13, 11, 14, 17, 10]] if nsppol != 1: raise RuntimeError( "Only nsppol=1 is supported. found {0}".format(nsppol)) if nspinor == 2: self.spinor = True elif nspinor == 1: self.spinor = False else: raise RuntimeError( "Unexpected value nspinor = {0}".format(nspinor)) #if usepaw==1: raise ValueError("usepaw==1 not implemented") nshiftk_orig = record[2][1] nshiftk = record[2][2] #print (bandtot,natom,nkpt,nsym,npsp,nsppol,ntypat) record = fWFK.read_record( '{nkpt}i4,{n2}i4,{nkpt}i4,{npsp}i4,{nsym}i4,({nsym},3,3)i4,{natom}i4,({nkpt},3)f8,{bandtot}f8,({nsym},3)f8,{ntypat}f8,{nkpt}f8' .format(nkpt=self.nkpt, n2=self.nkpt * nsppol, npsp=npsp, nsym=nsym, natom=self.natom, bandtot=bandtot, ntypat=ntypat))[0] #print (record) # write(unit=header) istwfk(1:nkpt),nband(1:nkpt*nsppol),& # & npwarr(1:nkpt),so_psp(1:npsp),symafm(1:nsym),symrel(1:3,1:3,1:nsym),typat(1:natom),& # & kpt(1:3,1:nkpt),occ(1:bantot),tnons(1:3,1:nsym),znucltypat(1:ntypat),wtk(1:nkpt) # wtk=record[11] self.npwarr = record[2] istwfk = record[0] if set(istwfk) != {1}: raise ValueError( "istwfk should be 1 for all kpoints. found {0}".format(istwfk)) self.typat = record[6] self.kpt = record[7] self.nband = record[1] assert (np.sum(self.nband) == bandtot) #print (kpt,nband) record = fWFK.read_record('f8,({natom},3)f8,f8,f8,{ntypat}f8'.format( natom=self.natom, ntypat=ntypat))[0] self.xred = record[1] self.efermi = record[3] # write(unit,err=10, iomsg=errmsg) hdr%residm, hdr%xred(:,:), hdr%etot, hdr%fermie, hdr%amu(:) #print (record) record = fWFK.read_record( "i4,i4,f8,f8,i4,(3,3)i4,(3,3)i4,({nshiftkorig},3)f8,({nshiftk},3)f8" .format(nshiftkorig=nshiftk_orig, nshiftk=nshiftk))[0] #record=fWFK.read_record("i4,i4,f8,f8,i4,i4,(3,3)f8,5f8,i4".format(nshiftkorig=nshiftk_orig,nshiftk=nshiftk) )[0] ##record=fWFK.read_record("i4,i4,f8,f8,i4,9i4,9i4,6f8".format(nshiftkorig=nshiftk_orig,nshiftk=nshiftk) )[0] # write(unit,err=10, iomsg=errmsg) & # hdr%kptopt, hdr%pawcpxocc, hdr%nelect, hdr%charge, hdr%icoulomb,& # hdr%kptrlatt,hdr%kptrlatt_orig, hdr%shiftk_orig(:,1:hdr%nshiftk_orig),hdr%shiftk(:,1:hdr%nshiftk) #print (record) for ipsp in range(npsp): record = fWFK.read_record("a132,f8,f8,5i4,a32")[0] # read(unit, err=10, iomsg=errmsg) & # & hdr%title(ipsp), hdr%znuclpsp(ipsp), hdr%zionpsp(ipsp), hdr%pspso(ipsp), hdr%pspdat(ipsp), & # & hdr%pspcod(ipsp), hdr%pspxc(ipsp), hdr%lmn_size(ipsp), hdr%md5_pseudos(ipsp) # print (record) if self.usepaw == 1: record = fWFK.read_record('i4') # print(record) record = fWFK.read_record('f8')