def test_4d(self): """Read string""" ffile = os.path.join(self.tdir, 'fort.4') fb = FortranBinary(ffile) rec = next(fb) self.assertEqual(len(rec), 3) fb.close()
def test_4b(self): """Read string""" ffile = os.path.join(self.tdir, 'fort.4') fb = FortranBinary(ffile) rec = fb.find(b'ABC') self.assertIn(b'ABC', rec) fb.close()
def test_4c(self): """Read string""" ffile = os.path.join(self.tdir, 'fort.4') fb = FortranBinary(ffile) with self.assertRaises(ValueError): rec = fb.find(1.0) fb.close()
def test_1(self): """Read int, float integer, parameter :: n = 3 double precision x(n) x = (/ 1.0D0, 2.0D0, 3.0D0 /) open(1, file='fort.1', status='new', form='unformatted') write(1) n write(1) x close(1) end """ ffile = os.path.join(self.tdir, 'fort.1') fb = FortranBinary(ffile) # first record is int 3 next(fb) n = fb.readbuf(1, 'i')[0] self.assertEqual(n, 3) # first record is float 1. 2. 3. next(fb) xref = (1., 2., 3.) x = fb.readbuf(n, 'd') np.testing.assert_allclose(x, xref) fb.close()
def read(*args, **kwargs): """Read response vector given property""" if "freqs" in kwargs: # linear response/one frequency bfreqs = kwargs.get("freqs") else: # non-linear response/two frequencies bfreqs = kwargs.get("bfreqs", (0.0, )) cfreqs = kwargs.get("cfreqs", (0.0, )) propfile = kwargs.get("propfile", "RSPVEC") lr_vecs = kwargs.get("lr_vecs", False) rspvec = FortranBinary(propfile) vecs = {} for rec in rspvec: for lab in args: try: lab1 = bytes(lab.ljust(16), "utf-8") except TypeError: lab1 = bytes(lab.ljust(16)) # alternative label with permuted labels lab2 = lab1[8:] + lab1[:8] if lab1 in rec or lab2 in rec: if lab1 in rec: rec.read(16, "c") bfreq, cfreq = rec.read(2, "d") elif lab2 in rec: rec.read(16, "c") cfreq, bfreq = rec.read(2, "d") if bfreq in bfreqs and cfreq in cfreqs: _rec = next(rspvec) kzyvar = len(_rec) // 8 buffer_ = rspvec.readbuf(kzyvar, "d") vecs[(lab, bfreq, cfreq)] = \ np.array(buffer_).view(full.matrix) vecs[(lab1, bfreq, bfreq)] = vecs[(lab, bfreq, cfreq)] vecs[(lab2, cfreq, bfreq)] = vecs[(lab, bfreq, cfreq)] # now check that all required vectors are saved for _l in args: for b in bfreqs: for c in cfreqs: if (_l, b, c) not in vecs: raise RspVecError( "Response vector N(%s,%g,%g) not found on file %s" % (_l, b, c, propfile)) # complement dict with lr pointers if cfreqs == (0.0, ): vecs.update({(_l, b): vecs[(_l, b, 0.0)] for _l in args for b in bfreqs}) if bfreqs == (0.0, ): vecs.update({_l: vecs[(_l, 0.0, 0.0)] for _l in args}) if lr_vecs: keys = ((a, w) for a in args for w in bfreqs) return {k: vecs[k] for k in keys} else: return vecs
def __init__(self, name="SIRIFC"): self.name = name self.file = FortranBinary(name) self._cmo = None self._dv = None self._pv = None self._fock = None self._fc = None self._fv = None self._orbdiag = None if not self.file.find(self.ifclabel): raise RuntimeError("Label %s not found on %s" % (self.ifclabel, name)) rec = next(self.file) # Integer size from first record, 4 floats, 5 ints # 1) POTNUC,EMY,EACTIV,EMCSCF,ISTATE,ISPIN,NACTEL,LSYM,MS2 try: self.INT = get_intcode(len(rec), 4, 5) except KeyError: # pragma no cover # Allow Dalton 2013 version self.INT = get_intcode(len(rec), 4, 4) self.FLOAT = "d" self.potnuc, self.emy, self.eactive, self.emcscf = self.file.readbuf( 4, self.FLOAT) self.istate, self.ispin, self.nactel, self.lsym = \ self.file.readbuf(4, self.INT) self.file.next() self.nisht, self.nasht, self.nocct, self.norbt, self.nbast,\ self.nconf, self.nwopt, self.nwoph, self.ncdets,\ self.ncmot, self.nnashx, self.nnashy, self.nnorbt,\ self.n2orbt, self.nsym = \ self.file.readbuf(15, self.INT) self.muld2h = numpy.array(self.file.readbuf(64, self.INT)).reshape( (8, 8)) self.nrhf = numpy.array(self.file.readbuf(8, self.INT)) self.nfro = numpy.array(self.file.readbuf(8, self.INT)) self.nish = numpy.array(self.file.readbuf(8, self.INT)) self.nash = numpy.array(self.file.readbuf(8, self.INT)) self.norb = numpy.array(self.file.readbuf(8, self.INT)) self.nbas = numpy.array(self.file.readbuf(8, self.INT)) self.nelmn1, self.nelmx1, self.nelmn3, self.nelmx3, self.mctype = \ self.file.readbuf(5, self.INT) self.nas1 = numpy.array(self.file.readbuf(8, self.INT)) self.nas2 = numpy.array(self.file.readbuf(8, self.INT)) self.nas3 = numpy.array(self.file.readbuf(8, self.INT)) self.file.close() return
def test_4d_warn(self): """Read string""" ffile = os.path.join(self.tdir, 'fort.4') fb = FortranBinary(ffile) rec = next(fb) with pytest.deprecated_call(): l = fb.reclen fb.close()
def readisordk(filename="AOONEINT"): """Read data under label ISORDK in AOONEINT""" header = readhead(filename) INT = header["int_fmt"] FLOAT = header["float_fmt"] aooneint = FortranBinary(filename) aooneint.find("ISORDK") next(aooneint) next(aooneint) sizeofi = struct.calcsize(INT) sizeofd = struct.calcsize(FLOAT) mxcent_ = (len(aooneint.data) - sizeofi) // (4 * sizeofd) chrn_ = aooneint.readbuf(mxcent_, FLOAT) nucdep = aooneint.readbuf(1, INT)[0] cooo_ = aooneint.readbuf(3 * mxcent_, FLOAT) isordk_ = { # "table":table1, "chrn": chrn_, "nucdep": nucdep, "cooo": cooo_, } aooneint.close() return isordk_
def test_4(self): """Read string character*3 x x = 'ABC' open(4, file='fort.4', status='new', form='unformatted') write(4) x close(4) end """ ffile = os.path.join(self.tdir, 'fort.4') fb = FortranBinary(ffile) rec = fb.find('ABC') self.assertIn(b'ABC', rec)
def list_buffers(filename="AOTWOINT", label="BASTWOEL"): """ Return integral buffers in AOTWOINT""" _aofile = FB(filename) _aofile.find(label) for rec in _aofile: lbuf = (len(rec) - 4) // 12 buf = np.array(rec.read(lbuf, 'd')) ibuf = np.array(rec.read(4 * lbuf, 'B')).reshape(lbuf, 4) length = rec.read(1, 'i')[0] if length < 0: return yield buf[:length], ibuf[:length]
def info(filename="AOTWOINT"): """Extract info block BASINFO on AOTWOINT""" _aotwoint = FB(filename) _aotwoint.find("BASINFO") rec = next(_aotwoint) fileinfo = rec.read(12, 'i') retinfo = { "nsym": fileinfo[0], "nbas": fileinfo[1:9], "lbuf": fileinfo[9], "nibuf": fileinfo[10], "nbits": fileinfo[11] } return retinfo
def list_buffers(filename="AOTWOINT", label="BASTWOEL"): """ Return integral buffers in AOTWOINT""" _aofile = FB(filename) _aofile.find(label) for rec in _aofile: lbuf = (len(rec)-4) // 12 buf = np.array(rec.read(lbuf,'d')) ibuf = np.array(rec.read(4*lbuf,'B')).reshape(lbuf, 4) length = rec.read(1,'i')[0] if length < 0: return yield buf[:length], ibuf[:length]
def info(filename="AOTWOINT"): """Extract info block BASINFO on AOTWOINT""" _aotwoint = FB(filename) _aotwoint.find("BASINFO") rec = next(_aotwoint) fileinfo = rec.read(12,'i') retinfo = { "nsym":fileinfo[0], "nbas":fileinfo[1:9], "lbuf":fileinfo[9], "nibuf":fileinfo[10], "nbits":fileinfo[11] } return retinfo
def readall(property_label, propfile="RSPVEC"): """Read response all vectors given property""" import numpy _rspvec = FortranBinary(propfile) found = [] while _rspvec.find(property_label) is not None: _rspvec.rec.read(16, "c") vfreq = _rspvec.rec.read(1, "d")[0] _rec = next(_rspvec) kzyvar = len(_rec) // 8 buffer_ = _rspvec.readbuf(kzyvar, "d") mat = numpy.array(buffer_).view(full.matrix) found.append((mat, vfreq)) return found
def read(*args, **kwargs): """Read property integral""" propfile = kwargs.get("filename") if not propfile: tmpdir = pathlib.Path(kwargs.get("tmpdir", "/tmp")) propfile = tmpdir / "AOPROPER" unpack = kwargs.get("unpack", True) AOPROPER = FortranBinary(propfile) mat = {} for rec in AOPROPER: buf = rec.read(32, "c") # stars, data, symtype, label = ( # buf[:8], buf[8:16], buf[16:24], buf[24:32] # ) b"".join(buf[:8]) symtype = b"".join(buf[16:24]) blabel = b"".join(buf[24:32]).strip() bargs = (s.encode() for s in args) if blabel.strip() in bargs: label = blabel.decode() rec = next(AOPROPER) buffer_ = rec.read(len(rec) // 8, "d") if symtype == b"SQUARE ": n = int(round(math.sqrt(len(buffer_)))) mat[label] = full.init(buffer_).reshape((n, n)) else: mat[label] = np.array(buffer_).view(full.triangular) mat[label].anti = symtype == b"ANTISYMM" if unpack: return tuple([mat[lab].unpack() for lab in args]) else: return tuple([mat[lab] for lab in args])
def test_1_cm(self): """Case 1 with context manager""" ffile = os.path.join(self.tdir, 'fort.1') with FortranBinary(ffile) as fb: n = next(fb).read(1, 'i')[0] x = next(fb).read(n, 'd') np.testing.assert_allclose(x, (1., 2., 3.))
def test_2_cm(self): """ Case 2 with context manager """ ffile = os.path.join(self.tdir, 'fort.2') with FortranBinary(ffile) as fb: rec = fb.find(b'LABEL') self.assertEqual(rec.data, b'LABEL')
def ci(self): if self._ci is None: with FortranBinary(self.name) as fb: fb.find("STARTVEC") ci_record = next(fb) self._ci = numpy.array(ci_record.read( len(ci_record) // 8, "d")) return self._ci
def test_2_str(self): """ Case 2 with str method """ ffile = os.path.join(self.tdir, 'fort.2') with FortranBinary(ffile) as fb: rec = fb.find(b'LABEL') self.assertEqual(rec.data.decode('utf-8'), 'LABEL')
def test_3b(self): """Read vecs integer, parameter :: nx = 3, ny=3 double precision x(nx), y(ny) x = (/ 1.0D0, 2.0D0, 3.0D0 /) y = (/ 5.0D0, 6.0D0, 7.0D0 /) open(3, file='fort.3', status='new', form='unformatted') write(3) nx, ny write(3) x write(3) y close(3) end """ ffile = os.path.join(self.tdir, 'fort.3') fb = FortranBinary(ffile) # first record is int 3 fb.next() x = [] for rec in fb: x += list(fb.readbuf(3, 'd')) xref = (1., 2., 3., 5., 6., 7.) np.testing.assert_allclose(x, xref) fb.close()
def test_2(self): """Find and read label character*5 lab integer n lab = 'LABEL' n = 0 open(1, file='fort.2', status='new', form='unformatted') write(1) n write(1) lab close(1) end """ ffile = os.path.join(self.tdir, 'fort.2') fb = FortranBinary(ffile) rec = fb.find(b'LABEL') self.assertEqual(rec.data, b'LABEL') fb.close()
def orbdiag(self): """Get orbital Hessian diagonal""" if self._orbdiag is None: with FortranBinary(self.name) as fb: if fb.find("ORBDIAG"): rec = next(fb) self._orbdiag = rec.read(self.nwopt, self.FLOAT) else: raise LabelNotFound("ORBDIAG not found") return numpy.array(self._orbdiag)
def test_2b(self): """Handle label not found character*5 lab integer n lab = 'LABEL' n = 0 open(1, file='fort.2', status='new', form='unformatted') write(1) n write(1) lab close(1) end """ ffile = os.path.join(self.tdir, 'fort.2') fb = FortranBinary(ffile) rec = fb.find(b'NOLABEL') fb.close() self.assertEqual(rec, None)
def test_3b_cm(self): """Case 3b with context manager""" ffile = os.path.join(self.tdir, 'fort.3') with FortranBinary(ffile) as fb: fb.next() x = [] for rec in fb: x += list(fb.readbuf(3, 'd')) xref = (1., 2., 3., 5., 6., 7.) np.testing.assert_allclose(x, xref)
def __init__(self, name="SIRIUS.RST"): self.name = name with FortranBinary(name) as sirrst: sirrst.find(BasInfo.label) next(sirrst) self.nsym, = sirrst.readbuf(1, "i") self.nbas = numpy.array(sirrst.readbuf(8, "i"))[: self.nsym] self.norb = numpy.array(sirrst.readbuf(8, "i"))[: self.nsym] self.nrhf = numpy.array(sirrst.readbuf(8, "i"))[: self.nsym] self.ioprhf, = sirrst.readbuf(1, "i")
def readhead(filename="AOONEINT"): """Read data in header of AOONEINT""" aooneint = FortranBinary(filename) rec = next(aooneint) if len(aooneint.data) == 144: # # Newer versions: title in own record # title = aooneint.data.decode() # # Next record contains MAXREP... # rec = next(aooneint) else: # # Older versions: not supported # raise RuntimeError # # Buffer should now contains MAXREP data # FLOAT = "d" INT = _get_integer_format(rec) nsym = rec.read(1, INT)[0] naos = rec.read(nsym, INT) potnuc = rec.read(1, FLOAT)[0] import collections unlabeled = collections.OrderedDict( [ ("ttitle", title), ("nsym", nsym), ("naos", naos), ("potnuc", potnuc), ("int_fmt", INT), ("float_fmt", FLOAT), ] ) aooneint.close() return unlabeled
def dv(self): """Get active density matrix""" if self._dv is None: with FortranBinary(self.name) as fb: fb.find(self.ifclabel) for _ in range(5): fb.next() # mmashx = max(self.nnashx, 4) dbl = fb.readbuf(self.nnashx, self.FLOAT) self._dv = full.triangular.init(dbl) return self._dv
def read(label="OVERLAP", filename="AOONEINT"): """Read integral for label""" lbuf = 600 # # Initialize # unlabeled = readhead(filename) nsym = unlabeled["nsym"] nbas = unlabeled["naos"] INT = unlabeled["int_fmt"] FLOAT = unlabeled["float_fmt"] nnbast = 0 for nbasi in nbas: nnbast += nbasi * (nbasi + 1) // 2 s = full.matrix((nnbast, )) # # Open file, locate label # aooneint = FortranBinary(filename) aooneint.find(label) # # Loop over records # for rec in aooneint: buf = rec.read(lbuf, FLOAT) ibuf = rec.read(lbuf, INT) length, = rec.read(1, INT) if length < 0: break for i, b in zip(ibuf[:length], buf[:length]): s[i - 1] = b _S = blocked.triangular(nbas) off = 0 for isym in range(nsym): nbasi = nbas[isym] * (nbas[isym] + 1) // 2 _S.subblock[isym] = np.array(s[off:off + nbasi]).view(full.triangular) off += nbasi # aooneint.close() return _S
def test_3a(self): """Integer*8 dimensions integer*8, parameter :: nx = 3, ny=3 double precision x(nx), y(ny) x = (/ 1.0D0, 2.0D0, 3.0D0 /) y = (/ 5.0D0, 6.0D0, 7.0D0 /) open(3, file='fort.3', status='new', form='unformatted') write(3) nx, ny write(3) x write(3) y close(3) end """ ffile = os.path.join(self.tdir, 'fort.3') fb = FortranBinary(ffile) # first record is int 3, 3 nx, ny = fb.next().read('q', 2) np.testing.assert_allclose((nx, ny), (3, 3)) fb.close()
def test_3b(self): """Read vecs integer, parameter :: nx = 3, ny=3 double precision x(nx), y(ny) x = (/ 1.0D0, 2.0D0, 3.0D0 /) y = (/ 5.0D0, 6.0D0, 7.0D0 /) open(3, file='fort.3', status='new', form='unformatted') write(3) nx, ny write(3) x write(3) y close(3) end """ ffile = os.path.join(self.tdir, 'fort.3') fb = FortranBinary(ffile) # first record is int 3 fb.next() x=[] for rec in fb: x += list(fb.readbuf(3, 'd')) xref = (1., 2., 3., 5., 6., 7.) np.testing.assert_allclose(x, xref) fb.close()
def cmo(self): if self._cmo is None: with FortranBinary(self.name) as fb: fb.find("NEWORB") cmo_rec = next(fb) nbas = self.basinfo.nbas norb = self.basinfo.norb assert len(cmo_rec) // 8 == numpy.dot(nbas, norb) cmo = blocked.BlockDiagonalMatrix(self.basinfo.nbas, self.basinfo.norb) for nbasi, norbi, cmoi in zip(nbas, norb, cmo.subblock): cmoi[:, :] = (numpy.array(cmo_rec.read( nbasi * norbi, "d")).reshape( (nbasi, norbi), order="F").view(full.matrix)) self._cmo = cmo return self._cmo
def pv(self): """Get two-electron density""" if self._pv is None: with FortranBinary(self.name) as fb: fb.find(self.ifclabel) for i in range(7): fb.next() m2ashy = max(self.nnashx**2, 4) dbl = fb.readbuf(m2ashy, self.FLOAT) self._pv = full.matrix((self.nnashx, self.nnashx)) n = 0 for i in range(self.nnashx): for j in range(self.nnashx): self._pv[j, i] = dbl[n] n += 1 assert n == self.nnashx**2 return self._pv
def cmo(self): """Read MO coefficients""" if self._cmo is None: with FortranBinary(self.name) as fb: fb.find(self.ifclabel) for _ in range(3): fb.next() ncmot4 = max(self.ncmot, 4) dbl = fb.readbuf(ncmot4, self.FLOAT) n = 0 self._cmo = blocked.BlockDiagonalMatrix(self.nbas, self.norb) for isym in range(8): for mo in range(self.norb[isym]): for ao in range(self.nbas[isym]): self._cmo.subblock[isym][ao, mo] = dbl[n] n += 1 assert n == self.ncmot return self._cmo
def test_count_records_and_lengths(self): ffile = os.path.join(self.tdir, 'fort.3') fb = FortranBinary(ffile) self.assertTupleEqual(fb.record_byte_lengths(), (16, 24, 24)) fb.close()