Beispiel #1
0
def gera_plot(path, data, ler, shape, total_variaveis):

    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path +
                                         hashName.lerKuttaDat())

    for variavel in range(1, int(total_variaveis + 1)):

        nomde_grafico = pasta_hash[0:11] + '_SecaoPoincare_C' + str(variavel)
        print(nomde_grafico)
        print("total de pontos plotados = %d" % (ler))

        # matplotlib plot
        # figura deve ser definida como subplots e retornas os axes para posterior configuracao do tick format
        fig, ax = pyplot.subplots(1, 1, figsize=(10, 10))

        data_1__x = []
        data_1__y = []

        print("total de seções de poincare=" + str(shape[0]))
        for j in range(shape[0] - ler, shape[0]):
            data_1__y.append(data[j, 2 * variavel])
            data_1__x.append(data[j, 2 * variavel - 1])

        config_plot = dict(marker='o', s=15, c='red', zorder=100)
        pyplot.scatter(data_1__x, data_1__y, **config_plot)

        # saving file to load in another python file
        # https://stackoverflow.com/questions/48912527/how-to-join-two-matplotlib-figures
        np.savez(path + pasta_hash[0:11] + "_poincare_C%d.npz" % (variavel),
                 method='scatter',
                 args=(data_1__x, data_1__y),
                 kwargs=config_plot)

        pyplot.xlim(
            min(data_1__x) - 0.01 * abs(min(data_1__x)),
            max(data_1__x) + 0.01 * abs(max(data_1__x)))
        pyplot.ylim(
            min(data_1__y) - 0.01 * abs(min(data_1__y)),
            max(data_1__y) + 0.01 * abs(max(data_1__y)))
        pyplot.ylabel(r'$\dot{W_{' + str(variavel) + '}}/h$')
        pyplot.xlabel(r'$W_{' + str(variavel) + '}/h$')
        pyplot.ticklabel_format(axis='both',
                                style='sci',
                                scilimits=(0, 0),
                                useOffset=False)
        #ax.xaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
        #ax.yaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
        pyplot.savefig(path + nomde_grafico + '.png',
                       dpi=300,
                       bbox_inches='tight')
        #pyplot.show()
        pyplot.cla()
        pyplot.clf()
        pyplot.close('all')
def gera_plot(path, data, ler, shape, total_variaveis):

    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path +
                                         hashName.lerKuttaDat())

    for variavel in range(1, int(total_variaveis + 1)):

        nomde_grafico = pasta_hash[0:11] + '_RespostaNoTempo_C' + str(variavel)
        print(nomde_grafico)
        print("total de pontos plotados = %d" % (ler))

        # matplotlib plot
        pyplot.figure(figsize=(23, 10))

        data_1__x = []
        data_1__y = []

        print("total de pontos=" + str(shape[0]))
        for j in range(shape[0] - ler, shape[0]):
            data_1__y.append(data[j, 2 * variavel])
            data_1__x.append(data[j, 0])

        pyplot.plot(data_1__x, data_1__y, linewidth=1)
        deltax = abs(min(data_1__x) - max(data_1__x))
        deltay = abs(min(data_1__y) - max(data_1__y))

        pyplot.xlim(
            min(data_1__x) - 0.0 * deltax,
            max(data_1__x) + 0.0 * deltax)
        pyplot.ylim(
            min(data_1__y) - 0.0 * deltay,
            max(data_1__y) + 0.0 * deltay)
        pyplot.ylabel(r'$W_{' + str(variavel) + '}/h$')
        pyplot.xlabel(r't(s)')
        pyplot.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
        pyplot.savefig("plots\\" + nomde_grafico + '.png',
                       dpi=300,
                       bbox_inches='tight')
        #pyplot.show()
        pyplot.close()
def gera_plot(path, data_plot_freq, data_plot_duracao_carga,
              data_plot_carga_inicial, correcao_frequencia, pontos):
    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path)

    nomde_grafico = pasta_hash + '_Espectro'
    print(nomde_grafico)

    # matplotlib plot
    # figura deve ser definida como subplots e retornas os axes para posterior configuracao do tick format
    fig, ax = pyplot.subplots(1, 1, figsize=(10, 10))

    freq_unica = set(data_plot_freq)
    num_pontos = len(freq_unica)
    minData1X = min(data_plot_freq)
    maxData1X = max(data_plot_freq)
    tamanho_barra = 1.1 * (maxData1X - minData1X) / (num_pontos)

    config_plot = dict(width=tamanho_barra, bottom=data_plot_carga_inicial)
    ax.bar(data_plot_freq, data_plot_duracao_carga, **config_plot)

    # saving file to load in another python file
    # https://stackoverflow.com/questions/48912527/how-to-join-two-matplotlib-figures
    np.savez(path + nomde_grafico + '.npz',
             method='bar',
             args=(data_plot_freq, data_plot_duracao_carga),
             kwargs=config_plot)

    pyplot.xlim(minData1X, maxData1X)
    pyplot.ylim(0, )
    #ax.xaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
    #ax.yaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
    pyplot.savefig(path + nomde_grafico + '.png', dpi=300, bbox_inches='tight')
    pyplot.show()
    pyplot.cla()
    pyplot.clf()
    pyplot.close('all')
Beispiel #4
0
def gera_plot(path, data, total_variaveis, correcao_frequencia, pontos,
              eixo_carga):
    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path)
    for variavel in range(1, int(total_variaveis + 1)):
        nomde_grafico = pasta_hash + '_C%s' % (variavel)
        print(nomde_grafico)
        col = 4 * variavel - 2
        print("col = %d" % (col))

        # matplotlib plot
        # figura deve ser definida como subplots e retornas os axes para posterior configuracao do tick format
        fig, ax = pyplot.subplots(1, 1, figsize=(10, 10))

        Data_caminhos = []
        for i in range(len(pontos)):
            Data_caminhos.append(i)

        minData1X = 1e9
        maxData1X = -1e9
        minData1Y = 1e9
        maxData1Y = -1e9

        for i in Data_caminhos:
            data_1__x = []
            data_1__y = []

            shape = data[i].shape
            for j in range(0, shape[0]):
                data_1__y.append(data[i][j, col])
                data_1__x.append(data[i][j, 1] * correcao_frequencia)
            print("Nummero de pontos caminho %s = %i" % (pontos[i], shape[0]))

            config_plot = dict(marker='o', color='blue', s=10)
            pyplot.scatter(data_1__x, data_1__y, **config_plot)

            # saving file to load in another python file
            # https://stackoverflow.com/questions/48912527/how-to-join-two-matplotlib-figures
            np.savez(path + nomde_grafico + '_c_' + str(pontos[i]) + '.npz',
                     method='scatter',
                     args=(data_1__x, data_1__y),
                     kwargs=config_plot)

            #calculo maximos e minimos do grafico
            minData1X = min([min(data_1__x), minData1X])
            maxData1X = max([max(data_1__x), maxData1X])
            minData1Y = min([min(data_1__y), minData1Y])
            maxData1Y = max([max(data_1__y), maxData1Y])

        pyplot.xlim(minData1X - 0.01 * abs(minData1X),
                    maxData1X + 0.01 * abs(maxData1X))
        pyplot.ylim(minData1Y - 0.01 * abs(minData1Y),
                    maxData1Y + 0.01 * abs(maxData1Y))
        pyplot.ylabel(r'$W_{' + str(variavel) + '}/h$')
        if eixo_carga == True:
            pyplot.xlabel(r'$P_{L}$')
            pass
        else:
            pyplot.xlabel(r'$\omega_{1}/\omega_{0}$')
            pass
        pyplot.ticklabel_format(axis='both',
                                style='sci',
                                scilimits=(0, 0),
                                useOffset=False)
        #ax.xaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
        #ax.yaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
        pyplot.savefig(path + nomde_grafico + '.png',
                       dpi=300,
                       bbox_inches='tight')
        #pyplot.show()
        pyplot.cla()
        pyplot.clf()
        pyplot.close('all')
Beispiel #5
0
def gera_plot(path, data, ler, shape, total_variaveis):

    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path +
                                         hashName.lerKuttaDat())

    for variavel in range(1, int(total_variaveis + 1)):

        nomde_grafico = pasta_hash[0:11] + '_PlanoFase_C' + str(variavel)
        print(nomde_grafico)
        print("total de pontos plotados = %d" % (ler))

        # matplotlib plot
        # figura deve ser definida como subplots e retornas os axes para posterior configuracao do tick format
        fig, ax = pyplot.subplots(1, 1, figsize=(10, 10))

        data_1__x = []
        data_1__y = []

        print("total de pontos=" + str(shape[0]))
        for j in range(shape[0] - ler, shape[0]):
            data_1__y.append(data[j, 2 * variavel])
            data_1__x.append(data[j, 2 * variavel - 1])

        #tenta juntar o plot da secao de poicanre se ela existir com o plot do plano fase
        try:
            juntar_plots(
                ax,
                [path + pasta_hash[0:11] + "_poincare_C%d.npz" % (variavel)])
        except:
            None

        config_plot = dict(linewidth=1)
        pyplot.plot(data_1__x, data_1__y, **config_plot)

        # saving file to load in another python file
        np.savez(path + pasta_hash[0:11] + "plano_fase_C%d.npz" % (variavel),
                 method='plot',
                 args=(data_1__x, data_1__y),
                 kwargs=config_plot)

        pyplot.xlim(
            min(data_1__x) - 0.01 * abs(min(data_1__x)),
            max(data_1__x) + 0.01 * abs(max(data_1__x)))
        pyplot.ylim(
            min(data_1__y) - 0.01 * abs(min(data_1__y)),
            max(data_1__y) + 0.01 * abs(max(data_1__y)))
        pyplot.ylabel(r'$\dot{W_{' + str(variavel) + '}}/h$')
        pyplot.xlabel(r'$W_{' + str(variavel) + '}/h$')
        pyplot.ticklabel_format(axis='both',
                                style='sci',
                                scilimits=(0, 0),
                                useOffset=False)
        #ax.xaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
        #ax.yaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
        pyplot.savefig(path + nomde_grafico + '.png',
                       dpi=300,
                       bbox_inches='tight')
        #pyplot.show()
        pyplot.cla()
        pyplot.clf()
        pyplot.close('all')
Beispiel #6
0
def gera_plot(path, data, total_linhas, total_colunas, correcao_frequencia, x1,
              x2, y1, y2, n_div_x: int, n_div_y: int, plotar_plano_fase):
    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path)

    #lista de cores
    lista_cores = [
        "white", "blue", "yellow", "green", "red", "purple", "black"
    ]
    lista_cores_indices = [0, 1, 2, 3, 4, 5, 6]

    print(lista_cores, lista_cores_indices)
    user_input = str(
        input(
            "\n Mudar indices da lista de cores?: \n ex= Digitar 0,1,2,3,5,4,6 troca o purple e o red \n Nova lista?: "
        ))
    if user_input != '':
        nova_lista_cores = []
        user_input = user_input.split(",")
        for temp in user_input:
            nova_lista_cores.append(lista_cores[int(temp)])
        lista_cores = nova_lista_cores

    # calculo de dx e dy
    dx = abs((x2 - x1) / (n_div_x - 1))
    dy = abs((y2 - y1) / (n_div_y - 1))

    y, x = np.mgrid[slice(y1 - dy / 2, y2 + dy, dy),
                    slice(x1 - dx / 2, x2 + dx, dx)]

    z = []
    z0 = np.zeros((n_div_y, n_div_x))

    ################
    #cria um array com os atratorez de cada célula
    from scipy import spatial

    listaAtratores = np.zeros((total_linhas, 2))
    listaIndices = np.zeros(total_linhas, dtype='int32')
    for i in range(total_linhas):
        listaAtratores[i] = np.array([data[i][3], data[i][4]])
        listaIndices[i] = i

    ## variavel de controle do nível de plotagem de cada atrator
    nivel = 6
    ArquivoAberto = False

    #verifica se a lista de atratores nao esta vazia
    while listaAtratores.size != 0:
        id_periodico = 0
        flag_convergiu = False
        #pesquisa os atratores que convergiram
        while (id_periodico + 1) < listaIndices.size:
            indice = data[listaIndices[id_periodico]][0]
            if indice < 0:
                id_periodico = id_periodico + 1
            else:
                flag_convergiu = True
                break
        #monta e pesquisa os pontos proximos
        if flag_convergiu == True:
            #https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.query_ball_point.html#scipy.spatial.KDTree.query_ball_point
            tree = spatial.KDTree(listaAtratores)
            pontosProximos = sorted(
                tree.query_ball_point(listaAtratores[id_periodico], 0.01))
            # imprime na tela o atrator que está sob analise
            print("==> Atrator encontrado[{:d}] d1 = {:f}, d2 = {:f}\n".format(
                listaIndices[id_periodico] + 1,
                listaAtratores[id_periodico][0],
                listaAtratores[id_periodico][1]))
        else:
            pontosProximos = np.zeros(listaIndices.size, dtype='int32')
            for i in range(listaIndices.size):
                pontosProximos[i] = i

        if flag_convergiu == True:
            for j in range(total_colunas - 6):
                sys.stdout.flush()
                print("verificando dados coluna {:d} para o atrator".format(
                    int(j + 6)),
                      end="\r")
                listaAtratoresVerificacao = np.zeros((len(pontosProximos), 1))
                for i in range(len(pontosProximos)):
                    linhaLerData = listaIndices[pontosProximos[i]]
                    listaAtratoresVerificacao[i] = np.array(
                        data[linhaLerData][5 + j])
                    pass
                #https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.query_ball_point.html#scipy.spatial.KDTree.query_ball_point
                tree = spatial.KDTree(listaAtratoresVerificacao)
                pontosProximosVerificacao = sorted(
                    tree.query_ball_point(listaAtratoresVerificacao[0], 0.01))
                #extrai de pontos proximos somente aqueles que passaram na verificacao
                pontosProximos = sorted(
                    np.take(pontosProximos, pontosProximosVerificacao))
                pass
            sys.stdout.flush()
            pass

        #definida a lista de pontos proximos determina para ela um nivel de plotagem em base de 2
        listaPontosExcluir = []
        listaIndicesConvergidosImprimir = []
        indice = 0
        for i in pontosProximos:
            if flag_convergiu == True and nivel > 0:
                norma = 64 - (6 - nivel) * 10
            elif flag_convergiu == True and nivel == 0:
                raise ValueError(
                    'A quantidade de atratores eh igual ao maximo de cores do Cmap,' \
                    + 'nao sendo possivel representar os pontos que nao convergiram!'
                )
            else:
                norma = 0
            indiceBuscarData = listaIndices[i]
            numCelula = data[indiceBuscarData][0]
            if numCelula < 0 and flag_convergiu == True:
                listaPontosExcluir.append(indice)
            else:
                listaIndicesConvergidosImprimir.append(indiceBuscarData + 1)
            # define linha em x
            numCelula = abs(numCelula)
            x_l = int((numCelula - 1) / n_div_y)
            y_l = int((numCelula - 1) % n_div_y)
            z0[y_l, x_l] = norma
            indice += 1
        if flag_convergiu == True:
            print("==> Nivel = {:f}                          \n".format(norma))
            if ArquivoAberto == False:
                f = open(path + 'impBaciaLog_' + pasta_hash[0:12] + '.txt',
                         "w")
                ArquivoAberto = True
            else:
                f = open(path + 'impBaciaLog_' + pasta_hash[0:12] + '.txt',
                         "a")
            f.write("Atrator encontrado[{:d}] d1 = {:f}, d2 = {:f}\n".format(
                listaIndices[id_periodico] + 1,
                listaAtratores[id_periodico][0],
                listaAtratores[id_periodico][1]))
            f.write("Nivel de cor = {:d}, Nome da cor = {:s}\n".format(
                norma, lista_cores[nivel]))
            f.write("Numero de pontos = {:d}\n".format(
                len(listaIndicesConvergidosImprimir)))
            np.savetxt(f, listaIndicesConvergidosImprimir, fmt='%.0f')
            f.write("\n\n")
            f.close()

            if plotar_plano_fase == True:
                import secao_de_poicare_plots as poincare
                import plano_fase_plots as planoFase
                import crossPlotsPlanoFase
                import shutil

                print("Executando runge kutta -> linha {0}\n".format(
                    listaIndicesConvergidosImprimir[0]))
                os.system("call ..\\..\\Rkutta.exe 6 {0}".format(
                    listaIndicesConvergidosImprimir[0]))

                #plota plano fase e poincare na pasta plots
                poincare.main_func()
                planoFase.main_func()
                # copia pasta crossPlots para plots
                diretorio_padrao = os.getcwd()
                try:
                    shutil.copytree(diretorio_padrao + "\\crossPlots",
                                    diretorio_padrao + "\\plots\\crossPlots")
                    os.chdir(diretorio_padrao + "\\plots\\crossPlots")
                    crossPlotsPlanoFase.main_func(True, lista_cores[nivel])
                    os.chdir(diretorio_padrao)
                except:
                    pass
                # renomeia pasta plots
                shutil.move(
                    diretorio_padrao + "\\plots",
                    diretorio_padrao + "\\plots_linha_{0}".format(
                        listaIndicesConvergidosImprimir[0]))
                pass

        #deleta os pontos proximos encontrados mas que nao convergiram da lista de pontos proximos
        pontosProximos = np.delete(pontosProximos, listaPontosExcluir, 0)
        #pontosProximos = np.insert(pontosProximos, 1, id_periodico)
        listaAtratores = np.delete(listaAtratores, pontosProximos, 0)
        listaIndices = np.delete(listaIndices, pontosProximos)
        nivel -= 1

    from matplotlib.colors import BoundaryNorm
    from matplotlib.ticker import MaxNLocator
    from matplotlib.colors import ListedColormap

    cmap = ListedColormap(lista_cores)
    levels = MaxNLocator(nbins=len(lista_cores)).tick_values(0, 64)
    norm = BoundaryNorm(levels, ncolors=cmap.N, clip=False)

    # matplotlib plot
    # figura deve ser definida como subplots e retornas os axes para posterior configuracao do tick format
    fig, ax = pyplot.subplots(1, 1, figsize=(10, 10))

    nomde_grafico = pasta_hash
    print(nomde_grafico)

    config_plot = dict(cmap=cmap, norm=norm)
    arg_plot = (x, y, z0)
    im = ax.pcolormesh(*arg_plot, **config_plot)
    #fig.colorbar(im, ax=ax)

    # saving file to load in another python file
    # https://stackoverflow.com/questions/48912527/how-to-join-two-matplotlib-figures
    np.savez(path + nomde_grafico + '.npz',
             method='pcolormesh',
             args=arg_plot,
             kwargs=config_plot)

    minData1X = x.min()
    maxData1X = x.max()
    minData1Y = y.min()
    maxData1Y = y.max()

    pyplot.xlim(minData1X - 0.01 * abs(minData1X),
                maxData1X + 0.01 * abs(maxData1X))
    pyplot.ylim(minData1Y - 0.01 * abs(minData1Y),
                maxData1Y + 0.01 * abs(maxData1Y))

    pyplot.ylabel(r'$\dot{W}_{' + str(1) + '}/h$')
    pyplot.xlabel(r'$W_{' + str(1) + '}/h$')
    pyplot.ticklabel_format(axis='both',
                            style='sci',
                            scilimits=(0, 0),
                            useOffset=False)
    #ax.xaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
    #ax.yaxis.set_major_formatter(pyplot.FuncFormatter('{:.2f}'.format))
    #pyplot.colorbar(im, ax=ax)
    pyplot.savefig(path + nomde_grafico + '.png', dpi=300, bbox_inches='tight')
    #pyplot.show()
    pyplot.cla()
    pyplot.clf()
    pyplot.close('all')
Beispiel #7
0
def gera_plot(path,
              data,
              variavel,
              tipo_plot,
              correcao_frequencia=1.0,
              ax_plt_window=None,
              wdw_aux=None):
    import hashName
    pasta_hash: str = hashName.nome_hash(os.getcwd() + "\\" + path)

    if tipo_plot == 'R':
        nome_wdw = 'RE_'
        nome_base_grafico = '_RESS_C'
        col = 4 * variavel
    if tipo_plot == 'B':
        nome_wdw = 'BP_'
        nome_base_grafico = '_BIFU_C'
        col = 4 * variavel - 2

    for var in range(0, 2):
        nomde_grafico = pasta_hash + nome_base_grafico + "%d_ponto_%d" % (
            variavel, var + 1)
        print(nomde_grafico)
        print("col = %d" % (col))

        if var == 0:
            plt_color = 'blue'
        else:
            plt_color = 'red'

        # matplotlib plot
        fig, ax = pyplot.subplots(num='%s%d_ponto_%d' %
                                  (nome_wdw, variavel, var + 1),
                                  figsize=(10, 10))

        data_1__x = []
        data_1__y = []

        #plotagem do ponto 1
        shape = data[var].shape
        for j in range(0, shape[0]):
            data_1__y.append(data[var][j, col])
            data_1__x.append(data[var][j, 1] * correcao_frequencia)
        print("Nummero de pontos caminho 1 = " + str(shape[0]))

        ax.scatter(data_1__x, data_1__y, marker='o', color=plt_color, s=10)

        if ax_plt_window != None:
            ax_plt_window.scatter(data_1__x,
                                  data_1__y,
                                  marker='o',
                                  color=plt_color,
                                  s=10)

        #pyplot.xlim(min(data_1__x)-0.1*abs(min(data_1__x)),max(data_1__x)+0.1*abs(max(data_1__x)))
        #pyplot.ylim(0,2)
        ax.set_xlabel(r'$\omega_{1}/\omega_{0}$')
        ax.set_ylabel(r'$W_{' + str(variavel) + '}/h$')
        #ax.legend(loc='upper right', ncol=1)
        #ax.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
        fig.savefig(path + nomde_grafico + '.png',
                    dpi=300,
                    bbox_inches='tight')
        if wdw_aux.upper() == "S" or wdw_aux.upper() == "Y":
            continue
        else:
            pyplot.close(fig)