Exemple #1
0
def plot_Scatter(fig,
                 x,
                 y,
                 subx1,
                 suby2,
                 subsize,
                 title,
                 xlabel,
                 ylabel,
                 linestyle,
                 errlow=[],
                 errhigh=[],
                 bound=False):
    x = np.array(x)
    y = np.array(y)

    if errlow == []:
        errlow = np.zeroes_like(x)
    else:
        errlow = np.array(errlow)

    if errhigh == []:
        errhigh = np.zeroes_like(x)
    else:
        errhigh = np.array(errhigh)

    nonnan = np.logical_not(np.isnan(x)) & np.logical_not(np.isnan(y))
    x = x[nonnan]
    y = y[nonnan]
    errlow = errlow[nonnan]
    errhigh = errhigh[nonnan]

    ax = fig.add_axes([subx1, suby2, subsize, subsize])
    if len(errlow) == 0:
        ax.plot(x, y, 'k', linestyle=linestyle)
    else:
        ax.errorbar(x,
                    y,
                    yerr=[errlow, errhigh],
                    fmt='k',
                    capsize=0,
                    ecolor='k',
                    elinewidth=0.7)
    ax.set_title(title, fontsize=8)
    ax.set_xlabel(xlabel, fontsize=8)
    ax.set_ylabel(ylabel, fontsize=8)
    if bound == True:
        ax.set_xlim(14.0, min(x))
        ax.set_xticks(np.array([14, 12, 10, 8, 6, 4, 2, 0]))
        ax.set_xticklabels(ax.get_xticks(), size=8)
        ax.set_yticklabels(ax.get_yticks(), size=8)
    else:
        ax.set_xlim(max(x), min(x))
        ax.set_xticklabels(ax.get_xticks(), size=8)
        ax.set_yticklabels(ax.get_yticks(), size=8)
        #ax.set_ylim(min(y)*0.8, max(y)*1.2)
        #ax.set_xticklabels(ax.get_xticks(), size=8)
        #ax.set_yticklabels(ax.get_yticks(), size=8)
    return ax
def display_lines(image, lines):
    line_image = np.zeroes_like(image)
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line.reshape(4)
            cv2.line(line_image, (x1, y1), (x2, y2), (0, 255, 0), 5)
    return line_image
Exemple #3
0
def lossFun(inputs, targets, hprev):
    xs, ys, hs, ps = {}, {}, {}, {}

    hs[-1] = np.copy(hprev)
    loss = 0
    #forward pass
    for t in range(len(inputs)):
        xs[t] = np.zeroes((vocab_size, 1))
        xs[t][inputs[t]] = 1
        hs[t] = np.tanh(np.dot(W_hh, hs[t-1]) + np.dot(W_xh, xs[t]) + b_h)
        ys[t] = np.dot(W_hy, hs[t]) + b_y
        ps[t] = np.exp(ys[t])/np.sum(np.exp(ys[t]))
        loss += -np.log(ps[t][targets[t], 0])

    #backward pass
    dW_xh, dW_hh, dW_hy = np.zeroes_like(W_xh), np.zeroes_like(W_hh), np.zeroes_like(W_hy)
    db_h, db_y = np.zeroes_like(b_h), np.zeroes_like(b_y)
    dhnext = 
Exemple #4
0
 def __init__(self, vN, tilt, p, nx1):
     self.nx = np.len(vN)
     self.t = np.round(
         np.append(np.linspace(-tilt, tilt, nx1 / 2),
                   np.linspace(tilt, -tilt, nx1 / 2))).astype(int)
     self.v = np.zeroes_like(vN)
     for j in range(nx):
         self.v[j] = np.roll(vN[j], -int(p), axis=0)
         for i in range(nx1):
             self.v[j, i] = np.roll(self.v[j, i], self.t[i], axis=0)
Exemple #5
0
def squarerootdiff(x0, kappa, theta, sigma, T, M, I, rand, row, cholesky_matrix):
    dt = T/M
    x = np.zeros((M+1,I), dtype=np.float)
    x[0] = x0
    xh=np.zeroes_like(x)
    xh[0]=x0sdt=math.sqrt(dt)
    for t in range(1, M+1):
        ran = np.dot(cholesky_matrix, rand[:,t])
        xh[t] = (xh[t-1]+kappa*(theta-np.maximum(0, xh[t-1]))*dt+np.sqrt(np.maximum(0,xh[t-1]))*simga*ran[row]*sdt)
    x[t] = np.maximum(0, xh[t])
    return x
Exemple #6
0
def pmk_r(x):
    """Calculate the R term of the Partial Mann Kendall test.

    Parameters
    ----------
    x : array
        A chronologically ordered sequence of observations.

    Returns
    -------
    An array of R values used in determing conditional covariance.
    """
    n = len(x)
    r = np.zeroes_like(x)

    for j in np.arange(1, n):
        s = 0

        for i in np.arange(1, n):
            s += np.sum(np.sign(x[j] - x[i]))
            r[j] = (n + 1 + s) / 2

    return r
Exemple #7
0
    def callback_find_obstacle(self, new_LaserScan=LaserScan()):
        data = np.array(new_LaserScan.ranges)
        obstacle = np.zeroes_like(data)

        # in meter
        # relevant_distance = z. B. 20
        #dangerous_distance = z.B. 3

        obstacle[data > self.relevant_distance] = 0
        obstacle[data <= self.relevant_distance
                 & data >= self.dangerous_distance] = 0.5
        obstacle[data < self.dangerous_distance] = 1.

        angle = abs(LaserScan.angle_min) + abs(LaserScan.angle_max)

        # removes all measurements outside of a relevant angle
        data = data[(abs(LaserScan.angle_min) - self.relevant_angle) / angle *
                    len(new_LaserScan):(abs(LaserScan.angel_max) -
                                        self.relevant_angle) / angle *
                    len(new_LaserScan)]

        # if a obsctacel is to close change loop to 'Follow the Wall'
        if max(obstacle) == 1:
            self.line_of_sight = False
Exemple #8
0
    def find_best_route(self, sx, sy, gx, gy):
        start_node = self.Node(sx-self.minx,
                               sy - self.miny, 0, 0)
        goal_node = self.Node(gx - self.minx,
                              gy-self.miny, 0, np.inf)
        
        drops = [self.start_node.copy() for i in range(self.drops)]
        selector = [i for i in range(len(self.motion))]
        cond = True
        neighbour_nodes_x = np.zeros(len(self.motion))
        neighbour_nodes_y = neighbour_nodes_x.copy()
        grads = neighbour_nodes_x.copy()
        probs = grads.copy()
        grads_i = neighbour_nodes_x.copy()
        denom = grads.copy()

        while(self.age<self.maxage):
            erosion_count = np.ones_like(self.obmap, dtype=int)
            erosion_value = np.zeroes_like(self.obmap, dtype=float)
            self.age+=1
            for drop in drops:
                visited[self.calc_index(drop)] = 1
                visited = dict()
                while 1:
                    neighbour_nodes_x = self.motion[:, 0]+drop.x
                    neighbour_nodes_y = self.motion[:, 1]+drop.y
                    grads = self.obmap[neighbour_nodes_x,
                                       neighbour_nodes_y]-self.obmap[drop.x,drop.y]
                    check = self.obmap[neighbour_nodes_x,neighbour_nodes_y]<Wall_height
                    for i, grad in enumerate(grads):
                        if grad<0:
                            grads_i[i]=0
                            probs[i]=grad
                        elif grad>0:
                            grad_i[i]=1
                            probs[i]= self.omega/grad
                        else:
                            grads_i[i]=2
                            probs[i]=self.delta   
                        if visited(calc_index(neighbour_nodes_x[i],neighbour_nodes_y[i])):
                            probs[i]=0
                    probs = np.multiply(probs,check)
                    denom = np.power(probs,self.alpha)
                    if probs==0:
                        self.obmap[drop.x, drop.y] = min(Wall_height, self.obmap[drop.x, drop.y]+drop.sand)
                        drop.x = sx
                        drop.y = sy
                        drop.path_length=0
                        drop.sand=0
                        break 
                    j = random.choices(selector, weights=probs)
                    drop.x=neighbour_nodes_x[j]
                    drop.y = neighbour_nodes_y[j]
                    drop.path_length+=1
                    visited[self.calc_index(drop)]=1
                    erosion_count[drop.x,drop.y]+=1
                    if grads[j] < 0:
                            erosion_value += (
                                self.epsilons[grads_i[j]]*grads[i]/(drop.path_length))
                    elif grads[j]>0:
                            erosion_value += (
                                self.epsilons[grads_i[j]]/(grads[i]*drop.path_length))
                    else:
                            erosion_value += (
                                self.epsilons[grads_i[j]]/(drop.path_length))
                    if drop.x==gx and drop.y==gy:
                        if self.best>drop.path_length:
                            self.maxage=0
                            self.best =drop.path_length

            erosion_value = np.divide(erosion_value,erosion_count)
            self.obmap += self.deposit-erosion_value
            self.obmap[gs,ge]=0.0

        if self.best < np.inf:
            print("path exist")
            px,py = self.calc_final_path()
        else:
            print("path does not exist")

        return px, py
Exemple #9
0
 def predict(self, X, threshold=0.5):
     prob = self.predict_prob(X)
     prediction = np.zeroes_like(prob, dtype=int)
     prediction[prob>threshold]=1
     return predict
Exemple #10
0
# %%
w = .5
y_lp = pm.sample_posterior_predictive_w([trace_1, trace_p],
                                        samples=1000,
                                        models=[model_1, model_p],
                                        weights=[w, 1 - w])

_, ax = plt.subplots(figsize=(10, 6))
az.plot_kde(y_1, plot_kwargs={'color': 'C1'}, label='linear model', ax=ax)
az.plot_kde(y_p, plot_kwargs={'color': 'C2'}, label='order 2 model', ax=ax)
az.plot_kde(y_lp['y_pred'],
            plot_kwargs={'color': 'C3'},
            label='weighted model',
            ax=ax)

plt.plot(y_1s, np.zeroes_like(y_1s), '|', label='observed data')

plt.y_ticks([])
plt.legend()
plt.show()

# %%
coins = 30
heads = 9
y_d = np.repeat([0, 1], [coins - heads, heads])

# %%
with pm.Model() as model_bf:
    p = np.array([.5, .5])
    model_index = pm.Categorical('model_index', p=p)
import numpy as np
import copy

np.random.seed(0)

def sigmoid(x):
    return 1/(1+np.exp(-x))

def sigmoid_prime(x):
    return x*(1-x)

synapse_0 = 2*np.random.random((2,16)) - 1
synapse_1 = 2*np.random.random((16,1)) - 1
synapse_h = 2*np.random.random((16,16)) - 1

synapse_0_update = np.zeroes_like(synapse_0)
synapse_1_update = np.zeroes_like(synapse_1)
synapse_h_update = np.zeroes_like(synapse_h)

X_1 = np.array([1,1])
y_1 = np.array([1])
X_2 = np.array([1,0])
y_2 = np.array([0])
X_3 = np.array([0,1])
y_3 = np.array([0])
X_4 = np.array([0,0])
y_4 = np.array([0])

Xs = [X_1,X_2,X_3,X_4]
Ys = [y_1,y_2,y_3,y_4]
Exemple #12
0
def loopFitJacobian(V, coef_vec):
    """
    Jacobian of 9 parameter fit function

    Parameters
    -----------
    V : 1D numpy array or list
        DC voltages
    coef_vec : 1D numpy array or list
        9 parameter coefficient vector

    Returns
    ---------
    F : 2D numpy array
        function values
    """

    a = coef_vec[:5]
    b = coef_vec[5:]
    d = 1000

    J = np.zeros([len(V), 9], dtype=np.float32)

    V1 = V[:(len(V) / 2)]
    V2 = V[(len(V) / 2):]

    g1 = (b[1] - b[0]) / 2 * (erf((V1 - a[2]) * d) + 1) + b[0]
    g2 = (b[3] - b[2]) / 2 * (erf((V2 - a[3]) * d) + 1) + b[2]

    # Some useful fractions
    oosqpi = 1.0 / np.sqrt(np.pi)
    oob01 = 1.0 / (b[0] + b[1])
    oob23 = 1.0 / (b[2] + b[3])

    # Derivatives of g1 and g2
    dg1a2 = -(b[1] - b[0]) / oosqpi * d * np.exp(-(V1 - a[2])**2)
    dg2a3 = -(b[3] - b[2]) / oosqpi * d * np.exp(-(V2 - a[3])**2)
    dg1b0 = -0.5 * (erf(V1 - a[2]) * d + 1)
    dg1b1 = -dg1b0
    dg2b2 = -0.5 * (erf(V2 - a[3]) * d + 1)
    dg2b3 = -dg2b2

    Y1 = oob01 * (g1 * erf((V1 - a[2]) / g1) + b[0])
    Y2 = oob23 * (g2 * erf((V2 - a[3]) / g2) + b[2])

    # Derivatives of Y1 and Y2
    dY1g1 = oob01 * (erf(
        (V1 - a[2]) / g1) - 2 * oosqpi * np.exp(-(V1 - a[2])**2 / g1**2))
    dY2g2 = oob23 * (erf(
        (V2 - a[4]) / g2) - 2 * oosqpi * np.exp(-(V2 - a[4])**2 / g2**2))

    dY1a2 = -2 * oosqpi * oob01 * np.exp(-(V1 - a[2])**2 / g1**2)

    dY2a3 = -2 * oosqpi * oob01 * np.exp(-(V2 - a[3])**2 / g2**2)

    dY1b0 = oob01 * (1 - Y1)
    dY1b1 = -oob01 * Y1

    dY2b2 = oob23 * (1 - Y2)
    dY2b3 = -oob23 * Y2
    '''
    Jacobian terms
    '''
    zeroV = np.zeroes_like(V1)
    # Derivative with respect to a[0] is always 1
    J[:, 0] = 1

    # Derivative with respect to a[1] is different for F1 and F2
    J[:, 1] = np.hstack(Y1, Y2)

    # Derivative with respect to a[2] is zero for F2, but not F1
    J21 = a[1] * (dY1g1 * dg1a2 + dY1a2)
    J22 = zeroV
    J[:, 2] = np.hstack(J21, J22)

    # Derivative with respect to a[3] is zero for F1, but not F2
    J31 = zeroV
    J32 = a[1] * (dY2g2 * dg2a3 + dY2a3)
    J[:, 3] = np.hstack(J31, J32)

    # Derivative with respect to a[4] is V
    J[:, 4] = V

    # Derivative with respect to b[0] is zero for F2, but not F1
    J51 = a[1] * (dY1g1 * dg1b0 + dY1b0)
    J52 = zeroV
    J[:, 5] = np.hstack(J51, J52)

    # Derivative with respect to b[1] is zero for F2, but not F1
    J61 = a[1] * (dY1g1 * dg1b1 + dY1b1)
    J62 = zeroV
    J[:, 6] = np.hstack(J61, J62)

    # Derivative with respect to b[2] is zero for F1, but not F2
    J71 = zeroV
    J72 = a[1] * (dY2g2 * dg2b2 + dY2b2)
    J[:, 7] = np.hstack(J71, J72)

    # Derivative with respect to b[3] is zero for F1, but not F2
    J81 = zeroV
    J82 = a[1] * (dY2g2 * dg2b3 + dY2b3)
    J[:, 8] = np.hstack(J81, J82)

    return J
np.random.seed(0)


def sigmoid(x):
    return 1 / (1 + np.exp(-x))


def sigmoid_prime(x):
    return x * (1 - x)


synapse_0 = 2 * np.random.random((2, 16)) - 1
synapse_1 = 2 * np.random.random((16, 1)) - 1
synapse_h = 2 * np.random.random((16, 16)) - 1

synapse_0_update = np.zeroes_like(synapse_0)
synapse_1_update = np.zeroes_like(synapse_1)
synapse_h_update = np.zeroes_like(synapse_h)

X_1 = np.array([1, 1])
y_1 = np.array([1])
X_2 = np.array([1, 0])
y_2 = np.array([0])
X_3 = np.array([0, 1])
y_3 = np.array([0])
X_4 = np.array([0, 0])
y_4 = np.array([0])

Xs = [X_1, X_2, X_3, X_4]
Ys = [y_1, y_2, y_3, y_4]