Loop through pixels containing catalog objects and calculate
        the magnitude limit. This gets a bit convoluted due to all
        the different pixel resolutions...
762833
def run(self,field=None,simple=False,force=False):
        
        if field is None: fields = [1,2]
        else:             fields = [field]
        for filenames in self.filenames.compress(~self.filenames.mask['catalog']).data:
            infile = filenames['catalog']
            for f in fields:
                outfile = filenames['mask_%i'%f]
                if os.path.exists(outfile) and not force:
                    logger.info("Found %s; skipping..."%outfile)
                    continue
                
                pixels,maglims=self.calculate(infile,f,simple)
                logger.info("Creating %s"%outfile)
                outdir = mkdir(os.path.dirname(outfile))
                data = odict()
                data['PIXEL']=pixels
                data['MAGLIM']=maglims.astype('f4')
                ugali.utils.healpix.write_partial_map(outfile,data,
                                                      self.nside_pixel)
734802
def full_pixels(space, data, gap_pixels=1):
    
    available = space - (len(data) - 1) * gap_pixels # 8 recs 7 gaps

    res = []
    for i, val in enumerate(data):
        # convert data to 0..1 scale so we deal with fractions
        data_sum = sum(data[i:])
        norm = val * 1.0 / data_sum


        w = max(int(round(available * norm)), 1)
        res.append(w)
        available -= w
    return res
1033668
def inFootprint(self, pixels, nside=None):
        
        if np.isscalar(pixels): pixels = np.array([pixels])
        if nside is None: nside = self.nside_likelihood

        inside = np.zeros( len(pixels), dtype='bool')
        if not self.nside_catalog:
            catalog_pix = [0]
        else:
            catalog_pix = superpixel(pixels,nside,self.nside_catalog)
            catalog_pix = np.intersect1d(catalog_pix,self.catalog_pixels)

        for filenames in self.filenames[catalog_pix]:
            # ADW: Need to replace with healpix functions...
            #logger.debug("Loading %s"%filenames['mask_1'])
            #subpix_1,val_1 = ugali.utils.skymap.readSparseHealpixMap(filenames['mask_1'],'MAGLIM',construct_map=False)
            _n,subpix_1,val_1 = read_partial_map(filenames['mask_1'],'MAGLIM',fullsky=False)
            #logger.debug("Loading %s"%filenames['mask_2'])
            #subpix_2,val_2 = ugali.utils.skymap.readSparseHealpixMap(filenames['mask_2'],'MAGLIM',construct_map=False)
            _n,subpix_2,val_2 = read_partial_map(filenames['mask_2'],'MAGLIM',fullsky=False)
            subpix = np.intersect1d(subpix_1,subpix_2)
            superpix = np.unique(superpixel(subpix,self.nside_pixel,nside))
            inside |= np.in1d(pixels, superpix)
            
        return inside
1040264
public static void magnitude( InterleavedF32 transform , GrayF32 magnitude ) {
		checkImageArguments(magnitude,transform);

		for( int y = 0; y < transform.height; y++ ) {

			int indexTran = transform.startIndex + y*transform.stride;
			int indexMag = magnitude.startIndex + y*magnitude.stride;

			for( int x = 0; x < transform.width; x++, indexTran += 2 ) {

				float real = transform.data[indexTran];
				float img = transform.data[indexTran+1];

				magnitude.data[indexMag++] = (float)Math.sqrt(real * real + img * img);
			}
		}
	}
588321
def pixels(self, zoom=None):
        """"""
        meter_x, meter_y = self.meters
        pixel_x = (meter_x + ORIGIN_SHIFT) / resolution(zoom=zoom)
        pixel_y = (meter_y - ORIGIN_SHIFT) / resolution(zoom=zoom)
        return abs(round(pixel_x)), abs(round(pixel_y))
667336
def _rgbtomask(self, obj):
        """"""
        dat = obj.get_image().get_data()  # RGB arrays
        return dat.sum(axis=2).astype(np.bool)
762035
def get_scene_splits(nlines_swath, nlines_scan, n_cpus):
    """"""

    nscans = nlines_swath // nlines_scan
    if nscans < n_cpus:
        nscans_subscene = 1
    else:
        nscans_subscene = nscans // n_cpus
    nlines_subscene = nscans_subscene * nlines_scan

    return range(nlines_subscene, nlines_swath, nlines_subscene)
21149
def dim(self):
        
        if len(self._orb.vxvv) == 2:
            return 1
        elif len(self._orb.vxvv) == 3 or len(self._orb.vxvv) == 4:
            return 2
        elif len(self._orb.vxvv) == 5 or len(self._orb.vxvv) == 6:
            return 3
777412
def results(self, limit=100):
        
        limited = True if self.high_mark is not None else False
        rmax = self.high_mark - self.low_mark if limited else None
        rnum = 0

        params = self.get_params()
        params["offset"] = self.low_mark
        params["limit"] = limit

        while not limited and rmax is None or rnum < rmax:
            if limited or rmax is not None:
                rleft = rmax - rnum
                params["limit"] = rleft if rleft < limit else limit

            r = self.resource._meta.api.http_resource("GET", self.resource._meta.resource_name, params=params)
            data = self.resource._meta.api.resource_deserialize(r.text)

            if not limited:
                rmax = data["meta"]["total_count"]

            if data["meta"]["total_count"] < rmax:
                rmax = data["meta"]["total_count"]

            params["offset"] = data["meta"]["offset"] + data["meta"]["limit"]

            for item in data["objects"]:
                rnum += 1
                yield item
710491
def _best_res_pixels(self):
        
        factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order)
        pix_l = []
        for iv in self._interval_set._intervals:
            for val in range(iv[0] >> factor, iv[1] >> factor):
                pix_l.append(val)

        return np.asarray(pix_l)
1043052
def for_pixels(cls, pixel_x, pixel_y, zoom):
        """"""
        tms_x = int(math.ceil(pixel_x / float(TILE_SIZE)) - 1)
        tms_y = int(math.ceil(pixel_y / float(TILE_SIZE)) - 1)
        return cls(tms_x=tms_x, tms_y=(2 ** zoom - 1) - tms_y, zoom=zoom)
906126
def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3):
        """"""
        if roi.shape[1] <= 700:
            scale_by = int(1050.0 / roi.shape[1] + 0.5)
            roi_lg = transform.rescale(roi, scale_by, order=filter_order, mode='constant', multichannel=False,
                                       anti_aliasing=True)
            new_text = ocr(roi_lg, extra_cmdline_params=self.extra_cmdline_params)
            new_mrz = MRZ.from_ocr(new_text)
            new_mrz.aux['method'] = 'rescaled(%d)' % filter_order
            if new_mrz.valid_score > cur_mrz.valid_score:
                cur_mrz = new_mrz
                cur_text = new_text
        return cur_text, cur_mrz
1229335
def segment_messages_from_magnitudes(magnitudes: np.ndarray, noise_threshold: float):
    
    return c_auto_interpretation.segment_messages_from_magnitudes(magnitudes, noise_threshold)
64497
def get_max_dim(self, obj):
        """"""

        try:
            iter(obj)

        except TypeError:
            return 0

        try:
            for o in obj:
                iter(o)
                break

        except TypeError:
            return 1

        return 2
415724
def _as_rescale(self, get, targetbitdepth):
        """"""

        width,height,pixels,meta = get()
        maxval = 2**meta['bitdepth'] - 1
        targetmaxval = 2**targetbitdepth - 1
        factor = float(targetmaxval) / float(maxval)
        meta['bitdepth'] = targetbitdepth
        def iterscale():
            for row in pixels:
                yield map(lambda x: int(round(x*factor)), row)
        if maxval == targetmaxval:
            return width, height, pixels, meta
        else:
            return width, height, iterscale(), meta
269980
def get_completeness_adjusted_table(catalogue, completeness, dmag,
                                    offset=1.0E-5, end_year=None, plot=False,
                                    figure_size=(8, 6), filename=None,
                                    filetype='png', dpi=300, ax=None):
    
    if not end_year:
        end_year = catalogue.end_year
    # Find the natural bin limits
    mag_bins = _get_catalogue_bin_limits(catalogue, dmag)
    obs_time = end_year - completeness[:, 0] + 1.
    obs_rates = np.zeros_like(mag_bins)
    durations = np.zeros_like(mag_bins)
    n_comp = np.shape(completeness)[0]
    for iloc in range(n_comp):
        low_mag = completeness[iloc, 1]
        comp_year = completeness[iloc, 0]
        if iloc == (n_comp - 1):
            idx = np.logical_and(
                catalogue.data['magnitude'] >= low_mag - offset,
                catalogue.data['year'] >= comp_year)
            high_mag = mag_bins[-1]
            obs_idx = mag_bins >= (low_mag - offset)
        else:
            high_mag = completeness[iloc + 1, 1]
            mag_idx = np.logical_and(
                catalogue.data['magnitude'] >= low_mag - offset,
                catalogue.data['magnitude'] < (high_mag - offset))

            idx = np.logical_and(mag_idx,
                                 catalogue.data['year'] >= (comp_year - offset))
            obs_idx = np.logical_and(mag_bins >= (low_mag - offset),
                                     mag_bins < (high_mag + offset))
        temp_rates = np.histogram(catalogue.data['magnitude'][idx],
                                  mag_bins[obs_idx])[0]
        temp_rates = temp_rates.astype(float) / obs_time[iloc]
        obs_rates[obs_idx[:-1]] = temp_rates
        durations[obs_idx[:-1]] = obs_time[iloc]
    selector = np.where(obs_rates > 0.)[0]
    mag_bins = mag_bins[selector]
    obs_rates = obs_rates[selector]
    durations = durations[selector]
    # Get cumulative rates
    cum_rates = np.array([sum(obs_rates[iloc:])
                          for iloc in range(0, len(obs_rates))])
    if plot:
        plt.figure(figsize=figure_size)
        plt.semilogy(mag_bins + dmag / 2., obs_rates, "bo",
                     label="Incremental")
        plt.semilogy(mag_bins + dmag / 2., cum_rates, "rs",
                     label="Cumulative")
        plt.xlabel("Magnitude (M)", fontsize=16)
        plt.ylabel("Annual Rate", fontsize=16)
        plt.grid(True)
        plt.legend(fontsize=16)
        if filename:
            plt.savefig(filename, format=filetype, dpi=dpi,
                        bbox_inches="tight")
    return np.column_stack([mag_bins, durations, obs_rates, cum_rates,
                            np.log10(cum_rates)])
1098053
def sky_fraction(self):
        
        pix_id = self._best_res_pixels()
        nb_pix_filled = pix_id.size
        return nb_pix_filled / float(3 << (2*(self.max_order + 1)))