예제 #1
0
def SnakeMoveIteration2D(b, p, f_ext, gamma, kappa, delta):
    "Iterate the contour one step, using both internal and external forces."
    p[0] = np.minimum(np.maximum(p[0],1), f_ext[0].size)
    p[1] = np.minimum(np.maximum(p[1],1), f_ext[1].size)
    
    x_coords = np.arange(f_ext[0].shape[0])
    y_coords = np.arange(f_ext[0].shape[1])
    f_ext_x = RectBivariateSpline(x_coords, y_coords, f_ext[0])
    f_ext_y = RectBivariateSpline(x_coords, y_coords, f_ext[1])
    
    # get interpolated points evaluated at the contour points
    f_ext_1 = np.empty(shape=p.shape)
    f_ext_1[0] = kappa*f_ext_x.ev(p[0], p[1])
    f_ext_1[1] = kappa*f_ext_y.ev(p[0], p[1])
    
    n = GetContourNormals2D(p)
    f_ext_2 = delta * n
    
    ssx = gamma*p[0] + f_ext_1[0] + f_ext_2[0]
    ssy = gamma*p[1] + f_ext_1[1] + f_ext_2[1]
    
    p[0] = np.dot(b, ssx)
    p[1] = np.dot(b, ssy)
    
    p[0] = np.minimum(np.maximum(p[0],1), f_ext[0].size)
    p[1] = np.minimum(np.maximum(p[1],1), f_ext[1].size)
    
    return p
예제 #2
0
    def test_evaluate(self):
        x = array([1,2,3,4,5])
        y = array([1,2,3,4,5])
        z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
        lut = RectBivariateSpline(x,y,z)

        xi = [1, 2.3, 5.3, 0.5, 3.3, 1.2, 3]
        yi = [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]
        zi = lut.ev(xi, yi)
        zi2 = array([lut(xp, yp)[0,0] for xp, yp in zip(xi, yi)])

        assert_almost_equal(zi, zi2)
예제 #3
0
 def test_derivatives(self):
     x = array([1, 2, 3, 4, 5])
     y = array([1, 2, 3, 4, 5])
     z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
                [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
     dx = array([0, 0, 2. / 3, 0, 0])
     dy = array([4, -1, 0, -.25, -4])
     dxdy = array([160, 65, 0, 55, 32]) / 24.
     lut = RectBivariateSpline(x, y, z)
     assert_array_almost_equal(lut(x, y, dx=1, grid=False), dx)
     assert_array_almost_equal(lut(x, y, dy=1, grid=False), dy)
     assert_array_almost_equal(lut(x, y, dx=1, dy=1, grid=False), dxdy)
예제 #4
0
 def test_derivatives_grid(self):
     x = array([1, 2, 3, 4, 5])
     y = array([1, 2, 3, 4, 5])
     z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
     dx = array([[0, 0, -20, 0, 0], [0, 0, 13, 0, 0], [0, 0, 4, 0, 0],
                 [0, 0, -11, 0, 0], [0, 0, 4, 0, 0]]) / 6.
     dy = array([[4, -1, 0, 1, -4], [4, -1, 0, 1, -4], [0, 1.5, 0, -1.5, 0],
                 [2, .25, 0, -.25, -2], [4, -1, 0, 1, -4]])
     dxdy = array([[40, -25, 0, 25, -40], [-26, 16.25, 0, -16.25, 26],
                   [-8, 5, 0, -5, 8], [22, -13.75, 0, 13.75, -22], [-8, 5, 0, -5, 8]]) / 6.
     lut = RectBivariateSpline(x, y, z)
     assert_array_almost_equal(lut(x, y, dx=1), dx)
     assert_array_almost_equal(lut(x, y, dy=1), dy)
     assert_array_almost_equal(lut(x, y, dx=1, dy=1), dxdy)
예제 #5
0
    def test_invalid_input(self):

        with assert_raises(ValueError) as info:
            x = array([6, 2, 3, 4, 5])
            y = array([1, 2, 3, 4, 5])
            z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
                       [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
            RectBivariateSpline(x, y, z)
        assert "x must be strictly increasing" in str(info.value)

        with assert_raises(ValueError) as info:
            x = array([1, 2, 3, 4, 5])
            y = array([2, 2, 3, 4, 5])
            z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
                       [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
            RectBivariateSpline(x, y, z)
        assert "y must be strictly increasing" in str(info.value)

        with assert_raises(ValueError) as info:
            x = array([1, 2, 3, 4, 5])
            y = array([1, 2, 3, 4, 5])
            z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
                       [1, 2, 2, 2, 1]])
            RectBivariateSpline(x, y, z)
        assert "x dimension of z must have same number of elements as x"\
               in str(info.value)

        with assert_raises(ValueError) as info:
            x = array([1, 2, 3, 4, 5])
            y = array([1, 2, 3, 4, 5])
            z = array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 3, 2], [1, 2, 2, 2],
                       [1, 2, 1, 2]])
            RectBivariateSpline(x, y, z)
        assert "y dimension of z must have same number of elements as y"\
               in str(info.value)

        with assert_raises(ValueError) as info:
            x = array([1, 2, 3, 4, 5])
            y = array([1, 2, 3, 4, 5])
            z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1],
                       [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
            bbox = (-100, 100, -100)
            RectBivariateSpline(x, y, z, bbox=bbox)
        assert "bbox shape should be (4,)" in str(info.value)

        with assert_raises(ValueError) as info:
            RectBivariateSpline(x, y, z, s=-1.0)
        assert "s should be s >= 0.0" in str(info.value)
예제 #6
0
파일: fuga.py 프로젝트: knutss/PyWake
    def __init__(self,
                 LUT_path=tfp +
                 'fuga/2MW/Z0=0.03000000Zi=00401Zeta0=0.00E+00/',
                 remove_wriggles=False,
                 method='linear'):
        """
        Parameters
        ----------
        LUT_path : str
            Path to folder containing 'CaseData.bin', input parameter file (*.par) and loop-up tables
        remove_wriggles : bool
            The current Fuga loop-up tables have significan wriggles.
            If True, all deficit values after the first zero crossing (when going from the center line
            and out in the lateral direction) is set to zero.
            This means that all speed-up regions are also removed
        """
        BlockageDeficitModel.__init__(self, upstream_only=True)
        FugaUtils.__init__(self, LUT_path, on_mismatch='input_par')
        self.remove_wriggles = remove_wriggles
        x, y, z, du = self.load()
        err_msg = "Method must be 'linear' or 'spline'. Spline is supports only height level only"
        assert method == 'linear' or (method == 'spline'
                                      and len(z) == 1), err_msg

        if method == 'linear':
            self.lut_interpolator = LUTInterpolator(x, y, z, du)
        else:
            du_interpolator = RectBivariateSpline(x, y, du[0].T)

            def interp(xyz):
                x, y, z = xyz
                assert np.all(
                    z == self.z[0]), f'LUT table contains z={self.z} only'
                return du_interpolator.ev(x, y)

            self.lut_interpolator = interp
예제 #7
0
 def test_defaults(self):
     x = array([1,2,3,4,5])
     y = array([1,2,3,4,5])
     z = array([[1,2,1,2,1],[1,2,1,2,1],[1,2,3,2,1],[1,2,2,2,1],[1,2,1,2,1]])
     lut = RectBivariateSpline(x,y,z)
     assert_array_almost_equal(lut(x,y),z)
예제 #8
0
 def test_broadcast(self):
     x = array([1, 2, 3, 4, 5])
     y = array([1, 2, 3, 4, 5])
     z = array([[1, 2, 1, 2, 1], [1, 2, 1, 2, 1], [1, 2, 3, 2, 1], [1, 2, 2, 2, 1], [1, 2, 1, 2, 1]])
     lut = RectBivariateSpline(x, y, z)
     assert_allclose(lut(x, y), lut(x[:, None], y[None, :], grid=False))
예제 #9
0
def read_radmap(args, base_path, fff):
    import numpy as np
    import os
    import rasterio
    from math import floor, ceil
    import umsgpack
    from scipy.interpolate.fitpack2 import RectBivariateSpline
    from collections import defaultdict
    import datetime
    import scipy.stats as stats

    rad_basedir = os.path.join(base_path, r'quantile_maps',
                               r'quantile_maps_monthly')
    #     rad_basedir_year = os.path.join(base_path, r'quantile_maps', r'quantile_maps_monthly_allyears')

    h, w, lat, lon, bbox84, base_paths, outdir = args

    days = [
        31.0, 28.0, 31.0, 30.0, 31.0, 30.0, 31.0, 31.0, 30.0, 31.0, 30.0, 31.0
    ]

    alpha_degs = np.arange(-180.0, 181.0, 15.0)
    beta_degs = np.arange(0.0, 95.0, 10.0)

    rad_inp = defaultdict(dict)
    rad_inp_rst = defaultdict(dict)

    #     for radkey in['avg', 'min', '25', '75', 'max']:
    for radkey in ['avg']:
        for radtype in ['sis', 'dif', 'dir']:
            rad_inp_rst[(radkey, radtype)] = np.zeros((12, 38, 91, 361),
                                                      dtype=np.uint16)

    for month in range(1, 13):
        #     for month in range(1, 2):

        fff.write("{} interpolate radiation month {}".format(
            str(datetime.datetime.now()), month))
        fff.write("\n")
        fff.flush()

        inparas = [
            'rad', 'h',
            int(h), 'w',
            int(w), 'lat', lat, 'lon', lon, 'month', month
        ]
        in_filename = "_".join(list(map(str, inparas))) + ".mp"
        in_path = os.path.join(rad_basedir, in_filename)

        with open(in_path, 'rb') as f:
            data_avg = umsgpack.load(f)

        for hour in range(3, 22):
            for mins in [0, 30]:
                hkey = (hour, mins)

                z_sis = np.zeros((len(beta_degs), len(alpha_degs)))
                z_dif = np.zeros((len(beta_degs), len(alpha_degs)))
                z_dir = np.zeros((len(beta_degs), len(alpha_degs)))

                for i, beta_deg in enumerate(beta_degs):
                    for j, alpha_deg in enumerate(alpha_degs):

                        akey = (alpha_deg, beta_deg)

                        z_sis[i, j] = float(
                            data_avg[hkey][akey]['sis']['avg']) * days[month -
                                                                       1] * 0.5
                        z_dif[i, j] = float(
                            data_avg[hkey][akey]['dif']['avg']) * days[month -
                                                                       1] * 0.5
                        z_dir[i, j] = float(
                            data_avg[hkey][akey]['sid']['avg']) * days[month -
                                                                       1] * 0.5

                rad_inp[('avg', 'sis', month)][hkey] = RectBivariateSpline(
                    beta_degs, alpha_degs, z_sis)
                rad_inp[('avg', 'dif', month)][hkey] = RectBivariateSpline(
                    beta_degs, alpha_degs, z_dif)
                rad_inp[('avg', 'dir', month)][hkey] = RectBivariateSpline(
                    beta_degs, alpha_degs, z_dir)
        del hour, mins, hkey, i, j, beta_deg, alpha_deg

        for radkey in ['avg']:

            #         for radkey in['avg', 'min', '25', '75', 'max']:
            for radtype in ['sis', 'dif', 'dir']:
                for hour in range(3, 22):
                    for mins in [0, 30]:
                        hkey = (hour, mins)

                        RBS = rad_inp[(radkey, radtype, month)][hkey]
                        interpolated = RBS(np.arange(0, 91, 1),
                                           np.arange(-180, 181, 1),
                                           grid=True).astype(np.float32)
                        interpolated[interpolated < 0] = 0

                        mmax = np.max(interpolated)
                        if mmax > 65535:
                            fff.write(
                                "{}: Overflow : {} / {} {} {} {} ".format(
                                    str(datetime.datetime.now()), mmax, radkey,
                                    radtype, hour, mins))
                            fff.write("\n")
                            fff.flush()
                        t = int(hour * 2 + mins / 30) - 6
                        rad_inp_rst[(radkey,
                                     radtype)][month - 1,
                                               t, :, :] = interpolated.astype(
                                                   np.uint16)

    mmax = 0.0
    mmin = 100000000
    for k in rad_inp_rst:
        fff.write("{}: Max/min rad for {}: {}/{}".format(
            str(datetime.datetime.now()), k, np.max(rad_inp_rst[k]),
            np.min(rad_inp_rst[k])))
        fff.write("\n")
        mmax = max(mmax, np.max(rad_inp_rst[k]))
        mmin = min(mmin, np.min(rad_inp_rst[k]))

    fff.write("{}: Max/min rad overall: {}/{}".format(
        str(datetime.datetime.now()), mmax, mmin))
    fff.write("\n")
    fff.flush()

    return rad_inp_rst