Пример #1
0
 def referenceFunc(point):
     """Reference implementation; point must be in range [-1, 1]
     """
     c1 = np.zeros((3, 3))
     c1[2, 0] = 1.2
     c1[1, 1] = -0.5
     c2 = np.zeros((3, 3))
     c2[0, 1] = 1.0
     x1, x2 = point
     return (
         chebval2d(x1, x2, c1),
         chebval2d(x1, x2, c2),
     )
Пример #2
0
 def referenceFunc(point):
     """Reference implementation; point must be in range [-1, 1]
     """
     c1 = np.zeros((3, 3))
     c1[2, 0] = 1.2
     c1[1, 1] = -0.5
     c2 = np.zeros((3, 3))
     c2[0, 1] = 1.0
     x1, x2 = point
     return (
         chebval2d(x1, x2, c1),
         chebval2d(x1, x2, c2),
     )
Пример #3
0
    def test_chebval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        #test exceptions
        assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)

        #test values
        tgt = y1*y2
        res = cheb.chebval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        #test shape
        z = np.ones((2, 3))
        res = cheb.chebval2d(z, z, self.c2d)
        assert_(res.shape == (2, 3))
Пример #4
0
    def test_chebval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        #test exceptions
        assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)

        #test values
        tgt = y1*y2
        res = cheb.chebval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        #test shape
        z = np.ones((2,3))
        res = cheb.chebval2d(z, z, self.c2d)
        assert_(res.shape == (2,3))
Пример #5
0
 def referenceFunc_f(point):
     """Reference forward implementation; point must be in range [-1, 1]
     """
     c1 = np.zeros((4, 4))
     c1[2, 0] = -1.1
     c1[3, 1] = 1.3
     x1, x2 = point
     return (chebval2d(x1, x2, c1), )
Пример #6
0
def cheb_eval(dim, coefs, coords):
    if dim == 1:
        return chebval(coords[0], coefs)
    elif dim == 2:
        return chebval2d(coords[0], coords[1], coefs)
    elif dim == 3:
        return chebval3d(coords[0], coords[1], coords[2], coefs)
    else:
        raise NotImplementedError('dimension %d not supported' % dim)
Пример #7
0
 def referenceFunc(point):
     """Reference implementation; point must be in range [-1, 1]
     """
     c1 = np.zeros((3, 3))
     c1[0, 0] = -2
     c1[1, 0] = 0.11
     c1[0, 1] = -0.2
     c1[2, 1] = 0.001
     c2 = np.zeros((3, 3))
     c2[0, 0] = 5.1
     c2[1, 0] = -0.55
     c2[0, 1] = 0.13
     c2[1, 2] = -0.002
     x1, x2 = point
     return (
         chebval2d(x1, x2, c1),
         chebval2d(x1, x2, c2),
     )
Пример #8
0
 def referenceFunc(point):
     """Reference implementation; point must be in range [-1, 1]
     """
     c1 = np.zeros((3, 3))
     c1[0, 0] = -2
     c1[1, 0] = 0.11
     c1[0, 1] = -0.2
     c1[2, 1] = 0.001
     c2 = np.zeros((3, 3))
     c2[0, 0] = 5.1
     c2[1, 0] = -0.55
     c2[0, 1] = 0.13
     c2[1, 2] = -0.002
     x1, x2 = point
     return (
         chebval2d(x1, x2, c1),
         chebval2d(x1, x2, c2),
     )
Пример #9
0
 def cheb2d(x, y, ord=[0,0], verbose=False):
     coefLen = np.max(ord)+1
     coef0 = np.zeros(coefLen)
     coef0[ord[0]] = 1
     coef1 = np.zeros(coefLen)
     coef1[ord[1]] = 1
     if verbose:
         print ord, coef0, coef1
     ch = chebval2d(x, y, c=np.outer(coef0, coef1))
     return ch
Пример #10
0
 def referenceFunc_f(point):
     """Reference forward implementation; point must be in range [-1, 1]
     """
     c1 = np.zeros((4, 4))
     c1[2, 0] = -1.1
     c1[3, 1] = 1.3
     x1, x2 = point
     return (
         chebval2d(x1, x2, c1),
     )
Пример #11
0
 def cheb2d(x, y, ord=[0, 0], verbose=False):
     coefLen = np.max(ord) + 1
     coef0 = np.zeros(coefLen)
     coef0[ord[0]] = 1
     coef1 = np.zeros(coefLen)
     coef1[ord[1]] = 1
     if verbose:
         print ord, coef0, coef1
     ch = chebval2d(x, y, c=np.outer(coef0, coef1))
     return ch
Пример #12
0
 def cheb2d(x, y, ord=[0, 0], verbose=False):
     from numpy.polynomial.chebyshev import chebval2d
     coefLen = np.max(ord) + 1
     coef0 = np.zeros(coefLen)
     coef0[ord[0]] = 1
     coef1 = np.zeros(coefLen)
     coef1[ord[1]] = 1
     if verbose:
         print ord, coef0, coef1
     ch = chebval2d(x, y, c=np.outer(coef0, coef1))
     return ch
Пример #13
0
def chebReconstruct(orders, locations, coeffs, unusedNumPts):
    if len(locations.shape) == 1:
        return np.array(cheb.chebval(locations, coeffs))
    else:
        if locations.shape[1] == 2:
            return cheb.chebval2d(locations[:, 0], locations[:, 1], coeffs)
        elif locations.shape[1] == 3:
            return cheb.chebval3d(locations[:, 0], locations[:, 1],
                                  locations[:, 2], coeffs)
        else:
            return genericChebVal(locations, coeffs)
Пример #14
0
 def cheb2d(x, y, ord=[0,0], verbose=False):
     from numpy.polynomial.chebyshev import chebval2d
     coefLen = np.max(ord)+1
     coef0 = np.zeros(coefLen)
     coef0[ord[0]] = 1
     coef1 = np.zeros(coefLen)
     coef1[ord[1]] = 1
     if verbose:
         print ord, coef0, coef1
     ch = chebval2d(x, y, c=np.outer(coef0, coef1))
     return ch
Пример #15
0
    def test_chebvander2d(self):
        # also tests chebval2d for non-square coefficient array
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = cheb.chebvander2d(x1, x2, [1, 2])
        tgt = cheb.chebval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # check shape
        van = cheb.chebvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))
Пример #16
0
    def test_chebvander2d(self) :
        # also tests chebval2d for non-square coefficient array
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = cheb.chebvander2d(x1, x2, [1, 2])
        tgt = cheb.chebval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # check shape
        van = cheb.chebvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))
Пример #17
0
def get_Cheb_logkf(rT,logP):
    """
    return log of Chebyshev kf
    """
    from numpy.polynomial.chebyshev import chebval2d
    import math
    log10 = math.log(10.0)
    Cheb_logkf = np.zeros(NR_CHEB)
    for i,(rTmax,rTmin,logPmax,logPmin,coeffs) in enumerate(ChebyshevReactionConsts):
        Tbar = (2*rT-rTmin-rTmax)/(rTmax-rTmin)
        Pbar = (2*logP - logPmax -logPmin)/(logPmax - logPmin)
        Cheb_logkf[i] = chebval2d(Tbar,Pbar,coeffs)*log10
    return Cheb_logkf
Пример #18
0
def get_Cheb_logkf(rT, logP):
    """
    return log of Chebyshev kf
    """
    from numpy.polynomial.chebyshev import chebval2d
    import math
    log10 = math.log(10.0)
    Cheb_logkf = np.zeros(NR_CHEB)
    for i, (rTmax, rTmin, logPmax, logPmin,
            coeffs) in enumerate(ChebyshevReactionConsts):
        Tbar = (2 * rT - rTmin - rTmax) / (rTmax - rTmin)
        Pbar = (2 * logP - logPmax - logPmin) / (logPmax - logPmin)
        Cheb_logkf[i] = chebval2d(Tbar, Pbar, coeffs) * log10
    return Cheb_logkf
Пример #19
0
    def fit_2d_polynomial(x, y, z, order):
        """Fit z = f(x,y) as a 2d polynomial function

        Returns a function object f.
        """
        # I seriously don't know why this isn't a first-level numpy function.
        # It required some sleuthing to find all the numpy primitives required, but once
        # I found them, it's almost trivial to put them together.

        from numpy.polynomial import chebyshev as cheby
        A = cheby.chebvander2d(x, y, (order, order))
        coeff = np.linalg.lstsq(A, z,
                                rcond=None)[0].reshape(order + 1, order + 1)
        fn = lambda x, y: cheby.chebval2d(x, y, coeff)
        return fn
Пример #20
0
def chebGauss2d(x, y, m=None, s=None, ord=[0, 0], beta=1., verbose=False):
    if m is None:
        m = [0., 0.]
    if s is None:
        s = [1., 1.]
    # cov = [[s[0], 0], [0, s[1]]]
    coefLen = np.max(ord)+1
    coef0 = np.zeros(coefLen)
    coef0[ord[0]] = 1
    coef1 = np.zeros(coefLen)
    coef1[ord[1]] = 1
    if verbose:
        print s, beta, ord, coef0, coef1
    ga = psf.singleGaussian2d(x, y, 0, 0, s[0]/beta, s[1]/beta)
    ch = chebval2d(x, y, c=np.outer(coef0, coef1))
    return ch * ga
Пример #21
0
def chebGauss2d(x, y, m=None, s=None, ord=[0, 0], beta=1., verbose=False):
    if m is None:
        m = [0., 0.]
    if s is None:
        s = [1., 1.]
    # cov = [[s[0], 0], [0, s[1]]]
    coefLen = np.max(ord) + 1
    coef0 = np.zeros(coefLen)
    coef0[ord[0]] = 1
    coef1 = np.zeros(coefLen)
    coef1[ord[1]] = 1
    if verbose:
        print s, beta, ord, coef0, coef1
    ga = psf.singleGaussian2d(x, y, 0, 0, s[0] / beta, s[1] / beta)
    ch = chebval2d(x, y, c=np.outer(coef0, coef1))
    return ch * ga
Пример #22
0
def trace_plane_intersection_curve(patches,
                                   hmin,
                                   hmax,
                                   tolchord,
                                   verbose=False):
    ori = patches[0].xyz[:, -1, -1]
    nor = numpy.cross(patches[0].xyz[:, 0, -1] - ori,
                      patches[0].xyz[:, -1, 0] - ori)
    # find correct border
    fc = numpy.array([nor.dot(xc - ori) for xc in patches[1].get_corners()])
    for ic in range(4):
        if numpy.amax(numpy.absolute(fc[[ic, (ic + 1) % 4]])) < EPS:
            if NORMAL_CURVATURE_ONLY:
                xyz, uvtmp, t = discretize_curve_on_surface(
                    uvborders_c[ic],
                    cht_xyz(patches[1].xyz),
                    hmin,
                    hmax,
                    tolchord,
                    ta=-1,
                    tb=1)
                uv = numpy.zeros((2, 2, len(t)))
                uv[1] = uvtmp
            else:
                xyz = patches[1].get_border(ic)
                c = lch.fcht(xyz).T
                xyz, t = discretize_curve(c, hmin, hmax, tolchord, ta=1, tb=-1)
                ivar = ic2ivar[ic]
                ival = ic2ival[ic]
                uv = numpy.zeros((2, 2, len(t)))
                uv[1, ivar, :] = (-1)**ival
                uv[1, (ivar + 1) % 2] = numpy.sign(1.5 - ic) * t
            break
    # project onto other plane surface
    if verbose: print('\n\n\n')
    for ip in range(len(t)):
        c = cht_xyz(patches[0].xyz)
        cu, cv = lch.diff2(c)
        u, v = [0, 0]  #uv[0,:,ip]
        # Newton
        if verbose: print('\n')
        for it in range(30):
            s = chebval2d(u, v, c)
            r = xyz[:, ip] - s
            su = chebval2d(u, v, cu)
            sv = chebval2d(u, v, cv)
            E = su.dot(su)
            F = su.dot(sv)
            G = sv.dot(sv)
            invdet = 1 / (E * G - F**2)
            rsu = r.dot(su)
            rsv = r.dot(sv)
            du = (rsu * G - rsv * F) * invdet
            dv = (rsv * E - rsu * F) * invdet
            u += du
            v += dv
            if verbose:
                print('it#%d:\tr = %s, duv = %s, (u,v) = (%s, %s)' %
                      (it, numpy.sqrt(r.dot(r)), numpy.hypot(du, dv), u, v))
            if du**2 + dv**2 < EPSuv**2 and r.dot(r) < EPSxyz**2:
                uv[0, 0, ip] = u
                uv[0, 1, ip] = v
                break
    #
    return Curve_t(patches=patches, xyz=xyz, uv=uv)
Пример #23
0
 def eval(self, x, y):
     return np.asarray([
         chebval2d(self.scaletodefault(x, self.lower[0], self.upper[0]),
                   self.scaletodefault(y, self.lower[1], self.upper[1]),
                   self.c[i]) for i in range(self.dim)
     ])
Пример #24
0
    tpsubn = np.zeros(nchan_new)
elif info['mode'] == 'single':
    info['nsub'] = nperiod
info['file_time'] = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
d.write_shape([nchan, info['nsub'], nbin, npol])
#
if args.period:
    dt = np.array([np.arange(nbin0) * tsamp] * nchan_new)
else:
    dt = (np.arange(nbin0) * tsamp - tsamp + np.float64(info['stt_sec']) -
          t0) / (t1 - t0) * 2 - 1
for f in np.arange(nchan):
    if args.period:
        phase = dt / period
    else:
        phase = nc.chebval2d(dt, np.ones_like(dt), coeff) + dispc / freq_end**2
    newphase = np.arange(totalbin)
    data = d0.read_chan(f)[0].T
    tpdata = np.zeros([npol, totalbin])
    for p in np.arange(npol):
        tpdata[p] = np.interp(newphase, phase / dphasebin, data[p, :])
    if temp_multi > 1:
        tpdata = tpdata.reshape(npol, -1, temp_multi).sum(2)
    if info['mode'] == 'single':
        d.write_chan(tpdata.T, f)
    else:
        tpdata = np.concatenate(
            (tpdata, np.zeros([npol,
                               (sub_nperiod - sub_nperiod_last) * nbin])),
            axis=1).reshape(npol, nsub, sub_nperiod,
                            nbin).sum(2).reshape(npol, nsub * nbin).T
Пример #25
0
def discretize_curve_on_surface(cc,
                                cs,
                                hmin,
                                hmax,
                                tolchord,
                                ta=-1,
                                tb=1,
                                n0=20):
    FRACsqr = 4 * tolchord * (2 - tolchord)
    cc_t = lch.diff(cc)
    cs_u, cs_v = lch.diff2(cs)
    cs_uu, cs_uv = lch.diff2(cs_u)
    cs_uv, cs_vv = lch.diff2(cs_v)
    #
    t = numpy.linspace(ta, tb, n0)
    uv = chebval(t, cc)
    uv_t = chebval(t, cc_t)
    xyz = chebval2d(uv[0], uv[1], cs)
    xyz_u = chebval2d(uv[0], uv[1], cs_u)
    xyz_v = chebval2d(uv[0], uv[1], cs_v)
    xyz_uu = chebval2d(uv[0], uv[1], cs_uu)
    xyz_uv = chebval2d(uv[0], uv[1], cs_uv)
    xyz_vv = chebval2d(uv[0], uv[1], cs_vv)
    curvature = numpy.maximum(
        EPS,
        normal_curvature(xyz_u, xyz_v, xyz_uu, xyz_uv, xyz_vv, uv_t[0],
                         uv_t[1]))

    hminsqr = hmin**2
    hmaxsqr = hmax**2
    hsqr = numpy.minimum(hmaxsqr, numpy.maximum(hminsqr,
                                                FRACsqr / curvature**2))
    #
    maxit = 100 * n0
    for it in range(maxit):
        changes = False
        for i in range(len(t) - 1):
            ei = xyz[:, i + 1] - xyz[:, i]
            lisqr = ei.dot(ei)
            if lisqr > 2 * max(hsqr[i], hsqr[i + 1]):
                # split
                hi = numpy.sqrt(hsqr[i])
                hj = numpy.sqrt(hsqr[i + 1])
                tm = (hj * t[i] + hi * t[i + 1]) / (hi + hj)
                uvm = chebval(tm, cc)
                uvm_t = chebval(tm, cc_t)
                xyzm = chebval2d(uvm[0], uvm[1], cs)
                xyzm_u = chebval2d(uvm[0], uvm[1], cs_u)
                xyzm_v = chebval2d(uvm[0], uvm[1], cs_v)
                xyzm_uu = chebval2d(uvm[0], uvm[1], cs_uu)
                xyzm_uv = chebval2d(uvm[0], uvm[1], cs_uv)
                xyzm_vv = chebval2d(uvm[0], uvm[1], cs_vv)
                curvaturem = numpy.maximum(
                    EPS,
                    normal_curvature(xyzm_u, xyzm_v, xyzm_uu, xyzm_uv, xyzm_vv,
                                     uvm_t[0], uvm_t[1]))
                hmsqr = numpy.minimum(
                    hmaxsqr, numpy.maximum(hminsqr, FRACsqr / curvaturem**2))
                t = numpy.insert(t, i + 1, tm)
                uv = numpy.insert(uv, i + 1, uvm, axis=1)
                xyz = numpy.insert(xyz, i + 1, xyzm, axis=1)
                hsqr = numpy.insert(hsqr, i + 1, hmsqr)
                changes = True
                break
            elif lisqr < 0.5 * min(hsqr[i], hsqr[i + 1]):
                if xyz.shape[1] <= 2: break
                # collapse
                if i == 0:
                    # remove i+1
                    t = numpy.delete(t, i + 1)
                    uv = numpy.delete(uv, i + 1, axis=1)
                    xyz = numpy.delete(xyz, i + 1, axis=1)
                    hsqr = numpy.delete(hsqr, i + 1)
                elif i == xyz.shape[1] - 2:
                    # remove i
                    t = numpy.delete(t, i)
                    uv = numpy.delete(uv, i, axis=1)
                    xyz = numpy.delete(xyz, i, axis=1)
                    hsqr = numpy.delete(hsqr, i)
                else:
                    # relocate i+1
                    hi = numpy.sqrt(hsqr[i])
                    hj = numpy.sqrt(hsqr[i + 1])
                    t[i + 1] = (hj * t[i] + hi * t[i + 1]) / (hi + hj)
                    uv[:, i + 1] = chebval(t[i + 1], cc)
                    uvm_t = chebval(t[i + 1], cc_t)
                    xyz[:, i + 1] = chebval2d(uv[0, i + 1], uv[1, i + 1], cs)
                    xyzm_u = chebval2d(uv[0, i + 1], uv[1, i + 1], cs_u)
                    xyzm_v = chebval2d(uv[0, i + 1], uv[1, i + 1], cs_v)
                    xyzm_uu = chebval2d(uv[0, i + 1], uv[1, i + 1], cs_uu)
                    xyzm_uv = chebval2d(uv[0, i + 1], uv[1, i + 1], cs_uv)
                    xyzm_vv = chebval2d(uv[0, i + 1], uv[1, i + 1], cs_vv)
                    curvaturem = numpy.maximum(
                        EPS,
                        normal_curvature(xyzm_u, xyzm_v, xyzm_uu, xyzm_uv,
                                         xyzm_vv, uvm_t[0], uvm_t[1]))
                    hsqr[i + 1] = numpy.minimum(
                        hmaxsqr, numpy.maximum(hminsqr,
                                               FRACsqr / curvaturem**2))
                    # remove i
                    t = numpy.delete(t, i)
                    uv = numpy.delete(uv, i, axis=1)
                    xyz = numpy.delete(xyz, i, axis=1)
                    hsqr = numpy.delete(hsqr, i)
                changes = True
                break
            else:
                continue
        if not changes: break
    #
    """
    for i in range(len(t)):
        if i == 0:
            print('%s' % numpy.sqrt(hsqr[i]))
        else:
            print('%s\t%s' % (
                numpy.sqrt(hsqr[i]),
                numpy.sqrt(numpy.dot(xyz[:,i] - xyz[:,i-1], xyz[:,i] - xyz[:,i-1]))
            ))
    """
    #
    return xyz, uv, t
Пример #26
0
 def __call__(self, y, x, shifts=None):
     cy, cx = self.coord(y, x, shifts)
     return chebval2d(cy, cx, self.coef)
Пример #27
0
                    vislim = [vislim[0], vismid]
            #
            x, y = lbf.convert_3d_to_2d_coords(xyzmid, normalize=True)
            edge_vis.append([x, y])
            edge_hid.append([x, y])

# EXPORT XY CURVES
numpy.savetxt(pthout + 'edge_visible.dat', edge_vis)
numpy.savetxt(pthout + 'edge_hidden.dat', edge_hid)
################################################################

################################################################
# ISO-U CURVE
u0 = -0.6
v0 = 0.05
isou_xyz = chebval2d(u0 * numpy.ones(n), v, c).T

isou = lbu.pydata_to_polyline(isou_xyz,
                              name='isou',
                              thickness=1e-3,
                              bevel_resolution=4,
                              fill_mode='FULL')
isou.hide_render = True

isou_xy = numpy.zeros((n, 2))
for i in range(n):
    isou_xy[i] = lbf.convert_3d_to_2d_coords(isou_xyz[i], normalize=True)
numpy.savetxt(pthout + 'iso-u_curve.dat', isou_xy)

e = chebval2d(u0, v0, c)
bpy.ops.object.empty_add(location=e)
Пример #28
0
 def full_model(self, points, *params):
     """"""
     return chebval2d(points[:, 0], points[:, 1],
                      self.params_to_coeff(params))
Пример #29
0
nf = 31
for iface in range(nf):
    strf = format(iface + 1, '03')
    print('\nface #', iface + 1)
    print('   load pydata...')

    tri = numpy.loadtxt(pthin + 'brepmesh' + suffixe + '/tri_' + strf + '.dat',
                        dtype=int) - 1
    uv = numpy.loadtxt(pthin + 'brepmesh' + suffixe + '/uv_' + strf + '.dat',
                       dtype=float)

    c = myl.readCoeffs(pthin + 'brepmesh' + suffixe + '/c_' + strf + '.cheb')
    c_u, c_v = lch.diff2(c)
    c_uu, c_uv = lch.diff2(c_u)
    c_uv, c_vv = lch.diff2(c_v)
    xyz = chebval2d(uv[:, 0], uv[:, 1], c).T

    verts = [[float(x) for x in p] for p in xyz]
    faces = [[int(v) for v in t] for t in tri]

    print('   pydata to mesh...')
    obj = lbu.pydata_to_mesh(verts, faces, name='face_' + strf)
    scene.objects.active = obj
    lbe.set_smooth(obj)

    print('   diffgeom...')
    # Diffgeom
    nor = []
    curvatures = []
    for u in uv:
        dxyz_du = chebval2d(u[0], u[1], c_u)
        numpy.sum(xyz_u * xyz_v, axis=0)**2)

    nor = numpy.zeros((3, m, m))
    for i in range(3):
        j = (i + 1) % 3
        k = (j + 1) % 3
        nor[i] = (xyz_u[j] * xyz_v[k] - xyz_u[k] * xyz_v[j]) * invsqrtdet

    xyz = xyz + rho * nor
    mverts, mfaces = lbu.tensor_product_mesh_vf(xyz[0], xyz[1], xyz[2])
    obj = lbu.pydata_to_mesh(mverts, mfaces, name='EdS_face_' + strf)
    lbe.set_smooth(obj)
    obj.data.materials.append(mat)

    # NORMAL AT VERTEX
    xyz = chebval2d(Vuv[iloc][0], Vuv[iloc][1], c)
    xyz_u = chebgrid2d(Vuv[iloc][0], Vuv[iloc][1], cu)
    xyz_v = chebgrid2d(Vuv[iloc][0], Vuv[iloc][1], cv)
    nor = Vector(xyz_u).cross(Vector(xyz_v))
    nor.normalize()

    normals.append(nor)
################################################################

################################################################
# OFFSET EDGES
ih = 2 * V.edge[0] + V.edge[1]
arcs = []
xyz_edges = []

iclr = [15, 29, 16]
Пример #31
0
#xyz_facelabel = []
normals = []
xyz_facecenter = []
for iloc, iface in enumerate(V.faces):
    strf = format(iface, '03')

    mat = bpy.data.materials.new('mat_face_' + strf)
    mat.diffuse_color = color_face[iface - 1]

    c = lcheb.read_polynomial2(pthin + 'brepmesh/c_' + strf + '.cheb')
    cu, cv = lcheb.diff2(c)

    xyz_u = chebgrid2d(Vuv[iloc][0], Vuv[iloc][1], cu)
    xyz_v = chebgrid2d(Vuv[iloc][0], Vuv[iloc][1], cv)
    normals.append(Vector(xyz_u).cross(Vector(xyz_v)).normalized())
    xyz_facecenter.append(chebval2d(0, 0, c))

normal_avg = Vector((0, 0, 0))
for nor in normals:
    normal_avg += nor
normal_avg.normalize()
################################################################

################################################################
# ADJUST CAMERA
# align with average normal at vertex
cam.rotation_mode = 'QUATERNION'
cam.rotation_quaternion = Vector(normal_avg).to_track_quat('Z', 'Y')

# fit view
bpy.ops.object.select_all(action='DESELECT')
    xyz = chebgrid2d(u, u, c)
    mverts, mfaces = lbu.tensor_product_mesh_vf(xyz[0], xyz[1], xyz[2])
    obj = lbu.pydata_to_mesh(mverts, mfaces, name='face_' + strf)
    lbe.set_smooth(obj)
    obj.data.materials.append(mat)

    # OFFSET
    c = lcheb.read_polynomial2(pthin + 'brepmesh_eos/c_' + strf + '.cheb')
    xyz = chebgrid2d(u, u, c)
    mverts, mfaces = lbu.tensor_product_mesh_vf(xyz[0], xyz[1], xyz[2])
    obj = lbu.pydata_to_mesh(mverts, mfaces, name='EdS_face_' + strf)
    lbe.set_smooth(obj)
    obj.data.materials.append(mat)

    #
    xyz = chebval2d(Vuv[iloc][0], Vuv[iloc][1], c)
    corners.append(xyz)

corner_avg = numpy.zeros(3)
for xyz in corners:
    corner_avg = corner_avg + xyz
corner_avg = corner_avg / len(corners)

# SPHERE RADIUS
rho = 0
for xyz in corners:
    rho += Vector(xyz - V.xyz).length
rho /= float(len(corners))

bpy.ops.mesh.primitive_uv_sphere_add(location=V.xyz,
                                     size=rho,
Пример #33
0
def trace_intersection_curve(patches, hmin, hmax, tolchord):
    xc = [Pa.get_corners() for Pa in patches]
    for jc in range(4):
        for ic in range(4):
            v1 = xc[0][ic] - xc[1][(jc + 1) % 4]
            v2 = xc[0][(ic + 1) % 4] - xc[1][jc]
            if max(v1.dot(v1), v2.dot(v2)) < EPS**2:
                jvar = ic2ivar[jc]
                jval = ic2ival[jc]
                ivar = ic2ivar[ic]
                ival = ic2ival[ic]
                if NORMAL_CURVATURE_ONLY:
                    xyz, uvtmp, t = discretize_curve_on_surface(
                        uvborders_c[jc],
                        cht_xyz(patches[1].xyz),
                        hmin,
                        hmax,
                        tolchord,
                        ta=-1,
                        tb=1)
                    uv = numpy.zeros((2, 2, len(t)))
                    uv[1] = uvtmp
                    uv[0, ivar, :] = (-1)**ival
                    uv[0, (ivar + 1) % 2] = numpy.sign(1.5 - ic) * t
                else:
                    xyz = patches[1].get_border(jc)
                    c = lch.fcht(xyz).T
                    xyz, t = discretize_curve(c,
                                              hmin,
                                              hmax,
                                              tolchord,
                                              ta=1,
                                              tb=-1)
                    uv = numpy.zeros((2, 2, len(t)))
                    uv[1, jvar, :] = (-1)**jval
                    uv[1, (jvar + 1) % 2] = numpy.sign(1.5 - jc) * t
                    uv[0, (ivar + 1) % 2] = -numpy.sign(1.5 - ic) * t
                    uv[0, ivar, :] = (-1)**ival
                #print([p.index for p in patches], ic, uv[0])
                print(
                    'ic = %d, uv0a = (%s, %s), uv0b = (%s, %s)' %
                    (ic, uv[0, 0, 0], uv[0, 1, 0], uv[0, 0, -1], uv[0, 1, -1]))
                print(
                    'jc = %d, uv1a = (%s, %s), uv1b = (%s, %s)' %
                    (jc, uv[1, 0, 0], uv[1, 1, 0], uv[1, 0, -1], uv[1, 1, -1]))
                for k, l in enumerate([ic, jc]):
                    ck = cht_xyz(patches[k].xyz)
                    xka = chebval2d(uv[k, 0, 0], uv[k, 1, 0], ck)
                    xkb = chebval2d(uv[k, 0, -1], uv[k, 1, -1], ck)
                    print('err / x%da = %s' %
                          (k,
                           numpy.sqrt(
                               numpy.sum((xka - xc[k][(l + 1 - k) % 4])**2))))
                    print(
                        'err / x%db = %s' %
                        (k, numpy.sqrt(numpy.sum(
                            (xkb - xc[k][(l + k) % 4])**2))))
                print('\n\n')
                #xyz = chebval2d(uv[0,0], uv[0,1], cht_xyz(patches[0].xyz))
                return Curve_t(patches=patches, xyz=xyz, uv=uv)
    return None
for k in range(1,6):
    y[k-1]=5+5*mt.cos(((2*k-1)*mt.pi)/(2*5))#Chebycheff nodes function
xx, yy = np.meshgrid(x, y)
xx = xx.reshape(20,1)# X coordinate
yy = yy.reshape(20,1)# Y coordinate
D = cheb2d(xx,yy,n)#Explicative variables.
f = ((3/4)*(xx)**(-3)+((1/4)*(yy)**(-3)))**(-(1/3))
model = sm.OLS(f,D)
results = model.fit()
p = results.params

x = np.linspace(0,10,40)
y = np.linspace(0,10,40)
xx, yy = np.meshgrid(x, y)
f = ((3/4)*(xx)**(-3)+((1/4)*(yy)**(-3)))**(-(1/3))
w = chebval2d(xx,yy,p)

fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(xx, yy, f, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
print('Production function CES, axes X = K, axes Y = L and axes Z = Output')

fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(xx, yy, w, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
plt.show()
print('Production function CES chebycheff aproximation, axes X = K, axes Y = L and axes Z = Output')
Пример #35
0
def gendata(cums,nsub,data,tpsub=0,tpsubn=0,last=False,first=True):
	print(cums)
	data=np.concatenate((np.zeros([2,npol,nchan]),data,np.zeros([2,npol,nchan])),axis=0).transpose(2,1,0)
	if args.reverse or (not bw_sign):
		if nchan==chanend:
			data=data[(nchan-chanstart-1)::-1]
		else:
			data=data[(nchan-chanstart-1):(nchan-chanend-1):-1]
	else:
		data=data[chanstart:chanend]
	if args.period:
		dt=np.array([np.arange(nsblk*cums-1,nsblk*cums+nsub+1)*tsamp]*nchan_new)
	else:
		dt=(np.arange(nsblk*cums-2,nsblk*cums+nsub+2)*tsamp+time0[:-1].sum()-delay-t0)/(t1-t0)*2-1
	for f in np.arange(nchan_new):
		if f+chanstart in zchan: continue
		if args.period:
			if dm:
				phase=(dt+dm/df[f]**2*4148.808)/period
			else:
				phase=dt/period
		else:
			phase=nc.chebval2d(dt,df0[f]*np.ones_like(dt,dtype=np.float64),coeff)+dispc/df[f]**2
		newphase=np.arange(phase[0]//dphasebin+1,phase[-1]//dphasebin+1,dtype=np.int64)
		if newphase[-1]<0 or newphase[0]>=totalbin:
			continue
		newphase=newphase[(newphase>=0) & (newphase<totalbin)]
		tpdata=np.zeros([npol,len(newphase)])
		for p in np.arange(npol):
			tpdata[p]=np.interp(newphase,phase/dphasebin,data[f,p,:])
		if temp_multi>1:
			startphase,phaseres0=divmod(newphase[0],temp_multi)
			phaseres0=np.int64(phaseres0)
			nphase=np.int64(np.ceil((newphase[-1]+1-newphase[0]+phaseres0)*1.0/temp_multi))
			tpdata=np.concatenate((np.zeros([npol,phaseres0]),tpdata,np.zeros([npol,nphase*temp_multi-newphase[-1]-1+newphase[0]-phaseres0])),axis=1).reshape(npol,nphase,temp_multi).sum(2)
		else:
			startphase=newphase[0]
			nphase=newphase.size
		if info['mode']=='single':
			write_data(d,tpdata,startphase,f)
		else:
			startperiod,phaseres1=divmod(startphase,nbin)
			phaseres1=np.int64(phaseres1)
			file_nperiod=np.int64(np.ceil((nphase+phaseres1)*1.0/nbin))
			startsub,periodres=divmod(startperiod,sub_nperiod)
			periodres=np.int64(periodres)
			file_nsub=np.int64(np.ceil((file_nperiod+periodres)*1.0/sub_nperiod))
			if file_nsub>1 or newphase[-1]==totalbin-1:
				file_sub_data=np.zeros([npol,file_nsub,nbin])
				if newphase[-1]==totalbin-1:
					if newphase[0]==0:
						tpdata=tpdata.reshape(npol,-1,nbin)
						file_sub_data[:,:-1]=tpdata[:,:(-sub_nperiod_last)].reshape(npol,file_nsub-1,sub_nperiod,nbin).sum(2)
						file_sub_data[:,-1]=tpdata[:,(-sub_nperiod_last):].sum(1)
					elif file_nsub>1:
						tpsub[f,:,phaseres1:]+=tpdata[:,:(nbin-phaseres1)]
						tpdata=tpdata[:,(nbin-phaseres1):].reshape(npol,-1,nbin)
						file_sub_data[:,1:-1]=tpdata[:,(sub_nperiod-periodres-1):(-sub_nperiod_last)].reshape(npol,file_nsub-2,sub_nperiod_last,nbin).sum(2)
						file_sub_data[:,0]=tpsub[f]+tpdata[:,:(sub_nperiod-periodres-1)].sum(1)
						file_sub_data[:,-1]=tpdata[:,(-sub_nperiod_last):].sum(1)
					else:
						tpsub[f,:,phaseres1:]+=tpdata[:,:(nbin-phaseres1)]
						tpdata=tpdata[:,(nbin-phaseres1):].reshape(npol,-1,nbin)
						file_sub_data[:,0]=tpsub[f]+tpdata.sum(1)
					write_data(d,file_sub_data.reshape(npol,-1),startsub*nbin,f)
				else:
					periodres_left=sub_nperiod-periodres
					periodres_right=(file_nsub-1)*sub_nperiod-periodres
					phaseres_left=periodres_left*nbin-phaseres1
					phaseres_right=periodres_right*nbin-phaseres1
					phaseres_left1=nbin-phaseres1
					phaseres_right1=(file_nperiod-1)*nbin-phaseres1
					file_sub_data[:,1:-1]=tpdata[:,phaseres_left:phaseres_right].reshape(npol,file_nsub-2,sub_nperiod,nbin).sum(2)
					file_sub_data[:,0]=tpdata[:,phaseres_left1:phaseres_left].reshape(npol,sub_nperiod-periodres-1,nbin).sum(1)
					file_sub_data[:,0,phaseres1:]+=tpdata[:,:phaseres_left1]
					file_sub_data[:,-1]=tpdata[:,phaseres_right:phaseres_right1].reshape(npol,file_nperiod-1-periodres_right,nbin).sum(1)
					file_sub_data[:,-1,:(nphase-phaseres_right1)]+=tpdata[:,phaseres_right1:]
					if tpsubn[f]<=startsub:
						file_sub_data[:,0]+=tpsub[f]
					else:
						file_sub_data[:,1]+=tpsub[f]
					write_data(d,file_sub_data[:,:-1].reshape(npol,-1),startsub*nbin,f)
					tpsub[f]=file_sub_data[:,-1]
					tpsubn[f]=startsub+file_nsub-1
					if args.multi and last:
						write_data(d,tpsub[f],tpsubn[f]*nbin,f)
			else:
				if file_nperiod>1:
					phaseres_left=nbin-phaseres1
					phaseres_right=(file_nperiod-1)*nbin-phaseres1
					tpsub[f,:,phaseres1:]+=tpdata[:,:phaseres_left]
					tpsub[f,:,:(nphase-phaseres_right)]+=tpdata[:,phaseres_right:]
					if file_nperiod>2:
						tpsub[f]+=tpdata[:,phaseres_left:phaseres_right].reshape(npol,file_nperiod-2,nbin).sum(1)
				else:
					tpsub[f,:,phaseres1:(phaseres1+tpdata.shape[1])]+=tpdata
				if args.multi and last:
					write_data(d,tpsub[f],startsub*nbin,f)
	return tpsub,tpsubn
curv3 = lbu.pydata_to_mesh(
    xyz.T,
    faces=[],
    edges=[(i, i+1) for i in range(len(t)-1)],
    name='curve3'
)

uvw = numpy.vstack([uv, numpy.zeros(len(t))])
curv2 = lbu.pydata_to_mesh(
    uvw.T,
    faces=[],
    edges=[(i, i+1) for i in range(len(t)-1)],
    name='curve2'
)
curv2.layers[1] = True
curv2.layers[0] = False



w = numpy.linspace(-1,1,300)
uv = chebval(w, cc)
xyz = chebval2d(uv[0], uv[1], cs)
unif3 = lbu.pydata_to_mesh(
    xyz.T,
    faces=[],
    edges=[(i, i+1) for i in range(len(w)-1)],
    name='uniform3'
)


mat.use_shadows = False
mat.use_shadeless = True
mat.use_cast_buffer_shadows = False

slot = mat.texture_slots.add()
slot.texture = texchecker
slot.texture_coords = 'UV'
slot.diffuse_color_factor = 1

################################################
# Face label
fid = numpy.loadtxt(pthout + 'faces/faces_id.dat', dtype=int)

stlabel = numpy.loadtxt(pthout + 'faces/face_uvlabel_' + strf + '.dat',
                        delimiter=',')
xyzfacelabel = chebval2d(stlabel[0], stlabel[1], c)
myl.addEmpty('label', xyzfacelabel)

u, v = lbf.convert_3d_to_2d_coords(xyzfacelabel)

f = open(pthout + 'faces/face_xyzlabel_' + strf + '.dat', 'w')
f.write(str(fid[iface] + 1) + ', ' + str(u) + ', ' + str(v))
f.close()

################################################
# Freestyle settings
freestyle = scene.render.layers.active.freestyle_settings
freestyle.use_smoothness = True

bpy.ops.scene.freestyle_lineset_add()  #2
Пример #38
0
Z3 = Z1*Z2
fig3 = plt.figure()
ax3 = fig3.add_subplot(111,projection='3d')
ax3.plot_surface(X,Y,Z3)
plt.show()










z4 = cheb.chebval2d(x,y, F1_mat)
print(z4.size)
fig4 = plt.figure()
ax4 = fig4.add_subplot(111,projection='3d')
ax4.plot_surface(x,y,z4)
plt.show()
#chebz = cheb.chebgrid2d(x,y)
x1_pol = [-4, .2, .1]
y1_pol = [0, -.6, .2]
#
#x1_cheb = cheb.cheb2poly(x1_pol)
#y1_cheb = cheb.cheb2poly(y1_pol)
#cheb_X = cheb.chebval(-5, x1_cheb)
#cheb_Y = cheb.chebval(-5, y1_cheb)
#p_X = fx1(X)
#p_Y = fy1(Y)