示例#1
0
def solver(sim):
    # State     variables: rho, rho*u, e
    # Primitive variables: rho, u, p
    # Auxiliary variables: c, mach

    # Create a mesh based on given geometry
    x, dx, xh, area, volume = mesh.initialize_mesh(sim.geom, sim.n_elem)

    # Used initial temperature to initialize primitive variables
    T = isentropic_T(sim.inlet_total_T, sim.inlet_mach, sim.gamma)

    # Initialize primitive variables
    p = np.linspace(sim.inlet_p, sim.outlet_p, sim.n_elem, endpoint=True)
    rho = evaluate_rho(p, T, sim.R)
    c = evaluate_c(p, rho, sim.gamma)
    u = evaluate_u(c, sim.inlet_mach)
    e = evaluate_e(rho, T, u, sim.Cv)

    W = np.empty([3, sim.n_elem])
    W = np.array([rho, rho * u, evaluate_e(rho, T, u, sim.Cv)])
    F = np.empty_like(W)
    Q = np.empty_like(W)

    fluxes = np.empty([3, sim.n_elem + 1])

    dt = np.empty_like(volume)
    residual = np.empty_like(W)
    dW = np.empty_like(W)

    W = solve_steady(sim, W, dx, area)

    return W
 def get_potentials_labels(self, mode):
     if mode == 'train':
         return self.potentials_train, np.empty_like(self.potentials_train)
     elif mode == 'test':
         return self.potentials_test, np.empty_like(self.potentials_test)
     else:
         return self.potentials_valid, np.empty_like(self.potentials_valid)
示例#3
0
def visualise_functions():
    nx, ny = (100, 100)
    x = np.linspace(-5, 5, nx)
    y = np.linspace(-5, 5, ny)
    xv, yv = np.meshgrid(x, y)
    eval_convex = np.empty_like(xv)
    eval_rosenbrock = np.empty_like(xv)
    eval_rastrigin = np.empty_like(xv)
    for i in range(nx):
        for j in range(ny):
            eval_convex[i, j] = convex_function([xv[i, j], yv[i, j]])
            eval_rosenbrock[i, j] = rosenbrock([xv[i, j], yv[i, j]])
            eval_rastrigin[i, j] = rastrigin([xv[i, j], yv[i, j]])

    plt.contourf(x, y, eval_convex)
    plt.colorbar()
    plt.show()
    plt.clf()
    plt.contourf(x, y, eval_rosenbrock)
    plt.colorbar()
    plt.show()
    plt.clf()
    plt.contourf(x, y, eval_rastrigin)
    plt.colorbar()
    plt.show()
示例#4
0
 def repeat_to_match_shape(g, A, axis=None):
     gout = np.empty_like(A)
     if np.ndim(gout) == 0:
         gout = g
     else:
         gout = np.ones_like(A) * g
     return gout
示例#5
0
文件: ddp.py 项目: pvarin/ncortex
    def __init__(self, env, x_init, u_init):
        ''' Initialize the DDP solver.
        '''

        self.env = env

        # Get number of states, controls and timesteps.
        self.n_steps, self.n_u = u_init.shape
        n_steps_x, self.n_x = x_init.shape
        assert self.n_steps + 1 == n_steps_x, \
            "Number of control steps must be one less than the number of states"

        # Allocate memory for relevant variables.
        self.x = x_init
        self.u = u_init
        self.du = np.empty_like(u_init)
        self.feedback = np.empty((self.n_steps, self.n_u, self.n_x))

        # Generate one-step cost derivative functions.
        self.l_x = autograd.grad(env.transition_cost, 0)
        self.l_u = autograd.grad(env.transition_cost, 1)
        self.l_xx = autograd.jacobian(self.l_x, 0)
        self.l_xu = autograd.jacobian(self.l_x, 1)
        self.l_uu = autograd.jacobian(self.l_u, 1)

        # Generate the final cost derivative functions.
        self.l_final_x = autograd.grad(env.final_cost, 0)
        self.l_final_xx = autograd.jacobian(self.l_final_x, 0)

        # Generate dynamics derivative functions.
        self.f_x = autograd.jacobian(env.step, 0)
        self.f_u = autograd.jacobian(env.step, 1)
        self.f_xx = autograd.jacobian(self.f_x, 0)
        self.f_xu = autograd.jacobian(self.f_x, 1)
        self.f_uu = autograd.jacobian(self.f_u, 1)
示例#6
0
def optimize(function, method, autodiff):
    eval_points_x = []
    eval_points_y = []

    def fill_eval_points(xk):
        eval_points_x.append(xk[0])
        eval_points_y.append(xk[1])

    x0 = np.array([2.5, 2.5])
    if autodiff:
        jac = grad(function)
    else:
        jac = None

    if method == 'shgo':
        bounds = [(-10, 10), (-10.0, 10.0)]
        res = shgo(function,
                   bounds,
                   callback=fill_eval_points,
                   options={'disp': True})
    else:
        res = minimize(function,
                       x0,
                       method=method,
                       callback=fill_eval_points,
                       jac=jac,
                       options={'disp': True})

    nx, ny = (100, 100)
    x = np.linspace(-5, 5, nx)
    y = np.linspace(-5, 5, ny)
    xv, yv = np.meshgrid(x, y)
    eval_function = np.empty_like(xv)
    for i in range(nx):
        for j in range(ny):
            eval_function[i, j] = function([xv[i, j], yv[i, j]])

    print(function.__name__)
    plt.clf()
    plt.contourf(x, y, eval_function)
    plt.plot(eval_points_x, eval_points_y, 'x-k')
    plt.colorbar()
    neval = res.nfev
    try:
        neval += res.njev
    except:
        print('no njev')
    try:
        neval += res.nhev
    except:
        print('no nhev')
    plt.title('iterations: {} evaluations: {}'.format(res.nit, neval))

    if autodiff:
        ext = '-auto.pdf'
    else:
        ext = '.pdf'

    plt.savefig(function.__name__ + '-' + method + ext)
示例#7
0
 def standardToNat( cls, pi ):
     if( np.any( np.isclose( pi, 0.0 ) ) ):
         n = np.empty_like( pi )
         n[ ~np.isclose( pi, 0.0 ) ] = np.log( pi[ ~np.isclose( pi, 0.0 ) ] )
         n[ np.isclose( pi, 0.0 ) ] = np.NINF
     else:
         n = np.log( pi )
     return ( n, )
 def placement(val):
     total = totalD
     ans = np.empty_like(Ds)
     for i, d in enumerate(Ds):
         total /= d
         ans[i] = val // total
         val -= (val // total) * total
     return ans
示例#9
0
    def _backwardPass(self, F_x, F_u, L_x, L_u, L_xx, L_ux, L_uu):
        V_x = L_x[-1]
        V_xx = L_xx[-1]
        k = np.empty_like(self.k)
        K = np.empty_like(self.K)
        for i in range(self.horizon-1,-1,-1):
            Q_x, Q_u, Q_xx, Q_ux, Q_uu = self._Q(F_x[i], F_u[i], L_x[i], L_u[i], L_xx[i], L_ux[i], L_uu[i], V_x, V_xx)
            k[i] = -np.linalg.solve(Q_uu, Q_u)
            K[i] = -np.linalg.solve(Q_uu, Q_ux)

            V_x = Q_x + K[i].T.dot(Q_uu).dot(k[i])
            V_x += K[i].T.dot(Q_u) + Q_ux.T.dot(k[i])

            V_xx = Q_xx + K[i].T.dot(Q_uu).dot(K[i])
            V_xx += K[i].T.dot(Q_ux) + Q_ux.T.dot(K[i])
            V_xx = 0.5 * (V_xx + V_xx.T)
        return np.array(k), np.array(K)
示例#10
0
文件: ddp.py 项目: pvarin/ncortex
    def forward(self, last_cost=None, dv1=None, dv2=None, stepsize=1.):
        ''' The forward pass of the DDP algorithm.
        '''
        u_proposed = np.empty_like(self.u)
        x_proposed = np.empty_like(self.x)
        x_proposed[0, :] = self.x[0, :]

        for i in range(self.n_steps):
            # Compute the action via the control law.
            x_err = x_proposed[i, :] - self.x[i, :]
            u_proposed[i, :] = self.u[i, :] + \
                               stepsize * self.du[i, :] + \
                               self.feedback[i, :, :].dot(x_err)

            # Evaluate the dynamics.
            x_proposed[i + 1, :] = self.env.step(x_proposed[i, :],
                                                 u_proposed[i, :])

        # Compute the transition cost.
        cost = np.sum(self.env.transition_cost(x_proposed[:-1, :], u_proposed))

        # Add the final cost and return.
        cost += self.env.final_cost(x_proposed[-1, :])

        # Accept if there is no prior cost.
        if last_cost is None:
            self.u = u_proposed
            self.x = x_proposed
            return cost, stepsize

        # Check the linesearch termination condition.
        relative_improvement = (cost - last_cost) / (stepsize * dv1 +
                                                     stepsize**2 * dv2)
        if relative_improvement > .1:
            # Accept the proposal.
            self.u = u_proposed
            self.x = x_proposed
            return cost, stepsize

        # Reduce the stepsize and recurse.
        return self.forward(last_cost=last_cost,
                            dv1=dv1,
                            dv2=dv2,
                            stepsize=.5 * stepsize)
示例#11
0
def sparsepowersum(arr, b, fact=None):
    tmp = np.empty_like(arr.data)
    np.exp(np.multiply(np.log(arr.data, tmp), b, tmp), tmp)
    if not type(arr.indptr) == np.int64:
        indptr = arr.indptr.astype(np.int64)
    else:
        indptr = arr.indptr
    if fact is not None:
        tmp *= fact
    result = pointer_sum(tmp, indptr)
    return result
示例#12
0
    def forwardBaseCase( self ):

        ans = self.pi0

        if( self.chainCuts is not None ):
            if( self.chainCuts[ 0, 0 ] == 0 ):
                ans = np.empty_like( self.pi0 )
                ans[ : ] = np.NINF
                x = self.chainCuts[ 0, 1 ]
                ans[ x ] = 0.0

        return ans + self.emissionProb( 0, forward=True )
示例#13
0
def DP_inv(vec,nx):
    Y = np.reshape(vec,(nx,nx))
    # Y = (Y+Y.T)/2
    s,U = np.linalg.eigh(Y)
    s_x = np.empty_like(s)
    for i in range(len(s)):
        s_x[i] = np.roots([1,-s[i],-1])[np.roots([1,-s[i],-1])>0]
    # print(s_x)
    TT = (U @ np.diag(s_x) @ np.linalg.inv(U))
    b, _ = np.linalg.eig(TT.reshape((nx, nx)))
    # print(b)
    return  TT.reshape((nx**2,1))
示例#14
0
def BC_outlet_residual(sim, W_g, W_d, dt, dx):
    # Returns the update of the ghost vector
    # W_g = Ghost state vector
    # W_d = Domain state vector
    #r_g = np.copy(W_g[0]) # Very important else dW_g = 0
    r_g = W_g[0]  # Very important else dW_g = 0
    u_g = W_g[1] / r_g
    p_g = evaluate_p1(W_g, sim.gamma)
    c_g = evaluate_c(p_g, r_g, sim.gamma)

    r_d = W_d[0]
    u_d = W_d[1] / W_d[0]
    p_d = evaluate_p1(W_d, sim.gamma)
    c_d = evaluate_c(p_d, r_d, sim.gamma)

    dtdx = dt / dx
    avgu = 0.5 * (u_d + u_g)
    avgc = 0.5 * (c_d + c_g)
    eigenvalues0 = avgu * dtdx
    eigenvalues1 = (avgu + avgc) * dtdx
    eigenvalues2 = (avgu - avgc) * dtdx

    dpdx = p_g - p_d
    dudx = u_g - u_d

    Ri0 = -eigenvalues0 * ((r_g - r_d) - dpdx / c_g**2)
    Ri1 = -eigenvalues1 * (dpdx + r_g * c_g * dudx)
    Ri2 = -eigenvalues2 * (dpdx - r_g * c_g * dudx)

    mach_outlet = avgu / avgc
    dp = 0
    if mach_outlet > 1.0:
        dp = 0.5 * (Ri1 + Ri2)

    drho = Ri0 + dp / c_g**2
    du = (Ri1 - dp) / (r_g * c_g)

    u_g_new = u_g + du
    r_g_new = r_g + drho
    p_g_new = p_g + dp
    T_g_new = p_g_new / (r_g_new * sim.R)
    e_g_new = evaluate_e(r_g_new, T_g_new, u_g_new, sim.Cv)

    dW_g = np.empty_like(W_g)
    dW_g[0] = r_g_new - W_g[0]
    dW_g[1] = r_g_new * u_g_new - W_g[1]
    dW_g[2] = e_g_new - W_g[2]
    return dW_g
示例#15
0
    def transitionProb( self, t, t1, forward=False ):

        ans = self.pi

        if( self.chainCuts is not None ):
            t1Index = self.chainCuts[ :, 0 ] == t1

            if( np.any( t1Index ) ):

                # Here, only 1 col of transitions is possible
                assert self.chainCuts[ t1Index ].size == 2
                ans = np.empty_like( self.pi )
                ans[ : ] = np.NINF
                x1 = self.chainCuts[ t1Index, 1 ]
                ans[ :, x1 ] = 0.0

        return ans if forward == True else ans.T
示例#16
0
def noise_inputs(inputs, TEMP, noise_type):
    count = 0
    perturbed = np.empty_like(inputs)
    perturbed[:] = inputs
    perturbed[perturbed == 1] = 5
    perturbed[perturbed == 0] = 1
    if noise_type == 2:
        TEMP = 1
    # [5,1,...] - softmax = [ 0.91610478,  0.01677904,  ...] for 6 dim
    # for each sequence time step, add gumbel noise
    # as per this blog post: http://www.inference.vc/instance-noise-a-trick-for-stabilising-gan-training/
    for pert in perturbed:  # Iterate over time steps.
        noise = npr.gumbel(loc=0.0, scale=1, size=pert.shape)
        output = TEMP * (pert + noise)
        perturbed[count] = output - logsumexp(output, axis=1, keepdims=True)
        count = count + 1
    return perturbed
示例#17
0
def shift(x, offsets):
    """Similar to np.roll, but fills with nan instead of rolling values over.

  Also shifts along multiple axes at the same time.

  Args:
    x: The input array to shift.
    offsets: How much to shift each axis, offsets[i] is the offset for the i-th
      axis.

  Returns:
    An array with same shape as the input, with specified shifts applied.
  """
    def to_slice(offset):
        return slice(offset, None) if offset >= 0 else slice(None, offset)

    out = np.empty_like(x)
    out.fill(np.nan)
    ind_src = tuple(to_slice(-o) for o in offsets)
    ind_dst = tuple(to_slice(o) for o in offsets)
    out[ind_dst] = x[ind_src]
    return out