Exemple #1
0
 def plot(self,
          stretch="hist",
          cmap="gray",
          origin="lower",
          ax=None,
          colorbar=False,
          title=""):
     if ax == None:
         self.fig, self.ax = plt.subplots()
     else:
         self.ax = ax
     if stretch == "hist":
         norm = ImageNormalize(stretch=HistEqStretch(self.data))
         self.im = self.ax.imshow(self.data,
                                  cmap=cmap,
                                  origin=origin,
                                  norm=norm)
     else:
         self.im = self.ax.imshow(self.data, cmap=cmap, origin=origin)
     self.ax.set_xlim(0, self.data.shape[1])  # cols
     self.ax.set_ylim(0, self.data.shape[0])  # rows
     self.ax.set_title(title, y=1.02)
     self.ax.set_xlabel("X pixels")
     self.ax.set_ylabel("Y pixels")
     if colorbar:
         self.fig.colorbar(self.im)
Exemple #2
0
def ref2image(data,positions,aper,fig_name):
    apertures = CircularAperture(positions, r=aper[0])
    annulus_apertures = CircularAnnulus(positions, r_in=aper[1], r_out=aper[2])          
    fig = plt.figure(figsize=(20,20));fig.add_subplot(111)
    apertures.plot(color='blue',lw=2,alpha=1)
    annulus_apertures.plot(color='red',lw=2,alpha=0.5)
    norm = ImageNormalize(stretch=HistEqStretch(data))
    plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
    for i in range(len(positions)):
        plt.text(positions[i][0]+10,positions[i][1]+10,str(i+1),fontdict={'size':'50','color':'blue'})
    plt.savefig(fig_name,dpi=150)
    plt.show()
Exemple #3
0
def LSBImage(dat, noise):
    plt.figure(figsize = (6,6))
    plt.imshow(dat, origin = 'lower', cmap = 'Greys',
               norm = ImageNormalize(stretch=HistEqStretch(dat))) 
    my_cmap = cm.Greys_r
    my_cmap.set_under('k', alpha=0)
    plt.imshow(np.clip(dat,a_min = noise, a_max = None),
               origin = 'lower', cmap = my_cmap,
               norm = ImageNormalize(stretch=LogStretch(), clip = False),
               clim = [3*noise, None], vmin = 3*noise) 
    plt.xticks([])
    plt.yticks([])
    plt.subplots_adjust(left=0.03, right=0.97, top=0.97, bottom=0.05)
Exemple #4
0
def imageshow(data,positions,aper=[8,12,20],rim_size=50):
    min_x=int(np.min(positions.T[0]))-rim_size;max_x=int(np.max(positions.T[0]))+rim_size
    min_y=int(np.min(positions.T[1]))-rim_size;max_y=int(np.max(positions.T[1]))+rim_size
    data=data[min_y:max_y,min_x:max_x]
    positions=positions-np.array([min_x,min_y])
    apertures = CircularAperture(positions, r=aper[0])
    annulus_apertures = CircularAnnulus(positions, r_in=aper[1], r_out=aper[2])          
    fig = plt.figure(figsize=(20,20));fig.add_subplot(111)
    apertures.plot(color='blue',lw=2,alpha=1)
    annulus_apertures.plot(color='red',lw=2,alpha=0.5)
    norm = ImageNormalize(stretch=HistEqStretch(data))
    plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
    plt.show()
 def plot(self, stretch="hist", cmap="gray", origin="lower"):
     self.fig, self.ax = plt.subplots()
     if stretch == "hist":
         norm = ImageNormalize(stretch=HistEqStretch(self.data))
         self.im = self.ax.imshow(self.data,
                                  cmap=cmap,
                                  origin=origin,
                                  norm=norm)
     else:
         self.im = self.ax.imshow(self.data, cmap=cmap, origin=origin)
     self.ax.set_xlim(0, self.data.shape[0])
     self.ax.set_ylim(0, self.data.shape[1])
     self.fig.colorbar(self.im)
Exemple #6
0
def HistEqNorm(data):
    """Custom Histogram Equalization Norm.

    Parameters
    ----------
    data

    Returns
    -------
    ImageNormalize

    """
    return ImageNormalize(stretch=HistEqStretch(data))
Exemple #7
0
def stretch_data(data, method="HistEqStretch"):
    """
    methods = 
    LogStretch,
    SqrtStretch,
    AsinhStretch,
    HistEqStretch
    """
    if method == "LogStretch":
        norm = ImageNormalize(stretch=LogStretch(data))
    elif method == "SqrtStretch":
        norm = ImageNormalize(stretch=SqrtStretch(data))
    elif method == "AsinhStretch":
        norm = ImageNormalize(stretch=AsinhStretch(data))
    elif method == "HistEqStretch":
        norm = ImageNormalize(stretch=HistEqStretch(data))
    else:
        norm = data
    return norm
Exemple #8
0
def LSBImage(dat, noise):
    plt.figure(figsize=(6, 6))
    plt.imshow(
        dat,
        origin="lower",
        cmap="Greys",
        norm=ImageNormalize(stretch=HistEqStretch(dat[dat <= 3*noise]), clip = False, vmax = 3*noise, vmin = np.min(dat)),
    )
    my_cmap = copy(cm.Greys_r)
    my_cmap.set_under("k", alpha=0)
    
    plt.imshow(
        np.ma.masked_where(dat < 3*noise, dat), 
        origin="lower",
        cmap=my_cmap,
        norm=ImageNormalize(stretch=LogStretch(),clip = False),
        clim=[3 * noise, None],
        interpolation = 'none',
    )
    plt.xticks([])
    plt.yticks([])
    plt.subplots_adjust(left=0.03, right=0.97, top=0.97, bottom=0.05)
    plt.xlim([0, dat.shape[1]])
    plt.ylim([0, dat.shape[0]])
Exemple #9
0
def HistEqNorm(data):
    return ImageNormalize(stretch=HistEqStretch(data))
Exemple #10
0
def PSF_Image(IMG, results, options):
    """PSF routine which identifies stars and averages the FWHM.

    Constructs an averaged PSF image. Extracts a window of pixels
    around each identified star (+-10 PSF) and normalizes the flux
    total to 1. All extraced normalized stars are median stacked. The
    final PSF is saved as "<name>_psf.fits" and added to the results
    dictionary. Also calculates the PSF FWHM and adds it to the
    results dictionary. This method is currently very slow.

    Parameters
    -----------------

    ap_guess_psf : float, default None
      Initialization value for the PSF calculation in pixels. If not
      given, AutoProf will default with a guess of 1/*ap_pixscale*

    ap_set_psf : float, default None
      force AutoProf to use this PSF value (in pixels) instead of
      calculating its own.

    Notes
    ----------
    :References:
    - 'background'
    - 'background noise'

    Returns
    -------
    IMG : ndarray
      Unaltered galaxy image

    results : dict
      .. code-block:: python

        {'psf fwhm':  # FWHM of the average PSF for the image
         'auxfile psf': # aux file message giving the PSF
         'psf img':   # image of the PSF as numpy array
        }

    """

    if "ap_set_psf" in options:
        logging.info("%s: PSF set by user: %.4e" %
                     (options["ap_name"], options["ap_set_psf"]))
        return IMG, {"psf fwhm": options["ap_set_psf"]}
    elif "ap_guess_psf" in options:
        logging.info("%s: PSF initialized by user: %.4e" %
                     (options["ap_name"], options["ap_guess_psf"]))
        fwhm_guess = options["ap_guess_psf"]
    else:
        fwhm_guess = max(1.0, 1.0 / options["ap_pixscale"])

    edge_mask = np.zeros(IMG.shape, dtype=bool)
    edge_mask[int(IMG.shape[0] / 4.0):int(3.0 * IMG.shape[0] / 4.0),
              int(IMG.shape[1] / 4.0):int(3.0 * IMG.shape[1] / 4.0), ] = True
    dat = IMG - results["background"]
    stars = StarFind(
        dat,
        fwhm_guess,
        results["background noise"],
        edge_mask,
        detect_threshold=5.0,
        maxstars=100,
    )
    if len(stars["fwhm"]) <= 10:
        logging.error(
            "%s: unable to detect enough stars! PSF results not valid, using 1 arcsec estimate psf of %f"
            % (options["ap_name"], fwhm_guess))

    def_clip = 0.1
    while np.sum(stars["deformity"] < def_clip) < max(
            10,
            len(stars["fwhm"]) * 2 / 3):
        def_clip += 0.1
    psf = np.median(stars["fwhm"][stars["deformity"] < def_clip])
    psf_iqr = np.quantile(stars["fwhm"][stars["deformity"] < def_clip],
                          [0.1, 0.9])
    psf_size = int(psf * 10)
    if psf_size % 2 == 0:  # make PSF odd for easier calculations
        psf_size += 1

    psf_img = None
    XX, YY = np.meshgrid(
        np.array(range(psf_size)) - psf_size // 2,
        np.array(range(psf_size)) - psf_size // 2,
    )
    XX, YY = np.ravel(XX), np.ravel(YY)

    for i in range(len(stars["x"])):
        # ignore objects that likely aren't stars
        if (stars["deformity"][i] > def_clip or stars["fwhm"][i] < psf_iqr[0]
                or stars["fwhm"][i] > psf_iqr[1]):
            continue
        # ignore objects that are too close to the edge
        if (stars["x"][i] < psf_size // 2
                or (dat.shape[1] - stars["x"][i]) < psf_size // 2
                or stars["y"][i] < psf_size // 2
                or (dat.shape[1] - stars["y"][i]) < psf_size // 2):
            continue
        flux = interpolate_Lanczos(dat, XX + stars["x"][i], YY + stars["y"][i],
                                   10).reshape((1, psf_size, psf_size))
        flux /= np.sum(flux)
        psf_img = flux if psf_img is None else np.concatenate((psf_img, flux))

    # stack the PSF
    psf_img = np.median(psf_img, axis=0)
    # normalize the PSF
    psf_img /= np.sum(psf_img)

    hdul = fits.HDUList([fits.PrimaryHDU(psf_img)])
    hdul.writeto(
        os.path.join(
            options["ap_saveto"] if "ap_saveto" in options else "",
            "%s_psf.fits" % options["ap_name"],
        ),
        overwrite=True,
    )

    if "ap_doplot" in options and options["ap_doplot"]:
        plt.imshow(
            psf_img,
            origin="lower",
            cmap="Greys",
            norm=ImageNormalize(stretch=HistEqStretch(psf_img)),
        )
        my_cmap = cm.Greys_r
        my_cmap.set_under("k", alpha=0)
        fluxpeak = psf_img[psf_size // 2 + 1, psf_size // 2 + 1] / 2
        plt.imshow(
            np.clip(psf_img, a_min=fluxpeak / 10, a_max=None),
            origin="lower",
            cmap=my_cmap,
            norm=ImageNormalize(stretch=LogStretch(), clip=False),
            clim=[fluxpeak / 9, None],
            vmin=fluxpeak / 9,
        )
        plt.axis("off")
        plt.tight_layout()
        if not ("ap_nologo" in options and options["ap_nologo"]):
            AddLogo(plt.gcf())
        plt.savefig(
            "%sPSF_%s.jpg" % (
                options["ap_plotpath"] if "ap_plotpath" in options else "",
                options["ap_name"],
            ),
            dpi=options["ap_plotdpi"] if "ap_plotdpi" in options else 300,
        )
        plt.close()

    return IMG, {
        "psf fwhm": psf,
        "auxfile psf": "psf fwhm: %.3f pix" % psf,
        "psf img": psf_img,
    }
Exemple #11
0
def plotfits(dirname):
    
    session.modifeid = True
    session['pathname'] = app.config['UPLOAD_FOLDER']+'/'+dirname+'/'
    session['stats'] = {}
    session['date'] = {} # pegar a data para converter em juliana e inserir nas análises

    with open(session['pathname']+'data.json') as f:
        dirdata = json.load(f)

    r = dirdata['r']
    session['r'] = r
    celestial = False
    # Faz logo algumas estatísticas da imagem
    for fil in BANDAS:
        for fname in dirdata[fil]:
            img, header = fits.getdata(session['pathname']+fname, header=True)
            session['stats'][fil+':'+fname] = sigma_clipped_stats(img,sigma=3.0)

            if not celestial:
                celestial = WCS(header).has_celestial
                session['wcs'] = session['pathname']+fname
                
            session['date'][fil+':'+fname] = Time(header['DATE-OBS']).jd # a data de observação de cada imagem

    # Abrindo coordenadas se salvas
    try:
        cordata = pd.read_excel(session['pathname']+'data.xlsx')
        # Dados que serão usados para fazer computação e visualizar os pontos
        source = ColumnDataSource(cordata)

        print('Coordenadas carregadas.')
    except FileNotFoundError:
        print('Não há coordenadas salvas em %s' % session['pathname'])
        # Dados que serão usados para fazer computação e visualizar os pontos
        source = ColumnDataSource(dict(
            ra=[],
            dec=[],
            x=[],
            y=[],
            flux = [],
            j = [],
            k = [],
            tipo=[], # se é obj, src ou sky
            banda=[], # o filtro da imagem e arquivo
            sid=[], # id da estrela copiada
            colors=[], # para colorir de acordo o tipo de objeto
        ))

    # Constrói a tabaela de table que poderá ser usada para designar as posições do objeto, estrela e céu
    tabela = DataTable(source=source,columns=[
        TableColumn(field='x',title='x'),
        TableColumn(field='y',title='y'),
        TableColumn(field='ra',title='ra'),
        TableColumn(field='dec',title='dec'),
        TableColumn(field='j',title='j'),
        TableColumn(field='k',title='k'),
        TableColumn(field='flux',title='flux'),
        TableColumn(field='tipo',title='tipo'),
        TableColumn(field='banda',title='banda'),
        TableColumn(field='sid',title='sid')
    ], editable=True)
    

    P = [] # lista de gráficos para o plot
    Nimg = [] # lista de imagens normalizadas para o contraste
    for fil in BANDAS:
        for fname in dirdata[fil]:
            img = fits.getdata(session['pathname']+fname)
            stretch = HistEqStretch(img) # Histograma, melhor função para granular a imagem
            h,w = img.shape # número de linhas e colunas da matriz da imagem
            nimg = stretch(normal(img)).tolist()
            p = figure(plot_width=700, active_scroll='wheel_zoom')
            p.image(image=[nimg], x=0, y=0, dw=w, dh=h, palette='Greys256', level="image")
            p.x_range.range_padding = p.y_range.range_padding = 0
            p.grid.grid_line_width = 0

            view = CDSView(source=source,filters=[GroupFilter(column_name='banda', group=fil+':'+fname)])
            c = p.circle('x','y', source=source, view=view, color='colors', fill_color=None, radius=r, line_width=2)
            cd = p.circle_dot('x','y', source=source, view=view, color='colors', size=2)
            tool = PointDrawTool(renderers=[c,cd],empty_value='na')
            p.add_tools(tool)
            p.toolbar.active_tap = tool
            p.toolbar.active_inspect = None

            tab = Panel(child=p, title=fil+':'+fname)

            P.append(tab)
            Nimg.append(nimg)
    
    graficos = Tabs(tabs=P)
    graficos.js_on_change('active', CustomJS(code='''
    tabs_onchange(cb_obj);
    '''))

    contrast = Slider(start=-1, end=6, value=1, step=0.05, title="Contraste")
    contrast.js_on_change('value',CustomJS(args = dict(tabs=graficos.tabs, im=Nimg), code = '''
    contrast_onchange(cb_obj,tabs,im);
    '''))

    # Selecionar o tipo de fonte luminosa: obj, src ou sky
    radio_title = Paragraph(text='Escolha o tipo:')
    LABELS = ['obj','src','sky']
    radio_group = RadioGroup(labels=LABELS, active=0)

    # Evento de mudança da tabela de table, para inserir table padrão nas colunas inalteradas
    source.js_on_change('data', CustomJS(args=dict(radio=radio_group, graficos=graficos), code='''
    source_onchange(cb_obj, radio, graficos);
    '''))
    
    # Muda o raio da abertura fotométrica
    spinner = Spinner(title="Raio", low=1, high=40, step=0.5, value=r, width=80)
    spinner.js_on_change('value', CustomJS(args=dict(source=source, tabs=graficos.tabs), code='''
    radius_onchange(cb_obj,source,tabs);
    '''))

    # Coluna de requisição
    text1 = Div(text='<b>Instruções:</b><p>1. Digite a chave do Astrometry.net')
    apikey_input = TextInput(title='Apikey do Astrometry.net', placeholder='digite a chave aqui')

    text2 = Div(text='''<p>2. Selecione qual imagem será usada como referência para o astrometry.net e
    para o cálculo das coordenadas celestes</p>''')
    seletor = Select(title='Escolha a imagem de referência', options=[*session['stats'].keys()])

    text3 = Div(text='3. Clique abaixo pra requisitar a correção WCS')
    send_astrometry = Toggle(label='Solução de placa do astrometry.net', disabled=celestial)
    send_astrometry.js_on_click(CustomJS(args=dict(key=apikey_input, source=source, selected=seletor), code='''
    send_astrometry(cb_obj,key,source,selected);
    '''))

    # o Botão de salvar irá enviar um json para o servidor que irá ler e fazer os procedimentos posteriores
    text4 = Div(text='4. Salve a tabela de table clicando em salvar.')
    salvar = Button(label='Salvar tabela', button_type="success")
    salvar.js_on_click(CustomJS(args=dict(source=source), code='''
    salvar_onclick(source);
    '''))

    reset = Button(label='Limpar', button_type='success')
    reset.js_on_click(CustomJS(args=dict(source=source), code='''
    reset_onclick(source);
    '''))

    copiar = Button(label='Copiar coordenadas', button_type='success')
    copiar.js_on_click(CustomJS(args=dict(source=source, ref=seletor, active=graficos), code='''
    add_data(source,ref,active);
    '''))

    div, script = components(row(column(contrast,spinner,radio_title,radio_group),\
        column(row(reset,copiar,salvar), graficos, tabela, sizing_mode='stretch_both'),
        column(text1,apikey_input,text2,seletor,text3,send_astrometry,text4)))

    return render_template('plot.html', the_div=div, the_script=script,filename=dirdata['name'])
Exemple #12
0
def qualitycontrolplot(img, bkg, evt, title=''):
    fig = plt.figure(figsize=(24, 18))
    fig.canvas.set_window_title(title)

    aximg = fig.add_axes([.05, .73, .2, .22])
    norm = ImageNormalize(img,
                          interval=MinMaxInterval(),
                          stretch=HistEqStretch(img))
    out = aximg.imshow(img.T, origin='lower', norm=norm, cmap=plt.cm.magma)
    # cbar of hist equalized plot does not work well
    # cbar = plt.colorbar(out, ax=aximg)
    aximg.set_title('Image')

    axbkg = fig.add_axes([.3, .73, .2, .22])
    norm = ImageNormalize(bkg.T, interval=MinMaxInterval())
    out = axbkg.imshow(bkg, origin='lower', norm=norm, cmap=plt.cm.magma)
    cbar = plt.colorbar(out, ax=axbkg)
    axbkg.set_title('Background')

    axasca = fig.add_axes([.65, .71, .3, .22])
    axasca.hist(evt['ASCA'],
                bins=np.arange(-0.5, 7.6, 1.),
                histtype='stepfilled')
    axasca.hist(evt['ASCA'][evt['GOOD']],
                bins=np.arange(-0.5, 7.6, 1.),
                histtype='stepfilled')
    axasca.set_title('ASCA grades')

    x0 = 0.08
    y0 = 0.08
    dx = 0.32
    dy = 0.45
    dx_s = 0.08
    dy_s = 0.15
    gap = dx + dx_s + 0.1

    axxy = fig.add_axes([x0, y0, dx, dy])
    axxyxhist = fig.add_axes([x0, y0 + dy, dx, dy_s], sharex=axxy)
    axxyyhist = fig.add_axes([x0 + dx, y0, dx_s, dy], sharey=axxy)
    plt.setp(axxyxhist.get_xticklabels(), visible=False)
    plt.setp(axxyyhist.get_yticklabels(), visible=False)

    for ind in [~evt['GOOD'], evt['GOOD']]:
        axxy.plot(evt['X'][ind], evt['Y'][ind], '.')

    xbinning = np.arange(0, 1340, 10)
    ybinning = np.arange(0, 1300, 10)
    n, bins, p = axxyxhist.hist(evt['X'], bins=xbinning, histtype='stepfilled')
    axxyxhist.hist(evt['X'][evt['GOOD']], bins=bins, histtype='stepfilled')
    n, bins, p = axxyyhist.hist(evt['Y'],
                                bins=ybinning,
                                orientation='horizontal',
                                histtype='stepfilled',
                                label='All events')
    axxyyhist.hist(evt['Y'][evt['GOOD']],
                   bins=bins,
                   orientation='horizontal',
                   histtype='stepfilled',
                   label='good events')
    axxyyhist.legend(loc=(.1, 1.1))
    axxy.set_xlabel('X position [pixel]')
    axxy.set_ylabel('Y position [pixel]')

    axevt = fig.add_axes([x0 + gap, y0, dx, dy], sharex=axxy)
    axxhist = fig.add_axes([x0 + gap, y0 + dy, dx, dy_s], sharex=axevt)
    axyhist = fig.add_axes([x0 + dx + gap, y0, dx_s, dy], sharey=axevt)
    plt.setp(axxhist.get_xticklabels(), visible=False)
    plt.setp(axyhist.get_yticklabels(), visible=False)

    for ind in [~evt['GOOD'], evt['GOOD']]:
        axevt.plot(evt['X'][ind], evt['ENERGY'][ind] / 1e3, '.')

    n, bins, p = axxhist.hist(evt['X'], bins=xbinning, histtype='stepfilled')
    axxhist.hist(evt['X'][evt['GOOD']], bins=bins, histtype='stepfilled')
    eng = evt['ENERGY'] / 1e3
    engmin = np.nanmin(eng)
    engmax = np.nanmax(eng)
    n, bins, p = axyhist.hist(eng,
                              bins=np.arange(engmin, engmax, .025),
                              orientation='horizontal',
                              range=[engmin, engmax],
                              histtype='stepfilled',
                              label='All events')
    axyhist.hist(eng[evt['GOOD']],
                 bins=bins,
                 orientation='horizontal',
                 range=[engmin, engmax],
                 histtype='stepfilled',
                 label='good events')
    axevt.set_ylim(np.percentile(eng[evt['GOOD']], [0., 98.]))
    axevt.set_xlabel('X position [pixel]')
    axevt.set_ylabel('energy [keV]')
Exemple #13
0
def imgshow(data):
    fig = plt.figure(figsize=(20, 20))
    fig.add_subplot(111)
    norm = ImageNormalize(stretch=HistEqStretch(data))
    plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
    plt.show()