コード例 #1
0
ファイル: layers_test.py プロジェクト: Sissipei/caffe2
        def _arc_cosine_hypothesis_test(ac_output, X, W, b, s):
            """
            Runs hypothesis test for Arc Cosine layer.

            Inputs:
                ac_output -- output of net after running arc cosine layer
                X -- input data
                W -- weight parameter from train_init_net
                b -- bias parameter from train_init_net
                s -- degree parameter
            """
            # Get output from net
            net_output = workspace.FetchBlob(ac_output)

            # Computing output directly
            x_rand = np.matmul(X, np.transpose(W)) + b
            x_pow = np.power(x_rand, s)
            if s > 0:
                h_rand_features = np.piecewise(x_rand,
                                               [x_rand <= 0, x_rand > 0],
                                               [0, 1])
            else:
                h_rand_features = np.piecewise(x_rand,
                                               [x_rand <= 0, x_rand > 0],
                                               [0, lambda x: x / (1 + x)])
            output_ref = np.multiply(x_pow, h_rand_features)

            # Comparing net output and computed output
            npt.assert_allclose(net_output, output_ref, rtol=1e-3, atol=1e-3)
コード例 #2
0
ファイル: extShock_adi.py プロジェクト: drJfunk/mnEpFit
        def EpEvo(t,eta,j,Gamma0,q):

            
            #
            # For now I'm going to set a few params at good values
            # Adjust later

            z=2.332

            #q=power(10.,q)
            #q=1.E-3
            #E0 = 1.E54
            E0 = 1.97E55        
            #E0 = power(10.,E0)
            
            g = (j+1.-eta)*0.5

            n0 = 1.E2

            #xd = ((3.-eta)*E0 / ( 4.*pi*n0*Gamma0**2. * mp  ) )**(1./3.)
            xd = 1.8E16*((1.+j-eta)*(E0/1.E54)/((n0/100.)*(Gamma0/300.)))**(1./3.)
            #td = (1.+z)*xd / (Gamma0**2. * c)
            td = 6.7*(1.+z)*((1.+j-eta)*(E0/1.E54)/((n0/100.)*(Gamma0/300.)**8.))**(1./3.)



            ### Calculate X(t)  ###

            test = td/(2. * g + 1.) *( Gamma0**(2.+1./g) + 2.*g)
            
            condition1 = t<td
            condition2 = logical_and(td<=t, t<=test)


            X = piecewise(t, [condition1, condition2],\
            [lambda t: t/td, \
            lambda t: ((2.*g+1.)*(t/td) - 2.*g)**(1./(2.*g+1.)) ])

            ### Calculate X(t)  ###



            ### Calculate Gamma(X)  ###

            condition3 = X<1.
            condition4 = logical_and(1.<=X, X<=Gamma0**(1./g))

            Gamma = piecewise(X, [condition3, condition4],\
            [lambda X: Gamma0, \
            lambda X: Gamma0*X**(-g) ])

            ### Calculate Gamma(X)  ###


            eE0 = 3.E-8 * (1E-3)  * n0**(.5)*q*Gamma0**4. /(1.+z)


            result = 511.8 *  eE0*(Gamma/Gamma0)**4. * (X)**(-eta/2.)
            
            return result
コード例 #3
0
ファイル: tdi.py プロジェクト: LiberTang0/lisasolve
def makewdnoise(f,wdstyle,obs='X'):
    if wdstyle == 'mldc':
        x = 2.0 * math.pi * model.lisaL * f
        t = 4 * x**2 * N.sin(x)**2 * (1.0 if obs == 'X' else 1.5)
        
        return t * ( N.piecewise(f,(f >= 1.0e-4  ) & (f < 1.0e-3  ),[lambda f: 10**-44.62 * f**-2.3, 0]) + \
                     N.piecewise(f,(f >= 1.0e-3  ) & (f < 10**-2.7),[lambda f: 10**-50.92 * f**-4.4, 0]) + \
                     N.piecewise(f,(f >= 10**-2.7) & (f < 10**-2.4),[lambda f: 10**-62.8  * f**-8.8, 0]) + \
                     N.piecewise(f,(f >= 10**-2.4) & (f < 10**-2.0),[lambda f: 10**-89.68 * f**-20.0,0])     )
    elif wdstyle in wdnoise:
        mod, p = wdnoise[wdstyle]
        p = p[0] if obs == 'X' else p[1] # assume AE if not X
        y = N.log10(f)
    
        if mod == 'rat42':
            return 10.0**( (p[0]*y**4+p[1]*y**3+p[2]*y**2+p[3]*y+p[4])/(y**2+p[5]*y+p[6]) )
        elif mod == 'poly4':
            return 10.0**( p[0]*y**4+p[1]*y**3+p[2]*y**2+p[3]*y+p[4] )
        else:
            raise NotImplementedError
    else:
        if '.txt' in wdstyle:
            conf = N.loadtxt(wdstyle)
            conf[N.isnan(conf[:,1]),1] = 0
        
            return N.interp(f,conf[:,0],conf[:,1])
        else:
            raise NotImplementedError
コード例 #4
0
ファイル: extShock_mulit.py プロジェクト: drJfunk/mnEpFit
        def EpEvo(t,eta,g,Gamma0,q):


            #
            # For now I'm going to set a few params at good values
            # Adjust later

            z=2.332
            
            #            q=1.E-4
#            q=1E-3


            
            E0 = 9.1E53        
            
            n0 = 1.E2

            #n0 = power(10,n0)
            
            #xd = ((3.-eta)*E0 / ( 4.*pi*n0*Gamma0**2. * mp  ) )**(1./3.)
            xd = 2.6E16*((1.-eta/3.)*(E0/1.E54)/((n0/100.)*(Gamma0/300.)))**(1./3.)
            #td = (1.+z)*xd / (Gamma0**2. * c)
            td = 9.7*(1.+z)*((1.-eta/3.)*(E0/1.E54)/((n0/100.)*(Gamma0/300.)**8.))**(1./3.)

            ### Calculate X(t)  ###
            test = td/(2. * g + 1.) *( Gamma0**(2.+1./g) + 2.*g)
            #frac = t/td

            condition1 = t<td
            condition2 = logical_and(td<=t, t<=test)


            X = piecewise(t, [condition1, condition2],\
            [lambda t: t/td, \
            lambda t: ((2.*g+1.)*(t/td) - 2.*g)**(1./(2.*g+1.)) ])

            ### Calculate X(t)  ###



            ### Calculate Gamma(X)  ###



            condition3 = X<1.
            condition4 = logical_and(1.<=X, X<=Gamma0**(1./g))

            Gamma = piecewise(X, [condition3, condition4],\
            [lambda X: Gamma0, \
            lambda X: Gamma0*X**(-g) ])

            ### Calculate Gamma(X)  ###
    
            eE0 = 3.E-8 * (1E-3)  * n0**(.5)*q  *Gamma0**4. /(1.+z)

#            eE0 = 3.E-8 * n0**(.5)*q*Gamma0**4. /(1.+z)

            return 511. *  eE0*(Gamma/Gamma0)**4. * (X/xd)**(-eta/2.)
コード例 #5
0
ファイル: BuchananFunc.py プロジェクト: csivilo/IPMP
 def __init__(self, Ymax, Y0, mumax, lag, x):
         # x is x data      
          
     a1 = np.piecewise(x, [x < lag, x >= lag], [0.0, 1.0])
     tc = (Ymax-Y0)/mumax+lag
     a2 = np.piecewise(x, [x < tc, x >= tc], [0.0, 1.0])
     self.Buchanan = Y0*(1.0-a1)+(Y0 + mumax*(x-lag))*a1*(1.0-a2) +  Ymax*a2
     
     print x, self.Buchanan
コード例 #6
0
ファイル: pathfollowing.py プロジェクト: wannesvl/topaf
    def _get_solution(self):
        """Get the solution from the solver output

        Fills the dictionary self.sol with the information:
            * 's': The optimal s as a function of time
            * 't': The time vector
            * 'states': Numerical values of the states defined in self.sys

        TODO: perform accurate integration to determine time
        TODO: Do exact interpolation
        """
        solver = self.prob['solver']
        N = self.options['N']
        x_opt = np.array(solver.getOutput("x")).ravel()
        b_opt = np.reshape(x_opt, (N + 1, -1), order='F')
        self.sol['b'] = b_opt

        # Determine time on a sufficiently fine spatial grid
        s0 = np.linspace(0, 1, 1001)
        delta = s0[1] - s0[0]

        pieces = [lambda s, b=b_opt, ss=ss, j=j:
                  sum([bb * (s - ss) ** i / fact[i]
                       for i, bb in enumerate(b[j])])
                  for j, ss in enumerate(self.prob['s'][:-1])]
        conds = lambda s0: [np.logical_and(self.prob['s'][i] <= s0,
                                           s0 <= self.prob['s'][i+1])
                            for i in range(N)]
        b0_opt = np.piecewise(s0, conds(s0), pieces)
        b0_opt[b0_opt < 0] = 0
        time = np.cumsum(np.hstack([0, 2 * delta / (np.sqrt(b0_opt[:-1]) +
                                    np.sqrt(b0_opt[1:]))]))

        # Resample to constant time-grid
        t = np.arange(time[0], time[-1], self.options['Ts'])
        st = np.interp(t, time, s0)
        # Evaluate solution on equidistant time grid
        b_opt = np.c_[[np.piecewise(st, conds(st), pieces, b=b_opt[:, i:])
                       for i in range(self.sys.order)]].T
        st = np.matrix(st)

        # Determine s and derivatives from b_opt
        b, Ds = self._make_path()[1:]
        Ds_f = cas.SXFunction([b], [Ds])  # derivatives of s wrt b
        Ds_f.init()
        s_opt = np.hstack((st.T, np.array([evalf(Ds_f, bb).toArray().ravel()
                                          for bb in b_opt])))
        self.sol['s'] = np.asarray(s_opt)
        self.sol['t'] = t
        # Evaluate the states
        f = cas.SXFunction([self.s], [cas.substitute(cas.vertcat(self.sys.x.values()),
                                           self.sys.y, self.path)])
        f_val = np.array([evalf(f, s.T).toArray().ravel() for s in s_opt])
        self.sol['states'] = dict([(k, f_val[:, i]) for i, k in
                          enumerate(self.sys.x.keys())])
コード例 #7
0
def EpEvo(t,A,eta,g,E0,Gamma0,n0,q):

        #c = 2.99E10 #cm/s
    c=1.
    mp = 1.67E-26   # keV ??

    z=1.
    #q=1.E-3
    #Gamma0 = 300.

    #g = (3.-eta)/2.
    #n0 = 1.E2

    #xd = ((3.-eta)*E0 / ( 4.*pi*n0*Gamma0**2. * mp  ) )**(1./3.)
    xd = 2.6E16*((1.-eta/3.)*(E0/1.E54)/((n0/100.)*(Gamma0/300.)))**(1./3.)
    #td = (1.+z)*xd / (Gamma0**2. * c)
    td = 9.7*(1.+z)*((1.-eta/3.)*(E0/1.E54)/((n0/100.)*(Gamma0/300.)**8.))**(1./3.)
        
    ### Calculate X(t)  ###
    test = (td/(2. * g + 1.) * Gamma0**(2.+1./g) + 2.*g)
    #frac = t/td

    condition1 = t<td
    condition2 = logical_and(td<=t, t<=test)

        
    X = piecewise(t, [condition1, condition2],\
    [lambda t: t/td, \
    lambda t: ((2.*g+1.)*(t/td) - 2.*g)**(1./(2.*g+1.)) ])

    ### Calculate X(t)  ###



    ### Calculate Gamma(X)  ###



    condition3 = X<1.
    condition4 = logical_and(1.<=X, X<=Gamma0**(1./g))

    Gamma = piecewise(X, [condition3, condition4],\
    [lambda X: Gamma0, \
    lambda X: Gamma0*X**(-g) ])

    ### Calculate Gamma(X)  ###

        
    eE0 = 3.E-8 * n0**(.5)*q*Gamma0**4. /(1.+z)

    return A*eE0*(Gamma/Gamma0)**4. * (X/xd)**(-eta/2.)
コード例 #8
0
def I(w, wa, wb, wc):
    wa,wb,wc = float(wa), float(wb), float(wc)
    f = (wb - wa) / (wc - wa)
    eps = (wc-wa)/1e3
    if (wb-wa)>eps and (wc-wb)>eps:
        w1 = wa+eps
        w2 = wb-eps
        w3 = wc-eps
        return np.piecewise(w, 
                            [(w <= wa-eps),
                            (wa-eps < w) & (w <= wa+eps),
                            (wa+eps < w) & (w < wb-eps),
                            (wb-eps <= w) & (w <= wb+eps),
                            (wb+eps < w) & (w < wc-eps),
                            (wc-eps <= w) & (w < wc+eps),
                            (wc+eps <= w)],
                            [0,
                             4/np.sqrt(f*(1-((w1 - wa) / (wc - wa)))) * K([(1-f)*((w1 - wa) / (wc - wa)) / (f*(1-((w1 - wa) / (wc - wa))))]),
                             lambda w: 4/np.sqrt(f*(1-((w - wa) / (wc - wa)))) * K((1-f)*((w - wa) / (wc - wa)) / (f*(1-((w - wa) / (wc - wa))))),
                             4/np.sqrt(f*(1-((w2 - wa) / (wc - wa)))) * K([(1-f)*((w2 - wa) / (wc - wa)) / (f*(1-((w2 - wa) / (wc - wa))))]),
                             lambda w: 4/np.sqrt(((w - wa) / (wc - wa))*(1-f)) * K((1-((w - wa) / (wc - wa)))*f / (((w - wa) / (wc - wa))*(1-f))),
                             4/np.sqrt(((w3 - wa) / (wc - wa))*(1-f)) * K([(1-((w3 - wa) / (wc - wa)))*f / (((w3 - wa) / (wc - wa))*(1-f))]),
                             0])
    elif (wb-wa)<=eps:
        w2 = wb+eps
        w3 = wc-eps
        return np.piecewise(w, 
                            [(w <= wa-eps),
                            (wa-eps < w) & (w <= wb+eps),
                            (wb+eps < w) & (w < wc-eps),
                            (wc-eps <= w) & (w < wc+eps),
                            (wc+eps <= w)],
                            [0,
                             4/np.sqrt(((w2 - wa) / (wc - wa))*(1-f)) * K([(1-((w2 - wa) / (wc - wa)))*f / (((w2 - wa) / (wc - wa))*(1-f))]),
                             lambda w: 4/np.sqrt(((w - wa) / (wc - wa))*(1-f)) * K((1-((w - wa) / (wc - wa)))*f / (((w - wa) / (wc - wa))*(1-f))),
                             4/np.sqrt(((w3 - wa) / (wc - wa))*(1-f)) * K([(1-((w3 - wa) / (wc - wa)))*f / (((w3 - wa) / (wc - wa))*(1-f))]),
                             0])
    elif (wc-wb)<=eps:
        w1 = wa+eps
        w2 = wb-eps
        return np.piecewise(w, 
                            [(w <= wa-eps),
                            (wa-eps < w) & (w <= wa+eps),
                            (wa+eps < w) & (w < wb-eps),
                            (wb-eps <= w) & (w <= wc+eps),
                            (wc+eps <= w)],
                            [0,
                             4/np.sqrt(f*(1-((w1 - wa) / (wc - wa)))) * K([(1-f)*((w1 - wa) / (wc - wa)) / (f*(1-((w1 - wa) / (wc - wa))))]),
                             lambda w: 4/np.sqrt(f*(1-((w - wa) / (wc - wa)))) * K((1-f)*((w - wa) / (wc - wa)) / (f*(1-((w - wa) / (wc - wa))))),
                             4/np.sqrt(f*(1-((w2 - wa) / (wc - wa)))) * K([(1-f)*((w2 - wa) / (wc - wa)) / (f*(1-((w2 - wa) / (wc - wa))))]),
                             0])
コード例 #9
0
ファイル: make_phi.py プロジェクト: drostie/invibro
def phi(xs, Z):
    """Evaluate phi(x) on a numpy list.
    
    This uses invibro.phi.phi0_cache to interpolate values."""
    Z0, x_bound = phi0_cache['Z0'], phi0_cache['xs'][0]
    c1 = pi ** 2 /6; c2 = 7 * pi ** 4 / 60.0
    neg = lambda x: log((Z - x) / (Z + x))
    interp = lambda x: phi0_cache['interp'](x) + log((Z + x) / (Z0 + x))
    large = lambda x: log(1 + Z / x) + c1 / x ** 2 + c2 / x ** 4
    return (
        piecewise(xs, [xs < 0], [neg, 0.0]) +
        piecewise(abs(xs), [abs(xs) < x_bound], [interp, large]) +
        complex(0, -0.5) * n(xs)
    )
コード例 #10
0
ファイル: kernels.py プロジェクト: INM-6/elephant-cs16
 def _evaluate(self, t):
     if self.direction == 1:
         kernel = np.piecewise(
             t, [t < 0, t >= 0], [
                 lambda t: 0,
                 lambda t: (1.0 / self._sigma_scaled.magnitude) * np.exp(
                     (-t / self._sigma_scaled).magnitude)]) / t.units
     elif self.direction == -1:
         kernel = np.piecewise(
             t, [t < 0, t >= 0], [
                 lambda t: (1.0 / self._sigma_scaled.magnitude) * np.exp(
                     (t / self._sigma_scaled).magnitude),
                 lambda t: 0]) / t.units
     return kernel
コード例 #11
0
ファイル: cameraData.py プロジェクト: stephanGit/eml
 def loadExampleData():
     data = pd.DataFrame({'Seconds': np.arange(0,15,1/200)})
     t = data.loc[:,'Seconds'].values
     data.loc[:,'T ACP'] = \
     np.piecewise(t, [t < 4, 4 <= t], [1,0]) * (1800/4*t) + \
     np.piecewise(t, [t < 4,(4<=t)*(t<=12)], [0,1]) * (1800 + (1200-1800)/8*(t-4)) + \
     np.piecewise(t, [12 < t, 20 < t], [1,0]) * (1500 + -400/8*(t-12))
      
     data.loc[:,'time'] = t           
     self.data = data
     self.initExampleData()
      
     self.camera = 'rad' 
     self.times = [4,7,12]          
コード例 #12
0
ファイル: recenter_dump.py プロジェクト: anyuzx/toolbox
def reposition(coords, box_size):
    com = compute_com_pbc(coords, box_size)
    cob = box_size / 2.0
    coords_recenter = coords - com + cob
    coords_recenter_x = coords_recenter[:,0]
    coords_recenter_y = coords_recenter[:,1]
    coords_recenter_z = coords_recenter[:,2]
    #print coords_recenter
    coords_recenter_x = np.piecewise(coords_recenter_x, [coords_recenter_x < 0.0, (coords_recenter_x >= 0.0) * (coords_recenter_x <= box_size[0]), coords_recenter_x > box_size[0]], \
        [lambda coords_recenter_x: coords_recenter_x + box_size[0], lambda coords_recenter_x: coords_recenter_x, lambda coords_recenter_x: coords_recenter_x - box_size[0]])
    coords_recenter_y = np.piecewise(coords_recenter_y, [coords_recenter_y < 0.0, (coords_recenter_y >= 0.0) * (coords_recenter_y <= box_size[1]), coords_recenter_y > box_size[1]], \
        [lambda coords_recenter_y: coords_recenter_y + box_size[1], lambda coords_recenter_y: coords_recenter_y, lambda coords_recenter_y: coords_recenter_y - box_size[1]])
    coords_recenter_z = np.piecewise(coords_recenter_z, [coords_recenter_z < 0.0, (coords_recenter_z >= 0.0) * (coords_recenter_z <= box_size[2]), coords_recenter_z > box_size[2]], \
        [lambda coords_recenter_z: coords_recenter_z + box_size[2], lambda coords_recenter_z: coords_recenter_z, lambda coords_recenter_z: coords_recenter_z - box_size[2]])
    return np.array(zip(coords_recenter_x,coords_recenter_y,coords_recenter_z))
コード例 #13
0
def I_axial(w, wa, wc):
    if wc > wa:
        return np.piecewise(w, [(w <= wa),
                                (wa < w) & (w < wc),
                                (wc <= w)],
                                [0, 
                                 lambda w: 1 / (2*np.sqrt((w - wa) / (wc - wa))),
                                 0])
    elif wa > wc:
        return np.piecewise(w, [(w <= wc),
                            (wc < w) & (w < wa),
                            (wa <= w)],
                            [0, 
                             lambda w: 1 / (2*np.sqrt((w - wa) / (wc - wa))),
                             0])
コード例 #14
0
ファイル: fit.py プロジェクト: Pitt-RAS/micromouse
def f(x, a1, b1, c1, d1, b2, c2, v0):
    a2_calculated = a2(a1, b1, c1, d1, b2, c2, v0)
    d2_calculated = d2(a1, b1, c1, d1, b2, c2, v0)
    return np.piecewise(
            x,
            [x < v0, x >= v0],
            [lambda x: p(x, a1, b1, c1, d1), lambda x: p(x, a2_calculated, b2, c2, d2_calculated)])
コード例 #15
0
ファイル: test_bsplines.py プロジェクト: Brucechen13/scipy
def B_012(x):
    """ A linear B-spline function B(x | 0, 1, 2)."""
    x = np.atleast_1d(x)
    return np.piecewise(x, [(x < 0) | (x > 2),
                            (x >= 0) & (x < 1),
                            (x >= 1) & (x <= 2)],
                           [lambda x: 0., lambda x: x, lambda x: 2.-x])
コード例 #16
0
ファイル: polylog.py プロジェクト: MaxParsons/amo-physics
def fermi_poly3(x):
    """fermi_poly3(x), equal to -Li_3(-e^x)"""

    def f0(x):
        return np.exp(x)
    def f1(x):
        ex = np.exp(x)
        return (1 + (-0.125 + (0.037037037037037035 + (-0.015625 + (0.008 - 0.004629629629629629*ex)*ex)*ex)*ex)*ex)*ex
    def f2(x):
        x2 = x**2
        return 0.9015426773696955 + (0.8224670334241131 + (0.34657359027997264 + (0.08333333333333333 + (0.010416666666666666 +(-0.00017361111111111112 + (6.200396825396825e-6 +(-2.927965167548501e-7 + (1.6179486665597777e-8 + (-9.90785651003905e-10 + (6.525181428041877e-11 +(-4.5372283133067906e-12 + 3.290608283068484e-13*x2)*x2)*x2)*x2)*x2)*x2)*x2)*x2)*x)*x)*x)*x
    def f3(x):
        invex = np.exp(-x)
        return (((((0.008*invex - 0.015625)*invex + 0.037037037037037035)*invex) - 0.125)*invex + 1)*invex + 1.6449340668482262*x + 0.16666666666666666*x**3
    def f4(x):
        return 1.6449340668482262*x + 0.16666666666666666*x**3

    # fix for bug in piecewise, fixed in more recent numpy
    if np.isscalar(x):
        x = np.array([x], dtype=float)
    # define piecewise function and evaluate
    ans = np.piecewise(x, [x<=-20, np.logical_and(x>-20, x<=-2), \
                       np.logical_and(x>-2, x<=2), np.logical_and(x>2, x<=20)],\
                       [f0, f1, f2, f3, f4])
    return ans
コード例 #17
0
ファイル: polylog.py プロジェクト: MaxParsons/amo-physics
def fermi_poly2(x):
    """fermi_poly2(x), equal to -Li_2(-e^x)"""

    def f0(x):
        return np.exp(x)
    def f1(x):
        ex = np.exp(x)
        return (1.+( -0.25+( 0.111111+( -0.0625+( 0.04+( -0.0277778+( 0.0204082+( -0.015625+( 0.0123457+( -0.01+( 0.00826446+( -0.00694444+( 0.00591716+( -0.00510204+( 0.00444444+( -0.00390625+( 0.00346021+( -0.00308642+( 0.00277008+ -0.0025*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex
    def f2(x):
        ex = x**2
        return 0.822467+(0.6931471805599453+( 0.25+( 0.04166666666666666+( -0.0010416666666666534+( 0.00004960317460316857+( -2.927965167558005e-6+(1.9415383998507108e-7+( -1.3870999148454729e-8+(1.0440288911003276e-9+(-8.167040926799743e-11+6.5806618711692295e-12*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*x)*x)*x
    def f3(x):
        ex = np.exp(-x)
        return 1.6449340668482262 + 0.5*x**2 - (1.+( -0.25+( 0.111111+( -0.0625+( 0.04+( -0.0277778+( 0.0204082+( -0.015625+( 0.0123457+( -0.01+( 0.00826446+( -0.00694444+( 0.00591716+( -0.00510204+( 0.00444444+( -0.00390625+( 0.00346021+( -0.00308642+( 0.00277008 -0.0025*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex
    def f4(x):
        return 1.6449340668482262 + 0.5*x**2

    # fix for bug in piecewise, fixed in more recent numpy
    if np.isscalar(x):
        x = np.array([x], dtype=float)

    # define piecewise function and evaluate
    ans = np.piecewise(x, [x<=-20, np.logical_and(x>-20, x<=-1), \
                       np.logical_and(x>-1, x<=1), np.logical_and(x>1, x<=20)],\
                       [f0, f1, f2, f3, f4])

    return ans
コード例 #18
0
ファイル: polylog.py プロジェクト: MaxParsons/amo-physics
def fermi_poly5half(x):
    """fermi_poly5half(x), equal to -Li_{5/2}(-e^x)
    FAILS TESTS (COMPARING TO LERCH), DO NOT USE WITHOUT INVESTIGATING MORE
    """

    def f0(x):
            return np.exp(x)
    def f1(x):
        ex = np.exp(x)
        return (1 + (-0.17677669529663687 + (0.06415002990995843 - (0.03125 + (0.01788854381999832 - (0.011340230290662863 + (0.007713560673657698 - (0.005524271728019902 + (0.00411522633744856 - 0.0031622776601683794*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex)*ex
    def f2(x):
        res = (7.999472242952045e-8 + (2.015789875039643e-8 + (-5.182488893752819e-9 + (-1.3550552937770878e-9 + (3.5944104666022113e-10 + (9.653703483078106e-11 + (-2.6209625544677692e-11 + (-7.185930974961928e-12 + (1.9812061650792594e-12 + 5.447084984800099e-13*x)*x)*x)*x)*x)*x)*x)*x)*x)*x
        return 0.8671998890121841+(0.7651470246254081+(0.30244932171081546+(0.06335080210161399+(0.0049450362799933825+(-0.0007320093393446121+(-0.00013339945006254949  + (0.000027147085179903566+(5.930588304137955e-6+(-1.3626304577484817e-6 + (-3.252451788607287e-7 + res*x)*x)*x)*x)*x)*x)*x)*x)*x)*x)*x
    def f3(x):
        res = 5.992860912139351e-7 + (-6.083668666935579e-8 + (5.041252634789406e-9  + (-3.386896134140133e-10 + (1.8196669171414837e-11 + (-7.642990316874879e-13 + (2.4202106712129105e-14 + (-5.437364923509245e-16 + (7.72925401611516e-18 -5.228771407811986e-20*x)*x)*x)*x)*x)*x)*x)*x)*x
        return 0.869416215427492 + (0.7603408345815055 + (0.30606614629176887 + (0.06361411550944529 + (0.002145410757189772 + (0.002020072416997651 + (-0.0017045762862650151 + (0.0006382881546811445 + (- 0.00016246851298525836 + (0.00003140383144730955 + (-4.819813947314412e-6+res*x)*x)*x)*x)*x)*x)*x)*x)*x)*x)*x
    def f4(x):
        x2 = x**2
        invex = np.sqrt(x)
        return (-2.0851412241155116/x/x - 0.5343060576801043)/x/invex + 1.8561093322772355*invex + 0.30090111122547003*x2*invex
    def f5(x):
        x2 = x**2
        invex = np.sqrt(x)
        return 1.8561093322772355*invex + 0.30090111122547003*x2*invex

    # fix for bug in piecewise, fixed in more recent numpy
    if np.isscalar(x):
        x = np.array([x], dtype=float)
    # define piecewise function and evaluate
    ans = np.piecewise(x, [x<=-20, np.logical_and(x>-20, x<=-2), \
                       np.logical_and(x>-2, x<=2), np.logical_and(x>2, x<=12), \
                       np.logical_and(x>12, x<=20)], [f0, f1, f2, f3, f4, f5])
    return ans
コード例 #19
0
ファイル: average_ensemble.py プロジェクト: raylee/CDT
def de_sitter_form_testing(x,s,A,C,N3,num_slices):
    """
    The functional form for de Sitter Space. x is position, s, A, C
    are all fit parameters. N3 is the total number of 3-simplices in
    the spacetime. num_slices is the number of time slices in the spacetime.
    """
    # A normalized cosine. used for clarity.
    n_cos = lambda y: np.cos(y/(s * N3**(1/3.)))

    # The full width/half-max of the spacetime
    fwhm = np.arccos(np.sqrt((np.pi * A/2.)*(s * N3**(1/3.)/N3)))
        
    # The conditional functions
    # for -num_slices/2.0 <= (x - C) < -s * N3**(1/3.) * fwhm 
    # or 
    # s * N3**(1/3.) * fwhm < (x-C) <= num_slices/2.0
    stem = lambda x: float(A)
    # for -s * N3**(1/3.) * fwhm <= (x - C) <= s * N3**(1/3.) * fwhm
    bulk = lambda x: (2/np.pi) * (N3/(s * N3**(1/3.))) * n_cos(x-C)**2

    # List of conditions for the piecewise function
    conds = [(-num_slices/2.0 <= (x-C))&((x-C) < -s * N3**(1/3.) * fwhm),
             (-s * N3**(1/3.) * fwhm <= (x-C))&((x-C) <= s * N3**(1/3.) * fwhm),
             (s * N3**(1/3.) * fwhm < (x-C))&((x-C) <= num_slices/2.0)]

    # List of return functions for the piecewise function
    returnfuncs = [stem,bulk,stem]

    return np.piecewise(x,conds,returnfuncs)
コード例 #20
0
ファイル: aindane.py プロジェクト: shiruilu/AINDANE
    def _ale(self):
        """ale algorithm in SubSection 3.1 of the paper.

        Basically just the implementation of the following formula:
            In_prime = f(In, z)
        Calculates In and z, then return In_prime

        :return In_prime:
        """

        # Calculate In
        In = self.img_gray / 255.0  # 2d array, equation 2

        # Calculate z
        cdf = cv2.calcHist([self.img_gray], [0], None, [256], [0, 256]).cumsum()
        L = np.searchsorted(cdf, 0.1 * self.img_gray.shape[0] * self.img_gray.shape[1], side='right')
        L_as_array = np.array([L])  # L as array, for np.piecewise
        z_as_array = np.piecewise(L_as_array,
                         [L_as_array <= 50,
                          50 < L_as_array <= 150,
                          L_as_array > 150
                          ],
                         [0, (L-50) / 100.0, 1]
                         )
        z = z_as_array[0]  # take the value out of array

        self.z = z

        # Result In_prime = f(In, z)
        In_prime = 0.5 * (In**(0.75*z+0.25) + (1-In)*0.4*(1-z) + In**(2-z))
        return In_prime
コード例 #21
0
ファイル: colorspace.py プロジェクト: Rufflewind/_urandom
def invert_or_zero(x):
    '''Calculate 1 / x unless x is zero, in which case zero is returned.'''
    return numpy.piecewise(
        x,
        [x == 0, x != 0],
        [lambda x: 0, lambda x: 1 / x],
    )
コード例 #22
0
ファイル: RTD.py プロジェクト: ulikoehler/UliEngineering
def ptx_temperature(r0, r, standard=ptxITS90, poly=None) -> Quantity("°C"):
    """
    Compute the PTx temperature at a given temperature.

    Accepts an additive correction polynomial that is applied to the resistance.
    If the poly kwarg is None, the polynom is automatically selected.
    noCorrection is used for other r0 values. In this case, use a
    custom polynomial (numpy poly1d object) as the poly kwarg.

    See http://www.thermometricscorp.com/pt1000 for reference
    """
    r = normalize_numeric(r)
    A, B = standard.a, standard.b
    # Select
    if poly is None:
        if abs(r0 - 1000.0) < 1e-3: poly = pt1000Correction
        elif abs(r0 - 100.0) < 1e-3: poly = pt100Correction
        else: poly = noCorrection

    t = ((-r0 * A + np.sqrt(r0 * r0 * A * A - 4 * r0 * B * (r0 - r))) /
         (2.0 * r0 * B))
    # For subzero-temperature refine the computation by the correction polynomial
    if isinstance(r, numbers.Number):
        if r < r0:
            t += poly(r)
    else:  # Treated like a numpy array
        t += poly(r) * np.piecewise(r, [r < r0, r >= r0], [1.0, 0.0])
    return t
コード例 #23
0
def intgl_simp38(f,a,b,steps=-1,h=1):
    if steps>0:
        xis = np.linspace(a,b,steps+1)
        h  = xis[1]-xis[0]
    fxis = f(xis)
    wis = np.zeros(steps+1)
    pcs = []; fpcs = []
    for i in xrange(0,steps-2,3):
        wis[i:i+4] += [1,3,3,1]
        pcs.append(xis[i:i+4])
        fpcs.append(fxis[i:i+4])
    wis *= 3*h/8
    if steps%3==2:
        wis[-3:] += [h/3,4*h/3,h/3]
        pcs.append(xis[-3:])
        fpcs.append(fxis[-3:])
    elif steps%3==1:
        wis[-2:] += [h/2,h/2]
        pcs.append(xis[-2:])
        fpcs.append(fxis[-2:])
    fapprox = lambda x: np.piecewise(x,
                                     [np.logical_and(p[0]<=x,x<=p[-1]) for p in pcs],
                                     [lagrange(pcs[i],fpcs[i]) for i in xrange(len(pcs))])# np.interp(x,xis,fxis)
    # fapprox = lambda x: np.interp(x,xis,fxis)
    return (sum(fxis*wis),xis,fxis,wis,fapprox) # h/2 * sum(np.array([f(x) for x in xs]) * np.array([1]+[2]*(len(xs)-2)+[1]))
コード例 #24
0
ファイル: bessint.py プロジェクト: JohanComparat/pyLPT
 def phiPrime(self,t):
     """
     derivative of the double exponential transform
     """
     if N.isscalar(t):
         t = M.array([t])
     return N.piecewise(t,[M.fabs(t)>5.0],[self.phiPrime1,self.phiPrime2])
コード例 #25
0
def crystalball(x,s,a,n,xbar,sigma):
    A = np.power(n/np.absolute(a),n)*np.exp(-np.absolute(a)**2/2)
    B = n/np.absolute(a)-np.absolute(a)
    C = n/np.absolute(a)*(1/(n-1))*np.exp(-np.absolute(a)**2/2)
    D = np.sqrt(np.pi/2)*(1+erf(np.absolute(a)/np.sqrt(2)))
    N = 1/(sigma*(C+D))
    return np.piecewise(x, [(x-xbar)/sigma > -a], [lambda x:s*N*np.exp(-np.power(x-xbar,2)/(2*sigma**2)), lambda x:s*N*A*np.power((B-(x-xbar)/sigma),-n)])
コード例 #26
0
ファイル: saspolymer.py プロジェクト: awacha/sastool
def BorueErukhimovich_Powerlaw(q, C, r0, s, t, nu):
    """Borue-Erukhimovich model ending in a power-law.

    Inputs:
    -------
        ``q``: independent variable
        ``C``: scaling factor
        ``r0``: typical el.stat. screening length
        ``s``: dimensionless charge concentration
        ``t``: dimensionless temperature
        ``nu``: excluded volume parameter

    Formula:
    --------
        ``C*(x^2+s)/((x^2+s)(x^2+t)+1)`` where ``x=q*r0`` if ``q<qsep``
        ``A*q^(-1/nu)``if ``q>qsep``
        ``A`` and ``qsep`` are determined from conditions of smoothness at the
        cross-over.
    """
    def get_xsep(alpha, s, t):
        A = alpha + 2
        B = 2 * s * alpha + t * alpha + 4 * s
        C = s * t * alpha + alpha + alpha * s ** 2 + alpha * s * t - 2 + 2 * s ** 2
        D = alpha * s ** 2 * t + alpha * s
        r = np.roots([A, B, C, D])
        #print "get_xsep: ", alpha, s, t, r
        return r[r > 0][0] ** 0.5
    get_B = lambda C, xsep, s, t, nu:C * (xsep ** 2 + s) / ((xsep ** 2 + s) * (xsep ** 2 + t) + 1) * xsep ** (1.0 / nu)
    x = q * r0
    xsep = np.real_if_close(get_xsep(-1.0 / nu, s, t))
    A = get_B(C, xsep, s, t, nu)
    return np.piecewise(q, (x < xsep, x >= xsep),
                        (lambda a:BorueErukhimovich(a, C, r0, s, t),
                         lambda a:A * (a * r0) ** (-1.0 / nu)))
コード例 #27
0
ファイル: scientific.py プロジェクト: julgp/oq-risklib
    def _apply(self, imls):
        """
        Given IML values, interpolate the corresponding loss ratio
        value(s) on the curve.

        Input IML value(s) is/are clipped to IML range defined for this
        vulnerability function.

        :param float array iml: IML value

        :returns: :py:class:`numpy.ndarray` containing a number of interpolated
            values equal to the size of the input (1 or many)
        """
        # for imls < min(iml) we return a loss of 0 (default)
        ret = numpy.zeros(len(imls))

        # imls are clipped to max(iml)
        imls_curve = numpy.piecewise(
            imls,
            [imls > self.imls[-1]],
            [self.imls[-1], lambda x: x])

        # for imls such that iml > min(iml) we get a mean loss ratio
        # by interpolation and sample the distribution

        idxs, = numpy.where(imls_curve >= self.imls[0])
        imls_curve = numpy.array(imls_curve)[idxs]
        means = self._mlr_i1d(imls_curve)

        # apply uncertainty
        covs = self._cov_for(imls_curve)
        ret[idxs] = self.distribution.sample(means, covs, covs * imls_curve)
        return ret
コード例 #28
0
ファイル: bessint.py プロジェクト: JohanComparat/pyLPT
 def phi(self,t):
     """
     double exponential transformation
     """
     if N.isscalar(t):
         t = M.array([t])
     return N.piecewise(t,[M.fabs(t)>5.0],[self.phi1,self.phi2])
コード例 #29
0
ファイル: variogram_models.py プロジェクト: bsmurphy/PyKrige
def spherical_variogram_model(m, d):
    """Spherical model, m is [psill, range, nugget]"""
    psill = float(m[0])
    range_ = float(m[1])
    nugget = float(m[2])
    return np.piecewise(d, [d <= range_, d > range_],
                        [lambda x: psill * ((3.*x)/(2.*range_) - (x**3.)/(2.*range_**3.)) + nugget, psill + nugget])
コード例 #30
0
ファイル: document_info.py プロジェクト: bogolla/DICOM
def get_LUT_value(data, window, level):
    """Apply the RGB Look-Up Table for the given data and window/level value."""
    f = lambda data: ((data - (level - 0.5)) / (window - 1) + 0.5) * (255 - 0)
    return np.piecewise(data, [
        data <= (level - 0.5 - (window - 1) / 2),
        data > (level - 0.5 + (window - 1) / 2)
    ], [0, 255, f])
コード例 #31
0
n = 8

pos.findEnergies(n)

# Plot some of the stationary states

V0 = pos.V0
b = pos.b

x = np.linspace(-b, b, 200 * b)

for i in range(0, n):
    plt.plot(x, energy(i) + psi_n(i, x), label="E: " + str(energy(i)))

xW = np.linspace(-b - 0.1, b + 0.1, 200 * b)

plt.plot(
    xW,
    np.piecewise(xW, [
        xW > b,
        np.logical_and(xW <= b, xW > 1),
        np.logical_and(1 >= xW, xW >= -1),
        np.logical_and(-1 > xW, xW >= -b), -b > xW
    ], [10 + energy(n), 0, -V0, 0, 10 + energy(n)]))
plt.ylim(-V0 - 1, energy(n - 1) + 1)
plt.xlabel("$x/a$")
plt.ylabel("$\psi(x)$")
#plt.legend()
#plt.show()
plt.savefig("WiW_stationarySolutions.png")
コード例 #32
0
def psi_n_odd(n, x):
  k = np.sqrt(-2*energies["odd"][n])
  l = np.sqrt(2*(energies["odd"][n] + V0))
  A = np.exp(k)*1/(np.sqrt(1/k+1/(np.sin(l))**2 - 1/np.tan(l)))
  return np.piecewise(x, [x > 1, np.logical_and(1 >= x, x >= -1), -1 > x], [lambda x: A*np.exp(-k*x), lambda x: A*np.exp(-k)/(np.sin(l))*np.sin(l*x), lambda x: -A*np.exp(k*x)])
コード例 #33
0
    "Small": lambda dwt: 0.831 * dwt - 0.2,
    "Handy": lambda dwt: 1.05 * (0.153 - 0.00000158 * dwt),
    "Handymax": lambda dwt: 1.05 * (0.151 - 0.00000127 * dwt),
    "Panamax": lambda dwt: 1.05 * 0.079,
    "Capesize": lambda dwt: 0.0817 - 0.0000000486 * dwt,
    "VLBC": lambda dwt: 1.05 * (0.076 - 0.0000000261 * dwt)
}

# Derived DWT regression formulas (with 5 significant digits)
SMALL_DWT = lambda L, B: 0.0029893 * L**3.0395 - 366.02 * np.sqrt(1737. - 67. *
                                                                  B) + 11575.0
HANDY_DWT = lambda L, B: 0.00030717 * L**3.0441 + 1894.9 * B - 28158.0
HANDYMAX_DWT = lambda L, B: 7.0187e-09 * L**5.5157 + 1841.0 * B - 34850.0
PANAMAX_DWT = lambda L, B: np.piecewise(
    L,
    [(L < 201.05) * (L >= 193.68), (L <= 226.32) * (L >= 201.05),
     (L > 226.32) * (L <= 233.68)],
    [(L - 107.00) / 0.0014, (L - 31.00) / 0.00267, (L - 180.50) / 0.0005],
)

CAPESIZE_DWT = lambda L, B: 0.0030344 * L**3.1056 + np.piecewise(
    B, [(B < 41) * (B >= 38), (B <= 47) *
        (B >= 41)], [1979.8 * B - 55038.1, 3167.7 * B - 103740.0])

VLBC_DWT = lambda L, B: 1602.29 * L - 279210.0

DERIVED_DWT = [
    SMALL_DWT,
    HANDY_DWT,
    HANDYMAX_DWT,
    PANAMAX_DWT,
    CAPESIZE_DWT,
コード例 #34
0
def safe_inverse_root(d):
    if (d < 0).any():
        raise ValueError
    return np.piecewise(d, [d > 0, d == 0], [lambda x: x**(-0.5), lambda x: x])
コード例 #35
0
def fu():
    return lambda x: np.piecewise(x, [x == 0, x > 0],
                                  [0, lambda x: x**2 * np.log(x)])
コード例 #36
0
ファイル: BandDiagrams.py プロジェクト: samueljamesbader/BTBT
def generate_pin_bandstructure(mat, Lp,Aname,Na,d, Ln,Dname,Nd, Va):
    
    # The Material class will find the bulk energy levels
    mp=Material(mat,{Aname:Na})
    mn=Material(mat,{Dname:Nd})
    
    # Band edges far on the p and n side
    Ecp=mp.Ec-mp.EBulk-Va/2
    Evp=mp.Ev-mp.EBulk-Va/2
    Ecn=mn.Ec-mn.EBulk+Va/2
    Evn=mn.Ev-mn.EBulk+Va/2
    
    # Depletion edges, assuming depletion fully within device.
    # Note, these are locations in x (with appropriate signs), where depletion ends
    # ...not the absolute widths of the respective regions!
    xn= (-Na*d+np.sqrt(Na**2*d**2+2*mn.eps*(Ecp-Ecn)/q*Na/Nd*(Na+Nd)))/(Na+Nd) + d/2
    xp=-(-Nd*d+np.sqrt(Nd**2*d**2+2*mn.eps*(Ecp-Ecn)/q*Nd/Na*(Na+Nd)))/(Na+Nd) - d/2
    
    # P-side depletion should stay within the device
    assert (xp > -Lp-d/2), "p-side depletion region extends outside device!"
    
    # x-grid for calculation
    x=np.linspace(-Lp-d/2,Ln+d/2,50000)
    
    # If the n-side depletion region is fully within the device
    if (xn<Ln+d/2):
        
        # Return np.piecewise band diagram from depletion approximation
        return {"x":x,\
            "Ec":np.piecewise(x,
                [x<xp, (x>=xp)&(x<-d/2), (x>=-d/2)&(x<d/2), (x>=d/2)&(x<xn), x>=xn],
                [lambda x: Ecp, lambda x: Ecp-.5*q*Na/mp.eps*(x-xp)**2,
                 lambda x: Ecp-.5*q*Na/mp.eps*(-d/2-xp)**2-q*Na/mp.eps*(-d/2-xp)*(x+d/2),
                 lambda x: Ecn+.5*q*Nd/mn.eps*(xn-x)**2, lambda x: Ecn]),\
            "Ev":np.piecewise(x,
                [x<xp, (x>=xp)&(x<-d/2), (x>=-d/2)&(x<d/2), (x>=d/2)&(x<xn), x>=xn],
                [lambda x: Evp, lambda x: Evp-.5*q*Na/mp.eps*(x-xp)**2,
                 lambda x: Evp-.5*q*Na/mp.eps*(-d/2-xp)**2-q*Na/mp.eps*(-d/2-xp)*(x+d/2),
                 lambda x: Evn+.5*q*Nd/mn.eps*(xn-x)**2, lambda x: Evn]),\
            "EB": np.piecewise(x,
                [x<xp, (x>=xp)&(x<xn), (x>=xn)],
                [lambda x: -Va/2, lambda x: np.NaN, lambda x: Va/2]),\
            "Vr": -Va,\
            "material": mp}
    
    # If the n-side depletion region hits the device edge
    else:
        # Assume a sheet charge after the n-side to rebalance charge
        # Recalculate xp, and the sheet charge.
        xp=-(-(d+Ln)+np.sqrt((d+Ln)**2+(Nd/Na*Ln**2+2*mp.eps*(Ecp-Ecn)/(q*Na))))-d/2
        sigma_n=Na*(-d/2-xp)-Nd*Ln
        
        # Again, make sure the p-side depletion is still inside the device
        assert (xp > -Lp), "p-side depletion region extends outside device!"
        
        # Return a np.piecewise bandstructure given our maxed out depletion
        return {"x":x,\
            "Ec":np.piecewise(x,
                [x<xp, (x>=xp)&(x<-d/2), (x>=-d/2)&(x<d/2), (x>=d/2)&(x<Ln+d/2), x>=Ln+d/2],
                [lambda x: Ecp, lambda x: Ecp-.5*q*Na/mp.eps*(x-xp)**2,
                 lambda x: Ecp-.5*q*Na/mp.eps*(-d/2-xp)**2-q*Na/mp.eps*(-d/2-xp)*(x+d/2),
                 lambda x: Ecn+.5*q*Nd/mn.eps*(Ln+d/2-x)**2+q*sigma_n*(Ln+d/2-x)/mn.eps, lambda x: Ecn]),\
            "Ev":np.piecewise(x,
                [x<xp, (x>=xp)&(x<-d/2), (x>=-d/2)&(x<d/2), (x>=d/2)&(x<Ln+d/2), x>=Ln+d/2],
                [lambda x: Evp, lambda x: Evp-.5*q*Na/mp.eps*(x-xp)**2,
                 lambda x: Evp-.5*q*Na/mp.eps*(-d/2-xp)**2-q*Na/mp.eps*(-d/2-xp)*(x+d/2),
                 lambda x: Evn+.5*q*Nd/mn.eps*(Ln+d/2-x)**2+q*sigma_n*(Ln+d/2-x)/mn.eps, lambda x: Evn]),\
            "EB": np.piecewise(x,
                [x<xp, (x>=xp)&(x<xn), (x>=Ln+d/2)],
                [lambda x: -Va/2, lambda x: np.NaN, lambda x: Va/2]),\
            "Vr": -Va,\
            "material": mn}
コード例 #37
0
def ReLU_derivative(x):
    y = x
    np.piecewise(y, [ReLU(y) == 0, ReLU(y) == y], [0, 1])
    return y
コード例 #38
0
    out : ndarray
       !!!  The output is the same shape and type as `x`  !!!
        and is found by calling the functions in `funclist` on the appropriate portions of `x`,
        as defined by the boolean arrays in `condlist`.
        Portions not covered by any condition have a default value of 0.

See also:  choose, select (Indexing routines),  where (Sorting, searching, and counting)

Notes
This is similar to `choose` or `select`,
except that functions are evaluated on elements of `x` that satisfy the corresponding condition from `condlist`.
"""

x = np.linspace(-2.5, 2.5, 6)
x
np.piecewise(x, [x < 0, x >= 0],
             [-1, 1])  # array([-1., -1., -1.,  1.,  1.,  1.])

# Define the absolute value, which is -x for x <0 and x for x >= 0.

np.piecewise(
    x, [x < 0, x >= 0],
    [lambda x: -x, lambda x: x])  # array([2.5,  1.5,  0.5,  0.5,  1.5,  2.5])

# Apply the same function to a scalar value.
y = -2
np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])  # array(2)

#%%
xx = np.arange(100)

import matplotlib.pyplot as plt
コード例 #39
0
def inc_tophat(x):
    J = x.size
    q = np.piecewise(x,[x < -0.25,x >= -0.25],[0.0,1.0])*np.piecewise(x,[x <= 0.25, x > 0.25],[1.0,0.0])
    return q
コード例 #40
0
import matplotlib.pyplot as plt
import numpy as np
import scipy.constants as sc
from matplotlib.widgets import Slider, Button, RadioButtons

fig, ax = plt.subplots(figsize=(20, 10))
plt.subplots_adjust(left=0.15, bottom=0.30)
po = 0.000002
a = 20
x = np.arange(0.01, 40, 0.01)

H1 = lambda x: np.piecewise(x, [x < 20.0, x >= 20], [1, 0])
H2 = lambda x: np.piecewise(x, [x < 20.0, x >= 20], [0, 1])

K = H1(x) * (po / sc.epsilon_0) * ((x / 3) - (x**3) / (5 * a**2)) + H2(x) * (
    (a**3) / x**2) * (po / sc.epsilon_0) * (0.133333333)
k1 = H2(x) * ((a**3) / x**2) * (po / sc.epsilon_0) * (0.133333333)

plt.plot(x,
         K,
         "blue",
         linewidth=2,
         label="Campo Electrico Interno",
         color="blue")

plt.plot(x, k1, linewidth=2, label="Campo Electrico Externo", color="green")
plt.legend(loc=1)

font1 = {"family": "century", "color": "black", "weight": "normal", "size": 1}

font2 = {"family": "century", "color": "black", "weight": "normal", "size": 1}
コード例 #41
0
def k(x, theta):
    return np.piecewise(x, [
        x < 0.25,
        np.logical_and(x >= 0.25, x < 0.5),
        np.logical_and(x < 0.75, x >= 0.5), (x >= 0.75)
    ], theta)
コード例 #42
0
ファイル: BandDiagrams.py プロジェクト: samueljamesbader/BTBT
def generate_spikedpn_bandstructure(mat, Lp,Aname,Na, sigmaD, Ln,Dname,Nd, Va):
    
    # The Material class will find the bulk energy levels
    mp=Material(mat,{Aname:Na})
    mn=Material(mat,{Dname:Nd})
    
    # Band edges far on the p and n side
    Ecp=mp.Ec-mp.EBulk-Va/2
    Evp=mp.Ev-mp.EBulk-Va/2
    Ecn=mn.Ec-mn.EBulk+Va/2
    Evn=mn.Ev-mn.EBulk+Va/2    
    
    # x-grid for calculation
    x=np.linspace(-Lp,Ln,50000)
    
    # Depletion edges, assuming spike is undepleted
    sigma=np.sqrt(2*mp.eps*Na*(Ecp-Ecn)/q)
    print ("Va",Va," sigma", sigma)
    xp=-sigma/Na
    
    # If the spike is not fully depleted
    if(sigma<sigmaD):
        
        print ("not dep")
    
        # P-side depletion should stay within the device
        assert (xp > -Lp), "p-side depletion region extends outside device!"
           
        
        # Depletion edges, assuming depletion fully within device.
        # Note, these are locations in x (with appropriate signs), where depletion ends
        # ...not the absolute widths of the respective regions!
        return {"x":x,\
                "Ec":np.piecewise(x,
                    [x<xp,(x>=xp)&(x<0),(x>=0)],
                    [lambda x: Ecp, lambda x: Ecp-.5*q*Na/mp.eps*(x-xp)**2,lambda x: Ecn]),\
                "Ev":np.piecewise(x,
                    [x<xp,(x>=xp)&(x<0),(x>=0)],
                    [lambda x: Evp, lambda x: Evp-.5*q*Na/mp.eps*(x-xp)**2,lambda x: Evn]),\
                "EB": np.piecewise(x,
                    [x<xp, (x>=xp)&(x<0), (x>=0)],
                    [lambda x: -Va/2, lambda x: np.NaN, lambda x: Va/2]),\
                "Vr": -Va,\
                "material": mp}
    
    # If the spike is fully depleted, we actually have to solve for xn
    else:
        xn=-sigmaD/(Nd+Na)+np.sqrt(sigmaD**2/(Nd+Na)**2-2/(Nd+Na)*(sigmaD**2/(2*Nd)-Na*mn.eps*(Ecp-Ecn)/(q*Nd)))
        xp=-(Nd/Na*xn+sigmaD/Na)
        
        # N-side depletion should stay within the device, because I haven't considered full depletion
        assert (xn < Ln), "n-side depletion region extends outside device, and I haven't coded that"
                
        # Return np.piecewise band diagram from depletion approximation
        return {"x":x,\
            "Ec":np.piecewise(x,
                [x<xp, (x>=xp)&(x<0), (x>=0)&(x<xn), x>=xn],
                [lambda x: Ecp, lambda x: Ecp-.5*q*Na/mp.eps*(x-xp)**2,
                 lambda x:Ecn+.5*q*Nd/mn.eps*(xn-x)**2, Ecn]),\
            "Ev":np.piecewise(x,
                [x<xp, (x>=xp)&(x<0), (x>=0)&(x<xn), x>=xn],
                [lambda x: Evp, lambda x: Evp-.5*q*Na/mp.eps*(x-xp)**2,
                 lambda x:Evn+.5*q*Nd/mn.eps*(xn-x)**2, Evn]),\
            "EB": np.piecewise(x,
                [x<xp, (x>=xp)&(x<xn), (x>=xn)],
                [lambda x: -Va/2, lambda x: np.NaN, lambda x: Va/2]),\
            "Vr": -Va,\
            "material": mp}
コード例 #43
0
def _int_piecewise(x, *condlist, **kwargs):
    return np.piecewise(x, list(condlist), kwargs["funclist"],
                        *kwargs["func_args"], **kwargs["func_kw"])
コード例 #44
0
ファイル: loss_func.py プロジェクト: oganesManasian/solar
 def inner(x, deg=2):
     return np.piecewise(
         x, [x < a, x > b],
         [lambda x: (a - x)**deg, lambda x: (x - b)**deg])
コード例 #45
0
def psi_n_even(n, x):
  k = np.sqrt(-2*energies["even"][n])
  l = np.sqrt(2*(energies["even"][n] + V0))
  A = np.exp(k)*1/(np.sqrt(1/k+1/(np.cos(l))**2 + np.tan(l)))
  return np.piecewise(x, [x > 1, 1 >= x, -1 > x], [lambda x: A*np.exp(-k*x), lambda x: A*np.exp(-k)/(np.cos(l))*np.cos(l*x), lambda x: A*np.exp(k*x)])
コード例 #46
0
apply_fit(freqs, p_lambertian, quartic_fit, "cyan", plt)
apply_fit(freqs, p_specular, quartic_fit, "r", plt)


def lambertian(f):
    return -2.98e-11 * (f**4) + 1.71e-8 * (f**3) - 2.47e-6 * (
        f**2) + 7.83e-4 * f + 5.88e-2


def total_diff(f):
    return -2.9e-13 * f**4 - 3.1e-9 * f**3 + 3.21e-6 * f**2 + 2.03e-4 * f + 7.16e-2


plt.plot(freqs,
         np.piecewise(freqs, [freqs < 366.2, freqs >= 366.2], [
             lambda f: -2.98e-11 * (f**4) + 1.71e-8 * (f**3) - 2.47e-6 *
             (f**2) + 7.83e-4 * f + 5.88e-2, 0.318
         ]),
         label='Physical Lambertian Probability',
         c='cyan')
plt.plot(
    freqs,
    np.piecewise(freqs, [freqs < 366.2, freqs >= 366.2],
                 [lambda f: total_diff(f), lambda f: 0.318 + 1.51e-14 * f**5]),
    c='g',
    label='Physical Total Diffusive Probability')
plt.plot(
    freqs,
    np.piecewise(
        freqs, [freqs < 366.2, freqs >= 366.2],
        [lambda f: 1 - total_diff(f), lambda f: 1 -
         (0.318 + 1.51e-14 * f**5)]),
コード例 #47
0
def trailer_profile(z):
    n = np.piecewise(z, [z<1.8558, z>2.8689],\
                        [      0.,       0., lambda z: 0.4+0.6/1.0131*(z-1.8558)])
    # the last value is the default value, when no condition is satisfied
    return (n)
コード例 #48
0
def init_progressive_mask(mask, bounds):
    random_nums = np.random.uniform(0, bounds, mask.shape)
    conds = [mask == 1, mask == -1]
    funcs = [lambda x: bounds - x, lambda x: x - bounds]
    return np.piecewise(random_nums, conds,
                        funcs)  # return initialised random numbers
コード例 #49
0
import numpy as np
import matplotlib.pyplot as mp

ary = np.array([60, 50, 70, 32, 65, 28, 73, 93])
r = np.piecewise(ary, [np.all([ary <= 100, ary >= 60], axis=0), ary < 60],
                 [1, 0])
print(r)
コード例 #50
0
def Huber_loss(a, delta):
    # a=y-t
    # H=np.where(abs(a)<=delta,1/2*a**2,delta*(abs(a)-delta/2))
    dH = np.piecewise(a, [abs(a) <= delta, a > delta, -a < delta], [a, delta, -delta])
    return dH
コード例 #51
0
def piecewise_linear_2(x, x0, y0, a1, a2):
    condlist = [x <= x0]
    funclist = [lambda x: a1*x + y0 - a1*x0, lambda x: a2*x + y0 - a2*x0]
    return np.piecewise(x, condlist, funclist)
コード例 #52
0
ファイル: demo03_sc.py プロジェクト: Bertram-Liu/Note
x = np.array([
    [3, 1],
    [2, 5],
    [1, 8],
    [6, 4],
    [5, 2],
    [3, 5],
    [4, 7],
    [4, -1]])
y = np.array([0, 1, 1, 0, 0, 1, 1, 0])
# 把整个空间分为500*500的网格化矩阵
l, r = x[:,0].min()-1, x[:,0].max()+1
b, t = x[:,1].min()-1, x[:,1].max()+1
grid_x, grid_y = np.meshgrid(
	np.linspace(l, r, 500),
	np.linspace(b, t, 500))
# grid_z存储了网格化矩阵中每个坐标点的类别标签:0 / 1
grid_z = np.piecewise(grid_x, 
	[grid_x>grid_y, grid_x<grid_y] , 
	[0, 1])

# 绘制散点图
mp.figure('Simple Classification', facecolor='lightgray')
mp.title('Simple Classification', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
# 为网格化矩阵中的每个元素填充背景颜色
mp.pcolormesh(grid_x, grid_y, grid_z, cmap='gray')
mp.scatter(x[:, 0], x[:, 1], c=y, cmap='brg', s=80)
mp.show()
コード例 #53
0
    def E_gsf(self, **kwargs):
        """
        Returns values for generalized stacking fault energy interpolated from
        the raw data.  Values can be obtained relative to a1, a2 fractional
        coordinates, x, y plotting coordinates, or pos Cartesian coordinates.
        
        Parameters
        ----------
        a1 : float(s), optional
            Fractional coordinate(s) along a1vect.
        a2 : float(s), optional
            Fractional coordinate(s) along a2vect.
        pos : np.array, optional
            3D Cartesian position vector(s).
        x : float(s), optional
            Plotting x coordinate(s).
        y : float(s), optional
            Plotting y coordinate(s).
        a1vect : np.array, optional
            Vector for the a1 fractional coordinates.  Default value of None 
            uses the saved a1vect.
        a2vect : np.array, optional
            Vector for the a2 fractional coordinates.  Default value of None 
            uses the saved a2vect.
        xvect : np.array, optional
            Cartesian vector corresponding to the plotting x-axis. If None
            (default), this is taken as the Cartesian of a1vect.
        smooth : bool, optional
            If True (default) the returned values are smoothed using a RBF fit.
            If False, the closest measured values are returned.
        """
        if not self.__hasdata:
            raise AttributeError('gamma surface data not set')
        
        smooth = kwargs.pop('smooth', True)

        # Convert x, y to a1, a2
        if 'x' in kwargs:
            x = kwargs.pop('x')
            y = kwargs.pop('y')
            a1vect = kwargs.pop('a1vect', None)
            a2vect = kwargs.pop('a2vect', None)
            xvect = kwargs.pop('xvect', None)
            assert len(kwargs) == 0, 'Unknown/incompatible arguments given'
            a1, a2 = self.xy_to_a12(x, y, a1vect=a1vect, a2vect=a2vect, xvect=xvect)
        
        # Convert pos to a1, a2
        elif 'pos' in kwargs:
            pos = kwargs.pop('pos')
            a1vect = kwargs.pop('a1vect', None)
            a2vect = kwargs.pop('a2vect', None)
            assert len(kwargs) == 0, 'Unknown/incompatible arguments given'
            a1, a2 = self.pos_to_a12(pos, a1vect=a1vect, a2vect=a2vect)
        
        # Get a1, a2 from kwargs
        else:
            a1 = np.array(kwargs.pop('a1'))
            a2 = np.array(kwargs.pop('a2'))
            a1vect = kwargs.pop('a1vect', None)
            a2vect = kwargs.pop('a2vect', None)
            assert len(kwargs) == 0, 'Unknown/incompatible arguments given'
            if a1vect is not None or a2vect is not None:
                shape = a1.shape
                # Convert into pos using given a1vect, a2vect, then back into a1, a2
                pos = self.a12_to_pos(a1, a2, a1vect=a1vect, a2vect=a2vect)
                a1, a2 = self.pos_to_a12(pos)
                a1 = a1.reshape(shape)
                a2 = a2.reshape(shape)

        # Return interpolated values
        if smooth:
            cushion = (1 - self.data.a1.max()) / 2
    
            # Wrap all a1, a2 values within [-cushion, 1.0 - cushion)
            while np.any(a1 >= 1.0 - cushion): 
                a1[a1 >= 1.0 - cushion] -= 1.0
            while np.any(a1 < -cushion): 
                a1[a1 < -cushion] += 1.0
            while np.any(a2 >= 1.0 - cushion): 
                a2[a2 >= 1.0 - cushion] -= 1.0
            while np.any(a2 < -cushion): 
                a2[a2 < -cushion] += 1.0
            
            # Compute weighting factors
            def zone1(x):
                return (x + cushion) / (2 * cushion)
            def zone2(x):
                return np.ones_like(x)
            x = np.piecewise(a1, [a1 < cushion, a1>= cushion], [zone1, zone2])
            y = np.piecewise(a2, [a2 < cushion, a2>= cushion], [zone1, zone2])
            
            # Linear smoothing across boundaries
            return ( x * y * self.__E_gsf_fit(a1, a2)
                + x * (1 - y) * self.__E_gsf_fit(a1, a2 + 1)
                + (1 - x) * y * self.__E_gsf_fit(a1 + 1, a2)
                + (1 - x) * (1 - y) * self.__E_gsf_fit(a1 + 1, a2 + 1))
        
        # Return nearest values
        else:

            # Wrap all values within 0.0 < a1, a2 < 1.0
            while np.any(a1 > 1.0): 
                a1[a1 > 1.0] -= 1.0
            while np.any(a1 < 0.0): 
                a1[a1 < 0.0] += 1.0
            while np.any(a2 > 1.0): 
                a2[a2 > 1.0] -= 1.0
            while np.any(a2 < 0.0): 
                a2[a2 < 0.0] += 1.0

            return self.__E_gsf_nearest(np.array([a1.flatten(), a2.flatten()]).T).reshape(a1.shape)
コード例 #54
0
def piecewise_linear_3(x, x0, x1, y0, a1, a2, a3):
    condlist = [x <= x0, x <= x1, x1 < x]
    funclist = [lambda x: a1*x + y0, lambda x: a2*x + (a1*x0 + y0 - a2*x0), lambda x: a3*x + (a2*(x1-x0) + a1*x0 + y0) - a3*x1, lambda x: 0]
    print(len(condlist), len(funclist))
    return np.piecewise(x, condlist, funclist)
コード例 #55
0
def piecewise_linear(x, x0, y0, k1, k2):
    return np.piecewise(
        x, [x < x0],
        [lambda x: k1 * x + y0 - k1 * x0, lambda x: k2 * x + y0 - k2 * x0])
コード例 #56
0
import matplotlib.pyplot as plt
import numpy as np
import pdb

x = np.linspace(-1, 1, 1000)

cutoff = 0.3
satslope = 10
y = np.piecewise(
    x, [x < -cutoff,
        np.logical_and(x >= -cutoff, x < cutoff), x >= cutoff], [
            lambda x: x * satslope +
            (satslope - 1) * cutoff, lambda x: x, lambda x: x * satslope -
            (satslope - 1) * cutoff
        ])

plt.plot(x, y)
plt.show()
コード例 #57
0
def f(x, b):
    return np.piecewise(x, [x < -b, x > b], [0, 1, 5])
コード例 #58
0
ファイル: parikkel_boks.py プロジェクト: ETStorli/kvante1
from scipy.sparse import diags
import scipy.linalg as la
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import scipy.constants as sc

l = 1e-9  # Lengde på boksen
Dx = 1.0E-11  # Steglengden
x = np.arange(0, l, Dx)  # x-kooridnatene
size = len(x)  # Størrelsen på matrisa
V = np.zeros(size)  # Potensialet, som et array

# konstanter, definert ved hjelp av scipy - biblioteket
h = sc.h
hbar = sc.hbar
m = sc.m_e
c = sc.c


def analy(i):
    E = (i**2 * sc.pi**2 * hbar**2) / (2 * m * l**2)
    return E / sc.eV


n = np.arange(1, (size + 1), 1)
V = np.piecewise(x, [x < 0, x > l], [np.inf, np.inf, 0])
energi_funk = np.sqrt(2 / l) - np.sin((n * np.pi * x) / l)
engeri_verdi = (n * np.pi * hbar) / (2 * m * l)
コード例 #59
0
def Vpot(x):  # Pozo de potencial
    y=np.piecewise(x, [x < -1, x >= 1],[lambda x:20, lambda x:20])
    return y
コード例 #60
0
    x_train, x_valid, y_train, y_valid, ids_train, ids_valid = train_test_split(
        X_train,
        Y_train,
        np.array(datamanager.train_ids),
        test_size=0.08,
        stratify=coverage[:, 1],
        random_state=RANDOM_STATE[FOLD_NUMBER])

    x_train_, y_train_ = augment_images(x_train, y_train)

    if PRED_ON_TRAIN:
        x_valid = x_train_
        y_valid = y_train_
        ids_valid = ids_train

    y_train_ = np.piecewise(y_train_, [y_train_ > 127.5, y_train_ < 127.5],
                            [1, 0])
    y_valid = np.piecewise(y_valid, [y_valid > 127.5, y_valid < 127.5], [1, 0])

    assert x_train_.shape[1:] == x_valid.shape[1:]
    time_delta = datetime.datetime.now() - start_time
    print('Loading time', time_delta)

if MODEL:
    amodel = create_model((datamanager.img_size_input,
                           datamanager.img_size_input, datamanager.im_chan))
    if LOAD_PREV_MODEL:
        print('Loading weights')
        amodel.load_weights('base_model.h5')
    if TRAIN:
        print('Start training')
        #