Esempio n. 1
0
def calc_borders_step(image,
                      sob,
                      pr,
                      ccl,
                      ccr,
                      sign=1,
                      refine=False,
                      plot=True,
                      barid=0,
                      px=0):
    cut1 = sob[pr, ccl:ccr + 1]
    mcut1 = image[pr, ccl:ccr + 1]

    res = feat.peak_local_max(sign * cut1, exclude_border=4, num_peaks=2)

    if len(res) != 0:
        res1 = res[:, 0]
    else:
        res1 = []

    if sign > 0:
        bar_s = 'l'
    else:
        bar_s = 'r'

    if plot:
        xdummy = np.arange(ccl, ccr + 1)
        plt.title("{}bar {}, prow={} px={}".format(bar_s, barid, pr, px))
        plt.plot(xdummy, sign * cut1)
        plt.axvline(px, color='g')
        ax1 = plt.gca()
        ax2 = ax1.twinx()
        ax2.plot(xdummy, mcut1, '--')
        for r in res1:
            plt.axvline(ccl + r, color='red')
        for r in res[:, 0]:
            plt.axvline(ccl + r, color='red', linestyle='--')
    xpeak = None
    if len(res1) != 0:
        idx = (sign * cut1)[res1].argmax()
        xpeak = ccl + res1[idx]

    if plot:
        if xpeak:
            plt.axvline(xpeak, color='black')
        plt.show()

    if xpeak:
        if refine:
            x_t, y_t = refine_peaks(sign * sob[pr],
                                    np.array([xpeak]),
                                    window_width=3)
            xpeak_ref = x_t
        else:
            xpeak_ref = xpeak
        return pr, xpeak, xpeak_ref
    else:
        return None
Esempio n. 2
0
    def run_on_image(self, rssdata, tracemap, current_vph):
        """Extract spectra, find peaks and compute FWHM."""

        # Extract the polynomials
        # FIXME: a little hackish
        valid_traces = get_valid_traces(tracemap)
        pols = [t.polynomial for t in tracemap.contents]
        vph_t = vph_thr['default']
        this_val = vph_t.get(current_vph)
        if this_val:
            flux_limit = this_val.get('flux_limit', 200000)
        else:
            flux_limit = 40000

        nwinwidth = 5
        times_sigma = 50.0
        lwidth = 20
        fpeaks = {}
        # FIXME: We are using here only one in 10 fibers
        for fibid in valid_traces[::10]:
            # sampling every 10 fibers...
            idx = fibid - 1
            row = rssdata[idx, :]

            the_pol = pols[idx]

            # FIXME: using here a different peak routine than in arc
            # find peaks
            threshold = numpy.median(row) + times_sigma * sigmaG(row)

            ipeaks_int1 = find_peaks_indexes(row, nwinwidth, threshold)
            # filter by flux
            self.logger.info('Filtering peaks over %5.0f', flux_limit)
            ipeaks_vals = row[ipeaks_int1]
            mask = ipeaks_vals < flux_limit
            ipeaks_int = ipeaks_int1[mask]
            self.logger.debug('LEN (ipeaks_int): %s', len(ipeaks_int))
            self.logger.debug('ipeaks_int: %s', ipeaks_int)
            ipeaks_float = refine_peaks(row, ipeaks_int, nwinwidth)[0]

            # self.pintarGrafica(refine_peaks(row, ipeaks_int, nwinwidth)[0] - refinePeaks_spectrum(row, ipeaks_int, nwinwidth))

            fpeaks[idx] = []
            for peak, peak_f in zip(ipeaks_int, ipeaks_float):
                try:
                    sl = numina.array.utils.slice_create(peak, lwidth)
                    rel_peak = peak - sl.start
                    qslit = row[sl]
                    peak_val, fwhm = fmod.compute_fwhm_1d_simple(qslit, rel_peak)
                    peak_on_trace = the_pol(peak)
                    fpeaks[idx].append((peak_f, peak_on_trace, fwhm))
                except ValueError as error:
                    self.logger.warning('Error %s computing FWHM in fiber %d', error, idx + 1)
                except IndexError as error:
                    self.logger.warning('Error %s computing FWHM in fiber %d', error, idx + 1)
            self.logger.debug('found %d peaks in fiber %d', len(fpeaks[idx]), idx)
        return fpeaks
Esempio n. 3
0
    def run_on_image(self, img, tracemap, flux_limit=40000, valid_traces=None, times_sigma=50):
        """Extract spectra, find peaks and compute FWHM."""

        rssdata = img[0].data

        if valid_traces:
            valid_traces_s = set(valid_traces) # use set for fast membership
            valid_apers = [aper for aper in tracemap.contents if aper.valid and aper.fibid in valid_traces_s]
        else:
            valid_apers = [aper for aper in tracemap.contents if aper.valid]

        nwinwidth = 5
        lwidth = 20
        fpeaks = {}

        for aper in valid_apers:
            fibid = aper.fibid
            idx = fibid - 1
            row = rssdata[idx, :]

            the_pol = aper.polynomial

            # FIXME: using here a different peak routine than in arc
            # find peaks
            threshold = numpy.median(row) + times_sigma * sigmaG(row)
            self.logger.debug('values for threshold: median: %f, scale: %f, sigma: %f',
                              numpy.median(row), times_sigma, sigmaG(row))
            self.logger.debug('threshold is: %f', threshold)
            ipeaks_int1 = find_peaks_indexes(row, nwinwidth, threshold)
            # filter by flux
            self.logger.info('Filtering peaks over %5.0f', flux_limit)
            ipeaks_vals = row[ipeaks_int1]
            mask = ipeaks_vals < flux_limit
            ipeaks_int = ipeaks_int1[mask]
            self.logger.debug('LEN (ipeaks_int): %s', len(ipeaks_int))
            self.logger.debug('ipeaks_int: %s', ipeaks_int)
            ipeaks_float = refine_peaks(row, ipeaks_int, nwinwidth)[0]

            # self.pintarGrafica(refine_peaks(row, ipeaks_int, nwinwidth)[0] - refinePeaks_spectrum(row, ipeaks_int, nwinwidth))

            fpeaks[fibid] = []
            for peak, peak_f in zip(ipeaks_int, ipeaks_float):
                try:
                    sl = numina.array.utils.slice_create(peak, lwidth)
                    rel_peak = peak - sl.start
                    qslit = row[sl]
                    peak_val, fwhm = fmod.compute_fwhm_1d_simple(qslit, rel_peak)
                    peak_on_trace = the_pol(peak)
                    fpeaks[fibid].append((peak_f, peak_on_trace, fwhm))
                except ValueError as error:
                    self.logger.warning('Error %s computing FWHM in fiber %d', error, fibid)
                except IndexError as error:
                    self.logger.warning('Error %s computing FWHM in fiber %d', error, fibid)
            self.logger.debug('found %d peaks in fiber %d', len(fpeaks[fibid]), fibid)
        return fpeaks
Esempio n. 4
0
def refine_bar_centroid(arr_deriv, centerx, centery, wx, wy, threshold, sign):
    # Refine values
    logger = logging.getLogger('emir.recipes.bardetect')

    logger.debug('collapsing a %d x %d region', 2 * wx + 1, 2 * wy + 1)
    #
    slicey = slice_create(centery, wy, start=1, stop=2047)
    slicex = slice_create(centerx, wx, start=1, stop=2047)
    region = arr_deriv[slicey, slicex]

    if region.size == 0:
        logger.debug('region to collapse is empty')
        return 0, 0, 1

    collapsed = sign * region.mean(axis=0)

    # Fine tunning
    idxs_t = find_peaks_indexes(collapsed, window_width=3, threshold=threshold)
    # Use only the peak nearest the original peak
    if len(idxs_t) == 0:
        logger.debug('no peaks after fine-tunning')
        return 0, 0, 2

    dist_t = numpy.abs(idxs_t - wx)
    only_this = dist_t.argmin()
    idxs_p = numpy.atleast_1d(idxs_t[only_this])
    x_t, y_t = refine_peaks(collapsed, idxs_p, window_width=3)

    if len(x_t) == 0:
        logger.debug('no peaks to refine after fitting')
        return 0, 0, 2

    if x_t[0] >= collapsed.shape[0]:
        logger.debug('wrong position %d when refining', x_t[0])
        return 0, 0, 2

    _, fwhm_x = fmod.compute_fwhm_1d_simple(collapsed, x_t[0])

    xl = centerx - wx + x_t[0]
    return xl, fwhm_x, 0
Esempio n. 5
0
def refine_bar_centroid(arr_deriv, centerx, centery, wx, wy, threshold, sign):
    # Refine values
    logger = logging.getLogger('emir.recipes.bardetect')

    logger.debug('collapsing a %d x %d region', 2 * wx + 1 , 2 * wy + 1)
    #
    slicey = slice_create(centery, wy, start=1, stop=2047)
    slicex = slice_create(centerx, wx, start=1, stop=2047)
    region = arr_deriv[slicey, slicex]

    if region.size == 0:
        logger.debug('region to collapse is empty')
        return 0, 0, 1

    collapsed = sign * region.mean(axis=0)

    # Fine tunning
    idxs_t = find_peaks_indexes(collapsed, window_width=3, threshold=threshold)
    # Use only the peak nearest the original peak
    if len(idxs_t) == 0:
        logger.debug('no peaks after fine-tunning')
        return 0, 0, 2

    dist_t = numpy.abs(idxs_t - wx)
    only_this = dist_t.argmin()
    idxs_p = numpy.atleast_1d(idxs_t[only_this])
    x_t, y_t = refine_peaks(collapsed, idxs_p, window_width=3)

    if len(x_t) == 0:
        logger.debug('no peaks to refine after fitting')
        return 0, 0, 2

    if x_t[0] >= collapsed.shape[0]:
        logger.debug('wrong position %d when refining', x_t[0])
        return 0, 0, 2

    _, fwhm_x = fmod.compute_fwhm_1d_simple(collapsed, x_t[0])

    xl = centerx - wx + x_t[0]
    return xl, fwhm_x, 0
Esempio n. 6
0
def init_traces(image, center, hs, boxes, box_borders, tol=1.5, threshold=0.37, debug_plot=0):

    _logger = logging.getLogger(__name__)

    cut_region = slice(center-hs, center+hs)
    cut = image[:, cut_region]
    colcut = cut.mean(axis=1)
    # trace local background with a min filter
    mincol = minimum_filter(colcut, size=7)

    _logger.debug('initial pairing fibers in column %d', center)

    fiber_traces = []
    total_peaks = 0
    lastid = 0
    counted_fibers = 0
    boxes_with_missing_fibers = []

    for boxid, box in enumerate(boxes):
        nfibers = box['nfibers']
        mfibers = box.get('missing', [])
        nfibers_max = nfibers - len(mfibers)
        sfibers = box.get('skipcount', [])
        _logger.debug('pseudoslit box: %s, id: %d', box['name'], boxid)
        _logger.debug('nfibers: %d, missing: %s',nfibers, mfibers)

        counted_fibers += nfibers
        b1 = int(box_borders[boxid])
        b2 = int(box_borders[boxid + 1])
        _logger.debug('box borders: %s %s', b1, b2)
        borders = [b1, b2]

        region = colcut[borders[0]:borders[1]+1]
        # Region for background computation
        # Remove the space of 1.5 fibers
        bb1 = b1 + 9
        bb2 = b2 - 9
        # a conservative background
        lowt = numpy.min(mincol[bb1:bb2+1])
        _logger.debug('conservative background in box is %f', lowt)

        # Find exactly the number of peaks expected
        _logger.debug('find %d peaks (max)', nfibers_max)
        ipeaks_int = peak_local_max(region, min_distance=3,
                                    threshold_abs=lowt,
                                    threshold_rel=threshold,
                                    num_peaks=nfibers_max,
                                    )[:, 0]

        npeaks = len(ipeaks_int)
        total_peaks += npeaks

        if npeaks == 0:
            # skip everything, go to next box
            boxes_with_missing_fibers.append((box['name'], nfibers))
            _logger.debug('no peaks detected, go to next box')
            continue

        # We always want the result sorted. The order changes in different versions
        # of scikit-image
        ipeaks_int.sort()
        ipeaks_float = refine_peaks(region, ipeaks_int, 3)[0]
        peaks_dist = numpy.diff(ipeaks_float)
        measured_scale = numpy.median(peaks_dist)
        _logger.debug('median distance between peaks is %s', measured_scale)

        peaks_y = numpy.ones((ipeaks_int.shape[0], 3))
        peaks_y[:, 0] = ipeaks_int + b1
        peaks_y[:, 1] = ipeaks_float + b1
        peaks_y[:, 2] = region[ipeaks_int]

        if debug_plot:
            plt.plot(region)
            plt.plot(ipeaks_int, region[ipeaks_int], 'r*')
            plt.savefig('central_cut_{:02d}.png'.format(boxid))
            plt.close()

        startid = lastid + 1
        fiber_model = fibermatch.generate_box_model(nfibers,
                                                    start=startid,
                                                    missing_relids=mfibers,
                                                    skip_fibids=sfibers
                                                    )
        lastid = fiber_model[-1].fibid
        _logger.debug('fibids %s - %s', startid, lastid)

        matched_peaks = fibermatch.count_peaks(peaks_y[:, 1])
        nmatched = len(matched_peaks)
        missing = nfibers - nmatched

        if missing != 0:
            boxes_with_missing_fibers.append((box['name'], missing))

        _logger.debug('matched %s, missing: %s', nmatched, missing)
        pos_solutions = fibermatch.complete_solutions(fiber_model, matched_peaks,
                                                      borders, scale=measured_scale)

        for fibid, match in fibermatch.iter_best_solution(fiber_model,
                                               matched_peaks,
                                               pos_solutions):
            fti = FiberTraceInfo(fibid, boxid)
            if match is not None:
                fti.start = (center, peaks_y[match, 1], peaks_y[match, 2])
            fiber_traces.append(fti)

    _logger.debug('total found peaks: %d', total_peaks)
    _logger.debug('total found + recovered peaks: %d', counted_fibers)
    if boxes_with_missing_fibers:
        for m1, n2 in boxes_with_missing_fibers:
            _logger.debug('missing %d fibers in box %s', n2, m1)
    return fiber_traces
Esempio n. 7
0
def init_traces(image, center, hs, boxes, box_borders, tol=1.5, threshold=0.37):

    _logger = logging.getLogger(__name__)

    cut_region = slice(center-hs, center+hs)
    cut = image[:,cut_region]
    colcut = cut.mean(axis=1)

    counted_fibers = 0
    fiber_traces = []
    total_peaks = 0
    total_peaks_pos = []

    # ipeaks_int = peak_local_max(colcut, min_distance=2, threshold_rel=0.2)[:, 0]
    ipeaks_int = peak_local_max(colcut, min_distance=3, threshold_rel=threshold)[:, 0] # All VPH

    if False:
        import matplotlib.pyplot as plt
        plt.plot(colcut)
        plt.plot(ipeaks_int, colcut[ipeaks_int], 'r*')
        for border in box_borders:
            plt.axvline(border, color='k')
        plt.show()

    ipeaks_float = refine_peaks(colcut, ipeaks_int, 3)[0]
    peaks_y = numpy.ones((ipeaks_int.shape[0], 3))
    peaks_y[:, 0] = ipeaks_int
    peaks_y[:, 1] = ipeaks_float
    peaks_y[:, 2] = colcut[ipeaks_int]
    box_match = numpy.digitize(peaks_y[:, 0], box_borders)

    _logger.debug('initial pairing fibers in column %d', center)
    for boxid, box in enumerate(boxes):
        nfibers = box['nfibers']
        dist_b_fibs = (box_borders[boxid + 1] - box_borders[boxid]) / (nfibers + 2.0)
        mask_fibers = (box_match == (boxid + 1))
        # Peaks in this box
        thispeaks = peaks_y[mask_fibers]
        npeaks = len(thispeaks)
        total_peaks += npeaks
        for elem in thispeaks:
            total_peaks_pos.append(elem.tolist())

        _logger.debug('pseudoslit box: %s, id: %d', box['name'], boxid)
        # Start by matching the first peak
        # with the first fiber
        fid = 0
        current_peak = 0
        pairs_1 = [(fid, current_peak)]
        fid += 1

        scale = 1
        while (current_peak < npeaks - 1) and (fid < nfibers):
            # Expected distance to next fiber
            expected_distance = scale * dist_b_fibs
            # _logger.debug('expected %s current peak %s', expected_distance, current_peak)
            for idx in range(current_peak + 1, npeaks):
                distance = abs(thispeaks[idx, 1] - thispeaks[current_peak, 1])
                if abs(distance - expected_distance) <= tol:
                    # We have a match
                    # We could update
                    # dist_b_fibs = distance / scale
                    # But is not clear this is better

                    # Store this match
                    pairs_1.append((fid, idx))
                    current_peak = idx
                    # Next
                    scale = 1
                    break
            else:
                # This fiber has no match
                pairs_1.append((fid, None))
                # Try a fiber further away
                scale += 1
            # Match next fiber
            fid += 1

        _logger.debug('matched %s \t missing: %s', len(pairs_1),nfibers-len(pairs_1))
        remainig = nfibers - len(pairs_1)
        if remainig > 0:
            _logger.debug('we have to pair %d miising fibers', remainig)
            # Position of first match fiber

            # Position of last match fiber
            for fid, peakid in reversed(pairs_1):
                if peakid is not None:
                    last_matched_peak = peakid
                    last_matched_fiber = fid
                    break
            else:
                raise ValueError('None matched')
            _logger.debug('peaks: %s \t %s', thispeaks[0, 1], thispeaks[last_matched_peak, 1])
            _logger.debug('borders: %s \t %s', box_borders[boxid], box_borders[boxid+1])
            ldist = thispeaks[0, 1] - box_borders[boxid]
            rdist = box_borders[boxid + 1] - thispeaks[last_matched_peak, 1]
            lcap = ldist / dist_b_fibs - 1
            rcap = rdist / dist_b_fibs - 1
            _logger.debug('L distance %s \t %s', ldist, lcap)
            _logger.debug('R distance %s \t %s', rdist, rcap)
            lcapi = int(lcap + 0.5)
            rcapi = int(rcap + 0.5)

            on_r = rcapi <= lcapi
            mincap = min(lcapi, rcapi)
            maxcap = max(lcapi, rcapi)

            cap1 = min(mincap, remainig)
            cap2 = min(maxcap, remainig - cap1)
            cap3 = remainig - cap1 - cap2

            if cap3 > 0:
                _logger.debug('we dont have space %s fibers no allocated', cap3)

            if on_r:
                # Fill rcap fibers, then lcap
                capr = cap1
                capl = cap2
            else:
                capr = cap2
                capl = cap1

            addl = [(x, None) for x in range(-capl, 0)]
            addr = [(x, None) for x in range(last_matched_fiber + 1, last_matched_fiber + 1 + capr)]
            _logger.debug('add %s fibers on the right', capr)
            _logger.debug('add %s fibers on the left', capl)
            pairs_1 = addl + pairs_1 + addr

        for fibid, (relfibid, match) in enumerate(pairs_1, counted_fibers):
            fti = FiberTraceInfo(fibid + 1, boxid)
            if match is not None:
                fti.start = (center, thispeaks[match, 1], thispeaks[match, 2])
            fiber_traces.append(fti)
            # else:
            #     fiber_traces[fibid].start = (center, 0, 0)
        counted_fibers += nfibers

        # import matplotlib.pyplot as plt
        # plt.xlim([box_borders[boxid], box_borders[boxid + 1]])
        # plt.plot(colcut, 'b-')
        # plt.plot(thispeaks[:, 1], thispeaks[:, 2], 'ro')
        # plt.plot(peaks_y[:,1], peaks_y[:, 2], 'ro')
        # plt.title('Box %s' %box['id'])
        # plt.show()

    # import matplotlib.pyplot as plt
    # total_peaks_pos = np.array(total_peaks_pos)
    # plt.plot(colcut, 'b-')
    # plt.plot(total_peaks_pos[:, 1], total_peaks_pos[:, 2], 'ro')
    # plt.show()

    _logger.debug('total found peaks: %d', total_peaks)
    _logger.debug('total found + recovered peaks: %d', counted_fibers)

    return fiber_traces
Esempio n. 8
0
    def calibrate_wl(self, rss, lines_catalog, poldeg, tracemap, nlines,
                     threshold=0.27,
                     min_distance=30):

        wv_master = lines_catalog[:, 0]
        ntriplets_master, ratios_master_sorted, triplets_master_sorted_list = \
            gen_triplets_master(wv_master)

        nwinwidth = 5
        error_contador = 0
        missing_fib = 0

        data_wlcalib = WavelengthCalibration(instrument='MEGARA')
        data_wlcalib.total_fibers = tracemap.total_fibers
        for trace in tracemap.contents:
            fibid = trace.fibid
            idx = trace.fibid - 1

            if trace.valid:
                row = rss[idx]

                trend = detrend(row)
                fibdata_detrend = row - trend
                # A fix for LR-V Jun 2016 test images
                # that only have lines there

                row = fibdata_detrend

                self.logger.info('Starting row %d, fibid %d', idx, fibid)

                # find peaks (initial search providing integer numbers)
                ipeaks_int = peak_local_max(row, threshold_rel=threshold,
                                             min_distance=min_distance)[:, 0]

                self.logger.debug('ipeaks_int.........: %s', ipeaks_int)

                # Filter by flux, selecting a maximum number of brightest
                # lines in each region
                region_size = (len(row)-1)/(len(nlines))
                ipeaks_int_filtered = numpy.array([], dtype=int)
                for iregion, nlines_in_region in enumerate(nlines):
                    if nlines_in_region > 0:
                        imin = int(iregion * region_size)
                        imax = int((iregion + 1) * region_size)
                        if iregion > 0:
                            imin += 1
                        ipeaks_int_region = ipeaks_int[numpy.logical_and(
                            ipeaks_int >= imin, ipeaks_int <= imax
                        )]
                        if len(ipeaks_int_region) > 0:
                            peak_fluxes = row[ipeaks_int_region]
                            spos = peak_fluxes.argsort()
                            ipeaks_tmp = ipeaks_int_region[
                                spos[-nlines_in_region:]
                            ]
                            ipeaks_tmp.sort()  # in-place sort
                            self.logger.debug('ipeaks_in_region...: %s',
                                              ipeaks_tmp)
                            ipeaks_int_filtered=numpy.concatenate(
                                (ipeaks_int_filtered, ipeaks_tmp)
                            )

                self.logger.debug('ipeaks_int_filtered: %s', ipeaks_int_filtered)
                ipeaks_float = refine_peaks(row, ipeaks_int_filtered, nwinwidth)[0]

                # if idx==299:
                if False:
                    import matplotlib.pyplot as plt
                    plt.title('fibid %d' % fibid)
                    plt.plot(row)
                    plt.plot(ipeaks_int, row[ipeaks_int], 'ro', alpha=.9, ms=7,
                             label="ipeaks_int")
                    plt.plot(ipeaks_int_filtered, row[ipeaks_int_filtered], 'ro', alpha=.9, ms=7,
                             label="ipeaks_int_filtered")
                    plt.legend()
                    plt.show()

                # FIXME: xchannel ???
                # This comes from Nico's code, so probably pixels
                # will start in 1
                naxis1 = row.shape[0]
                crpix1 = 1.0
                xchannel = numpy.arange(1, naxis1 + 1)

                finterp_channel = interp1d(range(xchannel.size), xchannel,
                                           kind='linear',
                                           bounds_error=False,
                                           fill_value=0.0)
                xpeaks_refined = finterp_channel(ipeaks_float)

                wv_range_catalog = lines_catalog[-1][0] - lines_catalog[0][0]
                delta_wv = 0.05 * wv_range_catalog
                wv_ini_search = int(lines_catalog[0][0] - delta_wv)
                wv_end_search = int(lines_catalog[-1][0] + delta_wv)

                try:

                    self.logger.info('wv_ini_search %s', wv_ini_search)
                    self.logger.info('wv_end_search %s', wv_end_search)

                    list_of_wvfeatures = arccalibration_direct(
                        wv_master,
                        ntriplets_master,
                        ratios_master_sorted,
                        triplets_master_sorted_list,
                        xpeaks_refined,
                        naxis1,
                        crpix1=crpix1,
                        wv_ini_search=wv_ini_search,
                        wv_end_search=wv_end_search,
                        error_xpos_arc=2.3, # initially: 2.0
                        times_sigma_r=3.0,
                        frac_triplets_for_sum=0.50,
                        times_sigma_theil_sen=10.0,
                        poly_degree_wfit=poldeg,
                        times_sigma_polfilt=10.0,
                        times_sigma_cook=10.0,
                        times_sigma_inclusion=5.0
                    )

                    self.logger.info('Solution for row %d completed', idx)
                    self.logger.info('Fitting solution for row %d', idx)
                    solution_wv = fit_list_of_wvfeatures(
                            list_of_wvfeatures,
                            naxis1_arc=naxis1,
                            crpix1=crpix1,
                            poly_degree_wfit=poldeg,
                            weighted=False,
                            debugplot=0,
                            plot_title=None
                        )

                    self.logger.info('linear crval1, cdelt1: %f %f',
                                     solution_wv.cr_linear.crval,
                                     solution_wv.cr_linear.cdelt)

                    self.logger.info('fitted coefficients %s',
                                     solution_wv.coeff)

                    trace_pol = trace.polynomial
                    # Update feature with measurements of Y coord in original image
                    # Peak and FWHM in RSS
                    for feature in solution_wv.features:
                        # Compute Y
                        feature.ypos = trace_pol(feature.xpos)
                        # FIXME: check here FITS vs PYTHON coordinates, etc
                        peak_int = int(feature.xpos)
                        try:
                            peak, fwhm = self.calc_fwhm_of_line(row, peak_int, lwidth=20)
                        except Exception as error:
                            self.logger.error("%s", error)
                            self.logger.error('error in feature %s', feature)
                            # workaround
                            peak = row[peak_int]
                            fwhm = 0.0
                        # I would call this peak instead...
                        feature.peak = peak
                        feature.fwhm = fwhm

                    # if True:
                    #     plt.title('fibid %d' % fibid)
                    #     plt.plot(row)
                    #     plt.plot(ipeaks_int, row[ipeaks_int],'ro', alpha=.9, ms=7, label="ipeaks_int")
                    #     # # plt.plot(ipeaks_int2, row[ipeaks_int2],'gs', alpha=.5 , ms=10)
                    #     plt.legend()
                    #     plt.show()

                    new = FiberSolutionArcCalibration(fibid, solution_wv)
                    data_wlcalib.contents.append(new)

                except (ValueError, TypeError, IndexError) as error:
                    self.logger.error("%s", error)
                    self.logger.error('error in row %d, fibid %d', idx, fibid)
                    traceback.print_exc()
                    data_wlcalib.error_fitting.append(fibid)

                    if False:
                        import matplotlib.pyplot as plt
                        plt.title('fibid %d' % fibid)
                        rrow = row[::-1]
                        rpeaks = 4096-ipeaks_int_filtered[::-1]
                        plt.plot(rrow)
                        plt.plot(rpeaks, rrow[rpeaks], 'ro', alpha=.9, ms=7, label="ipeaks_int_filtered")
                        # # plt.plot(ipeaks_int2, row[ipeaks_int2],'gs', alpha=.5 , ms=10)
                        plt.legend()
                        plt.show()
                    error_contador += 1

            else:
                self.logger.info('skipping row %d, fibid %d, not extracted', idx, fibid)
                missing_fib += 1
                data_wlcalib.missing_fibers.append(fibid)

        self.logger.info('Errors in fitting: %s', error_contador)
        self.logger.info('Missing fibers: %s', missing_fib)

        self.logger.info('Generating fwhm_image...')
        image = self.generate_fwhm_image(data_wlcalib.contents)
        fwhm_image = fits.PrimaryHDU(image)
        fwhm_hdulist = fits.HDUList([fwhm_image])

        self.logger.info('End arc calibration')

        return data_wlcalib, fwhm_hdulist
Esempio n. 9
0
def char_bar_height(arr_deriv_alt,
                    xpos1,
                    xpos2,
                    centery,
                    threshold,
                    wh=35,
                    wfit=3):

    logger = logging.getLogger('emir.recipes.bardetect')
    pcentery = coor_to_pix_1d(centery)
    slicey = slice_create(pcentery, wh, start=1, stop=2047)

    ref_pcentery = pcentery - slicey.start
    mm = arr_deriv_alt[slicey, xpos1:xpos2 + 1].mean(axis=-1)

    idxs_t = find_peaks_indexes(mm, window_width=3, threshold=threshold)
    idxs_u = find_peaks_indexes(-mm, window_width=3, threshold=threshold)
    # Peaks on the right

    status = 0
    npeaks_u = len(idxs_u)
    if npeaks_u == 0:
        # This is a problem, no peak on the right
        b2 = 0
        status = 4
        logger.debug('no bottom border found')
    else:
        # Filter over reference
        g_idxs_u = idxs_u[idxs_u >= ref_pcentery]
        if len(g_idxs_u) == 0:
            logger.debug('no peak over center')
            b2 = 0
            status = 4
        else:
            x_u, y_u = refine_peaks(-mm, g_idxs_u, window_width=wfit)
            # Select the peak with max derivative
            if len(x_u) == 0 or len(y_u) == 0:
                logger.warning("no 1st peak found after refine")
                b2 = 0
                status = 4
            else:
                idmax = y_u.argmax()
                b2 = x_u[idmax]
                b2val = y_u[idmax]
                logger.debug('main border in %f', slicey.start + b2)

    # peaks on the left
    npeaks_t = len(idxs_t)
    if npeaks_t == 0:
        # This is a problem, no peak on the left
        b1 = 0
        logger.debug('no top border found')
        status = 40 + status
    else:
        g_idxs_t = idxs_t[idxs_t <= ref_pcentery]
        if len(g_idxs_t) == 0:
            logger.debug('no peak under center')
            b1 = 0
            status = 40 + status
        else:
            x_t, y_t = refine_peaks(mm, g_idxs_t, window_width=wfit)
            # Select the peak with max derivative
            if len(x_t) == 0 or len(y_t) == 0:
                logger.warning("no 2nd peak found after refine")
                b1 = 0
                status = 40 + status
            else:
                idmax = y_t.argmax()
                b1 = x_t[idmax]
                b1val = y_t[idmax]
                logger.debug('second border in %f', slicey.start + b1)

    return slicey.start + b1, slicey.start + b2, status
Esempio n. 10
0
def char_bar_height(arr_deriv_alt, xpos1, xpos2, centery, threshold, wh=35, wfit=3):

    logger = logging.getLogger('emir.recipes.bardetect')
    pcentery = coor_to_pix_1d(centery)
    slicey = slice_create(pcentery, wh, start=1, stop=2047)

    ref_pcentery = pcentery - slicey.start
    mm = arr_deriv_alt[slicey, xpos1:xpos2 + 1].mean(axis=-1)

    idxs_t = find_peaks_indexes(mm, window_width=3,threshold=threshold)
    idxs_u = find_peaks_indexes(-mm, window_width=3,threshold=threshold)
    # Peaks on the right

    status = 0
    npeaks_u = len(idxs_u)
    if npeaks_u == 0:
        # This is a problem, no peak on the right
        b2 = 0
        status = 4
        logger.debug('no bottom border found')
    else:
        # Filter over reference
        g_idxs_u = idxs_u[idxs_u >= ref_pcentery]
        if len(g_idxs_u) == 0:
            logger.debug('no peak over center')
            b2 = 0
            status = 4
        else:
            x_u, y_u = refine_peaks(-mm, g_idxs_u, window_width=wfit)
            # Select the peak with max derivative
            if len(x_u) == 0 or len(y_u) == 0:
                logger.warning("no 1st peak found after refine")
                b2 = 0
                status = 4
            else:
                idmax = y_u.argmax()
                b2 = x_u[idmax]
                b2val = y_u[idmax]
                logger.debug('main border in %f', slicey.start + b2)

    # peaks on the left
    npeaks_t = len(idxs_t)
    if npeaks_t == 0:
        # This is a problem, no peak on the left
        b1 = 0
        logger.debug('no top border found')
        status = 40 + status
    else:
        g_idxs_t = idxs_t[idxs_t <= ref_pcentery]
        if len(g_idxs_t) == 0:
            logger.debug('no peak under center')
            b1 = 0
            status = 40 + status
        else:
            x_t, y_t = refine_peaks(mm, g_idxs_t, window_width=wfit)
            # Select the peak with max derivative
            if len(x_t) == 0 or len(y_t) == 0:
                logger.warning("no 2nd peak found after refine")
                b1 = 0
                status = 40 + status
            else:
                idmax = y_t.argmax()
                b1 = x_t[idmax]
                b1val = y_t[idmax]
                logger.debug('second border in %f', slicey.start + b1)

    return slicey.start + b1, slicey.start + b2, status