예제 #1
0
    def save_images(self, options):
        """
        Save the extracted images
        :return:
        """
        options = options.split('|')

        rgb_np = self.rgb_image_np
        thermal_np = self.thermal_image_np

        img_visual = Image.fromarray(rgb_np)
        thermal_normalized = (thermal_np - np.amin(thermal_np)) / (np.amax(thermal_np) - np.amin(thermal_np))
        img_thermal = Image.fromarray(np.uint8(cm.inferno(thermal_normalized) * 255))
        img_gray = Image.fromarray(np.uint8(cm.binary(thermal_normalized) * 255))

        fn_prefix, _ = os.path.splitext(self.flir_img_filename)
        thermal_filename = fn_prefix + self.thermal_suffix
        image_filename = fn_prefix + self.image_suffix
        grayscale_filename = fn_prefix + self.grayscale_suffix

        if self.use_thumbnail:
            image_filename = fn_prefix + self.thumbnail_suffix

        if self.is_debug:
            print("DEBUG Saving RGB image to:{}".format(image_filename))
            print("DEBUG Saving Thermal image to:{}".format(thermal_filename))
            print("DEBUG Saving Gray image to:{}".format(grayscale_filename))
        if 'rgb' in options:
            img_visual.save(image_filename)
        if 'thermal' in options:
            img_thermal.save(thermal_filename)
        if 'gray' in options:
            img_gray.save(grayscale_filename)
예제 #2
0
def plot_corr_ellipses(data, ax=None, **kwargs):

    M = np.array(data)
    if not M.ndim == 2:
        raise ValueError('data must be a 2D array')
    if ax is None:
        fig, ax = plt.subplots(1, 1, subplot_kw={'aspect': 'equal'})
        ax.set_xlim(-0.5, M.shape[1] - 0.5)
        ax.set_ylim(-0.5, M.shape[0] - 0.5)

    # xy locations of each ellipse center
    xy = np.indices(M.shape)[::-1].reshape(2, -1).T
    x, y = zip(*xy)
    x = np.array(x, dtype=np.int8)
    y = np.array(y, dtype=np.int8)
    ind = x <= y

    # set the relative sizes of the major/minor axes according to the strength of
    # the positive/negative correlation
    w = np.ones_like(M).ravel()
    h = 1 - np.abs(M).ravel()
    w *= 0.85
    h *= 0.85
    a = 45 * np.sign(M).ravel()
    w = w[ind]
    h = h[ind]
    a = a[ind]
    xymat = xy[ind]
    Mfull = M.ravel()
    Mhalf = Mfull[ind]

    linewidths = np.repeat(1 + np.abs(Mhalf), len(h))
    edgecolors = cm.binary(np.abs(Mhalf))

    ec = EllipseCollection(widths=w,
                           heights=h,
                           angles=a,
                           units='x',
                           offsets=xymat,
                           linewidths=linewidths,
                           edgecolors=edgecolors,
                           transOffset=ax.transData,
                           array=Mhalf,
                           **kwargs)
    ax.add_collection(ec)
    for xt, yt, val in zip(x[~ind], y[~ind], Mfull[~ind]):
        strval = '{:+.2f}'.format(val).replace('0.', '.')
        ax.text(xt, yt, strval, ha='center', va='baseline', fontsize='small')

    # if data is a DataFrame, use the row/column names as tick labels
    if isinstance(data, pd.DataFrame):
        ax.set_xticks(np.arange(M.shape[1]))
        ax.set_xticklabels(data.columns, rotation=30)
        ax.set_yticks(np.arange(M.shape[0]))
        ax.set_yticklabels(data.index, rotation=30)
    ax.set_xlim(x.min() - 0.5, x.max() + 0.5)
    ax.set_ylim(x.min() - 0.5, x.max() + 0.5)
    ax.set_aspect('equal')
    return ec
def add_line(xlim, ylim, w, b, level=0.0):
    slope = -w[0] / w[1]
    bias = -b / w[1]
    xrange = np.linspace(xlim[0], xlim[1], 1000)
    yrange = slope * xrange + bias

    plt.plot(xrange, yrange, "-", c=cm.binary(level), linewidth=1.0)
    return None
예제 #4
0
        def frame(i):
            nonlocal rhos, ax

            ax.clear()
            ax.axis('equal')

            rhos_i = rhos[i]

            elementos_poli = []
            elementos_barra = []

            x_bar_max = 0
            if self.dados.tem_barras():
                x_bar_max = max(rhos_i[self.dados.num_elementos_poli::])

            for j, el in enumerate(self.dados.elementos):
                if j < self.dados.num_elementos_poli:
                    if tipo_cmap == 'jet':
                        elementos_poli.append(
                            patches.Polygon(self.dados.nos[el],
                                            linewidth=0,
                                            fill=True,
                                            facecolor=cm.jet(rhos_i[j])))
                    else:
                        elementos_poli.append(
                            patches.Polygon(self.dados.nos[el],
                                            linewidth=0,
                                            fill=True,
                                            facecolor=cm.binary(rhos_i[j])))
                else:
                    verts = [self.dados.nos[el[0]], self.dados.nos[el[1]]]
                    codes = [path.Path.MOVETO, path.Path.LINETO]

                    rho = 5 * rhos_i[j] / x_bar_max
                    # rho = 3 if rho_final[j] > 0 else 0

                    if rho > 0:
                        if tipo_cmap == 'jet':
                            elementos_barra.append(
                                patches.PathPatch(path.Path(verts, codes),
                                                  linewidth=rho,
                                                  edgecolor='black'))
                        else:
                            elementos_barra.append(
                                patches.PathPatch(path.Path(verts, codes),
                                                  linewidth=rho,
                                                  edgecolor='red'))

            ax.add_collection(
                PatchCollection(elementos_poli, match_original=True))

            if self.dados.tem_barras():
                ax.add_collection(
                    PatchCollection(elementos_barra, match_original=True))

            return ax
예제 #5
0
def save_segmentation(filename, gcam, threshold):
    # gcam = gcam.cpu().numpy()

    # prune with threshold
    gcam_binary = np.copy(gcam)
    gcam_binary[gcam <= threshold] = 1.0
    gcam_binary[gcam > threshold] = 0.0

    cmap = cm.binary(gcam_binary)[..., :3] * 255.0
    gcam = cmap.astype(np.float)

    cv2.imwrite(filename, np.uint8(gcam))
예제 #6
0
def highlight_gradcam(filename, gcam, raw_image, threshold):

    # prune with threshold
    gcam_binary = np.copy(gcam)
    gcam_binary[gcam <= threshold] = 0.0
    gcam_binary[gcam > threshold] = 1.0

    alpha = gcam[..., None]
    cmap = cm.binary(gcam_binary)[..., :3] * 255.0

    gcam = (1 - alpha) * cmap + alpha * raw_image
    # gcam = alpha * cmap + (1 - alpha) * raw_image
    cv2.imwrite(filename, np.uint8(gcam))
예제 #7
0
def show_powexp(ax, set_color="color"):
    """ plot pow_exp model.
    """
    covfunc = "pow_exp"
    numin, numax, nnu = 0.01, 1.99, 10
    nuarr = np.linspace(numin, numax, nnu)
    print("plotting %s model with %4d numbers of nu from %.4g to %.4g\
            "%(covfunc, nnu, numin, numax))
    for i, nu in enumerate(nuarr):
        if set_color:
            color= cm.jet(1.*i/len(nuarr))
        else:
            color= cm.binary(1.*(i+2)/len(nuarr))
        plotcov(ax, covfunc=covfunc, color=color, ls="-", nu=nu)
예제 #8
0
def show_powexp(ax, set_color="color"):
    """ plot pow_exp model.
    """
    covfunc = "pow_exp"
    numin, numax, nnu = 0.01, 1.99, 10
    nuarr = np.linspace(numin, numax, nnu)
    print("plotting %s model with %4d numbers of nu from %.4g to %.4g\
            " % (covfunc, nnu, numin, numax))
    for i, nu in enumerate(nuarr):
        if set_color:
            color = cm.jet(1. * i / len(nuarr))
        else:
            color = cm.binary(1. * (i + 2) / len(nuarr))
        plotcov(ax, covfunc=covfunc, color=color, ls="-", nu=nu)
예제 #9
0
def show_paretoexp(ax, set_color="color"):
    """ plot matern model.
    """
    covfunc = "pareto_exp"
    numin, numax, nnu = 1.0, 5.0, 10
    nuarr = np.power(10.0, np.linspace(np.log10(numin), np.log10(numax), nnu))
    print("plotting %s model with %4d numbers of nu from %.4g to %.4g\
            " % (covfunc, nnu, numin, numax))
    for i, nu in enumerate(nuarr):
        if set_color:
            color = cm.jet(1. * i / len(nuarr))
        else:
            color = cm.binary(1. * (i + 2) / len(nuarr))
        plotcov(ax, covfunc=covfunc, color=color, scale=1.0, ls="-", nu=nu)
예제 #10
0
def show_matern(ax, set_color="color"):
    """ plot matern model.
    """
    covfunc = "matern"
    numin, numax, nnu = 0.10, 2.50, 10
    nuarr = np.power(10.0, np.linspace(np.log10(numin), np.log10(numax), nnu))
    print("plotting %s model with %4d numbers of nu from %.4g to %.4g\
            "%(covfunc, nnu, numin, numax))
    for i, nu in enumerate(nuarr):
        if set_color:
            color= cm.jet(1.*i/len(nuarr))
        else:
            color= cm.binary(1.*(i+2)/len(nuarr))
        plotcov(ax, covfunc=covfunc, color=color, scale=np.sqrt(2.0), ls="-", nu=nu)
예제 #11
0
def show_keplerexp(ax, xtuple=None, set_color="color"):
    """ plot matern model.
    """
    covfunc = "kepler_exp"
    numin, numax, nnu = 0.0, 0.8, 10
    nuarr = np.linspace(numin, numax, nnu)
    print("plotting %s model with %4d numbers of nu from %.4g to %.4g\
            "%(covfunc, nnu, numin, numax))
    for i, nu in enumerate(nuarr):
        if set_color:
            color= cm.jet(1.*i/len(nuarr))
        else:
            color= cm.binary(1.*(i+2)/len(nuarr))
        plotcov(ax, covfunc=covfunc, color=color, scale=1.0, ls="-",
                xtuple=xtuple, nu=nu)
예제 #12
0
def show_keplerexp(ax, xtuple=None, set_color="color"):
    """ plot matern model.
    """
    covfunc = "kepler_exp"
    numin, numax, nnu = 0.0, 0.8, 10
    nuarr = np.linspace(numin, numax, nnu)
    print("plotting %s model with %4d numbers of nu from %.4g to %.4g\
            " % (covfunc, nnu, numin, numax))
    for i, nu in enumerate(nuarr):
        if set_color:
            color = cm.jet(1. * i / len(nuarr))
        else:
            color = cm.binary(1. * (i + 2) / len(nuarr))
        plotcov(ax,
                covfunc=covfunc,
                color=color,
                scale=1.0,
                ls="-",
                xtuple=xtuple,
                nu=nu)
def image_depth(image):
    global depth_sess
    global left
    global depth_model
    global config
    global coordinator
    global threads
    global restore_path
    input_image = np.asarray(image)
    original_height, original_width, num_channels = input_image.shape
    input_image = scipy.misc.imresize(input_image, [args.input_height, args.input_width], interp='lanczos')
    input_image = input_image.astype(np.float32) / 255
    input_images = np.stack((input_image, np.fliplr(input_image)), 0)
    disp = depth_sess.run(depth_model.disp_left_est[0], feed_dict={left: input_images})
    disp_pp = post_process_disparity(disp.squeeze()).astype(np.float32)
    disp_to_img = scipy.misc.imresize(disp_pp.squeeze(), [original_height, original_width])
    result = Image.fromarray(np.uint8(cm.binary(disp_to_img)*255))
    result = result.convert("RGB")
    numpyResult = np.array(result)
    numpyResult = cv2.cvtColor(numpyResult, cv2.COLOR_RGB2GRAY)
    return numpyResult
예제 #14
0
    def plotar_estrutura_otimizada(self,
                                   tecnica_otimizacao: int,
                                   rmin: float = 0,
                                   tipo_cmap: str = 'binary',
                                   visualizar_areas_barras=False):
        """Exibe a malha final gerada. cmad jet ou binary"""
        logger.info('Criando o desenho da malha final')

        plt.rcParams['pdf.fonttype'] = 42
        plt.rcParams['font.family'] = 'Calibri'

        # Resultados finais
        rho_final = self.dados.rhos_iteracao_final()
        results_gerais_finais = self.dados.resultados_gerais_iteracao_final()

        fig, ax = plt.subplots()
        win = plt.get_current_fig_manager()
        win.window.state('zoomed')
        ax.axis('equal')

        xmin, ymin, xmax, ymax = self.dados.poligono_dominio_estendido.bounds
        dx = xmax - xmin
        dy = ymax - ymin
        plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx)
        plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy)

        elementos_poli = []
        elementos_barra = []

        x_bar_max = 0
        if self.dados.tem_barras():
            x_bar_max = max(rho_final[self.dados.num_elementos_poli::])

        for j, el in enumerate(self.dados.elementos):
            if j < self.dados.num_elementos_poli:
                if tipo_cmap == 'jet':
                    elementos_poli.append(
                        patches.Polygon(self.dados.nos[el],
                                        linewidth=0,
                                        fill=True,
                                        facecolor=cm.jet(rho_final[j])))
                else:
                    elementos_poli.append(
                        patches.Polygon(self.dados.nos[el],
                                        linewidth=0,
                                        fill=True,
                                        facecolor=cm.binary(rho_final[j])))
            else:
                verts = [self.dados.nos[el[0]], self.dados.nos[el[1]]]
                codes = [path.Path.MOVETO, path.Path.LINETO]

                rho = 15 * rho_final[j] / x_bar_max
                # rho = 6 if rho_final[j] > 0 else 0

                if rho > 0:
                    if tipo_cmap == 'jet':
                        elementos_barra.append(
                            patches.PathPatch(path.Path(verts, codes),
                                              linewidth=rho,
                                              edgecolor='black'))
                    else:
                        elementos_barra.append(
                            patches.PathPatch(path.Path(verts, codes),
                                              linewidth=rho,
                                              edgecolor='red'))
        # Enumerar os pontos
        if self.dados.tem_barras():
            if visualizar_areas_barras:
                for i in range(self.dados.num_elementos_poli,
                               self.dados.num_elementos):
                    if rho_final[i] > 0:
                        # Centro da barra
                        nos_barra_i = self.dados.nos[self.dados.elementos[i]]
                        c = (nos_barra_i[0] + nos_barra_i[1]) / 2

                        cor = 'white' if tipo_cmap == 'jet' else 'blue'
                        ax.text(c[0],
                                c[1],
                                f'{rho_final[i] / x_bar_max:.2E}',
                                ha="center",
                                va="center",
                                size=0.05 * min(dx, dy),
                                color=cor)

        # Desenhar o domínio do desenho
        # contorno = self.dados.poligono_dominio_estendido.boundary.coords[:]
        # linhas_cont = []
        # for lin in contorno:
        #     linhas_cont.append(patches.PathPatch(path.Path(lin, [path.Path.MOVETO, path.Path.LINETO]),
        #                                          linewidth=1, edgecolor='black'))

        # Adicionar marcador do diâmetro mínimo dos elementos
        path_diam_verts = [[xmax - rmin * 2 - 0.01 * dx, ymax - 0.01 * dx],
                           [xmax - 0.01 * dx, ymax - 0.01 * dx]]
        path_diam_codes = [path.Path.MOVETO, path.Path.LINETO]
        path_diam = path.Path(path_diam_verts, path_diam_codes)
        ax.add_patch(patches.PathPatch(path_diam, linewidth=2,
                                       color='magenta'))

        ax.add_collection(PatchCollection(elementos_poli, match_original=True))

        if self.dados.tem_barras():
            ax.add_collection(
                PatchCollection(elementos_barra, match_original=True))
        # ax.add_collection(PatchCollection(linhas_cont, match_original=True))
        plt.axis('off')
        plt.grid(b=None)

        # Título
        # Fixos
        di = f'Di: {results_gerais_finais[5]:.2f}%'
        els = f'NumElems: {len(self.dados.elementos)}'
        vf = f'vol: {results_gerais_finais[4]:.4f}%'
        # Variáveis
        rmin = ''
        tecnica_otm = 'Técnica: '

        if tecnica_otimizacao == 0:
            tecnica_otm += 'Sem filtro'
        else:
            rmin = f'rmin: {rmin}'

            if tecnica_otimizacao in OC.TECNICA_OTM_EP_LINEAR:
                tecnica_otm += 'Linear '
            elif tecnica_otimizacao in OC.TECNICA_OTM_EP_HEAVISIDE:
                tecnica_otm += 'Heaviside '
            else:
                raise ValueError(
                    f'A técnica de otimização "{tecnica_otimizacao}" não é válida!'
                )

            if tecnica_otimizacao in OC.TECNICA_OTM_EP_DIRETO:
                tecnica_otm += 'direto'
            elif tecnica_otimizacao in OC.TECNICA_OTM_EP_INVERSO:
                tecnica_otm += 'inverso'
            else:
                raise ValueError(
                    f'A técnica de otimização "{tecnica_otimizacao}" não é válida!'
                )

        plt.title(f'{tecnica_otm}     {els}     {vf}     {di}    {rmin}')
        plt.show()
예제 #15
0
psi_0 = data_file['wavefunction/psi_0'][108:148, 108:148, frame]
psi_minus = data_file['wavefunction/psi_minus'][108:148, 108:148, frame]

dens = abs(psi_plus)**2 + abs(psi_0)**2 + abs(psi_minus)**2
psi_plus /= np.sqrt(dens)
psi_0 /= np.sqrt(dens)
psi_minus /= np.sqrt(dens)

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_axis_off()

scaling = 30

for i in range(0, psi_plus.shape[0], 16):
    for j in range(0, psi_plus.shape[1], 8):
        sph_harm = psi_plus[i, j] * Y_1p1 + psi_0[i, j] * Y_10 + psi_minus[
            i, j] * Y_1m1
        xx = scaling * abs(sph_harm)**2 * sin(Theta) * cos(Phi) + X[i, j]
        yy = scaling * abs(sph_harm)**2 * sin(Theta) * sin(Phi) + Y[i, j]
        zz = scaling * abs(sph_harm)**2 * cos(Theta)

        ax.plot_surface(xx,
                        yy,
                        zz,
                        rstride=1,
                        cstride=1,
                        facecolors=cm.binary(np.angle(sph_harm)))

plt.show()
예제 #16
0
import matplotlib.cm as cm

# %matplotlib inline

# generate some random data
npoints = 5
x = np.random.randn(npoints)
y = np.random.randn(npoints)

# make the size proportional to the distance from the origin
s = [0.1 * np.linalg.norm([a, b]) for a, b in zip(x, y)]
s = [a / max(s) for a in s]  # scale

# set color based on size
c = s
colors = [cm.binary(color) for color in c]  # gets the RGBA values from a float

# create a new figure
fig, ax = plt.subplots()
# ax = fig.gca()
for a, b, color, size in zip(x, y, colors, s):
    # plot circles using the RGBA colors
    circle = plt.Circle((a, b), size, color=color, fill=True)
    # add_patch(circle)
    ax.add_artist(circle)

# you may need to adjust the lims based on your data
minxy = 1.5 * min(min(x), min(y))
maxxy = 1.5 * max(max(x), max(y))
plt.xlim([minxy, maxxy])
plt.ylim([minxy, maxxy])
예제 #17
0
def periodradius_2x2(epos):
    f, axes = plt.subplots(2, 2, sharex=True, sharey=True)
    ((ax1, ax2), (ax3, ax4)) = axes
    f.set_size_inches(9, 7)  # default 7, 5
    f.subplots_adjust(wspace=0.5, hspace=0.5)

    if False:
        #f.suptitle(epos.name)
        f.suptitle(
            "Compare Planet Formation Models to Observed Exoplanets with epos")
    else:
        words = [
            'Compare', 'Planet Formation Models', 'to', 'Observed Exoplanets',
            'with', 'epos'
        ]
        colors = ['b', '0.5', 'k', 'r', 'k', 'g']

        helpers.rainbow_text(0.05,
                             0.95,
                             words,
                             colors,
                             size=16,
                             f=f,
                             fudge=1.5)
        #helpers.rainbow_text(0.05, 1.1, words, colors, size=18, ax=axes[0,0])

    helpers.set_axes(axes[1, 0], epos, Trim=True)
    ''' Top left: model '''
    ax = axes[0, 0]
    ax.set_title('Formation Model: {}'.format(epos.name))
    pfm = epos.pfm
    ax.plot(pfm['P'], pfm['R'], ls='', marker='.', ms=5.0, color='0.5')
    ''' Top right: synthetic obs'''
    ax = axes[0, 1]
    ax.set_title('Simulated Observations')

    if epos.MonteCarlo:
        sim = epos.synthetic_survey
        ax.plot(sim['P'],
                sim['Y'],
                ls='',
                marker='.',
                mew=0,
                ms=5.0,
                color='r',
                alpha=0.5)
    else:
        levels = np.linspace(0, np.max(sim['pdf']))
        ax.contourf(epos.MC_xvar,
                    epos.MC_yvar,
                    sim['pdf'].T,
                    cmap='Reds',
                    levels=levels)
    ''' Bottom left: occurrnce rates'''
    ax = axes[1, 0]
    ax.set_title('Occurrence Rates')

    occbin = epos.occurrence['bin']
    maxocc = np.max(occbin['occ'])
    for k, (xbin, ybin, n, inbin, occ) in enumerate(
            zip(occbin['x'], occbin['y'], occbin['n'], occbin['i'],
                occbin['occ'])):

        # box
        ax.add_patch(
            patches.Rectangle((xbin[0], ybin[0]),
                              xbin[1] - xbin[0],
                              ybin[1] - ybin[0],
                              fill=True,
                              ls='-',
                              fc=cm.binary(occ / maxocc)))

        #xnudge=1.01
        #ynudge=1.02
        #ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top',
        #	size=8)

    # colored dots
    #ax.plot(epos.obs_xvar, epos.obs_yvar,
    #	ls='', marker='.', mew=0, ms=2.0, color='k')
    ''' Bottom right: observations '''
    ax = axes[1, 1]
    ax.set_title('Observed Planets')
    ax.plot(epos.obs_xvar,
            epos.obs_yvar,
            ls='',
            marker='.',
            mew=0,
            ms=5.0,
            color='C3')
    ''' Draw arrows between plots'''
    props = dict(transform=f.transFigure,
                 arrowstyle='simple',
                 connectionstyle='arc3',
                 alpha=0.3,
                 fc='g',
                 mutation_scale=80.)
    xl, xr = 0.44, 0.57
    yt, yb = 0.75, 0.25
    arrow1 = patches.FancyArrowPatch((xl, yt), (xr, yt), **props)
    arrow2 = patches.FancyArrowPatch((xr, yb), (xl, yb), **props)

    f.text((xl + xr) / 2,
           yt,
           'Bias',
           color='k',
           ha='center',
           va='center',
           transform=f.transFigure)
    f.text((xl + xr) / 2,
           yb,
           'Debias',
           color='k',
           ha='center',
           va='center',
           transform=f.transFigure)

    # and top-bottom
    props['connectionstyle'] = 'arc3,rad=0.9'
    props['mutation_scale'] = 30.
    props['fc'] = 'b'
    xl, xr = 0.27, 0.75
    xw = 0.03
    yt, yb = 0.55, 0.46

    arrow3 = patches.FancyArrowPatch((xl - xw, yt), (xl - xw, yb), **props)
    arrow4 = patches.FancyArrowPatch((xl + xw, yb), (xl + xw, yt), **props)
    for xt in [xl, xr]:
        f.text(xt, (yt + yb) / 2,
               'Compare',
               color='b',
               ha='center',
               va='center',
               transform=f.transFigure)

    arrow5 = patches.FancyArrowPatch((xr - xw, yt), (xr - xw, yb), **props)
    arrow6 = patches.FancyArrowPatch((xr + xw, yb), (xr + xw, yt), **props)

    f.patches.extend([arrow1, arrow2, arrow3, arrow4, arrow5, arrow6])

    #f.tight_layout()
    helpers.save(plt, epos.plotdir + 'workflow/arrows_2x2')
예제 #18
0
urlFormat = 'http://a.tile.openstreetmap.org/{0}/{1}/{2}.png'

# OpenStreetMapのタイル画像を読み込み連結して1枚の画像として返す
imgColors = load_imgColors(urlFormat, z, x1, x2, y1, y2)

# 地図画像RGBデータは256で割って0..1に正規化しておく
imgColors = imgColors / 256.

# 勾配を求める
(Zy, Zx) = np.gradient(Z)

# Y軸方向の勾配を0..1に正規化
Zgradient_norm = (Zy - Zy.min()) / (Zy.max() - Zy.min())

# Y軸方向の勾配をグレイスケール化する
projectionIMG = cm.binary(Zgradient_norm)

# 透過情報はカット
projectionIMG = projectionIMG[:, :, :3]

# 地図画像と射影印影図を足して2で割りゃ画像が合成される
imgColors = (imgColors * 1.2 + projectionIMG) / 2

# 合成画像の輝度値の標準偏差を32,平均を80になんとなく変更
imgColors = (imgColors - np.mean(imgColors)) / np.std(imgColors) * 32 + 80
imgColors = (imgColors - imgColors.min()) / (imgColors.max() - imgColors.min())

# 地図の描画範囲の緯度経度を求める
xlim = Z.shape[1]
ylim = Z.shape[0]
예제 #19
0
mitosisSUB = mitosisSUB[mitosisSUB['GEN'].str.contains(
    '2'
)]  #find if it is tracked to mitosis. this is just going to be generation of interest+1 at the end of the string/list.  these 2 values are important as they are modifiable parameters which decide which generation you are finding the time point for mitosos for.

mitTimeList = []
for a in range(0, len(mitosisSUB)):
    valueInList = mitosisSUB["GEN"].iloc[a]
    genToList = ast.literal_eval(valueInList)
    xLOC = mitosisSUB["X"].iloc[a]
    xVAL = ast.literal_eval(xLOC)
    yLOC = mitosisSUB["Y"].iloc[a]
    yVAL = ast.literal_eval(yLOC)
    zLOC = mitosisSUB["Z"].iloc[a]
    zVAL = ast.literal_eval(zLOC)
    tLOC = mitosisSUB["T"].iloc[a]
    tVAL = ast.literal_eval(tLOC)
    genLEN = len(genToList)
    print("{},{},{},{}".format(xVAL[-1], yVAL[-1], zVAL[-1], tVAL[-1], genLEN))

    plotcrd = (xVAL[-1], yVAL[-1], zVAL[-1], genLEN
               )  #create tuple with all the coordinates we could need, x,y,z,T
    mitTimeList.append(plotcrd)
print(mitTimeList)
for b in mitTimeList:
    print("b= ", b)
    plt.scatter(
        b[1], b[2], c=cm.binary(b[3] * 15), s=100
    )  #need to multiply the mitosis time value by 15 as the colour pallette doesn't register the small time differences. scaling up puts distance between time points and these register better on colour scale. make points nice and big to emphasise colours.

plt.show()
예제 #20
0
        # print("Dsolver: ", time.time() - dsynth_starttime)
        # assert dinv == inv

        # print("Solving Bits: ", 7)
        # print("Solver Steps: ", steps)
        # print("Safe Size:", system.mgr.count(safe, p_precision + v_precision))
        print("Invariant Size:", inv.count_nb(p_precision + v_precision))

        # try:
        #     fig, ax = scatter2D(system.mgr, ('v', vspace), ('p', pspace), inv, fig=fig, ax=ax, alpha = numapplied/3000, fname=str(numapplied))
        # except:
        #     fig, ax = scatter2D(system.mgr, ('v', vspace), ('p', pspace), inv,alpha = numapplied/3000, fname=str(numapplied))

import matplotlib.cm as cm
offset = 10
colors = cm.binary(np.linspace(.1, .9, len(growing_inv)))

# for i, safeinv in enumerate(growing_inv[::-1]):
#     try:
#         fig, ax = scatter2D(system.mgr, ('v', vspace), ('p', pspace), safeinv.assum, fig=fig, ax=ax, co = colors[i])
#     except:
#         fig, ax = scatter2D(system.mgr, ('v', vspace), ('p', pspace), safeinv.assum, co = colors[i])

# fig.savefig("asdf.png",  dpi=400)

print("Abstraction Time: ", time.time() - abs_starttime)

# system = pcomp * vcomp
# # Control system declaration
# for nbits in [6]:
예제 #21
0
def fuel_type(fl, color_):
    """doc"""
    i.shared.update({'fuel': fl})
    criteria = list(i.shared.values())

    df = u.run_sql_query(u.full_path('Ann_report_sql', 'offSpecsPeriodic.sql'), i.shared)

    for col in df.columns:
        if df[col].dtype == 'int64' and col[-1] == 'a':
            df = df.drop(col, axis=1)

    df2 = df.sum()
    df3 = df2[df2 != 0]
    df4 = pd.DataFrame(df3)
    df4 = df4.reset_index()
    df4.columns = ['test', 'count']
    df4['count'] = df4['count'].astype(float)

    def truncy(s):
        """doc"""
        if s is not None:
            return s[:len(s)-9]

    df4.test = df4.test.apply(truncy)
    df4['perc'] = ((df4['count'] / df4['count'].sum()) * 100).round(2)
    df4['labels'] = df4.test.str.cat(df4['perc'].astype(str), sep='\n')
    df4 = df4.sort_values(by='count').reset_index(drop=True)
    df4['counts'] = np.arange(1, max(df4.index)+2)

    plt.figure(figsize=(5, 5))
    ax = plt.axes([0.025, 0.025, 1, 1], polar=True)
    theta = df4.test
    theta = np.linspace(0.0, 2*np.pi, len(df4.test), endpoint=False)
    theta3 = np.linspace(0, np.pi)
    radii = df4['count']
    width = np.pi/(len(df4)/2)
    bars = plt.bar(theta, radii, width=width, bottom=0)
    radii2 = 10 * np.arange(0, len(df4), 1)
    for r, bars in zip(radii2, bars):
        bars.set_facecolor(cm.binary(r / (len(df4)*10.)))
        bars.set_alpha(0.8)

    ax.set_ylim(0, max(df4['count']))
    ax.set_yticklabels([])
    ax.set_xlim(0, len(theta3)+0.262)
    ax.spines['polar'].set_visible(False)
    print(criteria)
    if criteria[4] == 1:
        ax.set_title('Global off specification characteristics\nHFO percentage'
                     , color='#282f65', size=12)
    else:
        ax.set_title('Global off specification characteristics\nMGO percentage'
                     , color='#282f65', size=12)
    t = ax.title
    t.set_position([.5, 1.15])

    ax.set_xticklabels(df4['labels'], color=color_, fontsize=8)
    ax.patch.set_facecolor(color_)
    ax.patch.set_alpha(0.25)
    ax.set_xticks(np.pi/180 * np.linspace(-360, -360/len(df4.index), 
                                          len(df4.index)))
    ax.set_theta_offset(360 + len(df4) / 100)
    ax.yaxis.grid(False)
    plt.savefig('plots/PPTOffSpecPerc{}.png'.format(fl)
                , bbox_inches='tight', dpi=200)
    plt.show()
예제 #22
0
def makeColorMap(limit):
    colors1 = cm.binary(np.linspace(0,1,256*limit))
    colors2 = cm.viridis(np.linspace(0,1,256*(1-limit)))
    colors=np.vstack((colors1, colors2))
    mymap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)
    return mymap
예제 #23
0
            D[j] = distance
        Dtemp = D[(D > 0.) * (
            D < upper_bound[I]
        )]  # Array containing all distances between centres, greater than 0., but less than upperbound on the diameter

        for item in Dtemp:  # Append all these distances to the array Dtouch. This contains all distances to particles that are in contact w\ this one
            Dtouch.append(item)

    Dtouch = np.array(Dtouch)  # Convert to numpy array
    C.append(float(np.size(Dtouch)) /
             float(N))  # The size of Dtouch/total part number is the mean

    if I < 3:
        plt.bar(I,
                C[-1],
                color=cm.binary(1. * I / 3),
                label='{}'.format(cont[I]))
    elif I > 2 and I < 6:
        plt.bar(I, C[-1], color=cm.binary(1. * (I - 3) / 3))
    elif I > 5 and I < 9:
        plt.bar(I, C[-1], color=cm.binary(1. * (I - 6) / 3))
    else:
        plt.bar(I, C[-1], color=cm.binary(1. * (I - 9) / 3))

    plt.ylabel(r'Average Contact Points [Particle$^{-1}$]')
    I += 1
C = np.array(C)
labels = ([
    '  ', ' 6', '  ', '  ', ' 8', '  ', '  ', '10', '  ', '  ', '12', '  '
])
plt.xticks(range(I), labels, size='small',
예제 #24
0
#!/usr/bin/env python
# coding: utf-8

# In[2]:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(nrows=7, sharex=True)

x = np.linspace(0, 2 * np.pi, 100)
for i in range(30):
    y = i * np.sin(x)
    ax1.plot(x, y, color=cm.rainbow(i / 30.0))
    ax2.plot(x, y, color=cm.Reds(i / 30.0))
    ax3.plot(x, y, color=cm.binary(i / 30.0))
    ax4.plot(x, y, color=cm.PiYG(i / 30.0))
    ax5.plot(x, y, color=cm.twilight(i / 30.0))
    ax6.plot(x, y, color=cm.Pastel1(i / 30.0))
    ax7.plot(x, y, color=cm.flag(i / 30.0))

ax1.set_xlim(0, 2 * np.pi)
fig.show()

# In[ ]:
예제 #25
0
                '1=%1.0i 2=%1.0i 3=%1.0i 4=%1.0i 5=%1.0i 6=%1.0i 7=%1.0i 8%1.0i\n 9=%1.0i 10=%1.0i 11=%1.0i 12=%1.0i 13=%1.0i 14=%1.0i 15=%1.0i 16=%1.0i none=%1.0i'
                % (count1, count2, count3, count4, count5, count6, count7,
                   count8, count9, count10, count11, count12, count13, count14,
                   count15, count16, count18))
            ax.set_ylabel('Ky GLOBAL')
            ax.set_title('Activity: min=%1.1f, max=%1.1f time=%d' %
                         (0, 8, a1.time))
            #ax.format_coord = format_coord
            ax.imshow(AF,
                      cmap=cm.binary,
                      interpolation='nearest',
                      vmin=0.,
                      vmax=1)

            ax.text(140.0, 0.0, "How Many Above Half of Max")
            ax.text(140.0, 5.0, "1", backgroundcolor=cm.binary(0.0))
            ax.text(140.0, 10.0, "2", backgroundcolor=cm.binary(0.06))
            ax.text(140.0, 15.0, "3", backgroundcolor=cm.binary(0.12))
            ax.text(140.0, 20.0, "4", backgroundcolor=cm.binary(0.18))
            ax.text(140.0, 25.0, "5", backgroundcolor=cm.binary(0.24))
            ax.text(140.0, 30.0, "6", backgroundcolor=cm.binary(0.30))
            ax.text(140.0, 35.0, "7", backgroundcolor=cm.binary(0.36))
            ax.text(140.0, 40.0, "8", backgroundcolor=cm.binary(0.42))
            ax.text(140.0, 45.0, "9", backgroundcolor=cm.binary(0.48))
            ax.text(140.0, 50.0, "10", backgroundcolor=cm.binary(0.54))
            ax.text(140.0, 55.0, "11", backgroundcolor=cm.binary(0.60))
            ax.text(140.0, 60.0, "12", backgroundcolor=cm.binary(0.66))
            ax.text(140.0, 66.0, "13", backgroundcolor=cm.binary(0.72))
            ax.text(140.0, 70.0, "14", backgroundcolor=cm.binary(0.78))
            ax.text(140.0, 75.0, "15", backgroundcolor=cm.binary(0.84))
            ax.text(140.0, 80.0, "16", backgroundcolor=cm.binary(0.9))
예제 #26
0
def Sol(u, initdata, runtime, xmesh, ymesh, negval, bndrypoints,\
        roaddata=None,presdata=None,presyears=None,nodeloc=None):
    """Prompt user for time step and plot Epona solution
    
    Arguments:
        -u
        -initdata
        -runtime
        -xmesh
        -ymesh
        -negval
        -bndrypoints
        -roadloc
        -presdata=None
        -presyear=None
        -suitability=None
    """
    #Norm definition
    mynorm = mcl.Normalize(0, 1, clip=True)
    #Get bndry and road locations
    xbndry = []
    ybndry = []
    xinit = []
    yinit = []
    for row in bndrypoints:
        xbndry.append(row[0])
        ybndry.append(row[1])
    for row in initdata:
        xinit.append(row[0])
        yinit.append(row[1])
    if roaddata is not None:
        try:
            roadmask = np.ma.array(roaddata[::-1,:],\
                mask = roaddata[::-1,:] != 1, fill_value = 0)
            roadnorm = mcl.Normalize(0, 1)
        except:
            print 'Error in road raster plot. Layer omitted.'
            roadmask = None

    #plot selected time steps
    suit_mode = -1
    while True:
        tt = raw_input("Input time step to plot, 0-"+str(runtime)+\
            ", s to use/setup suitability data, or q to quit:")
        tt = tt.strip()
        if tt == "q" or tt == "Q":
            break
        elif tt == "s" or tt == "S":

            if suit_mode == -1:
                #no suitability loaded
                import cPickle
                filename = raw_input("Input suitability .dat file to load, "+\
                    "or press enter to load suitdata.dat:")
                filename = filename.strip()
                if filename == '':
                    try:
                        fobj = open('suitdata.dat', 'r')
                        suit = cPickle.load(fobj)
                        fobj.close()
                        #flip for plotting
                        suit = suit[::-1, :]
                        suit_mode = 0
                    except IOError as e:
                        print "I/O error: {0}".format(e.strerror)
                        continue
                else:
                    if '.dat' not in filename:
                        filename = filename + '.dat'
                    #read data
                    try:
                        fobj = open(filename, 'r')
                        suit = cPickle.load(fobj)
                        fobj.close()
                        #flip for plotting
                        suit = suit[::-1, :]
                        suit_mode = 0
                    except IOError as e:
                        print "I/O error: {0}".format(e.strerror)
                        continue

            #once loaded:
            ss = raw_input("0 - do not plot suitability\n"+\
                           "1 - plot suitabilty separately\n"+\
                           "2 - scale presence solution by local suitability\n"+\
                           "3 - do both\n:")
            try:
                ss = int(ss)
            except ValueError:
                print "Unrecognized input. No change made."
                continue
            if ss > 3 or ss < 0:
                print "Unrecognized input. No change made."
                continue
            suit_mode = ss
            continue
        else:
            try:
                tt = int(tt)
            except ValueError:
                print "Unrecognized input."
                continue
        if tt < 0 or tt > runtime:
            print "Input is outside of the data range."
            continue
        if suit_mode < 2:
            #flip matrix updown-pcolor plots upsidedown
            plotvalues = np.ma.array(u[tt,::-1,:],\
                mask = u[tt,::-1,:] < negval, fill_value = 0)
        else:
            plotvalues = np.ma.array(u[tt,::-1,:]*suit,\
                mask = u[tt,::-1,:] < negval, fill_value = 0)

        #prompt for color or B/W
        c_switch = raw_input(''.join(["Hit enter for color ", \
                "or input any character for B/W:"]))
        c_switch = c_switch.strip()
        if c_switch == '':
            #color
            #cmap = cm.gist_earth_r
            #take a portion of the gist_earth_r colormap
            cmap = cm.colors.LinearSegmentedColormap.from_list(\
                'trunc({n},{a:.2f},{b:.2f})'.format(n=cm.gist_earth_r,\
                a=0.15, b=0.85), cm.gist_earth_r(np.linspace(0.15,0.85,100)))
        else:
            #grayscale. want to leave out black, so need a new colormap
            #get a grayscale colormap with 10000 steps
            rgba_array = cm.binary(np.linspace(0, 1, num=10000, endpoint=True))
            #get 10%-70% of it. This is our new colormap.
            extract_rgba_array_255 = rgba_array[1000:7000, 0:3]
            cmap = cm.colors.ListedColormap(extract_rgba_array_255)

        print('Rendering...')
        cmap.set_bad('w', 1.)
        mpl.rc('xtick', labelsize=18)
        mpl.rc('ytick', labelsize=18)
        plt.pcolor(xmesh, ymesh, plotvalues, norm=mynorm, cmap=cmap)
        plt.autoscale(tight=True)
        plt.colorbar(ticks=np.linspace(0, 1, 11))
        plt.xlabel('UTM Easting', fontsize=24)
        plt.ylabel('UTM Northing', fontsize=24)
        if suit_mode < 2:
            plt.title('Species Range Probability at Year '+str(tt),\
            fontsize=36)
        else:
            plt.title('Species Presence Probability at Year '+str(tt),\
            fontsize=36)
        plt.hold(True)
        #plot boundary
        plt.scatter(xbndry, ybndry, s=10, c='k', marker='D')
        #plot roads
        if roadmask is not None:
            try:
                cmaproad = cm.binary
                cmaproad.set_bad(alpha=0)  #transparent
                plt.pcolor(xmesh,
                           ymesh,
                           roadmask,
                           norm=roadnorm,
                           cmap=cmaproad)
            except:
                print 'Error in road raster plot. Layer omitted.'

        #show original presence data
        if c_switch == '':
            #color
            plt.scatter(xinit,
                        yinit,
                        s=100,
                        c=(0.85, 0, 0),
                        marker='x',
                        linewidths=3)
        else:
            #grayscale
            plt.scatter(xinit, yinit, s=100, c='k', marker='x', linewidths=3)
            plt.scatter(xinit, yinit, s=80, c='w', marker='x')

        #plot presence data for most recent year
        if presdata is not None:
            #find the last year <= than the current year in sorted list
            year = -1
            for yr in presyears:
                if yr < tt:
                    year = yr
                elif yr == tt:
                    year = yr
                    break
                else:
                    break
            if year > -1:
                xpres = []
                ypres = []
                for row in presdata[year]:
                    xpres.append(row[0])
                    ypres.append(row[1])
                if c_switch == '':
                    #color
                    plt.scatter(xpres,
                                ypres,
                                s=120,
                                c='m',
                                marker='+',
                                linewidths=3)
                else:
                    #grayscale
                    plt.scatter(xpres,
                                ypres,
                                s=120,
                                c='k',
                                marker='+',
                                linewidths=3)
                    plt.scatter(xpres, ypres, s=96, c='w', marker='+')

        #plot graph node locations
        if nodeloc is not None:
            xloc = []
            yloc = []
            for row in nodeloc:
                xloc.append(row[0])
                yloc.append(row[1])
            if c_switch == '':
                #color
                plt.scatter(xloc, yloc, s=120, c=(0, .75, 0), marker='H')
            else:
                #grayscale
                plt.scatter(xloc, yloc, s=120, c='w', marker='H')

        plt.hold(False)

        if suit_mode == 1 or suit_mode == 3:
            plt.figure()
            cmap.set_bad('w', 1.)
            mpl.rc('xtick', labelsize=18)
            mpl.rc('ytick', labelsize=18)
            plt.pcolor(xmesh, ymesh, suit, norm=mynorm, cmap=cmap)
            plt.autoscale(tight=True)
            plt.colorbar(ticks=np.linspace(0, 1, 11))
            plt.xlabel('UTM Easting', fontsize=24)
            plt.ylabel('UTM Northing', fontsize=24)
            plt.title('Species Suitability Map', fontsize=36)
            plt.hold(True)
            #plot boundary
            plt.scatter(xbndry, ybndry, s=10, c='k', marker='D')
        plt.show()
예제 #27
0
    def cluster_plot_normal_data_weight_euclidean(self, xpts, ypts, colors,
                                                  power, ncenters, step_size):
        xpts_nor = normalization(xpts)
        ypts_nor = normalization(ypts)

        var = np.ndarray(2)
        # print(xpts.size, xpts)

        #     print('data is ',data[0]
        var.itemset(0, np.var(xpts_nor))
        var.itemset(1, np.var(ypts_nor))

        #     print('the variance is ', var)
        # Set up the loop and plot
        self.fig.set_size_inches(12, 6)
        ax = self.fig.subplots(1, 2)
        # self.fig, ax = plt.subplots(1, 3, figsize=(18, 6))

        alldata = np.vstack((xpts_nor, ypts_nor))
        #     print(alldata)
        fpcs = []
        radius_lst = np.zeros(1)
        insert_index = 0
        for image_index, ax in enumerate(ax.reshape(-1), 2):
            if (image_index == 2):
                #     print(ncenters)
                cntr, u, u0, d, jm, p, fpc = cmeans(alldata,
                                                    ncenters,
                                                    2,
                                                    error=0.000005,
                                                    maxiter=1000,
                                                    var=var,
                                                    method=1,
                                                    init=None)

                # Store fpc values for later
                fpcs.append(fpc)

                # Plot assigned clusters, for each data point in training set
                cluster_membership = np.argmax(u, axis=0)
                x_lst = np.zeros(1)
                y_lst = np.zeros(1)
                radius_map = np.zeros(1)
                radius_lst, cov_sp_lst = generate_new_coverage_new(
                    u, d, power, ncenters, 2)
                print('ro lst is ', radius_lst)
                for j in range(ncenters):
                    ax.plot(xpts_nor[cluster_membership == j],
                            ypts_nor[cluster_membership == j], '.')

                    #             #create  a circle centered at calculated ventroid with radius of the longest
                    #             normal_data = normalization(d[j])
                    #             # print('normal_data is ', normal_data)
                    #             coverage = np.zeros(1)
                    #             # coverage1 = np.zeros(1)
                    #
                    #
                    base_coverage = float(find_base_coverage(power))
                    max_cov = float(base_coverage * (1 - base_coverage)**power)
                    #             # print('max cov is ', max_cov, type(max_cov))
                    x_lst = np.hstack((x_lst, cntr[j][0]))
                    y_lst = np.hstack((y_lst, cntr[j][1]))
                    radius_map = np.hstack((radius_map, radius_lst[j]))
                    #             radius_1 = np.zeros(1)
                    #             for i in range(d[j].size):
                    #                 if(normal_data[i] < base_coverage):
                    #                     coverage = np.hstack((coverage, u[j][i]))
                    #                     # coverage1 = np.hstack((coverage1, normal_data[i]))
                    #             coverage = np.delete(coverage, 0)
                    #
                    # #             coverage1 = np.delete(coverage1, 0)
                    #             radius_1 = np.sum(coverage) / u[j].size
                    #             radius_lst = np.hstack((radius_lst, radius_1))
                    #             # print('base is ', base_coverage, type(base_coverage), 'radius is ', radius_1)

                    circle = plt.Circle(
                        (cntr[j][0], cntr[j][1]),
                        radius_lst[j],
                        facecolor=cm.binary(float(cov_sp_lst[j]) / max_cov),
                        edgecolor='k',
                        fill=True)

                    # circle = plt.Circle((cntr[j][0], cntr[j][1]),
                    #         radius_1,
                    #        facecolor='None', edgecolor= 'k')

                    ax.add_artist(circle)
                    ax.plot(cntr[j][0], cntr[j][1], 'rs')

                    #     membership_graph(ncenters, u, xpts, ypts)
                    ax.set_title('Beta={0}'.format(power))

                    # ax.axis('off')
                    self.ax_euclidean.insert(insert_index, ax)
                    insert_index += 1
                    #             ax.axis('off')

            elif (image_index == 3):
                radius_map = np.delete(radius_map, 0)
                #             ax.plot(range(100))
                power, power_lst, intersect_num_lst = fin_best_beta(
                    ncenters, cntr, u, d, power, radius_lst, step_size, var)
                # Plot assigned clusters, for each data point in training set
                cluster_membership = np.argmax(u, axis=0)
                radius_lst, cov_sp_lst = generate_new_coverage_new(
                    u, d, power, ncenters, 2)
                x_lst = np.zeros(1)
                y_lst = np.zeros(1)
                radius_map = np.zeros(1)
                for j in range(ncenters):
                    ax.plot(xpts_nor[cluster_membership == j],
                            ypts_nor[cluster_membership == j], '.')

                    #             #create  a circle centered at calculated ventroid with radius of the longest
                    #             normal_data = normalization(d[j])
                    #             # print('normal_data is ', normal_data)
                    #             coverage = np.zeros(1)
                    #             coverage1 = np.zeros(1)
                    #
                    #
                    base_coverage = float(find_base_coverage(power))
                    max_cov = float(base_coverage * (1 - base_coverage)**power)
                    x_lst = np.hstack((x_lst, cntr[j][0]))
                    y_lst = np.hstack((y_lst, cntr[j][1]))
                    radius_map = np.hstack((radius_map, radius_lst[j]))
                    #             radius_1 = np.zeros(1)
                    #             for i in range(d[j].size):
                    #                 if(normal_data[i] < base_coverage):
                    #                     coverage = np.hstack((coverage, u[j][i]))
                    #                     coverage1 = np.hstack((coverage1, normal_data[i]))
                    #             coverage = np.delete(coverage, 0)
                    #
                    # #             coverage1 = np.delete(coverage1, 0)
                    #             radius_1 = np.sum(coverage) / u[j].size
                    #             radius_lst = np.hstack((radius_lst, radius_1))

                    # circle = plt.Circle((cntr[j][0], cntr[j][1]),
                    #         radius_1,
                    #        color = cm.binary(radius_1/max_cov))
                    # print('base is ', base_coverage, type(base_coverage), 'radius is ', radius_1)

                    circle = plt.Circle(
                        (cntr[j][0], cntr[j][1]),
                        radius_lst[j],
                        facecolor=cm.binary(float(cov_sp_lst[j]) / max_cov),
                        edgecolor='k',
                        fill=True)

                    #
                    # # ax.add_patch(circle)
                    ax.add_artist(circle)
                    ax.plot(cntr[j][0], cntr[j][1], 'rs')

                    #     membership_graph(ncenters, u, xpts, ypts)

                    #         ax.set_title('Beta={0};Coverage={1:.4f}'.format(power, radius_1))
                    ax.set_title('Best Beta={:10.2f}'.format(power))
                    self.ax_euclidean.insert(insert_index, ax)
                    insert_index += 1
            # elif(image_index == 4):
            #     ax.axis('off')
            # ax('off')
            # ax.plot(power_lst, intersect_num_lst)
            # ax.set_title('interctect num as func of beta')
            # self.ax_euclidean.insert(insert_index, ax)
            # insert_index+=1

        self.fig.tight_layout()
        radius_map = np.delete(radius_map, 0)
        x_lst = np.delete(x_lst, 0)
        y_lst = np.delete(y_lst, 0)
        c = radius_map / np.amax(radius_map)
        self.scatter = plt.scatter(x_lst, y_lst, s=0, c=c, cmap='binary')
        # plt.grid()
        self.colorbar = plt.colorbar()  # this works because of the scatter
        # plt.show()
        self.canvas.draw()
    Z = np.array((ProfileLines[j + 1].strip().split(" "))[1:], dtype="float64")

    #read in concentration data
    X2 = np.array((ConcentrationLines[j].strip().split(" "))[1:],
                  dtype="float64")
    N = np.array((ConcentrationLines[j + 1].strip().split(" "))[1:],
                 dtype="float64")

    if j == 1:
        CliffPositionX = X[0]
        TimeOld = Time
        CliffPositionXOld = CliffPositionX

        #plot profiles
        Color = 0.2
        ax1.plot(X, Z, '-', color=cm.binary(Color), lw=1.5)
        datestring = '%.1f' % (Time / 1000.)
        ax1.text(X[0] - 4,
                 6,
                 datestring + " ka",
                 rotation=270,
                 color=cm.binary(Color))
        continue

    #only plot every plottime
    if (Time == PlotTime):
        #Get color for plotting
        Color = PlotTime / EndTime

        #plot profiles
        ax1.plot(X, Z, '-', color=cm.binary(Color), lw=1.5)
예제 #29
0
	D -= 1.
	for j in range(N-1):				   # find distances between current particle and ALL other particles and store these in D
	    dx = X[i] - X[j]
	    dy = Y[i] - Y[j]
	    distance = np.sqrt(dx**2. + dy**2.)
	    D[j] = distance
	Dtemp = D[(D>0.)*(D<upper_bound[I])]		   # Array containing all distances between centres, greater than 0., but less than upperbound on the diameter
	
	for item in Dtemp:				   # Append all these distances to the array Dtouch. This contains all distances to particles that are in contact w\ this one
	    Dtouch.append(item)

    Dtouch = np.array(Dtouch)				   # Convert to numpy array
    C.append(float(np.size(Dtouch))/float(N))		   # The size of Dtouch/total part number is the mean
	
    if I<3:
    	plt.bar(I,C[-1],color=cm.binary(1.*I/3),label = '{}'.format(cont[I]))
    elif I>2 and I<6:
    	plt.bar(I,C[-1],color=cm.binary(1.*(I-3)/3))
    elif I>5 and I<9:
    	plt.bar(I,C[-1],color=cm.binary(1.*(I-6)/3))
    else:
    	plt.bar(I,C[-1],color=cm.binary(1.*(I-9)/3))

    plt.ylabel(r'Average Contact Points [Particle$^{-1}$]')
    I += 1
C = np.array(C)
labels = (['  ',' 6','  ','  ',' 8','  ','  ','10','  ','  ','12','  '])
plt.xticks(range(I),labels,size='small',ha='left')#,rotation='vertical',ha='left')
plt.xlabel('No. Cells Per Particle Radius (cppr)')
plt.legend(fontsize='x-small',loc='best',framealpha=0.5)
cppr = np.array([6,8,10,12])
예제 #30
0
         ax4.set_title("Number of Neurons that Respond to Higher than .5 max firing rate")
         ax4.set_ylabel("Number of Neurons")
         ax4.set_xlabel("Number of Presented Lines")


         fig = plt.figure()
         ax = fig.add_subplot(1,1,1)

         ax.set_xlabel('1=%1.0i 2=%1.0i 3=%1.0i 4=%1.0i 5=%1.0i 6=%1.0i 7=%1.0i 8%1.0i\n 9=%1.0i 10=%1.0i 11=%1.0i 12=%1.0i 13=%1.0i 14=%1.0i 15=%1.0i 16=%1.0i none=%1.0i' %(count1, count2, count3, count4, count5, count6, count7, count8, count9, count10, count11, count12, count13, count14, count15, count16, count18))
         ax.set_ylabel('Ky GLOBAL')
         ax.set_title('Activity: min=%1.1f, max=%1.1f time=%d' %(0, 8, a1.time))
      #ax.format_coord = format_coord
         ax.imshow(AF, cmap=cm.binary, interpolation='nearest', vmin=0., vmax=1)

         ax.text(140.0, 0.0, "How Many Above Half of Max") 
         ax.text(140.0, 5.0, "1", backgroundcolor = cm.binary(0.0))
         ax.text(140.0, 10.0, "2", backgroundcolor = cm.binary(0.06))
         ax.text(140.0, 15.0, "3", backgroundcolor = cm.binary(0.12))
         ax.text(140.0, 20.0, "4", backgroundcolor = cm.binary(0.18))
         ax.text(140.0, 25.0, "5", backgroundcolor = cm.binary(0.24))
         ax.text(140.0, 30.0, "6", backgroundcolor = cm.binary(0.30))
         ax.text(140.0, 35.0, "7", backgroundcolor = cm.binary(0.36))
         ax.text(140.0, 40.0, "8", backgroundcolor = cm.binary(0.42))
         ax.text(140.0, 45.0, "9", backgroundcolor = cm.binary(0.48))
         ax.text(140.0, 50.0, "10", backgroundcolor = cm.binary(0.54))
         ax.text(140.0, 55.0, "11", backgroundcolor = cm.binary(0.60))
         ax.text(140.0, 60.0, "12", backgroundcolor = cm.binary(0.66))
         ax.text(140.0, 66.0, "13", backgroundcolor = cm.binary(0.72))
         ax.text(140.0, 70.0, "14", backgroundcolor = cm.binary(0.78))
         ax.text(140.0, 75.0, "15", backgroundcolor = cm.binary(0.84))
         ax.text(140.0, 80.0, "16", backgroundcolor = cm.binary(0.9))
예제 #31
0
paths = []
pathfluxes = []
for line in lines:
    pathi = line.split()
    pathfluxes += [float(pathi[0])]
    paths += [[int(s) for s in pathi[1:]]]
pathfluxes = np.array(pathfluxes)
paths = np.array(paths)

#(paths,pathfluxes) = tpt.pathways(fraction=0.95,maxiter=2000)

maxflux = np.max(pathfluxes)
minflux = np.min(pathfluxes)
n_paths = 1681
for i in range(340, n_paths, 10):
    pathi = paths[i]
    #print(pathi)
    pathi_real = np.array([state_label[s] for s in pathi])
    tica_pathi = clusterer.cluster_centers_[pathi_real]
    #print(pathi_real)
    #print(tica_pathi)
    #flux_i = (pathfluxes[i])/(maxflux)
    flux_i = (pathfluxes[i] - minflux) / (maxflux - minflux)
    #ax.plot(tica_pathi[:,0],tica_pathi[:,1],c=cm.bwr(i*1.0/n_paths))
    ax.plot(tica_pathi[:, 0], tica_pathi[:, 1], c=cm.binary(flux_i))

plt.show()
############################################################################
###                              END                                     ###
############################################################################