Exemplo n.º 1
0
def T_Owen_int(h, a, jmax=50, cut_point=6):
    """
    Return Owens T
    ==============
    @param: h   the h parameter of Owen's T
    @param: a   the a parameter of Owen's T (-1 <= a <= 1)
    Python-numpy-scipy version for Owen's T translated from matlab version
        T_owen.m of R module sn.T_int
    """
    if type(h) in (float, float64):
        h = array([h])
    low = where(h <= cut_point)[0]
    high = where(h > cut_point)[0]
    n_low = low.size
    n_high = high.size
    irange = arange(0, jmax)
    series = zeros(h.size)
    if n_low > 0:
        h_low = h[low].reshape(n_low, 1)
        b = fui(h_low, irange)
        cumb = b.cumsum(axis=1)
        b1 = np_exp(-0.5 * h_low**2) * cumb
        matr = ones((jmax, n_low)) - b1.transpose()  # matlab ' means transpose
        jk = kron(ones(jmax), [1.0, -1.0])
        jk = jk[0:jmax] / (2 * irange + 1)
        matr = inner((jk.reshape(jmax, 1) * matr).transpose(),
                     a**(2 * irange + 1))
        series[low] = (np_arctan(a) - matr.flatten(1)) / (2 * pi)
    if n_high > 0:
        h_high = h[high]
        atana = np_arctan(a)
        series[high] = (atana * np_exp(-0.5 * (h_high**2) * a / atana) *
                        (1.0 + 0.00868 * (h_high**4) * a**4) / (2.0 * pi))
    return series
Exemplo n.º 2
0
def T_Owen_int(h, a, jmax=50, cut_point=6):
    """
    Return Owens T
    ==============
    @param: h   the h parameter of Owen's T
    @param: a   the a parameter of Owen's T (-1 <= a <= 1)
    Python-numpy-scipy version for Owen's T translated from matlab version
        T_owen.m of R module sn.T_int
    """
    if type(h) in (float, float64):
        h = array([h])
    low = where(h <= cut_point)[0]
    high = where(h > cut_point)[0]
    n_low = low.size
    n_high = high.size
    irange = arange(0, jmax)
    series = zeros(h.size)
    if n_low > 0:
        h_low = h[low].reshape(n_low, 1)
        b = fui(h_low, irange)
        cumb = b.cumsum(axis=1)
        b1 = np_exp(-0.5 * h_low ** 2) * cumb
        matr = ones((jmax, n_low)) - b1.transpose()  # matlab ' means transpose
        jk = kron(ones(jmax), [1.0, -1.0])
        jk = jk[0: jmax] / (2 * irange + 1)
        matr = inner((jk.reshape(jmax, 1) * matr).transpose(),
                     a ** (2 * irange + 1))
        series[low] = (np_arctan(a) - matr.flatten(1)) / (2 * pi)
    if n_high > 0:
        h_high = h[high]
        atana = np_arctan(a)
        series[high] = (atana * np_exp(-0.5 * (h_high ** 2) * a / atana) *
                    (1.0 + 0.00868 * (h_high ** 4) * a ** 4) / (2.0 * pi))
    return series
Exemplo n.º 3
0
def funbgh(s, a, b, R, df):
    sqrt_df = np.sqrt(df+0.5)
    ret = chi_logpdf(s,df)
    ret += np_log(mvstdnormcdf(s*a/sqrt_df, s*b/sqrt_df, R,
                                         maxpts=1000000, abseps=1e-6))
    ret = np_exp(ret)
    return  ret
Exemplo n.º 4
0
def funbgh2(s, a, b, R, df):
    n = len(a)
    sqrt_df = np.sqrt(df)
    #np.power(s, df-1) * np_exp(-s*s*0.5)
    return  np_exp((df-1)*np_log(s)-s*s*0.5) \
           * mvstdnormcdf(s*a/sqrt_df, s*b/sqrt_df, R[np.tril_indices(n, -1)],
                          maxpts=1000000, abseps=1e-4)
Exemplo n.º 5
0
def ArrheniusRate(barrier):
    #For now setting these here, Ideally we'd have a way to pass in this variable.
    A = 1.0e12
    T = 300
    kb = 8.617e-5  # units of ev/K
    from numpy import exp as np_exp
    return A * np_exp(-barrier / (kb * T))
Exemplo n.º 6
0
def plot_derivs(df, prms=False, n=6):
    deriv = diff(df.y) / diff(df.x)

    fig, ax = subplots(figsize=(15, 10))
    ax.plot(df.x[:-1], deriv, 'k-', linewidth=1)

    ax.set_xlabel('T/C')
    ax.set_ylabel('Weight derivative/ % T$^{-1}$')

    if prms:
        pred_deriv = 0
        for i in range(n):
            A, k, s = prms[f'A{i}'], prms[f'k{i}'], prms[f's{i}']

            expc = np_exp(k * (df.x - s))  #Exponential term
            func_i = -A * k * expc / (expc + 1)**2
            pred_deriv += func_i
            ax.plot(df.x, func_i, '-.')

    ax.grid()
    #ax.set_xlim(300,1000)
    #ax.set_ylim(-1,0.3)
    #ax.plot(df.x,pred_deriv,'-',color='lime')
    #savefig('Deriv.png',dpi=300)
    show()
Exemplo n.º 7
0
def approach_goal(y, dy, goal):
    # based on Hoffmann (2009) but instead of
    # avoiding obstacles, we approach a goal

    gamma = 10  # 1/5
    beta = 1 / np.pi
    p = np.zeros(2)

    if np_norm(dy) > 1e-5:
        # calculate current heading
        phi_dy = np.arctan2(dy[1], dy[0])
        # calc vector to goal
        goal_vec = goal - y
        phi_goal = np.arctan2(goal_vec[1], goal_vec[0])

        # angle diff
        phi = phi_goal - phi_dy

        # tuned inverse sigmoid to create force towards goal
        dphi = gamma * phi * np_exp(-beta * np_abs(phi))
        pval = goal_vec * dphi
        # print("force vector:", pval, dy)

        p += pval
    return p
Exemplo n.º 8
0
def funbgh2(s, a, b, R, df):
    n = len(a)
    sqrt_df = np.sqrt(df)
    #np.power(s, df-1) * np_exp(-s*s*0.5)
    return np_exp((df-1)*np_log(s)-s*s*0.5) \
           * mvstdnormcdf(s*a/sqrt_df, s*b/sqrt_df, R[np.tril_indices(n, -1)],
                          maxpts=1000000, abseps=1e-4)
Exemplo n.º 9
0
def funbgh(s, a, b, R, df):
    sqrt_df = np.sqrt(df + 0.5)
    ret = chi_logpdf(s, df)
    ret += np_log(
        mvstdnormcdf(s * a / sqrt_df,
                     s * b / sqrt_df,
                     R,
                     maxpts=1000000,
                     abseps=1e-6))
    ret = np_exp(ret)
    return ret
Exemplo n.º 10
0
def image_gaussian(kernel_sig_x=None,kernel_sig_y=None,l_mesh=None,m_mesh=None,cell_reso=None):
    '''Takes desired properties for a kernel in u,v space (in pixel coords),
    and creates FT of this'''

    fiddle = 2*pi
    sig_l, sig_m = 1.0/(fiddle*cell_reso*kernel_sig_x), 1.0/(fiddle*cell_reso*kernel_sig_y)

    l_bit = l_mesh*l_mesh / (2*sig_l*sig_l)
    m_bit = m_mesh*m_mesh / (2*sig_m*sig_m)

    return np_exp(-(l_bit + m_bit))
Exemplo n.º 11
0
def derivs(f, x, params):
    # Electrostatic potential.
    phi = f[0]
    # Electric field.
    e   = f[1]
    # Calculate vi.
    vi  = np_sqrt(params[0]**2 - 2*phi)
    # Derivatives (d2phidx2 is actually de/dx which is the negative of d^2phi/dx^2).
    dphidx   = -e
    d2phidx2 = params[0]/vi - np_exp(phi)
    # Result of the function in the order f is given.
    return [dphidx, d2phidx2]
Exemplo n.º 12
0
def gaussian(sig_x=None,sig_y=None,gridsize=KERNEL_SIZE,x_offset=0,y_offset=0):
    '''Creates a gaussian array of a specified gridsize, with the
    the gaussian peak centred at an offset from the centre of the grid'''
    x_cent = int(gridsize / 2.0) + x_offset
    y_cent = int(gridsize / 2.0) + y_offset

    x = arange(gridsize)
    y = arange(gridsize)
    x_mesh, y_mesh = meshgrid(x,y)

    x_bit = (x_mesh - x_cent)*(x_mesh - x_cent) / (2*sig_x*sig_x)
    y_bit = (y_mesh - y_cent)*(y_mesh - y_cent) / (2*sig_y*sig_y)

    amp = 1 / (2*pi*sig_x*sig_y)
    gaussian = amp*np_exp(-(x_bit + y_bit))
    return gaussian
Exemplo n.º 13
0
    def selfUpdate(self):
        '''First run the self-update function of superclass, 
            then convert unit-value to actuator value,
            then operate actuator on the unit value scaled 
            to the actuator range'''
        
        super(HomeoUnitNewtonianActuator, self).selfUpdate()
        
        #=======================================================================
        # 'write value to file, if needed'
        # if self._fileOut is not None:
        #     self._fileOut.write(str(self.criticalDeviation))
        #     self._fileOut.flush()
        #=======================================================================
            
        #=======================================================================
        # '''For testing'''
        # if self.actuator._wheel == 'right':
        #     self.rightSpeed = scaleTo([-self.maxDeviation,self.maxDeviation],self.transducer.range(),self.criticalDeviation)
        # else:
        #     self.leftSpeed = scaleTo([-self.maxDeviation,self.maxDeviation],self.transducer.range(),self.criticalDeviation)
        # delta = self.leftSpeed - self.rightSpeed 
        # if abs(delta) > self.maxDelta:
        #     self.maxDelta = abs(delta)
        # hDebug('unit', ("The unit value is %f and its scaled value is %f. The delta b/w wheels is %f and maxDelta is %f" % (self.criticalDeviation,
        #                                                            scaleTo([-self.maxDeviation,self.maxDeviation],self.transducer.range(),self.criticalDeviation),
        #                                                            delta,
        #                                                            self.maxDelta))
        # 'end testing'
        #=======================================================================

#        setSpeed = scaleTo([-self.maxDeviation,self.maxDeviation],self.transducer.range(),self.criticalDeviation)        
#        setSpeed = self.criticalDeviation
        ''' Use logistic function to normalize speed to [-1,1]'''        
        if self._maxSpeed is None:
            try:
                self._maxSpeed = self._transducer.range()[1]* self._maxSpeedFraction
            except:
                raise HomeoUnitError("Cannot get max speed from Transducer")
        hDebug('unit', ("critDev for unit: %s is %.3f" % (self.name, self.criticalDeviation)))                  
        setSpeed = float(-self._maxSpeed) + ((2 * self._maxSpeed)/ (1+np_exp(- self._switchingRate * self.criticalDeviation)))
        setSpeed = round(setSpeed,3)
        hDebug('unit', ("Speed set by %s is %f with critDev: %.3f " % (self.name, setSpeed, self.criticalDeviation)))
        self.transducer.funcParameters = setSpeed
        self.transducer.act()
Exemplo n.º 14
0
def plot_f(df, prms, pts):
    def f(prms, X, n):
        func = prms['B']
        for i in range(n):
            A, k, s = prms[f'A{i}'], prms[f'k{i}'], prms[f's{i}']
            func += A / (1 + np_exp(k * (X - s)))
        return func

    n = pts.shape[1]
    pred = f(prms, array(df.x), n).flatten()

    fig, ax = subplots(figsize=(15, 10))
    ax.plot(df.x, pred, 'r-')
    ax.plot(df.x, df.y, 'k--')

    for i in range(n):
        A, k, s = prms[f'A{i}'], prms[f'k{i}'], prms[f's{i}']
        func_i = A / (1 + np_exp(k * (df.x - s))) + pts[1, i]
        #The last term moves the funtion up or down to match the chosen center
        ax.plot(df.x, func_i, '--')
    show()
Exemplo n.º 15
0
def image2kernel(image=None,cell_reso=None,u_off=0.0,v_off=0.0,l_mesh=None,m_mesh=None):
    '''Takes an input image array, and FTs to create a kernel
    Uses the u_off and v_off (given in pixels values), cell resolution
    and l and m coords to phase    shift the image, to create a kernel
    with the given u,v offset'''

    ##TODO WARNING - if you want to use a complex image for the kernel,
    ##may need to either take the complex conjugate, or flip the sign in
    ##the phase shift, or reverse the indicies in l_mesh, m_mesh. Or some
    ##combo of all!! J. Line 20-07-2016
    phase_shift_image =  image * np_exp(2.0j * pi*(u_off*cell_reso*l_mesh + v_off*cell_reso*m_mesh))
    #phase_shift_image =  image * np_exp(2j * pi*(u_off*l_mesh + v_off*m_mesh))

    ##FFT shift the image ready for FFT
    phase_shift_image = fft.ifftshift(phase_shift_image)
    ##Do the forward FFT as we define the inverse FFT for u,v -> l,m.
    ##Scale the output correctly for the way that numpy does it, and remove FFT shift
    recovered_kernel = fft.fft2(phase_shift_image) / (image.shape[0] * image.shape[1])
    recovered_kernel = fft.fftshift(recovered_kernel)
    #return recovered_kernel
    return recovered_kernel
Exemplo n.º 16
0
def gaussian(x, mu, sig):
    """ Not normally distributed!
    """
    diff = np.array([x - mu])
    return np_exp((-np_sqrt(np_dot(diff, diff))**2.) / (2. * sig**2.))
Exemplo n.º 17
0
# Plot electrostatic potential and electric field.
ax1.plot(x,y[:, 0], label = r"Electrostatic Potential, $\phi$", linestyle = "-")
ax1.plot(x,y[:, 1], label = r"Electric Field, $E$", linestyle = "-")
ax1.set_xlabel(r"Debye Lengths")
ax1.set_ylabel(r"Normalised Potential \& Electric Field")
ax1.grid(b = True, which = "major", linestyle = "--", alpha = 0.6)
# Minor ticks option.
#ax1.grid(b = True, which = "minor", linestyle = "-.", alpha = 0.05)
#ax1.minorticks_on()
ax1.legend(loc = 3)

# Plot current.
mi = 1840
me = 1
j  = np_sqrt(mi/(2*np_pi*me)) * np_exp(y[:,0]) - 1

ax2.plot(x, j, label = r"Current, $J$")
ax2.set_xlabel(r"Debye Lengths")
ax2.set_ylabel(r"Normalised Current")
ax2.grid(b = True, which = "major", linestyle = "--", alpha = 0.6)
# Minor ticks option.
#ax2.grid(b = True, which = "minor", linestyle = "-.", alpha = 0.05)
#ax2.minorticks_on()
ax2.legend(loc = 0)

# Tighten layout.
plt.tight_layout()
# Show figure.
plt.show()
# Save figure.
Exemplo n.º 18
0
def chi_pdf(x, df):
    tmp = (df-1.)*np_log(x) + (-x*x*0.5) - (df*0.5-1)*np_log(2.0) \
          - sps_gammaln(df*0.5)
    return np_exp(tmp)
Exemplo n.º 19
0
 def f(prms, X, n):
     func = prms['B']
     for i in range(n):
         A, k, s = prms[f'A{i}'], prms[f'k{i}'], prms[f's{i}']
         func += A / (1 + np_exp(k * (X - s)))
     return func
Exemplo n.º 20
0
 def exponentiate(self):
     result_df = np_exp(self._df)
     return Curve("", self._df.X, result_df.Y)
Exemplo n.º 21
0
def rate(diff):
    J = 1.0
    kbT = 1.0
    from numpy import exp as np_exp
    return min(1.0, np_exp(-diff * J / kbT))
Exemplo n.º 22
0
 def BoltzmannP(self, Enew):
     '''Given a new value of the energy, return the Boltzmann factor'''
     return np_exp(-(Enew - self.E) / self.T)
Exemplo n.º 23
0
def gaussian(x, mu, sig):
    return np_exp(-np_power(x - mu, 2.) / (2 * np_power(sig, 2.)))
Exemplo n.º 24
0
def soft_max(distribution):
    """ Calculate softmax for given distribution
    """
    sum_exps = np_sum(np_exp(distribution[:, 0]), axis=0)
    distribution[:, 0] = np_exp(distribution[:, 0]) / sum_exps
    return distribution
Exemplo n.º 25
0
def search_isa(
    seed_node, scaler, par_inputs_fn
):  # Picks out of a subset of its neighbors and adds the best node
    with open(par_inputs_fn, 'rb') as f:
        inputs = pickle_load(f)
    with open(inputs['modelfname'], 'rb') as f:
        model = pickle_load(f)

    folNm = inputs['folNm']
    folNm_out = inputs['folNm_out']

    score_prev = 0
    cd, g1 = starting_edge(folNm, seed_node)
    if cd == 0:
        return
    max_nodes = inputs["max_size"] - len(g1)

    num_iter = 1
    last_iter_imp = 0
    thres_neig = inputs["thres_neig"]
    T = inputs["T0"]  # T0 value
    alpha = inputs["alpha"]

    while num_iter < max_nodes:  # Limiting number of iteration rounds

        logging_debug("Adding next node")
        # neig_list_old = neig_list
        # g1, cc, node_to_add, score_curr, comp_bool, rand_flag, neig_list = add_top_neig(g1, thres_neig, folNm, inputs, model, scaler, neig_list)
        g1, cc, node_to_add, score_curr, comp_bool, rand_flag = add_top_neig(
            g1, thres_neig, folNm, inputs, model, scaler)
        if (score_curr is None) or (comp_bool is None):
            score_curr, comp_bool = get_score(g1, model, scaler,
                                              inputs['model_type'])

        if cc == 0:
            break
        if score_curr < inputs["classi_thresh"]:
            logging_debug("Complex found")

            # Remove the node last added
            g1.remove_node(node_to_add)
            break

        cur_trial = rand_uniform(low=0.0, high=1.0)
        if score_curr < score_prev:

            prob_isa = np_exp((score_curr - score_prev) / T)
            if cur_trial > prob_isa:
                # Remove the node last added
                g1.remove_node(node_to_add)
                # neig_list = neig_list_old
            else:
                logging_debug("Accepting with low probability")
                rand_flag = 1
        elif score_curr > score_prev:
            last_iter_imp = num_iter

        if (num_iter - last_iter_imp
            ) > 10:  # Has been a long time since a score improvement
            logging_debug("Long time since score improvement")
            break

        score_prev = score_curr
        num_iter += 1
        T = float(T) / alpha

    # If number of nodes is less than 2, don't write.
    with open(folNm_out + "/" + seed_node, 'wb') as f:
        pickle_dump((frozenset(g1.nodes()), score_prev), f)
Exemplo n.º 26
0
def rate(diff):
    J   = 1.0
    kbT = 1.0
    from numpy import exp as np_exp
    return min(1.0, np_exp(-diff*J/kbT))
Exemplo n.º 27
0
def chi_pdf(x, df):
    tmp = (df-1.)*np_log(x) + (-x*x*0.5) - (df*0.5-1)*np_log(2.0) \
          - sps_gammaln(df*0.5)
    return np_exp(tmp)