コード例 #1
0
def main():
    if (len(sys.argv) != 2):
        print "Usage: " + sys.argv[0] + " matrix-name"
        sys.exit(0)
    # end if

    matrixName = sys.argv[1] + ".mtx"
    mm = open(sys.argv[1] + '.mm', 'w')
    outputName = sys.argv[1] + ".png"
    #outputName=sys.argv[1]+ ".pdf"

    (n, n, nz, void, fld, symm) = mminfo(matrixName)

    A = mmread(matrixName).tocsr().tocoo()

    # creating a file in coo format
    #print n, n, A.size
    mm.write(str(n) + ' ' + str(n) + ' ' + str(A.size) + '\n')
    for i in range(A.size):
        mm.write(
            str(A.row[i]) + ' ' + str(A.col[i]) + ' ' + str(A.data[i]) + '\n')
        #print A.row[i]+1, A.col[i]+1 , A.data[i]
    # end for
    #print repr(A)
    #print A.col
    #print A.size
    # end of creating a file in coo format

    #pylab.title("Matrix :" + matrixName, fontsize=22)
    pylab.title("Matrix: " + sys.argv[1] + ", n:" + str(n) + ", nz:" +
                str(A.size) + '\n',
                fontsize=10)
    pylab.spy(A, marker='.', markersize=1)
    pylab.savefig(outputName, format=None)
コード例 #2
0
def plotDf(x,f,title=None):
    """ Quick test routine to display derivative matrices and plot
        derivatives of an arbitrary function f(x)
        input: x: numpy array of mesh-points
               f: function pointer to function to differentiate
    """  
    # calculate first and second derivative matrices
    D1 = setDn(1,x,5) 
#    D1 = setD(1,x) 
    D2 = setD(2,x)
#    
#    print D1
#    print D2
    
    # show sparsity pattern of D1
    pylab.figure()
    pylab.spy(D1)
    pylab.title("Sparsity pattern of D1")
        
    # plot a function and it's derivatives
    y = f(x)    
    pylab.figure()
    pylab.plot(x,y,x,D1*y,x,D2*y)
    pylab.legend(['f','D1*f','D2*f'],loc="best")
    if title:
        pylab.title(title)
    pylab.show()
コード例 #3
0
def plot_possible_hist(mapping, filename, mass_tol, rt_tol):
    no_trans = (mapping > 0).sum(1)
    mini_hist = []
    for i in np.arange(10) + 1:
        mini_hist.append((no_trans == i).sum())
    print 'mini_hist ' + str(mini_hist)
    plt.figure()
    plt.subplot(1, 2, 1)
    plt.bar(np.arange(10) + 1, mini_hist)
    title = 'Binning -- MASS_TOL ' + str(mass_tol) + ', RT_TOL ' + str(rt_tol)
    plt.title(title)
    plt.subplot(1, 2, 2)
    plt.spy(mapping, markersize=1)
    plt.title('possible')
    plt.suptitle(filename)
    plt.show()     
コード例 #4
0
ファイル: Matrix and RHS.py プロジェクト: LeiDai/agros2d
def analyse_matrix_and_rhs(filename_matrix, filename_rhs):  
    # read matrix and rhs from file
    mat_object = sio.loadmat(filename_matrix)
    matrix = mat_object["matrix"]
    rhs_object = sio.loadmat(filename_rhs)
    rhs = rhs_object["rhs"]
    
    # size of the matrix
    print("Matrix size: " + str(len(rhs)))
    print("Number of nonzeros: " + str(matrix.getnnz()) + " (" + str(round(float(matrix.getnnz()) / (len(rhs)**2) * 100.0, 3)) + " %)")
    
    # visualize matrix sparsity pattern
    fig = pl.figure()
    pl.spy(matrix, markersize=1)
    fn_pattern = pythonlab.tempname("png")
    pl.savefig(fn_pattern, dpi=60)
    pl.close(fig)   
    # show in console
    pythonlab.image(fn_pattern)
コード例 #5
0
ファイル: helpers.py プロジェクト: echu/dist_ecos
def show_spy(socp_vars):
    '''Show the sparsity pattern of A and G in
    the socp_vars dictionary
    '''
    import pylab

    pylab.figure(1)
    pylab.subplot(211)
    # print 'A is', socp_vars['A']
    if socp_vars['A'] is not None:
        pylab.spy(socp_vars['A'], marker='.')
    pylab.xlabel('A')

    # print 'G is', socp_vars['G']
    pylab.subplot(212)
    pylab.spy(socp_vars['G'], marker='.')
    pylab.xlabel('G')

    pylab.show()
コード例 #6
0
ファイル: Matrix and RHS.py プロジェクト: smr99/agros2d
def analyse_matrix_and_rhs(filename_matrix, filename_rhs):
    # read matrix and rhs from file
    mat_object = sio.loadmat(filename_matrix)
    matrix = mat_object["matrix"]
    rhs_object = sio.loadmat(filename_rhs)
    rhs = rhs_object["rhs"]

    # size of the matrix
    print("Matrix size: " + str(len(rhs)))
    print("Number of nonzeros: " + str(matrix.getnnz()) + " (" +
          str(round(float(matrix.getnnz()) /
                    (len(rhs)**2) * 100.0, 3)) + " %)")

    # visualize matrix sparsity pattern
    fig = pl.figure()
    pl.spy(matrix, markersize=1)
    fn_pattern = pythonlab.tempname("png")
    pl.savefig(fn_pattern, dpi=60)
    pl.close(fig)
    # show in console
    pythonlab.image(fn_pattern)
コード例 #7
0
def plot_clustering(A, l, v, type="spectral"):
    fig1 = pylab.figure(1)
    x = range(len(v))
    pylab.plot(x, v)
    if type == "spectral":
        pylab.title("v2: $\lambda_2$=%f"%l)
    elif type == "modularity":
        pylab.title("v1: $\lambda_1$=%f"%l)
    else:
        pylab.title("v1")
    pylab.ylabel("Vector component")
    fig1.show()

    fig2 = pylab.figure(2)
    pylab.plot(x, sorted(v))
    if type == "spectral":
        pylab.title("v2 sorted: $\lambda_2$=%f"%l)
    elif type == "modularity":
        pylab.title("v1: $\lambda_1$=%f"%l)
    else:
        pylab.title("v1")
    pylab.ylabel("Vector component")
    fig2.show()

    sorted_indices = sorted((e, i) for i, e in enumerate(v))
    indices = [i for (e, i) in sorted_indices]

    fig3 = pylab.figure(3)
    pylab.spy(A)
    pylab.title("Adjacency Matrix")
    fig3.show()

    A1 = A[:, indices][indices]

    fig4 = pylab.figure(4)
    pylab.spy(A1)
    pylab.title("Adjacency Matrix Sorted")
    fig4.show()

    pylab.show()
コード例 #8
0
def spy(L):
    import pylab

    if isinstance(L, (matrix, spmatrix)):
        pylab.spy(matrix(L))
        return

    n = 0
    for (i, j) in L.keys():
        if i > n:
            n = i

        if j > n:
            n = j

    A = zeros(n+1)

    for (i, j) in L.keys():
        if isnonzero(L[i,j]):
            A[i,j] = 1.0


    pylab.spy(matrix(A))
コード例 #9
0
def generate_mm_and_plot(matrixname):
    matrixName=matrixname+ ".mtx"
    mm = open(matrixname +'.mm', 'w')
    outputName=matrixname + ".png"
    #outputName=matrixname + ".pdf"
    
    (n,n,nz,void,fld,symm) = mminfo(matrixName)
    A = mmread(matrixName).tocsr().tocoo()
    
    # creating a file in coo format    
    #print n, n, A.size
    mm.write( str(n) + ' ' + str(n) + ' ' + str(A.size) + '\n')
    for i in range(A.size):
        mm.write(  str(A.row[i])+ ' ' + str(A.col[i])+ ' ' + str(A.data[i])+  '\n')
        #print A.row[i]+1, A.col[i]+1 , A.data[i]
    # end for    
    #print repr(A)
    #print A.col
    #print A.size
    # end of creating a file in coo format    
    #pylab.title("Matrix :" + matrixname, fontsize=22)
    pylab.title("Matrix: " + matrixname + ", n:" + str(n) + ", nz:" + str(A.size) + '\n' ,fontsize=10 )
    pylab.spy(A,marker='.',markersize=1)
    pylab.savefig(outputName,format=None)
コード例 #10
0
ファイル: jacSparsity.py プロジェクト: cfpperche/casadi
#     Lesser General Public License for more details.
#
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
#
#! jacSparsity
#!======================
from casadi import *
from numpy import *
import casadi as c
from pylab import spy, show

#! We construct a simple SX expression
x = SX.sym("x",40)
y = x[:-2]-2*x[1:-1]+x[2:]

#! Let's see what the first 5 entries of y look like
print y[:5]

#! Next, we construct a function
f = SXFunction([x],[y])
f.init()

#! And we visualize the sparsity of the jacobian
spy(f.jacSparsity())

show()

コード例 #11
0
ファイル: test_fixed_part.py プロジェクト: echu/dist_ecos
    socp_vars = data['socp_vars']
    objval = data['objval']
    N = data['N']
    partition_list = data['partition_list']

    # first, solve with ecos
    import ecos
    sol = ecos.solve(**socp_vars)
    ecos_time = sol['info']['timing']['runtime']

    # next, solve with dist_ecos
    def objective(x):
        return socp_vars['c'].dot(x)

    if args.show_plot:
        pylab.spy(socp_vars['G'], marker='.', alpha=0.2)
        pylab.show()

    t = time.time()
    prox_list, global_indices = form_prox_list(socp_vars, partition_list)
    split_time = time.time() - t

    result = solve(prox_list, global_indices, parallel=True, max_iters=1000, rho=2)

    pri = result['res_pri']
    dual = result['res_dual']

    if args.show_plot:
        pylab.semilogy(range(len(pri)), pri, range(len(dual)), dual)
        pylab.legend(['primal', 'dual'])
        pylab.show()
コード例 #12
0
# Assemble Helmholtz
A = K*scl**2 + kx**2*M

A_t = np.zeros((4*(n+1)-3, 4*(n+1)-3))
A_t[0, 0] = 1
A_t[1:n+1, :n+1] = A[1:]
A_t[n:2*n+1, n:2*n+1] += A[:]
A_t[2*n:3*n+1, 2*n:3*n+1] += A[:]
A_t[3*n:4*n, 3*n:4*n+1] += A[:-1]
A_t[-1, -1] = 1

f_hat = np.zeros(4*n+1)
f_hat[:(n+1)] = np.dot(w*P.T, fj[0])
f_hat[n:2*n+1] += np.dot(w*P.T, fj[1])
f_hat[2*n:3*n+1] += np.dot(w*P.T, fj[2])
f_hat[3*n:4*n+1] += np.dot(w*P.T, fj[3])

f_hat[0] = a
f_hat[-1] = b

u_hat = np.linalg.solve(A_t, f_hat)

uq = np.array([np.dot(P, u_hat[n*i:(i+1)*n+1]) for i in range(4)])

assert np.allclose(uq, uj)

plot(xx.flatten(), uq.flatten())
figure()
spy(A_t, precision=1e-8)
show()
コード例 #13
0
ファイル: sparsity_jac.py プロジェクト: DrLiLab/optCasadi
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     Lesser General Public License for more details.
#
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
#
#! sparsity_jac
#!======================
from casadi import *
from numpy import *
import casadi as c
from pylab import spy, show

#! We construct a simple SX expression
x = SX.sym("x", 40)
y = x[:-2] - 2 * x[1:-1] + x[2:]

#! Let's see what the first 5 entries of y look like
print(y[:5])

#! Next, we construct a function
f = Function("f", [x], [y])

#! And we visualize the sparsity of the jacobian
spy(f.sparsity_jac(0, 0))

show()
コード例 #14
0
def poisson_solver_nc_ds(filename, mesh_no, flag=0):

    mshfile_fullpath = icemcfd_project_folder + filename

    part_names, xy_no, xy_fa, xy_cv, noofa, cvofa, faono, faocv, partofa = umesh_reader.read_unstructured_grid(
        mshfile_fullpath, node_reordering=True)

    # Two slices
    x_slice_1 = np.linspace(1.0, 1.5, 51)
    y_slice_1 = np.linspace(0.1, 0.4, 51)

    x_slice_2 = 1.5 * np.ones(51)
    y_slice_2 = np.linspace(0.3, 0.8, 51)

    nno = xy_no.shape[0]  # No. of nodes
    ncv = xy_cv.shape[0]  # No. of CVs
    nfa = xy_fa.shape[0]  # No. of faces
    partofa1 = np.array(partofa)  # Converting partofa to an array
    faono1 = np.array(faono)  # Converting faono to an array
    cold_bc = np.where(
        partofa1 ==
        'COLD')  # Vectorized approach to find face belonging to part 'COLD'
    hot_bc = np.where(
        partofa1 ==
        'HOT')  # Vectorized approach to find face belonging to part 'HOT'
    solid = np.where(
        partofa1 ==
        'SOLID')  # Vectorized approach to find face belonging to part 'SOLID'

    # Find part to which each node belongs to
    partono = []
    for j in np.arange(nno):
        part_name = partofa1[faono1[j]]
        hot_count = np.array(np.where(part_name == 'HOT')).size
        cold_count = np.array(np.where(part_name == 'COLD')).size
        if cold_count != 0:
            partono.append('COLD')
        elif hot_count != 0:
            partono.append('HOT')
        else:
            partono.append('SOLID')

    partono1 = np.array(partono)

    phi = np.zeros(nno)  #Full phi

    #Temperature for internal nodes
    phi_int = np.zeros(
        nno - np.unique(noofa[cold_bc]).size -
        np.unique(noofa[hot_bc]).size)  # Define zero internal nodes
    nno_int = phi_int.size  # No. of internal nodes

    # Initializing values for hot and cold boundary nodes
    phi_cold = 300
    phi_hot = 500

    #Defining boundary values in phi
    phi[[np.unique(noofa[cold_bc])]] = phi_cold
    phi[[np.unique(noofa[hot_bc])]] = phi_hot

    source = -1.

    if mesh_no == 3:

        # For bivariate fit validation
        max_nn = np.zeros(nno_int)

    A = scysparse.csr_matrix(
        (nno_int, nno_int
         ))  # Thank God that boundary nodes get numbered towards the end!
    b = source * np.ones(nno_int)

    for i in np.arange(nno_int):
        n_nodes = np.unique(
            noofa[faono[i]])  # Neighbouring nodes for the collocation point
        if mesh_no == 3:
            max_nn[i] = n_nodes.size
        x_stencil = xy_no[
            n_nodes,
            0]  # X-co-ordinates of neighbouring nodes of ith node. All of them have been taken as stencil
        y_stencil = xy_no[
            n_nodes,
            1]  # Y-co-ordinates of neighbouring nodes of ith node. All of them have been taken as stencil
        xc = xy_no[i, 0]  # X-co-ordinates of centroid
        yc = xy_no[i, 1]  # Y-co-ordinates of centroid

        # Weights for 2nd derivative for all stencil points
        weights_dx2 = np.zeros(len(n_nodes))
        weights_dy2 = np.zeros(len(n_nodes))
        for ino in range(0, len(n_nodes)):
            phi_base = np.zeros(len(n_nodes))
            phi_base[ino] = 1.0
            _, _, weights_dx2[ino] = fit.BiVarPolyFit_X(
                xc, yc, x_stencil, y_stencil, phi_base)
            _, _, weights_dy2[ino] = fit.BiVarPolyFit_Y(
                xc, yc, x_stencil, y_stencil, phi_base)

        parts = partono1[n_nodes]
        for jj, node in enumerate(n_nodes):
            if parts[jj] == 'COLD':
                b[i] -= phi_cold * (weights_dx2[jj] + weights_dy2[jj])
            elif parts[jj] == 'HOT':
                b[i] -= phi_hot * (weights_dx2[jj] + weights_dy2[jj])
            else:
                A[i, node] += weights_dx2[jj] + weights_dy2[jj]

    if mesh_no == 3:
        pol_validation(mesh_no, max_nn)

    start_time1 = default_timer()
    phi_int = splinalg.spsolve(A, b)
    end_time1 = default_timer() - start_time1
    phi[:nno_int] = phi_int
    plot_data.plot_data(
        xy_no[:, 0], xy_no[:, 1], phi,
        "Mesh " + str(mesh_no) + ": Final Temperature Field Direct Solve.pdf")

    plt.spy(A)
    plt.savefig(figure_folder + "Mesh " + str(mesh_no) + ": Spy of A.pdf")
    plt.close()

    slice_1 = griddata(np.vstack(
        (xy_no[:, 0].flatten(), xy_no[:, 1].flatten())).T,
                       np.vstack(phi.flatten()), (x_slice_1, y_slice_1),
                       method="cubic")
    slice_2 = griddata(np.vstack(
        (xy_no[:, 0].flatten(), xy_no[:, 1].flatten())).T,
                       np.vstack(phi.flatten()), (x_slice_2, y_slice_2),
                       method="cubic")

    if flag == 1:

        print "The time required for execution of spsolve is: 2.10f" % (
            end_time1)
        return (A)

    else:

        return (A, phi, slice_1, slice_2)
コード例 #15
0
def Gradient(filename, mesh_no, flag=0):

    mshfile_fullpath = icemcfd_project_folder + filename

    part_names, xy_no, xy_fa, xy_cv, noofa, cvofa, faono, faocv, partofa = umesh_reader.read_unstructured_grid(
        mshfile_fullpath, node_reordering=True)

    nno = xy_no.shape[0]  # No. of nodes
    ncv = xy_cv.shape[0]  # No. of CVs
    nfa = xy_fa.shape[0]  # No. of faces
    partofa1 = np.array(partofa)  # Converting partofa to an array
    faono1 = np.array(faono)  # Converting faono to an array
    cold_bc = np.where(
        partofa1 ==
        'COLD')  # Vectorized approach to find face belonging to part 'COLD'
    hot_bc = np.where(
        partofa1 ==
        'HOT')  # Vectorized approach to find face belonging to part 'HOT'
    solid = np.where(
        partofa1 ==
        'SOLID')  # Vectorized approach to find face belonging to part 'SOLID'

    # Find part to which each node belongs to
    partono = []
    for j in np.arange(nno):
        part_name = partofa1[faono1[j]]
        hot_count = np.array(np.where(part_name == 'HOT')).size
        cold_count = np.array(np.where(part_name == 'COLD')).size
        if cold_count != 0:
            partono.append('COLD')
        elif hot_count != 0:
            partono.append('HOT')
        else:
            partono.append('SOLID')

    partono1 = np.array(partono)

    Gx_int = scysparse.csr_matrix(
        (ncv, ncv))  # Matrix to calculate X-gradient at CVs
    Gy_int = scysparse.csr_matrix(
        (ncv, ncv))  # Matrix to calculate Y-gradient at CVs

    nfa_int = np.size(np.where(partofa1 == 'SOLID'))
    Avg_cv2f = scysparse.csr_matrix((nfa_int, ncv))

    for i in np.arange(ncv):
        neigh_cv = np.unique(
            cvofa[faocv[i]])  # Gives neighbouring CVs including the central CV
        neigh_cv = np.delete(
            neigh_cv, np.where(neigh_cv == i)
        )  # Find index of central CV and delete that entry from neighbouring CV array
        neigh_cv = np.delete(
            neigh_cv, np.where(neigh_cv == -1)
        )  # Find index of boundary CV and delete the -1 entry from neighbouring CV array
        dx_ik = (xy_cv[neigh_cv, 0] - xy_cv[i, 0]
                 )  # Stores dx for all neighbouring CVs
        dy_ik = (xy_cv[neigh_cv, 1] - xy_cv[i, 1]
                 )  # Stores dy for all neighbouring CVs
        w_ik = 1. / np.sqrt(
            (dx_ik**2) + (dy_ik**2))  # Array of weights for least-squared fit
        a_ik = sum((w_ik * dx_ik)**2)
        b_ik = sum(
            ((w_ik)**2) * dx_ik * dy_ik
        )  #Co-efficients a_ik, b_ik, c_ik from least-squared fitting algorithm.
        c_ik = sum((w_ik * dy_ik)**2)

        det = (a_ik * c_ik) - (b_ik**2)

        # Filling out weights for collocation point
        Gx_int[i, i] -= sum(((c_ik * ((w_ik)**2) * dx_ik) -
                             (b_ik * ((w_ik)**2) * dy_ik)) / det)
        Gy_int[i, i] -= sum(((a_ik * ((w_ik)**2) * dy_ik) -
                             (b_ik * ((w_ik)**2) * dx_ik)) / det)

        for j, n in enumerate(neigh_cv):
            Gx_int[i, n] += ((c_ik * ((w_ik[j])**2) * dx_ik[j]) -
                             (b_ik * ((w_ik[j])**2) * dy_ik[j])) / det
            Gy_int[i, n] += ((a_ik * ((w_ik[j])**2) * dy_ik[j]) -
                             (b_ik * ((w_ik[j])**2) * dx_ik[j])) / det

    for ii in np.arange(nfa_int):
        cvs = cvofa[ii]
        Avg_cv2f[ii, cvs] = 0.5

    Gx = Avg_cv2f * Gx_int
    Gy = Avg_cv2f * Gy_int
    if flag == 1:
        # Validation of gradient evaluation

        phi_cv = analytical_f(xy_cv[:, 0], xy_cv[:, 1])

        grad_phi_analytical_x = grad_x(xy_fa[:nfa_int, 0], xy_fa[:nfa_int, 1])

        grad_phi_analytical_y = grad_y(xy_fa[:nfa_int, 0], xy_fa[:nfa_int, 1])

        grad_phi_num_x = Gx * phi_cv
        grad_phi_num_y = Gy * phi_cv

        plt.quiver(xy_fa[:nfa_int, 0],
                   xy_fa[:nfa_int, 1],
                   grad_phi_analytical_x,
                   grad_phi_analytical_y,
                   color='b')
        plt.quiver(xy_fa[:nfa_int, 0],
                   xy_fa[:nfa_int, 1],
                   grad_phi_num_x,
                   grad_phi_num_y,
                   color='r')
        print "Saving figure: " + figure_folder + "Mesh" + str(
            mesh_no) + "Quiver plot for gradient.pdf"
        plt.savefig(figure_folder + "Mesh" + str(mesh_no) +
                    "Quiver_gradient.pdf")
        plt.close()

        plt.spy(Gx)
        plt.savefig(figure_folder + "Mesh " + str(mesh_no) + ": Spy of Gx.pdf")
        plt.close()

        plt.spy(Gy)
        plt.savefig(figure_folder + "Mesh " + str(mesh_no) + ": Spy of Gy.pdf")
        plt.close()

    return (Gx, Gy)
コード例 #16
0
opti.subject_to(pos[0] == 0)  # start at position 0 ...
opti.subject_to(speed[0] == 0)  # ... from stand-still
opti.subject_to(pos[-1] == 1)  # finish line at position 1

# ---- misc. constraints  ----------
opti.subject_to(T >= 0)  # Time must be positive

# ---- initial values for solver ---
opti.set_initial(speed, 1)
opti.set_initial(T, 1)

# ---- solve NLP              ------
opti.solver("ipopt")  # set numerical backend
sol = opti.solve()  # actual solve

# ---- post-processing        ------
from pylab import plot, step, figure, legend, show, spy

plot(sol.value(speed), label="speed")
plot(sol.value(pos), label="pos")
plot(limit(sol.value(pos)), 'r--', label="speed limit")
step(range(N + 1), sol.value(U), 'k', label="throttle")
legend(loc="upper left")

figure()
spy(sol.value(jacobian(opti.g, opti.x)))
figure()
spy(sol.value(hessian(opti.f + dot(opti.lam_g, opti.g), opti.x)[0]))

show()
コード例 #17
0
ファイル: sparsity_jac.py プロジェクト: casadi/casadi
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     Lesser General Public License for more details.
#
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
#
#! sparsity_jac
#!======================
from casadi import *
from numpy import *
import casadi as c
from pylab import spy, show

#! We construct a simple SX expression
x = SX.sym("x",40)
y = x[:-2]-2*x[1:-1]+x[2:]

#! Let's see what the first 5 entries of y look like
print(y[:5])

#! Next, we construct a function
f = Function("f", [x],[y])

#! And we visualize the sparsity of the jacobian
spy(f.sparsity_jac(0, 0))

show()
コード例 #18
0
ファイル: race_car.py プロジェクト: casadi/casadi
opti.subject_to(pos[0]==0)   # start at position 0 ...
opti.subject_to(speed[0]==0) # ... from stand-still 
opti.subject_to(pos[-1]==1)  # finish line at position 1

# ---- misc. constraints  ----------
opti.subject_to(T>=0) # Time must be positive

# ---- initial values for solver ---
opti.set_initial(speed, 1)
opti.set_initial(T, 1)

# ---- solve NLP              ------
opti.solver("ipopt") # set numerical backend
sol = opti.solve()   # actual solve

# ---- post-processing        ------
from pylab import plot, step, figure, legend, show, spy

plot(sol.value(speed),label="speed")
plot(sol.value(pos),label="pos")
plot(limit(sol.value(pos)),'r--',label="speed limit")
step(range(N),sol.value(U),'k',label="throttle")
legend(loc="upper left")

figure()
spy(sol.value(jacobian(opti.g,opti.x)))
figure()
spy(sol.value(hessian(opti.f+dot(opti.lam_g,opti.g),opti.x)[0]))

show()
コード例 #19
0
# HELLO Assembles HELLO matrix.  See Trefethen&Bau Exercise 9.3.
from pylab import ones, zeros, spy, show

bl = ones((8,6))
H = bl.copy()
H[0:3,2:4] = zeros((3,2))
H[5:8,2:4] = zeros((3,2))
E = bl.copy()
E[2,2:6]   = zeros((1,4))
E[5,2:6]   = zeros((1,4)) 
L = bl.copy()
L[0:6,2:6] = zeros((6,4))
O = bl.copy()
O[2:6,2:4] = zeros((4,2))

HELLO = zeros((15,40))
HELLO[1:9,1:7]    = H
HELLO[2:10,9:15]  = E
HELLO[3:11,17:23] = L
HELLO[4:12,25:31] = L
HELLO[5:13,33:39] = O

spy(HELLO,marker='.'); show()
コード例 #20
0
    #追跡用画像作成。サイズは適当に。
    init_pos = (120,160)
    images = create_images((320,320,20), 15, init_pos)

    #izipはzip関数のiteration返す版
    #zip関数は二つのリストを各リストの要素ごとにタプルにして固めたリストを作る。
    #imにseq,pにparticlefilter関数からの値が逐次返ってきている
    for image, p in itertools.izip(images, particlefilter(images, init_pos, 8, 100)):
        #予測位置、パーティクル、ウェイトを返却
        position_center, position_particles, weights_particle = p
        #予測フィルタからの結果を取得
        #zeros_likeは同じサイズの零行列(配列)を戻す関数
        position_overlay = numpy.zeros_like(image)
        position_overlay[tuple(position_center)] = 1
        #バラ撒いたparticleの場所を取得
        particle_overlay = numpy.zeros_like(image)
        particle_overlay[tuple(position_particles.T)] = 1
        #上書きしていかないで追記する
        pylab.hold(False)
        #強制再描画。ファイルに吐くときのflash的なもんか?公式サイトにも1行しか説明なし
        pylab.draw()
        time.sleep(1)
        #画像(image)を指定したカラーマップ(cm.gray)で書く
        #help(cm)とかすれば他のカラーマップにどういうのがあるのか情報取れる
        pylab.imshow(image, cmap = pylab.cm.gray)
        #予測フィルタから出てきた物体の位置を青で書く
        #markerには's’:四角(default)、'o’:円、‘.’:点、‘,’ :ピクセルが指定可能
        pylab.spy(position_overlay, marker='.', color='b')
        #バラ撒いたパーティクルを赤く書く
        pylab.spy(particle_overlay, marker=',', color='r')
    pylab.show()
コード例 #21
0
# This command-line utility plots the sparsity pattern from a file. To use this
# script, first generate a sparsity pattern file using MocoCasADiSolver's
# optim_write_sparsity property.
#
# Usage:
#       python plot_casadi_sparsity.py <prefix>_constraint_Jacobian_sparsity.mtx
#
# In this example, <prefix> is the value of the optim_write_sparsity property.

df = pd.read_csv(sys.argv[1],
                 skiprows=2,
                 sep=' ',
                 names=['row_indices', 'column_indices'])

with open(sys.argv[1]) as f:
    # The first line is a comment.
    f.readline()
    # The second line contains the number of row, columns, and nonzeroes.
    line1 = f.readline()
    numbers = line1.split(' ')
    num_rows = int(numbers[0])
    num_cols = int(numbers[1])

spmat = scipy.sparse.coo_matrix(
    (np.ones_like(df.index),
     (df['row_indices'] - 1, df['column_indices'] - 1)),
    shape=(num_rows, num_cols))
pl.spy(spmat, markersize=2, markeredgecolor='k', marker='.')
pl.show()
コード例 #22
0
coef = np.zeros((n_tasks, n_features))
times = np.linspace(0, 2 * np.pi, n_tasks)
for k in range(n_relevant_features):
    coef[:, k] = np.sin((1. + rng.randn(1)) * times + 3 * rng.randn(1))

X = rng.randn(n_samples, n_features)
Y = np.dot(X, coef.T) + rng.randn(n_samples, n_tasks)

coef_lasso_ = np.array([Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T])
coef_multi_task_lasso_ = MultiTaskLasso(alpha=1.).fit(X, Y).coef_

###############################################################################
# Plot support and time series
fig = pl.figure(figsize=(8, 5))
pl.subplot(1, 2, 1)
pl.spy(coef_lasso_)
pl.xlabel('Feature')
pl.ylabel('Time (or Task)')
pl.text(10, 5, 'Lasso')
pl.subplot(1, 2, 2)
pl.spy(coef_multi_task_lasso_)
pl.xlabel('Feature')
pl.ylabel('Time (or Task)')
pl.text(10, 5, 'MultiTaskLasso')
fig.suptitle('Coefficient non-zero location')

feature_to_plot = 0
pl.figure()
pl.plot(coef[:, feature_to_plot], 'k', label='Ground truth')
pl.plot(coef_lasso_[:, feature_to_plot], 'g', label='Lasso')
pl.plot(coef_multi_task_lasso_[:, feature_to_plot],
コード例 #23
0
ファイル: preview.py プロジェクト: zarthur/github-messages
def preview(message):
    """Diplay message in 3x3 font using pylab."""
    array = fontify.convert(message)
    pylab.spy(array)
    pylab.show()
コード例 #24
0
ファイル: sparsity_jac.py プロジェクト: meduardov/casadi
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     Lesser General Public License for more details.
#
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
#
#! sparsity_jac
#!======================
from casadi import *
from numpy import *
import casadi as c
from pylab import spy, show

#! We construct a simple SX expression
x = SX.sym("x", 40)
y = x[:-2] - 2 * x[1:-1] + x[2:]

#! Let's see what the first 5 entries of y look like
print y[:5]

#! Next, we construct a function
f = Function("f", [x], [y])

#! And we visualize the sparsity of the jacobian
spy(f.sparsity_jac())

show()
コード例 #25
0
def Divergence_val(filename, mesh_no):

    mshfile_fullpath = icemcfd_project_folder + filename

    part_names, xy_no, xy_fa, xy_cv, noofa, cvofa, faono, faocv, partofa = umesh_reader.read_unstructured_grid(
        mshfile_fullpath, node_reordering=True)

    nno = xy_no.shape[0]  # No. of nodes
    ncv = xy_cv.shape[0]  # No. of CVs
    nfa = xy_fa.shape[0]  # No. of faces
    partofa1 = np.array(partofa)  # Converting partofa to an array
    faono1 = np.array(faono)  # Converting faono to an array
    cold_bc = np.where(
        partofa1 ==
        'COLD')  # Vectorized approach to find face belonging to part 'COLD'
    hot_bc = np.where(
        partofa1 ==
        'HOT')  # Vectorized approach to find face belonging to part 'HOT'
    solid = np.where(
        partofa1 ==
        'SOLID')  # Vectorized approach to find face belonging to part 'SOLID'

    # Find part to which each node belongs to
    partono = []
    for j in np.arange(nno):
        part_name = partofa1[faono1[j]]
        hot_count = np.array(np.where(part_name == 'HOT')).size
        cold_count = np.array(np.where(part_name == 'COLD')).size
        if cold_count != 0:
            partono.append('COLD')
        elif hot_count != 0:
            partono.append('HOT')
        else:
            partono.append('SOLID')

    partono1 = np.array(partono)

    nfa_int = np.size(np.where(partofa1 == 'SOLID'))
    # Divergence operator
    Dx_f2cv = scysparse.csr_matrix(
        (ncv, nfa_int), dtype="float64")  #Creating x part of operator
    Dy_f2cv = scysparse.csr_matrix(
        (ncv, nfa_int), dtype="float64")  #Creating y part of operator

    q_bc = np.zeros(ncv)
    u_bc = np.zeros(nfa)
    v_bc = np.zeros(nfa)

    u = (xy_fa[:, 1]) * (xy_fa[:, 0]**2)  #x-component of velocity
    v = -(xy_fa[:, 0]) * (xy_fa[:, 1]**2)  #y-component of velocity

    for l in np.arange(nfa):
        if partofa1[l] != 'SOLID':
            u_bc[l] = u[l]
            v_bc[l] = v[l]

    NORMAL = []  #blank normal array to be filled up
    AREA = np.zeros(ncv)

    #Pre-processing and finding normals over all CVs
    for i in np.arange(ncv):
        nocv = noofa[faocv[i]]  # Nodal pairs for each face of the CV
        face_co = xy_fa[faocv[i]]  # Face centroids of each face of CV
        check_vecs = face_co - xy_cv[i]  #Vectors from CV centre to face centre
        par_x = xy_no[nocv[:, 1], 0] - xy_no[
            nocv[:, 0],
            0]  #x-component of vector parallel to face. Convention, 2nd point - 1st point in nocv
        par_y = xy_no[nocv[:, 1], 1] - xy_no[
            nocv[:, 0],
            1]  #y-component of vector parallel to face. Convention, 2nd point - 1st point in nocv
        normal_fa = np.c_[
            -par_y,
            par_x]  #Defining normal vector to faces. Convention, normal is 90* clock-wise.
        dir_check = normal_fa[:,
                              0] * check_vecs[:,
                                              0] + normal_fa[:,
                                                             1] * check_vecs[:,
                                                                             1]  # Checks if normal_fa is aligned in the same direction as check_vecs.
        normal_fa[np.where(dir_check < 0)] = -normal_fa[np.where(
            dir_check < 0
        )]  # Flips sign of components in normal_fa where the dot product i.e. dir_check is negative
        NORMAL.append(normal_fa)  # Spits out all normals indexed by Cvs

        #Calculating areas of CV assuming rectangles or triangles
        if np.size(faocv[i]) == 3:
            area_cv = np.abs(0.5 * ((par_x[0] * par_y[1]) -
                                    (par_x[1] * par_y[0])))
            AREA[i] = area_cv

        if np.size(faocv[i]) == 4:
            area_cv = max(
                np.abs((par_x[0] * par_y[1]) - (par_x[1] * par_y[0])),
                np.abs((par_x[0] * par_y[2]) - (par_x[2] * par_y[0])))
            AREA[i] = area_cv

    for j in np.arange(ncv):
        normal = NORMAL[j]  # Normals of the CV
        #Works as there are utmost 4 nodes right now. Dont know how slow it will be for higher order element shapes
        for ii, nn in enumerate(faocv[j]):
            if partofa1[nn] == 'SOLID':
                Dx_f2cv[j, nn] += normal[ii, 0] / AREA[j]
                Dy_f2cv[j, nn] += normal[ii, 1] / AREA[j]

            else:
                q_bc[j] += u_bc[nn] * normal[
                    ii, 0] / AREA[j] + v_bc[nn] * normal[ii, 1] / AREA[j]

    DIVERGENCE = (Dx_f2cv.dot(u[:nfa_int])) + (Dy_f2cv.dot(v[:nfa_int])) + q_bc

    e_RMS = np.sqrt(np.average(DIVERGENCE**2))

    plot_data.plot_data(
        xy_cv[:, 0], xy_cv[:, 1], DIVERGENCE,
        "Mesh " + str(mesh_no) + "Flooded_Contour_of_Divergence.pdf")

    plt.spy(Dx_f2cv)
    plt.savefig(figure_folder + "Mesh " + str(mesh_no) + ": Spy of Dx.pdf")
    plt.close()

    plt.spy(Dy_f2cv)
    plt.savefig(figure_folder + "Mesh " + str(mesh_no) + ": Spy of Dy.pdf")
    plt.close()

    return (Dx_f2cv, Dy_f2cv, q_bc, e_RMS)
コード例 #26
0
def calcSolution(ax,bx,ay,by,mx,my,show_matrix,show_result):
    hx = (bx-ax)/mx    
    hy = (by-ay)/my  
    alpha = hx/hy
    
    x = np.linspace(ax,bx,mx+2)   # grid points x including boundaries
    y = np.linspace(ay,by,my+2)   # grid points y including boundaries

    X,Y = np.meshgrid(x,y)     # 2d arrays of x,y values
    X = X.T                    # transpose so that X(i,j),Y(i,j) are
    Y = Y.T                    # coordinates of (i,j) point

    Xint = X[1:-1,1:-1]        # interior points
    Yint = Y[1:-1,1:-1]
    rhs = f(Xint,Yint)         # evaluate f at interior points for right hand side
                           # rhs is modified below for boundary conditions.

    # set boundary conditions around edges of usoln array:

    usoln = np.zeros(X.shape) 
    usoln[:,0] = u_exact(x,ay)
    usoln[:,-1] = u_exact(x,by)
    usoln[0,:] = u_exact(ax,y)
    usoln[-1,:] = u_exact(bx,y)

    # adjust the rhs to include boundary terms: 
    rhs[:,0] -= usoln[1:-1,0] / hy**2
    rhs[:,-1] -= usoln[1:-1,-1] / hy**2
    rhs[0,:] -= usoln[0,1:-1] / hx**2
    rhs[-1,:] -= usoln[-1,1:-1] / hx**2


    # convert the 2d grid function rhs into a column vector for rhs of system:
    F = rhs.reshape((mx*my,1))
    
    # form matrix A:
    Ix = sp.eye(mx,mx)
    Iy = sp.eye(my,my)
    ex = np.ones(mx)
    ey = np.ones(my)
    T = sp.spdiags([alpha*ey,-2*(alpha+1/alpha)*ey,alpha*ey],[-1,0,1],my,my)
    S = sp.spdiags([1/alpha*ex,1/alpha*ex],[-1,1],mx,mx)
    A = (sp.kron(Ix,T) + sp.kron(S,Iy)) / (hx*hy)    
    A = A.tocsr()
    
    show_matrix = True
    if (show_matrix):
        pylab.figure()
        pylab.spy(A,marker='.')
        
    # Solve the linear system:
    tic = time.time()
    uvec = spsolve(A, F)
    toc = time.time()
    
    # reshape vector solution uvec as a grid function and
    # insert this interior solution into usoln for plotting purposes:
    # (recall boundary conditions in usoln are already set)
    
    usoln[1:-1, 1:-1] = uvec.reshape( (mx,my) )
    
    show_result = True
    if show_result:
        # plot results:
        pylab.figure()
        ax = Axes3D(pylab.gcf())
        ax.plot_surface(X,Y,usoln, rstride=1, cstride=1, cmap=pylab.cm.jet)
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('u')
        #pylab.axis([a, b, a, b])
        #pylab.daspect([1 1 1])
        pylab.title('Surface plot of computed solution')
        
        pylab.show(block=False)
コード例 #27
0
# form matrix A:
I = np.eye(m, m)
e = np.ones(m)
Tcol = np.zeros((m, ))
Tcol[:2] = [-4, 1]
T = toeplitz(Tcol)
Scol = np.zeros((m, ))
Scol[:2] = [0, 1]

S = toeplitz(Scol)
A = (np.kron(I, T) + np.kron(S, I)) / h**2

show_matrix = False
if (show_matrix):
    pylab.spy(A, marker='.')
    pylab.show()

# Solve the linear system:

uvec = solve(A, F)

# reshape vector solution uvec as a grid function and
# insert this interior solution into usoln for plotting purposes:
# (recall boundary conditions in usoln are already set)

usoln[1:-1, 1:-1] = uvec.reshape((m, m))

# using Linf norm of spectral solution good to 10 significant digits
umax_true = 0.07367135328
umax = usoln.max()
コード例 #28
0
# Assemble Helmholtz
A = K * scl**2 + kx**2 * M

A_t = np.zeros((4 * (n + 1) - 3, 4 * (n + 1) - 3))
A_t[0, 0] = 1
A_t[1:n + 1, :n + 1] = A[1:]
A_t[n:2 * n + 1, n:2 * n + 1] += A[:]
A_t[2 * n:3 * n + 1, 2 * n:3 * n + 1] += A[:]
A_t[3 * n:4 * n, 3 * n:4 * n + 1] += A[:-1]
A_t[-1, -1] = 1

f_hat = np.zeros(4 * n + 1)
f_hat[:(n + 1)] = np.dot(w * P.T, fj[0])
f_hat[n:2 * n + 1] += np.dot(w * P.T, fj[1])
f_hat[2 * n:3 * n + 1] += np.dot(w * P.T, fj[2])
f_hat[3 * n:4 * n + 1] += np.dot(w * P.T, fj[3])

f_hat[0] = a
f_hat[-1] = b

u_hat = np.linalg.solve(A_t, f_hat)

uq = np.array([np.dot(P, u_hat[n * i:(i + 1) * n + 1]) for i in range(4)])

assert np.allclose(uq, uj)

plot(xx.flatten(), uq.flatten())
figure()
spy(A_t, precision=1e-8)
show()
コード例 #29
0
ファイル: jacSparsity.py プロジェクト: kozatt/casadi
#     Lesser General Public License for more details.
# 
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
# 
# 
#! jacSparsity
#!======================
from casadi import *
from numpy import *
import casadi as c
from pylab import spy, show

#! We construct a simple SX expression
x = ssym("x",40)
y = x[:-2]-2*x[1:-1]+x[2:]

#! Let's see what the first 5 entries of y look like
print y[:5]

#! Next, we construct a function
f = SXFunction([x],[y])
f.init()

#! And we visualize the sparsity of the jacobian
spy(f.jacSparsity())

show()

コード例 #30
0
coef = np.zeros((n_tasks, n_features))
times = np.linspace(0, 2 * np.pi, n_tasks)
for k in range(n_relevant_features):
    coef[:, k] = np.sin((1.0 + rng.randn(1)) * times + 3 * rng.randn(1))

X = rng.randn(n_samples, n_features)
Y = np.dot(X, coef.T) + rng.randn(n_samples, n_tasks)

coef_lasso_ = np.array([Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T])
coef_multi_task_lasso_ = MultiTaskLasso(alpha=1.0).fit(X, Y).coef_

###############################################################################
# Plot support and time series
fig = pl.figure(figsize=(8, 5))
pl.subplot(1, 2, 1)
pl.spy(coef_lasso_)
pl.xlabel("Feature")
pl.ylabel("Time (or Task)")
pl.text(10, 5, "Lasso")
pl.subplot(1, 2, 2)
pl.spy(coef_multi_task_lasso_)
pl.xlabel("Feature")
pl.ylabel("Time (or Task)")
pl.text(10, 5, "MultiTaskLasso")
fig.suptitle("Coefficient non-zero location")

feature_to_plot = 0
pl.figure()
pl.plot(coef[:, feature_to_plot], "k", label="Ground truth")
pl.plot(coef_lasso_[:, feature_to_plot], "g", label="Lasso")
pl.plot(coef_multi_task_lasso_[:, feature_to_plot], "r", label="MultiTaskLasso")
コード例 #31
0
ファイル: sparsity_jac.py プロジェクト: andrescodas/casadi
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     Lesser General Public License for more details.
#
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
#
#! sparsity_jac
#!======================
from casadi import *
from numpy import *
import casadi as c
from pylab import spy, show

#! We construct a simple SX expression
x = SX.sym("x",40)
y = x[:-2]-2*x[1:-1]+x[2:]

#! Let's see what the first 5 entries of y look like
print(y[:5])

#! Next, we construct a function
f = Function("f", [x],[y])

#! And we visualize the sparsity of the jacobian
spy(f.sparsity_jac())

show()

コード例 #32
0
ファイル: preview.py プロジェクト: zarthur/github-messages
def preview(message):
    """Diplay message in 3x3 font using pylab."""
    array = fontify.convert(message)
    pylab.spy(array)
    pylab.show()
コード例 #33
0
def calcSolution(m, show_matrix, show_result):
    a = 0.0
    b = 1.0
    h = (b - a) / (m + 1)
    x = np.linspace(a, b, m + 2)  # grid points x including boundaries
    y = np.linspace(a, b, m + 2)  # grid points y including boundaries

    X, Y = np.meshgrid(x, y)  # 2d arrays of x,y values
    X = X.T  # transpose so that X(i,j),Y(i,j) are
    Y = Y.T  # coordinates of (i,j) point

    Xint = X[1:-1, 1:-1]  # interior points
    Yint = Y[1:-1, 1:-1]
    rhs = f(Xint, Yint)  # evaluate f at interior points for right hand side
    # rhs is modified below for boundary conditions.

    # set boundary conditions around edges of usoln array:
    usoln = np.zeros(X.shape)
    usoln[:, 0] = u_exact(x, a)
    usoln[:, -1] = u_exact(x, b)
    usoln[0, :] = u_exact(a, y)
    usoln[-1, :] = u_exact(b, y)

    # adjust the rhs to include boundary terms:
    rhs[:, 0] -= usoln[1:-1, 0] / h**2
    rhs[:, -1] -= usoln[1:-1, -1] / h**2
    rhs[0, :] -= usoln[0, 1:-1] / h**2
    rhs[-1, :] -= usoln[-1, 1:-1] / h**2

    # convert the 2d grid function rhs into a column vector for rhs of system:
    F = rhs.reshape((m * m, 1))

    # form matrix A:
    I = sp.eye(m, m)
    e = np.ones(m)
    T = sp.spdiags([e, -4. * e, e], [-1, 0, 1], m, m)
    S = sp.spdiags([e, e], [-1, 1], m, m)
    A = (sp.kron(I, T) + sp.kron(S, I)) / h**2
    A = A.tocsr()

    if show_matrix:
        pylab.figure()
        pylab.spy(A, marker='.')

    # Solve the linear system:
    tic = time.time()
    uvec = spsolve(A, F)
    toc = time.time()

    # reshape vector solution uvec as a grid function and
    # insert this interior solution into usoln for plotting purposes:
    # (recall boundary conditions in usoln are already set)

    usoln[1:-1, 1:-1] = uvec.reshape((m, m))

    # Find errors
    abs_err = grid_norm2(usoln - u_exact(X, Y), h)
    rel_err = abs_err / grid_norm2(usoln, h)
    print "m = {0}".format(m)
    print "Absolute error = {0:10.3e}, relative error = {1:10.3e}".format(
        abs_err, rel_err)
    print 'Elapsed Time = {0} s'.format(toc - tic)

    if show_result:
        # plot results:
        pylab.figure()
        ax = Axes3D(pylab.gcf())
        ax.plot_surface(X, Y, usoln, rstride=1, cstride=1, cmap=pylab.cm.jet)
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('u')
        #pylab.axis([a, b, a, b])
        #pylab.daspect([1 1 1])
        pylab.title('Surface plot of computed solution')

        pylab.show(block=False)

    return [abs_err, rel_err]
コード例 #34
0
# distance_from_center = np.sqrt(np.power(Xc-Lx/2.,2.0)+np.power(Yc-Ly/2.,2.0))
# j_obstacle,i_obstacle = np.where(distance_from_center<obstacle_radius)
# pressureCells_Mask[j_obstacle,i_obstacle] = False

# number of actual pressure cells
Np = len(np.where(pressureCells_Mask==True)[0])
q  = np.ones((Np,1))


# a more advanced option is to separately create the divergence and gradient operators
DivGrad = spatial_operators.create_DivGrad_operator(Dxc,Dyc,Xc,Yc,pressureCells_Mask,boundary_conditions="Homogeneous Dirichlet")
# DivGrad = spatial_operators.create_DivGrad_operator(Dxc,Dyc,Xc,Yc,pressureCells_Mask)
Divx = spatial_operators.Divx_operator(Dxc,Xc,pressureCells_Mask,boundary_conditions="Homogeneous Dirichlet")
# Divx = spatial_operators.Divx_operator(Dxc,Xc,pressureCells_Mask,boundary_conditions="Homogeneous Neumann")
# if boundary_conditions are not specified, it defaults to "Homogeneous Neumann"
plt.spy(DivGrad)
# plt.title('Spy plot for Homogeneous Neumann')
# plt.savefig('Spy plot for Homogeneous Neumann.png')
plt.show()
print(DivGrad.shape)


############# Successive over relaxation ##################
def fcn_q(Xc,Yc,n,Re):
    fcn_q = np.sin(2*np.pi*n*Yc)*(2*np.pi*n*np.cos(2*np.pi*n*Xc)+(8*n**2*np.pi**2/Re)*(np.sin(2*np.pi*n*Xc)))
    return fcn_q
fc = []
for i in range(Nxc):
    for j in range(Nyc):
        fc.append(fcn_q(x_u[i],y_v[j],n,Re))
fc = np.array(fc)
コード例 #35
0
ファイル: test_fixed_part.py プロジェクト: echu/dist_ecos
    socp_vars = data['socp_vars']
    objval = data['objval']
    N = data['N']
    partition_list = data['partition_list']

    # first, solve with ecos
    import ecos
    sol = ecos.solve(**socp_vars)
    ecos_time = sol['info']['timing']['runtime']

    # next, solve with dist_ecos
    def objective(x):
        return socp_vars['c'].dot(x)

    if args.show_plot:
        pylab.spy(socp_vars['G'], marker='.', alpha=0.2)
        pylab.show()

    t = time.time()
    prox_list, global_indices = form_prox_list(socp_vars, partition_list)
    split_time = time.time() - t

    result = solve(prox_list,
                   global_indices,
                   parallel=True,
                   max_iters=1000,
                   rho=2)

    pri = result['res_pri']
    dual = result['res_dual']