コード例 #1
0
ファイル: run.py プロジェクト: Hawax/hills_cipher
def deszyfrowanie():
    form = Deszyfrowanie()
    if form.validate_on_submit():
        try:
            matrix_decryption, decryption_multiplier, matrix_from_key, inverse_key, matrix_encrypted, decrypted_message =\
                HillCipher(alphabet=form.alphabet.data)\
                    .decrypt(key=form.key.data, message_enc=form.message.data)
            matrix_from_key = a2l.to_ltx(matrix_from_key,
                                         frmt='{:6}',
                                         print_out=False)
            matrix_decryption = a2l.to_ltx(matrix_decryption,
                                           frmt='{:6}',
                                           print_out=False)
            matrix_encrypted = a2l.to_ltx(matrix_encrypted,
                                          frmt='{:6}',
                                          print_out=False)
            inverse_key = a2l.to_ltx(inverse_key, frmt='{:6}', print_out=False)
            decryption_multiplier = a2l.to_ltx(decryption_multiplier,
                                               frmt='{:6}',
                                               print_out=False)
            flash(f'Wiadomość została odszyfrowana.', 'success')
            return render_template('deszyfrowanie.html',
                                   title='About',
                                   form=form,
                                   matrix_from_key=matrix_from_key,
                                   matrix_encrypted=matrix_encrypted,
                                   matrix_decryption=matrix_decryption,
                                   decrypted_message=decrypted_message,
                                   inverse_key=inverse_key,
                                   decryption_multiplier=decryption_multiplier,
                                   modulo=len(form.alphabet.data))
        except Exception as e:
            flash(Markup(e), 'danger')
    form.alphabet.data = default_aplh
    return render_template('deszyfrowanie.html', title='About', form=form)
コード例 #2
0
def do_pca(xyzs, inds, energies, labels):
    # Report employed internals
    print("Primitive internals:")
    for inds_ in inds:
        print(f"\t{PRIM_DICT[len(inds_)]}: {inds_}")
    print()

    # Calculate coordinate values
    X = np.array([calc_params(xyz, inds) for xyz in xyzs])
    # Variance 1, mean at 0
    X_scaled = preprocessing.scale(X)

    pca = PCA()
    X_new = pca.fit_transform(X_scaled)

    # Report eigenvalues
    print("Explained variance ratio:")
    ev_thresh = 0.05
    cumsum = 0.
    for i, ev in enumerate(pca.explained_variance_ratio_):
        cumsum += ev
        if ev <= ev_thresh:
            print(f"\tRemaining eigenvalues are below {ev_thresh:.4f}")
            break
        print(f"\tPC {i:02d}: {ev:.4f}, Σ {cumsum:.4f}")
    print()

    joblib.dump(pca, "pca.pkl")
    np.savetxt("energies_kjmol.dat", energies)
    np.savetxt("X_new.dat", X_new)

    # Only report first two PCs
    tab = a2l.to_ltx(pca.components_[:2].T,
                     frmt="{:.2f}",
                     arraytype="tabular",
                     print_out=False)

    with open("pca_comps_tabular.tex", "w") as handle:
        handle.write(tab)

    fig_skree, skree_ax = skree_plot(pca)
    fig_2d, ax_2d = two_components(X_new, energies, pca, labels)
    # import matplotlib
    # from mpl_toolkits.mplot3d import Axes3D
    # fig_3d, ax_3d = three_components(X_new, energies, pca)
    # fig_cross, cross_arr = cross_components(X_new, energies, pca, 4)

    plt.tight_layout()
    plt.show()

    fig_skree.savefig("skree.pdf")
    fig_skree.savefig("skree.svg")
    fig_2d.savefig("geompca_2d.pdf")
    fig_2d.savefig("geompca_2d.svg")
    # fig_3d.savefig("geompca_3d.pdf")
    # fig_3d.savefig("geompca_3d.svg")
    # fig_cross.savefig("geompca_cross.pdf")
    # fig_cross.savefig("geompca_cross.svg")

    return X_new
コード例 #3
0
ファイル: make_problem.py プロジェクト: haharay/python_lib
def array_disp(ZZ, frmt):
    import array_to_latex as a2l
    from bs4 import BeautifulSoup
    global code_exec
    if ZZ==0:
        return ''
    elif ZZ==1:
        with open("./test001.py", 'w') as fa:
            fa.write(code_exec)
        lines = check_output("python3 ./test001.py", shell=True).decode('utf-8')
        lines = lines.replace('<', '&lt;')
        lines = lines.replace('>', '&gt;')
        lines = '执行上述程序,输出:\n'+lines
        print(lines)
        return markdown(lines.replace('\n', '<br/>'))
    elif ZZ==2:
        exec(code_exec)
        if 'df' in locals():
            df =df
        elif 'result' in locals():
            df = result
        else:
            print('找不到ndarray或pandas的结果变量')
        lx = a2l.to_ltx(df, frmt=frmt,
                            arraytype='bmatrix', print_out=False)
        with open("./latex_txt.text", 'w') as fa:
            fa.write(lx)
        os.system('pandoc latex_txt.text -s --mathjax --metadata title="latexTxt" -o math_mathjax.html')
        # time.sleep(1.0)
        with open('./math_mathjax.html', 'r') as fr:
            lines = fr.readlines()
        soup = BeautifulSoup(''.join(lines), 'html.parser')
        return str(soup.find_all('span')[0])
    else:
        return ''
def coeff_matrix(model:Model, latex = False, digits = 2, arraytype = 'pmatrix'):
    V = list(model.getVars())
    cons = list(model.getConstrs())
    A = np.array([[int(model.getCoeff(c,v)) for v in V] for c in cons])
    if latex:
        return a2l.to_ltx(coeff_matrix(model), frmt = '{:6.' + str(digits) + 'f}', arraytype = 'pmatrix')
    return A
コード例 #5
0
ファイル: run.py プロジェクト: Hawax/hills_cipher
def szyfrowanie():
    form = Szyfrowanie()
    if form.validate_on_submit():
        try:
            message_fixed, encryption_matrix_mutipled, message_matrix, matrix_from_key, matrix_encrypted, encrypted_message = \
                HillCipher(alphabet=form.alphabet.data).encrypt(message=form.message.data, key=form.key.data)
            matrix_from_key = a2l.to_ltx(matrix_from_key,
                                         frmt='{:6}',
                                         print_out=False)
            matrix_encrypted = a2l.to_ltx(matrix_encrypted,
                                          frmt='{:6}',
                                          print_out=False)
            message_matrix = a2l.to_ltx(message_matrix,
                                        frmt='{:6}',
                                        print_out=False)
            encryption_matrix_mutipled = a2l.to_ltx(encryption_matrix_mutipled,
                                                    frmt='{:6}',
                                                    print_out=False)
            flash(f'Wiadomość została zaszyfrowana.', 'success')
            if form.message.data.lower() != message_fixed:
                return render_template(
                    'szyfrowanie.html',
                    title='About',
                    form=form,
                    matrix_from_key=matrix_from_key,
                    matrix_encrypted=matrix_encrypted,
                    message_matrix=message_matrix,
                    message_fixed=message_fixed,
                    encrypted_message=encrypted_message,
                    encryption_matrix_mutipled=encryption_matrix_mutipled,
                    modulo=len(form.alphabet.data))
            return render_template(
                'szyfrowanie.html',
                title='About',
                form=form,
                matrix_from_key=matrix_from_key,
                matrix_encrypted=matrix_encrypted,
                message_matrix=message_matrix,
                encrypted_message=encrypted_message,
                encryption_matrix_mutipled=encryption_matrix_mutipled,
                modulo=len(form.alphabet.data))
        except Exception as e:
            flash(Markup(e), 'danger')
    form.alphabet.data = default_aplh
    return render_template('szyfrowanie.html', title='About', form=form)
コード例 #6
0
def Matrix2tex(Mat, name):
    """
		Converting a Matrix Object to a Tex Matrix.

		============== =========== ===========================
		**Parameters**   **Type**   **Description**
		*Mat*            Matrix     The Matrix to convert
		*name*           String     The name of the .tex file
		============== =========== ===========================

		:returns:  None
	"""
    npa = Matrix2Numpy(Mat)
    latex_code = '\\documentclass{article}\n\\usepackage{nicematrix}\n\\begin{document}\n$'
    latex_code += a.to_ltx(npa,
                           frmt='{:6.2f}',
                           arraytype='bmatrix',
                           print_out=False)
    latex_code = latex_code + '$\n\\end{document}'
    f = open(name + '.tex', 'w')
    f.write(latex_code)
コード例 #7
0
ファイル: Mapper_real.py プロジェクト: pshariati/thesis
def real_noise():

    blockPrint()

    class Real:
        def __init__(self, graph, data, mapper):
            self.graph = graph
            self.data = data
            self.mapper = mapper

    realList = []

    f = open('chicago_election_data_modified.csv', 'r')

    from numpy import genfromtxt

    my_data = genfromtxt('chicago_election_data_modified.csv',
                         dtype=float,
                         delimiter=',',
                         skip_header=1,
                         usecols=[*range(1, 33)])

    scaler2 = 0

    for i in range(10):

        data_noise = np.random.normal(scale=scaler2, size=my_data.shape)

        data_noise = my_data + data_noise

        garcia_mapper = km.KeplerMapper(verbose=1)

        garcia_proj_data = garcia_mapper.fit_transform(data_noise,
                                                       projection=[31],
                                                       scaler=None)

        graph_garcia = garcia_mapper.map(garcia_proj_data,
                                         data_noise,
                                         cover=km.Cover(n_cubes=40,
                                                        perc_overlap=.3))

        garcia_mapper.visualize(graph_garcia,
                                color_values=garcia_proj_data,
                                path_html=str(i) + "garcia_keppler.html",
                                title="mapper applied to garcia" + str(i))

        garcia_obj = Real(graph_garcia, data_noise, garcia_mapper)

        realList.append(garcia_obj)

        scaler2 = scaler2 + 0.1 / 10

    enablePrint()

    rmat = np.ones((10, 10))

    for i in range(10):
        for j in range(10):
            if i == j:
                rmat[i][j] = 0

            else:
                rmat[i][j] = calc_gromov(realList[i].graph, realList[i].mapper,
                                         realList[i].data, realList[j].graph,
                                         realList[j].mapper, realList[j].data)

    print(rmat)
    print(' ')
    a2l.to_ltx(rmat, frmt='{:6.2f}', arraytype='array')
    print(' ')

    plt.figure()
    im = plt.imshow(rmat, cmap='hot')
    plt.colorbar(im)
    plt.show()
コード例 #8
0
      \\array{*\\c@MaxMatrixCols r}}

\\AtBeginEnvironment{bmatrix}{\\setlength{\\arraycolsep}{2pt}}
  
    
    \\begin{document}\n''')

for n in ns:
    for m in ms:
        print()
        print('\\section{', f'm={m}, n={n}', '}\n')
        print()
        A, b, c, x, runtime = m_n_to_matrices[(m,n)]
        for name, code in [
                ('A', 
                    lambda: a2l.to_ltx(np.array(A), frmt = '{}', arraytype = 'bmatrix')),
                ('b^T',
                    lambda: a2l.to_ltx(np.array(b).T, frmt = '{}', arraytype = 'bmatrix')),
                ('c',
                    lambda: a2l.to_ltx(np.array(c), frmt = '{}', arraytype = 'bmatrix')),
                ('x^T',
                    lambda: a2l.to_ltx(np.array(x), frmt = '{:3.2}', arraytype = 'bmatrix'))]:
            print()
            if n == 30:
                print('\\small')
            if n == 40:
                print('\\tiny')
            if n == 50:
                print('\\tiny')
            print(f'$ {name} =')
            code()
コード例 #9
0
ファイル: lab2_optim.py プロジェクト: zuevval/source
def print_mtx(mtx: np.array, title: str) -> None:
    print("\n{}".format(title))
    alt.to_ltx(mtx, frmt="{:.4f}")
コード例 #10
0
ファイル: lab3.py プロジェクト: mertkoc/Simple-SVM
plt.xlabel("lg(C)")
plt.ylabel("Accuracies (%)")
plt.savefig("Accuracies.png", bbox_inches='tight')
plt.close()

### Now cross validation
grid_mtx = np.zeros((13,13))
for i in range(13):
	for j in range(13):
		C = 2.0 ** (i - 4)
		gamma = 2.0 ** (j - 4)
		avg_acc = cross_validation_n_folds(train_pathname, gamma, C, n=5)  # 5-Fold cross validation
		grid_mtx[i,j] = avg_acc

print(grid_mtx)
a2l.to_ltx(grid_mtx, frmt = '{:.2f}', arraytype = 'array')
highest_acc = np.amax(grid_mtx)
indicies = unravel_index(grid_mtx.argmax(), grid_mtx.shape)
best_gamma = 2.0 ** (indicies[1] - 4)
best_C = 2.0 ** (indicies[0] - 4)
print(f"Highest validation accuracy is {highest_acc:.2f}% at {indicies[0] + 1}th row and {indicies[1] + 1}th column")
print(f"Which means best C={best_C}, best gamma={best_gamma}")

train_pathname = sys.argv[1]
file_name = os.path.split(train_pathname)[1]
model_file = file_name + ".model"

if len(sys.argv) > 2:
	test_pathname = sys.argv[2]
	file_name = os.path.split(test_pathname)[1]
	predict_test_file = file_name + ".predict"
コード例 #11
0
ファイル: GT_dirichlet.py プロジェクト: thoeschler/shenfun
        weights = dct(d, w)
        result = np.sqrt(np.sum(weights*(u['g']-ue)**2))
    elif method == 3:
        # Roundtrip roundoff with uniform f
        A = solver.subproblems[0].L_exp
        g = np.random.rand(A.shape[0])
        v = solver.subproblem_matsolvers[solver.subproblems[0]].solve(g)
        f = A * v
        u = solver.subproblem_matsolvers[solver.subproblems[0]].solve(f)
        result = np.max(np.abs(u-v))
    return result

if __name__=='__main__':
    import sys
    import array_to_latex as a2l
    method = int(sys.argv[-2])
    tau = int(sys.argv[-1])
    if method == 0:
        N = (32, 64, 128, 256, 512, 1024, 2048)
    else:
        N = (2**4, 2**8, 2**12, 2**16, 2**20)
    alphas = (0, 1, 1000)
    cond = []
    for alpha in alphas:
        cond.append([])
        for n in N:
            cond[-1].append(main(n, alpha, method, tau))
            print(alpha, n, cond[-1][-1])
    a2l.to_ltx(np.array(cond), frmt='{:6.2e}', mathform=False, print_out=True)

コード例 #12
0
def LatexArr(A, frmt='{:6.3f}', arrtype='array'):
  return a2l.to_ltx(A, frmt = frmt, arraytype = arrtype)
#
# End --------------------------------------------------------------------------
コード例 #13
0
# files_multiscale.sort(key=lambda f:
#                int(re.search(r"ensemble-([0-9]*).txt", f).group(1)))

files_pCN = glob.glob(data_dir_pCN + "/ensemble-*.txt")
files_pCN.sort(
    key=lambda f: int(re.search(r"ensemble-([0-9]*).txt", f).group(1)))

files_aldi = glob.glob(data_dir_aldi + "/ensemble-*.txt")
files_aldi.sort(
    key=lambda f: int(re.search(r"ensemble-([0-9]*).txt", f).group(1)))

utruth = np.loadtxt(data_dir_aldi + "/utruth.txt")
# umap = np.mean(np.loadtxt(files_cbs[-1]), axis=1)
# umap_eks = np.mean(np.loadtxt(files_eks[-1]), axis=1)

a2l.to_ltx(utruth, frmt='{:6.2f}', arraytype='array')
# a2l.to_ltx(umap, frmt = '{:6.2f}', arraytype = 'array')
# a2l.to_ltx(umap_eks, frmt = '{:6.2f}', arraytype = 'array')

fig, ax = plt.subplots()
utruth = utruth[:16]
d = len(utruth)
N = int(np.sqrt(d))
indices = [(m, n) for m in range(0, N) for n in range(0, N)]
indices.sort(key=lambda i: (max(i), sum(i), i[0]))


def update(index):
    f = files_aldi[index]
    ax.clear()
    iteration = re.search(r"ensemble-([0-9]*).txt", f).group(1)
コード例 #14
0
plt.loglog([100, 31**2, 10000],
           np.array([0.04005085099925054, 1.1138713059999645, 96.31783088499924]) / 5,
           label="2 loops")

plt.legend()

# + [markdown] pycharm={"name": "#%% md\n"}
# ## 250. Write to LaTeX
# I found the `array_to_latex` package, but there could be better options.
# It seems to work quite neat.

# + pycharm={"name": "#%%\n"}
import array_to_latex as a2l

B = zero_loops(3)
a2l.to_ltx(B.toarray(), frmt='{:1.0f}')

# + [markdown] pycharm={"name": "#%% md\n"}
# ## 253. semilogy
# Reconsider: What is the MF3 matrix? Reproduce it with that particular matrix if necessary.

# + pycharm={"name": "#%%\n"}
A = sparse.random(100, 100, 0.2)
plt.semilogy(np.sort(A.data))

# + [markdown] pycharm={"name": "#%% md\n"}
# ## 254. spy

# + pycharm={"name": "#%%\n"}
A = sparse.random(10, 10, 0.1)
plt.spy(A)
コード例 #15
0
def to_latex(a):
    return a2l.to_ltx(a, frmt='{:6.2f}', arraytype='bmatrix')
コード例 #16
0
ファイル: Mapper_real.py プロジェクト: pshariati/thesis
def real_data():

    blockPrint()

    class Real:
        def __init__(self, graph, data, mapper):
            self.graph = graph
            self.data = data
            self.mapper = mapper

    realList = []

    f = open('chicago_election_data.csv', 'r')

    from numpy import genfromtxt

    my_data = genfromtxt('chicago_election_data.csv',
                         dtype=float,
                         delimiter=',',
                         skip_header=1,
                         usecols=[*range(1, 51)])

    eman_mapper = km.KeplerMapper(verbose=1)

    eman_proj_data = eman_mapper.fit_transform(my_data,
                                               projection=[46],
                                               scaler=None)

    graph_eman = eman_mapper.map(eman_proj_data,
                                 my_data,
                                 cover=km.Cover(n_cubes=40, perc_overlap=.3))
    eman_mapper.visualize(graph_eman,
                          path_html="eman_keppler.html",
                          title="mapper applied to eman")

    eman_obj = Real(graph_eman, my_data, eman_mapper)

    realList.append(eman_obj)

    garcia_mapper = km.KeplerMapper(verbose=1)

    garcia_proj_data = garcia_mapper.fit_transform(my_data,
                                                   projection=[49],
                                                   scaler=None)

    graph_garcia = garcia_mapper.map(garcia_proj_data,
                                     my_data,
                                     cover=km.Cover(n_cubes=40,
                                                    perc_overlap=.3))

    garcia_mapper.visualize(graph_garcia,
                            color_values=my_data[:, 49],
                            path_html="garcia_keppler.html",
                            title="mapper applied to garcia")

    stuff = plotlyviz(graph_garcia, color_values=my_data[:, 49])

    stuff.show()

    plt.figure()
    img = plt.imshow(np.array([[0, 1]]), cmap="viridis")
    img.set_visible(False)
    plt.colorbar(orientation="vertical")
    plt.show()

    garcia_obj = Real(graph_garcia, my_data, garcia_mapper)

    realList.append(garcia_obj)

    lhg_mapper = km.KeplerMapper(verbose=1)

    lhg_proj_data = lhg_mapper.fit_transform(my_data,
                                             projection=[43],
                                             scaler=None)

    graph_lhg = lhg_mapper.map(lhg_proj_data,
                               my_data,
                               cover=km.Cover(n_cubes=40, perc_overlap=.3))

    lhg_mapper.visualize(graph_lhg,
                         path_html="lhg_keppler.html",
                         title="mapper applied to lhg")

    lhg_obj = Real(graph_lhg, my_data, lhg_mapper)

    realList.append(lhg_obj)

    preck_mapper = km.KeplerMapper(verbose=1)

    preck_proj_data = preck_mapper.fit_transform(my_data,
                                                 projection=[35],
                                                 scaler=None)

    graph_preck = preck_mapper.map(preck_proj_data,
                                   my_data,
                                   cover=km.Cover(n_cubes=40, perc_overlap=.3))

    preck_mapper.visualize(graph_preck,
                           path_html="preck_keppler.html",
                           title="mapper applied to preck")

    preck_obj = Real(graph_preck, my_data, preck_mapper)

    realList.append(preck_obj)

    enablePrint()

    rmat = np.ones((4, 4))

    for i in range(4):
        for j in range(4):
            if i == j:
                rmat[i][j] = 0

            else:
                rmat[i][j] = calc_gromov(realList[i].graph, realList[i].mapper,
                                         realList[i].data, realList[j].graph,
                                         realList[j].mapper, realList[j].data)

    print(rmat)
    print(' ')
    a2l.to_ltx(rmat, frmt='{:6.2f}', arraytype='array')
    print(' ')
コード例 #17
0
ファイル: Mapper_real.py プロジェクト: pshariati/thesis
def GW_matrix(num_circ, num_line, num_y, num_eight):

    total_num = num_circ + num_line + num_y + num_eight

    class Shape:
        def __init__(self, shape_type, graph, data, mapper):
            self.shape = shape_type
            self.graph = graph
            self.data = data
            self.mapper = mapper

    shapes = []

    blockPrint()

    points_in_interval = np.arange(0, 1, 0.0065)
    points_in_line = np.arange(-2, 2, 0.026)

    X = [2 * np.cos(t * 2 * np.pi) for t in points_in_interval]
    Y = [2 * np.sin(t * 2 * np.pi) for t in points_in_interval]

    Z = [t for t in points_in_line]
    W = [t for t in points_in_line]

    points_in2 = np.arange(-2.0, 0.1, 0.04)
    points_in3 = np.arange(0.1, 2.0, 0.04)
    P = [t for t in points_in2]
    a = [t for t in points_in3]
    a = np.repeat(a, 2, axis=0)
    P = np.concatenate((P, a))

    G = [0 for t in points_in2]
    V = [(t - 0.1) for t in points_in3]
    V = np.repeat(V, 2, axis=0)
    V[::2] = -V[::2]
    G = np.concatenate((G, V))

    t = np.linspace(0, 2 * np.pi, 150)
    q = 2 * (np.sin(t))
    m = 2 * (np.sin(t) * np.cos(t))

    #scaler = 0

    for i in range(num_circ):

        X_noise = np.random.normal(scale=0.1, size=len(X))
        Y_noise = np.random.normal(scale=0.1, size=len(Y))
        X_noise = np.array(X) + np.array(X_noise)
        Y_noise = np.array(Y) + np.array(Y_noise)

        plt.figure()
        plt.scatter(X_noise, Y_noise)
        plt.axis('equal')

        circ_data = np.array(list(zip(X_noise, Y_noise)))
        circ_mapper = km.KeplerMapper(verbose=1)
        circ_proj_data = circ_mapper.fit_transform(circ_data,
                                                   projection=[1],
                                                   scaler=None)
        circ_graph = circ_mapper.map(circ_proj_data,
                                     circ_data,
                                     cover=km.Cover(n_cubes=6,
                                                    perc_overlap=0.3))
        circ_mapper.visualize(circ_graph,
                              path_html=str(i) + "circle_keppler.html",
                              title="mapper applied to circle" + str(i))

        circ_obj = Shape("circle", circ_graph, circ_data, circ_mapper)

        shapes.append(circ_obj)

        #scaler = scaler + 0.35/num_circ

    for i in range(num_line):
        Z_noise = np.random.normal(scale=0.1, size=len(Z))
        W_noise = np.random.normal(scale=0.1, size=len(W))
        Z_noise = np.array(Z) + np.array(Z_noise)
        W_noise = np.array(W) + np.array(W_noise)

        plt.figure()
        plt.scatter(W_noise, Z_noise)
        plt.axis('equal')

        my_data_line = np.array(list(zip(W_noise, Z_noise)))

        mapper_line = km.KeplerMapper(verbose=1)
        projected_data_line = mapper_line.fit_transform(my_data_line,
                                                        projection=[1],
                                                        scaler=None)

        graph_line = mapper_line.map(projected_data_line,
                                     my_data_line,
                                     cover=km.Cover(n_cubes=6,
                                                    perc_overlap=.3))

        mapper_line.visualize(graph_line,
                              path_html=str(i) + "line_keppler.html",
                              title="mapper applied to line" + str(i))

        line_obj = Shape("line", graph_line, my_data_line, mapper_line)

        shapes.append(line_obj)

    for i in range(num_y):
        G_noise = np.random.normal(scale=0.1, size=len(G))
        P_noise = np.random.normal(scale=0.1, size=len(P))
        G_noise = np.array(G) + np.array(G_noise)
        P_noise = np.array(P) + np.array(P_noise)

        plt.figure()
        plt.scatter(G_noise, P_noise)
        plt.axis('equal')

        y_data = np.array(list(zip(G_noise, P_noise)))
        y_mapper = km.KeplerMapper(verbose=1)
        y_proj_data = y_mapper.fit_transform(y_data,
                                             projection=[1],
                                             scaler=None)
        y_graph = y_mapper.map(y_proj_data,
                               y_data,
                               cover=km.Cover(n_cubes=6, perc_overlap=0.3))
        y_mapper.visualize(y_graph,
                           path_html=str(i) + "y_keppler.html",
                           title="mapper applied to y-shape" + str(i))

        y_obj = Shape("y", y_graph, y_data, y_mapper)

        shapes.append(y_obj)

    for i in range(num_eight):
        m_noise = np.random.normal(scale=0.1, size=len(m))
        q_noise = np.random.normal(scale=0.1, size=len(q))
        m_noise = np.array(m) + np.array(m_noise)
        q_noise = np.array(q) + np.array(q_noise)

        plt.figure()
        plt.scatter(m_noise, q_noise)
        plt.axis('equal')

        eight_data = np.array(list(zip(m_noise, q_noise)))
        eight_mapper = km.KeplerMapper(verbose=1)
        eight_proj_data = eight_mapper.fit_transform(eight_data,
                                                     projection=[1],
                                                     scaler=None)
        eight_graph = eight_mapper.map(eight_proj_data,
                                       eight_data,
                                       cover=km.Cover(n_cubes=6,
                                                      perc_overlap=0.3))
        eight_mapper.visualize(eight_graph,
                               path_html=str(i) + "eight_keppler.html",
                               title="mapper applied to figure 8" + str(i))

        eight_obj = Shape("figure 8", eight_graph, eight_data, eight_mapper)

        shapes.append(eight_obj)

    enablePrint()

    shmat = np.ones((total_num, total_num))

    for i in range(total_num):
        for j in range(total_num):
            if i == j:
                shmat[i][j] = 0

            else:
                shmat[i][j] = calc_gromov(shapes[i].graph, shapes[i].mapper,
                                          shapes[i].data, shapes[j].graph,
                                          shapes[j].mapper, shapes[j].data)

    print(shmat)
    print(' ')
    a2l.to_ltx(shmat, frmt='{:6.2f}', arraytype='array')
    print(' ')
    print(shmat[0:4, 0:4])

    triang(shmat)

    plt.figure()
    im = plt.imshow(shmat, cmap='hot')
    plt.colorbar(im)
    plt.show()
コード例 #18
0
import numpy as np
import array_to_latex as a2l

to_tex = lambda A: a2l.to_ltx(
    A, frmt='{:.3f}', arraytype='pmatrix', mathform=True)

A = np.array([[-2, -2, -2], [-2, -1, -1], [1, 0, -1]])
A1 = A
a1 = A1[:, 0].reshape((3, 1))
v1 = a1 + (np.sign(A1[0, 0]) * np.linalg.norm(a1) * np.eye(3)[:, 0]).reshape(
    (3, 1))
H1 = np.eye(3) - 2 * (v1 @ v1.T) / (v1.T @ v1)

A2 = (H1 @ A1)[1:, 1:]
a2 = A2[:, 0].reshape((2, 1))
v2 = a2 + (np.sign(A2[0, 0]) * np.linalg.norm(a2) * np.eye(2)[:, 0]).reshape(
    (2, 1))
H2 = np.eye(2) - 2 * (v2 @ v2.T) / (v2.T @ v2)

A3 = (H2 @ A2)[1:, 1:]
a3 = A3[:, 0].reshape((1, 1))
v3 = a3 + (np.sign(A3[0, 0]) * np.linalg.norm(a3) * np.eye(1)[:, 0]).reshape(
    (1, 1))
H3 = np.eye(1) - 2 * (v3 @ v3.T) / (v3.T @ v3)

print('$')
print('A=')
to_tex(A)
print('\\\\')

print('A_1=')
コード例 #19
0
def format_matrix(A):
    return a2l.to_ltx(A, frmt='{:d}', arraytype="pmatrix", print_out=False)
コード例 #20
0
ファイル: HW1.py プロジェクト: edenx/cws-ML
     plt.scatter(x[0, :], x[1, :], c=labels_new)
     plt.title('Cluster label obtained from kmeans, k=2')
     plt.xlabel("X1")
     plt.ylabel("X2")
     plt.savefig('fig02.png')
     plt.show()
     plt.close()

     # Queastion 2 --------------------------------------------------------------------
     # use default random state for analysis, i.e. 132
     import numpy as np
     from matplotlib import pyplot as plt

     # output matrix to latex code
     import array_to_latex as a2l
     to_tex = lambda A : a2l.to_ltx(A, frmt = '{:6.2f}', 
                         arraytype = 'array', mathform=True)

     # a) Generate 25 obs in each of three classes with 50 features ------------------
     n=25; K=3; m=50
     sim = genData(n, K, m)
     simDat = sim['Data']
     labels = sim['labels']

     print(simDat.shape)
     # Visualise in first two features
     plt.figure()
     plt.scatter(simDat[0], simDat[1], c=labels)
     plt.xlabel('Feature 1')
     plt.ylabel('Feature 2')
     plt.title('Generated Data')
     plt.savefig('fig1.png')