Exemplo n.º 1
0
def test_load_txt_fixed():
    a = np.arange(10, dtype=np.int32).reshape((2, 5))
    fp = StringIO(dedent(u'''\
        01234X
        56789
    '''))
    fa = Util2d.load_txt(a.shape, fp, a.dtype, '(5I1)')
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    fp = StringIO(dedent(u'''\
        0123X
        4
        5678
        9
    '''))
    fa = Util2d.load_txt(a.shape, fp, a.dtype, '(4I1)')
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.array([[-1, 1, -2, 2, -3],
                  [3, -4, 4, -5, 5]], np.int32)
    fp = StringIO(dedent(u'''\
        -1 1-2 2-3
        3 -44 -55
    '''))
    fa = Util2d.load_txt(a.shape, fp, a.dtype, '(5I2)')
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype
Exemplo n.º 2
0
def test_load_txt_free():
    a = np.ones((10,), dtype=np.float32) * 250.0
    fp = StringIO(u'10*250.0')
    fa = Util2d.load_txt(a.shape, fp, a.dtype, '(FREE)')
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.arange(10, dtype=np.int32).reshape((2, 5))
    fp = StringIO(dedent(u'''\
        0 1,2,3, 4
        5 6, 7,  8 9
    '''))
    fa = Util2d.load_txt(a.shape, fp, a.dtype, '(FREE)')
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.ones((2, 5), dtype=np.float32)
    a[1, 0] = 2.2
    fp = StringIO(dedent(u'''\
        5*1.0
        2.2 2*1.0, +1E-00 1.0
    '''))
    fa = Util2d.load_txt(a.shape, fp, a.dtype, '(FREE)')
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype
Exemplo n.º 3
0
def test_load_bin():

    def temp_file(data):
        # writable file that is destroyed as soon as it is closed
        f = TemporaryFile()
        f.write(data)
        f.seek(0)
        return f

    # INTEGER
    a = np.arange(3 * 4, dtype=np.int32).reshape((3, 4)) - 1
    fp = temp_file(a.tobytes())
    fh, fa = Util2d.load_bin((3, 4), fp, np.int32)
    assert fh is None  # no header_dtype
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    # check warning if wrong integer type is used to read 4-byte integers
    # e.g. on platforms where int -> int64
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        fp.seek(0)
        fh, fa = Util2d.load_bin((3, 4), fp, np.int64)
        fp.close()
        assert len(w) == 1
        assert a.dtype == np.int32
        assert fh is None  # no header_dtype
        np.testing.assert_equal(fa, a)

    # REAL
    real_header_fmt = '2i2f16s3i'
    header_data = (1, 2, 3.5, 4.5, b'Hello', 6, 7, 8)
    real_header = pack(real_header_fmt, *header_data)
    assert len(real_header) == 44

    a = np.arange(10).reshape((2, 5))
    fp = temp_file(real_header + pack('10f', *list(range(10))))
    fh, fa = Util2d.load_bin((2, 5), fp, np.float32, 'Head')
    fp.close()
    for h1, h2 in zip(fh[0], header_data):
        assert h1 == h2
    np.testing.assert_equal(a.astype(np.float32), fa)
    assert fa.dtype == np.float32

    # DOUBLE PRECISION
    dbl_header_fmt = '2i2d16s3i'
    dbl_header = pack(dbl_header_fmt, *header_data)
    assert len(dbl_header) == 52

    fp = temp_file(real_header + pack('10d', *list(range(10))))
    fh, fa = Util2d.load_bin((2, 5), fp, np.float64, 'Head')
    fp.close()
    for h1, h2 in zip(fh[0], header_data):
        assert h1 == h2
    np.testing.assert_equal(a.astype(np.float64), fa)
    assert fa.dtype == np.float64
Exemplo n.º 4
0
def test_load_bin():

    def temp_file(data):
        # writable file that is destroyed as soon as it is closed
        f = TemporaryFile()
        f.write(data)
        f.seek(0)
        return f

    # INTEGER
    a = np.arange(3 * 4, dtype=np.int32).reshape((3, 4)) - 1
    fp = temp_file(a.tobytes())
    fh, fa = Util2d.load_bin((3, 4), fp, np.int32)
    assert fh is None  # no header_dtype
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    # check warning if wrong integer type is used to read 4-byte integers
    # e.g. on platforms where int -> int64
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        fp.seek(0)
        fh, fa = Util2d.load_bin((3, 4), fp, np.int64)
        fp.close()
        assert len(w) == 1
        assert a.dtype == np.int32
        assert fh is None  # no header_dtype
        np.testing.assert_equal(fa, a)

    # REAL
    real_header_fmt = '2i2f16s3i'
    header_data = (1, 2, 3.5, 4.5, b'Hello', 6, 7, 8)
    real_header = pack(real_header_fmt, *header_data)
    assert len(real_header) == 44

    a = np.arange(10).reshape((2, 5))
    fp = temp_file(real_header + pack('10f', *list(range(10))))
    fh, fa = Util2d.load_bin((2, 5), fp, np.float32, 'Head')
    fp.close()
    for h1, h2 in zip(fh[0], header_data):
        assert h1 == h2
    np.testing.assert_equal(a.astype(np.float32), fa)
    assert fa.dtype == np.float32

    # DOUBLE PRECISION
    dbl_header_fmt = '2i2d16s3i'
    dbl_header = pack(dbl_header_fmt, *header_data)
    assert len(dbl_header) == 52

    fp = temp_file(real_header + pack('10d', *list(range(10))))
    fh, fa = Util2d.load_bin((2, 5), fp, np.float64, 'Head')
    fp.close()
    for h1, h2 in zip(fh[0], header_data):
        assert h1 == h2
    np.testing.assert_equal(a.astype(np.float64), fa)
    assert fa.dtype == np.float64
Exemplo n.º 5
0
def test_load_block():
    a = np.ones((2, 5), dtype=np.int32) * 4
    fp = StringIO(
        dedent(
            u"""\
        1
        1 2 1 5 4
    """
        )
    )
    fa = Util2d.load_block(a.shape, fp, a.dtype)
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.ones((2, 5), dtype=np.float32) * 4
    a[0:2, 1:2] = 9.0
    a[0, 2:4] = 6.0
    fp = StringIO(
        dedent(
            u"""\
        3
        1 2 1 5 4.0
        1 2 2 2 9.0
        1 1 3 4 6.0
    """
        )
    )
    fa = Util2d.load_block(a.shape, fp, a.dtype)
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.zeros((2, 5), dtype=np.int32)
    a[0, 2:4] = 8
    fp = StringIO(
        dedent(
            u"""\
        1
        1 1 3 4 8
    """
        )
    )
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        fa = Util2d.load_block(a.shape, fp, a.dtype)
        assert len(w) == 1
        assert "blocks do not cover full array" in str(w[-1].message)
        np.testing.assert_equal(fa, a)
        assert fa.dtype == a.dtype
Exemplo n.º 6
0
def test_arrayformat():
    ml = flopy.modflow.Modflow(model_ws=out_dir)
    u2d = Util2d(ml, (15, 2), np.float32, np.ones((15, 2)), 'test')

    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()

    u2d.format.npl = 1
    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()

    u2d.format.npl = 2
    u2d.format.width = 8
    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()

    u2d.format.free = True
    u2d.format.width = 8
    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()

    u2d.format.free = False
    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()

    u2d.fmtin = "(10G15.6)"
    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()

    u2d.format.binary = True
    fmt_fort = u2d.format.fortran
    cr = u2d.get_control_record()
    parsed = Util2d.parse_control_record(cr)
    print(fmt_fort, parsed["fmtin"])
    assert fmt_fort.upper() == parsed["fmtin"].upper()
    assert u2d.get_file_array() == ''
Exemplo n.º 7
0
def test_load_block():
    a = np.ones((2, 5), dtype=np.int32) * 4
    fp = StringIO(dedent(u'''\
        1
        1 2 1 5 4
    '''))
    fa = Util2d.load_block(a.shape, fp, a.dtype)
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.ones((2, 5), dtype=np.float32) * 4
    a[0:2, 1:2] = 9.0
    a[0, 2:4] = 6.0
    fp = StringIO(dedent(u'''\
        3
        1 2 1 5 4.0
        1 2 2 2 9.0
        1 1 3 4 6.0
    '''))
    fa = Util2d.load_block(a.shape, fp, a.dtype)
    np.testing.assert_equal(fa, a)
    assert fa.dtype == a.dtype

    a = np.zeros((2, 5), dtype=np.int32)
    a[0, 2:4] = 8
    fp = StringIO(dedent(u'''\
        1
        1 1 3 4 8
    '''))
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        fa = Util2d.load_block(a.shape, fp, a.dtype)
        assert len(w) == 1
        assert 'blocks do not cover full array' in str(w[-1].message)
        np.testing.assert_equal(fa, a)
        assert fa.dtype == a.dtype
Exemplo n.º 8
0
    def load(f, model, nper=None, ext_unit_dict=None):
        """
        Load an existing package.

        Parameters
        ----------
        f : filename or file handle
            File to load.
        model : model object
            The model object (of type :class:`flopy.modflow.mf.Modflow`) to
            which this package will be added.
        nper : int
            The number of stress periods.  If nper is None, then nper will be
            obtained from the model object. (default is None).
        ext_unit_dict : dictionary, optional
            If the arrays in the file are specified using EXTERNAL,
            or older style array control records, then `f` should be a file
            handle.  In this case ext_unit_dict is required, which can be
            constructed using the function
            :class:`flopy.utils.mfreadnam.parsenamefile`.

        Returns
        -------
        evt : ModflowEvt object
            ModflowEvt object.

        Examples
        --------

        >>> import flopy
        >>> m = flopy.modflow.Modflow()
        >>> evt = flopy.modflow.mfevt.load('test.evt', m)

        """
        if model.verbose:
            sys.stdout.write("loading evt package file...\n")

        if not hasattr(f, "read"):
            filename = f
            f = open(filename, "r")
        # Dataset 0 -- header
        while True:
            line = f.readline()
            if line[0] != "#":
                break
        npar = 0
        if "parameter" in line.lower():
            raw = line.strip().split()
            npar = int(raw[1])
            if npar > 0:
                if model.verbose:
                    print("  Parameters detected. Number of parameters = ", npar)
            line = f.readline()
        # Dataset 2
        t = line.strip().split()
        nevtop = int(t[0])
        ipakcb = 0
        try:
            if int(t[1]) != 0:
                model.add_pop_key_list(int(t[1]))
                ipakcb = 53
        except:
            pass

        # Dataset 3 and 4 - parameters data
        pak_parms = None
        if npar > 0:
            pak_parms = mfparbc.loadarray(f, npar, model.verbose)

        if nper is None:
            nrow, ncol, nlay, nper = model.get_nrow_ncol_nlay_nper()

        # Read data for every stress period
        surf = {}
        evtr = {}
        exdp = {}
        ievt = {}
        current_surf = []
        current_evtr = []
        current_exdp = []
        current_ievt = []
        for iper in range(nper):
            line = f.readline()
            t = line.strip().split()
            insurf = int(t[0])
            inevtr = int(t[1])
            inexdp = int(t[2])
            if nevtop == 2:
                inievt = int(t[3])
            if insurf >= 0:
                if model.verbose:
                    print("   loading surf stress period {0:3d}...".format(iper + 1))
                t = Util2d.load(f, model, (nrow, ncol), np.float32, "surf", ext_unit_dict)
                current_surf = t
            surf[iper] = current_surf

            if inevtr >= 0:
                if npar == 0:
                    if model.verbose:
                        print("   loading evtr stress period {0:3d}...".format(iper + 1))
                    t = Util2d.load(f, model, (nrow, ncol), np.float32, "evtr", ext_unit_dict)
                else:
                    parm_dict = {}
                    for ipar in range(inevtr):
                        line = f.readline()
                        t = line.strip().split()
                        pname = t[0].lower()
                        try:
                            c = t[1].lower()
                            if c in pak_parms.bc_parms:
                                iname = c
                            else:
                                iname = "static"
                        except:
                            iname = "static"
                        parm_dict[pname] = iname
                    t = mfparbc.parameter_bcfill(model, (nrow, ncol), parm_dict, pak_parms)

                current_evtr = t
            evtr[iper] = current_evtr
            if inexdp >= 0:
                if model.verbose:
                    print("   loading exdp stress period {0:3d}...".format(iper + 1))
                t = Util2d.load(f, model, (nrow, ncol), np.float32, "exdp", ext_unit_dict)
                current_exdp = t
            exdp[iper] = current_exdp
            if nevtop == 2:
                if inievt >= 0:
                    if model.verbose:
                        print("   loading ievt stress period {0:3d}...".format(iper + 1))
                    t = Util2d.load(f, model, (nrow, ncol), np.int32, "ievt", ext_unit_dict)
                    current_ievt = t
                ievt[iper] = current_ievt

        # create evt object
        args = {}
        if ievt:
            args["ievt"] = ievt
        if nevtop:
            args["nevtop"] = nevtop
        if evtr:
            args["evtr"] = evtr
        if surf:
            args["surf"] = surf
        if exdp:
            args["exdp"] = exdp
        args["ipakcb"] = ipakcb
        evt = ModflowEvt(model, **args)
        # return evt object
        return evt
Exemplo n.º 9
0
def test_util2d():
    ml = flopy.modflow.Modflow()
    u2d = Util2d(ml, (10, 10), np.float32, 10., "test")
    a1 = u2d.array
    a2 = np.ones((10, 10), dtype=np.float32) * 10.
    assert np.array_equal(a1, a2)

    # test external filenames - ascii and binary
    fname_ascii = os.path.join(out_dir, 'test_a.dat')
    fname_bin = os.path.join(out_dir, 'test_b.dat')
    np.savetxt(fname_ascii, a1, fmt="%15.6E")
    u2d.write_bin(a1.shape, fname_bin, a1, bintype="head")
    dis = flopy.modflow.ModflowDis(ml, 2, 10, 10)
    lpf = flopy.modflow.ModflowLpf(ml, hk=[fname_ascii, fname_bin])
    ml.lpf.hk[1].fmtin = "(BINARY)"
    assert np.array_equal(lpf.hk[0].array, a1)
    assert np.array_equal(lpf.hk[1].array, a1)

    # test external filenames - ascii and binary with model_ws and external_path
    ml = flopy.modflow.Modflow(model_ws=out_dir,
                               external_path=os.path.join(out_dir, "ref"))
    u2d = Util2d(ml, (10, 10), np.float32, 10., "test")
    fname_ascii = os.path.join(out_dir, 'test_a.dat')
    fname_bin = os.path.join(out_dir, 'test_b.dat')
    np.savetxt(fname_ascii, a1, fmt="%15.6E")
    u2d.write_bin(a1.shape, fname_bin, a1, bintype="head")
    dis = flopy.modflow.ModflowDis(ml, 2, 10, 10)
    lpf = flopy.modflow.ModflowLpf(ml, hk=[fname_ascii, fname_bin])
    ml.lpf.hk[1].fmtin = "(BINARY)"
    assert np.array_equal(lpf.hk[0].array, a1)
    assert np.array_equal(lpf.hk[1].array, a1)

    # bin read write test
    fname = os.path.join(out_dir, 'test.bin')
    u2d.write_bin((10, 10), fname, u2d.array)
    a3 = u2d.load_bin((10, 10), fname, u2d.dtype)[1]
    assert np.array_equal(a3, a1)
    # ascii read write test
    fname = os.path.join(out_dir, 'text.dat')
    u2d.write_txt((10, 10), fname, u2d.array)
    a4 = u2d.load_txt((10, 10), fname, u2d.dtype, "(FREE)")
    assert np.array_equal(a1, a4)

    # fixed format read/write with touching numbers - yuck!
    data = np.arange(100).reshape(10, 10)
    u2d_arange = Util2d(ml, (10, 10), np.float32, data, "test")
    u2d_arange.write_txt((10, 10), fname, u2d_arange.array,
                         python_format=[7, "{0:10.4E}"])
    a4a = u2d.load_txt((10, 10), fname, np.float32, "(7E10.6)")
    assert np.array_equal(u2d_arange.array, a4a)

    # test view vs copy with .array
    a5 = u2d.array
    a5 += 1
    assert not np.array_equal(a5, u2d.array)

    # Util2d.__mul__() overload
    new_2d = u2d * 2
    assert np.array_equal(new_2d.array, u2d.array * 2)

    # test the cnstnt application
    u2d.cnstnt = 2.0
    a6 = u2d.array
    assert not np.array_equal(a1, a6)
    u2d.write_txt((10, 10), fname, u2d.array)
    a7 = u2d.load_txt((10, 10), fname, u2d.dtype, "(FREE)")
    assert np.array_equal(u2d.array, a7)

    # test binary integer file
    fname = os.path.join(out_dir, 'test.int')
    e8 = np.arange(3 * 4).reshape((3, 4)) - 1
    with open(fname, 'wb') as fp:
        fp.write(e8.tobytes())
    h8, a8 = Util2d.load_bin((3, 4), fname, np.int)
    assert h8 is None  # no header_dtype
    np.testing.assert_equal(a8, e8)

    return