Create a Constellation from a criteria search of the whole sky.

        Parameters
        ----------
        distancelimit : float
            Maximum distance (parsecs).
        magnitudelimit : float
            Maximum magnitude (for Gaia G).
346827
def from_sky(cls, distancelimit=15, magnitudelimit=18):
        '''
        

        '''

        # define a query for cone search surrounding this center
        criteria = []
        if distancelimit is not None:
            criteria.append('parallax >= {}'.format(1000.0/distancelimit))
        if magnitudelimit is not None:
            criteria.append('phot_g_mean_mag <= {}'.format(magnitudelimit))

        allskyquery = """{} WHERE {}""".format(cls.basequery, ' and '.join(criteria))
        print(allskyquery)

        # run the query
        print('querying Gaia DR2, for distance<{} and G<{}'.format(distancelimit, magnitudelimit))
        table = query(allskyquery)

        # store the search parameters in this object
        c = cls(cls.standardize_table(table))

        c.standardized.meta['query'] = allskyquery
        c.standardized.meta['magnitudelimit'] = magnitudelimit
        c.standardized.meta['distancelimit'] = distancelimit

        #c.distancelimit = distancelimit
        #c.magnitudelimit = magnitudelimit or c.magnitudelimit
        return c
829192
def _initialise_approximator(self, closest_point=None,
        wavelengths_required=None, rescale=True, **kwargs):
        

        if self._initialised and not kwargs.get("force", False):
            logger.debug("Ignoring call to re-initialise approximator because "
                "we already have.")
            return self._subset_bounds


        logger.info("Initialising approximator near {0}".format(closest_point))

        N = self.grid_points.size
        dtype = [(name, '<f8') for name in self.grid_points.dtype.names]
        grid_points = self.grid_points.astype(dtype).view(float).reshape(N, -1)

        # If closest_point is given then we will slice a small part of the grid.
        if closest_point is not None:

            default = 1.0
            grid_subset = self._configuration.get("settings", 
                { "grid_subset": default }).get("grid_subset", default)

            # Use nearest N points in interpolator.
            # If grid subset is a fraction, scale it to real numbers.
            if 1 >= grid_subset > 0:
                grid_subset = int(np.round(grid_subset * N))

            logger.debug("Using {0} nearest points for interpolator".format(
                grid_subset))

            # Use closest N points.
            distance = np.sum(np.abs(grid_points - closest_point)/
                np.ptp(grid_points, axis=0), axis=1)
            grid_indices = np.argsort(distance)[:grid_subset]

        else:
            grid_indices = np.ones(N, dtype=bool)

        # What wavelengths will be required? Assume all if not specified.
        if wavelengths_required is not None:
            mask = np.zeros(self.wavelengths.size, dtype=bool)
            for start, end in wavelengths_required:
                idx = np.clip(
                    self.wavelengths.searchsorted([start, end]) + [0, 1],
                    0, self.wavelengths.size)
                mask[idx[0]:idx[1]] = True
        else:
            mask = np.ones(self.wavelengths.size, dtype=bool)

        # Apply model masks.
        mask *= self._model_mask()

        # Slice small part of the intensities grid.
        intensities = np.memmap(
            self._configuration["model_grid"]["intensities"],
            dtype="float32", mode="r", shape=(N, self.wavelengths.size))
        subset = np.copy(intensities[grid_indices, :])
        subset[:, ~mask] = np.nan
        del intensities

        # Create an interpolator.
        try:
            interpolator = interpolate.LinearNDInterpolator(
                grid_points[grid_indices], subset, rescale=rescale)

        except TypeError:
            logger.warn("Could not rescale the LinearNDInterpolator because "\
                "you need a newer version of scipy")
            interpolator = interpolate.LinearNDInterpolator(
                grid_points[grid_indices], subset)

        generate.init()
        generate.wavelengths.append(self.wavelengths)
        generate.intensities.append(interpolator)
        
        self._initialised = True

        # Return the subset boundaries of the grid.
        self._subset_bounds = {}
        for name in self.grid_points.dtype.names:
            points = self.grid_points[name][grid_indices]
            self._subset_bounds[name] = (min(points), max(points))

        return self._subset_bounds
1073274
def _get_catalogue_bin_limits(catalogue, dmag):
    
    mag_bins = np.arange(
        float(np.floor(np.min(catalogue.data['magnitude']))) - dmag,
        float(np.ceil(np.max(catalogue.data['magnitude']))) + dmag,
        dmag)
    counter = np.histogram(catalogue.data['magnitude'], mag_bins)[0]
    idx = np.where(counter > 0)[0]
    mag_bins = mag_bins[idx[0]:(idx[-1] + 2)]
    return mag_bins
1173132
def search(self, coords=None, distance_modulus=None, tolerance=1.e-2):
        
        nmoduli = len(self.distance_modulus_array)
        npixels    = len(self.roi.pixels_target)
        self.log_likelihood_sparse_array       = np.zeros([nmoduli, npixels])
        self.richness_sparse_array             = np.zeros([nmoduli, npixels])
        self.richness_lower_sparse_array       = np.zeros([nmoduli, npixels])
        self.richness_upper_sparse_array       = np.zeros([nmoduli, npixels])
        self.richness_upper_limit_sparse_array = np.zeros([nmoduli, npixels])
        self.stellar_mass_sparse_array         = np.zeros([nmoduli, npixels])
        self.fraction_observable_sparse_array  = np.zeros([nmoduli, npixels])

        # Specific pixel/distance_modulus
        coord_idx, distance_modulus_idx = None, None
        if coords is not None:
            # Match to nearest grid coordinate index
            coord_idx = self.roi.indexTarget(coords[0],coords[1])
        if distance_modulus is not None:
            # Match to nearest distance modulus index
            distance_modulus_idx=np.fabs(self.distance_modulus_array-distance_modulus).argmin()

        lon, lat = self.roi.pixels_target.lon, self.roi.pixels_target.lat
            
        logger.info('Looping over distance moduli in grid search ...')
        for ii, distance_modulus in enumerate(self.distance_modulus_array):

            # Specific pixel
            if distance_modulus_idx is not None:
                if ii != distance_modulus_idx: continue

            logger.info('  (%-2i/%i) Distance Modulus=%.1f ...'%(ii+1,nmoduli,distance_modulus))

            # Set distance_modulus once to save time
            self.loglike.set_params(distance_modulus=distance_modulus)

            for jj in range(0, npixels):
                # Specific pixel
                if coord_idx is not None:
                    if jj != coord_idx: continue

                # Set kernel location
                self.loglike.set_params(lon=lon[jj],lat=lat[jj])
                # Doesn't re-sync distance_modulus each time
                self.loglike.sync_params()
                                         
                args = (jj+1, npixels, self.loglike.source.lon, self.loglike.source.lat)
                msg = '    (%-3i/%i) Candidate at (%.2f, %.2f) ... '%(args)

                self.log_likelihood_sparse_array[ii][jj], self.richness_sparse_array[ii][jj], parabola = self.loglike.fit_richness()
                self.stellar_mass_sparse_array[ii][jj] = self.stellar_mass_conversion * self.richness_sparse_array[ii][jj]
                self.fraction_observable_sparse_array[ii][jj] = self.loglike.f
                if self.config['scan']['full_pdf']:
                    #n_pdf_points = 100
                    #richness_range = parabola.profileUpperLimit(delta=25.) - self.richness_sparse_array[ii][jj]
                    #richness = np.linspace(max(0., self.richness_sparse_array[ii][jj] - richness_range),
                    #                          self.richness_sparse_array[ii][jj] + richness_range,
                    #                          n_pdf_points)
                    #if richness[0] > 0.:
                    #    richness = np.insert(richness, 0, 0.)
                    #    n_pdf_points += 1
                    # 
                    #log_likelihood = np.zeros(n_pdf_points)
                    #for kk in range(0, n_pdf_points):
                    #    log_likelihood[kk] = self.loglike.value(richness=richness[kk])
                    #parabola = ugali.utils.parabola.Parabola(richness, 2.*log_likelihood)
                    #self.richness_lower_sparse_array[ii][jj], self.richness_upper_sparse_array[ii][jj] = parabola.confidenceInterval(0.6827)
                    self.richness_lower_sparse_array[ii][jj], self.richness_upper_sparse_array[ii][jj] = self.loglike.richness_interval(0.6827)
                    
                    self.richness_upper_limit_sparse_array[ii][jj] = parabola.bayesianUpperLimit(0.95)

                    args = (
                        2. * self.log_likelihood_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_lower_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_upper_sparse_array[ii][jj],
                        self.stellar_mass_conversion*self.richness_upper_limit_sparse_array[ii][jj]
                    )
                    msg += 'TS=%.1f, Stellar Mass=%.1f (%.1f -- %.1f @ 0.68 CL, < %.1f @ 0.95 CL)'%(args)
                else:
                    args = (
                        2. * self.log_likelihood_sparse_array[ii][jj], 
                        self.stellar_mass_conversion * self.richness_sparse_array[ii][jj],
                        self.fraction_observable_sparse_array[ii][jj]
                    )
                    msg += 'TS=%.1f, Stellar Mass=%.1f, Fraction=%.2g'%(args)
                logger.debug(msg)
                
                #if coords is not None and distance_modulus is not None:
                #    results = [self.richness_sparse_array[ii][jj],
                #               self.log_likelihood_sparse_array[ii][jj],
                #               self.richness_lower_sparse_array[ii][jj],
                #               self.richness_upper_sparse_array[ii][jj],
                #               self.richness_upper_limit_sparse_array[ii][jj],
                #               richness, log_likelihood, self.loglike.p, self.loglike.f]
                #    return results

            jj_max = self.log_likelihood_sparse_array[ii].argmax()
            args = (
                jj_max+1, npixels, lon[jj_max], lat[jj_max],
                2. * self.log_likelihood_sparse_array[ii][jj_max], 
                self.stellar_mass_conversion * self.richness_sparse_array[ii][jj_max]
            )
            msg = '  (%-3i/%i) Maximum at (%.2f, %.2f) ... TS=%.1f, Stellar Mass=%.1f'%(args)
            logger.info(msg)
1368149
def detectionLimit(self):
        
        surveys_elem = self.et.find("surveys")
        if surveys_elem is None:
            return None

        try:
            detectionLimit = float(surveys_elem.attrib["detectionLimit"])
        except KeyError:
            detectionLimit = None
        return detectionLimit
387780
def make_from_catalogue(cls, catalogue, spacing, dilate):
        '''
        
        '''
        new = cls()
        cat_bbox = get_catalogue_bounding_polygon(catalogue)

        if dilate > 0:
            cat_bbox = cat_bbox.dilate(dilate)

        # Define Grid spacing
        new.update({'xmin': np.min(cat_bbox.lons),
                    'xmax': np.max(cat_bbox.lons),
                    'xspc': spacing,
                    'ymin': np.min(cat_bbox.lats),
                    'ymax': np.max(cat_bbox.lats),
                    'yspc': spacing,
                    'zmin': 0.,
                    'zmax': np.max(catalogue.data['depth']),
                    'zspc': np.max(catalogue.data['depth'])})

        if new['zmin'] == new['zmax'] == new['zspc'] == 0:
            new['zmax'] = new['zspc'] = 1

        return new
341571
def make_range(clusters, extend=0):
    
    eclusters = []
    for cluster in clusters:
        xlist, ylist, scores = zip(*cluster)
        score = _score(cluster)

        xchr, xmin = min(xlist)
        xchr, xmax = max(xlist)
        ychr, ymin = min(ylist)
        ychr, ymax = max(ylist)

        # allow fuzziness to the boundary
        xmax += extend
        ymax += extend
        # because extend can be negative values, we don't want it to be less than min
        if xmax < xmin:
            xmin, xmax = xmax, xmin
        if ymax < ymin:
            ymin, ymax = ymax, ymin

        eclusters.append(((xchr, xmin, xmax),
                          (ychr, ymin, ymax), score))

    return eclusters
623646
def is_valid_maximum_distance(self):
        
        if 'gsim_logic_tree' not in self.inputs:
            return True  # don't apply validation
        gsim_lt = self.inputs['gsim_logic_tree']
        trts = set(self.maximum_distance)
        unknown = ', '.join(trts - set(self._gsims_by_trt) - set(['default']))
        if unknown:
            self.error = ('setting the maximum_distance for %s which is '
                          'not in %s' % (unknown, gsim_lt))
            return False
        for trt, val in self.maximum_distance.items():
            if val <= 0:
                self.error = '%s=%r < 0' % (trt, val)
                return False
            elif trt not in self._gsims_by_trt and trt != 'default':
                self.error = 'tectonic region %r not in %s' % (trt, gsim_lt)
                return False
        if 'default' not in trts and trts < set(self._gsims_by_trt):
            missing = ', '.join(set(self._gsims_by_trt) - trts)
            self.error = 'missing distance for %s and no default' % missing
            return False
        return True
825137
def _validate(self):
        
        if self.region_type not in regions_attributes:
            raise ValueError("'{0}' is not a valid region type in this package"
                             .format(self.region_type))

        if self.coordsys not in valid_coordsys['DS9'] + valid_coordsys['CRTF']:
            raise ValueError("'{0}' is not a valid coordinate reference frame "
                             "in astropy".format(self.coordsys))
680237
def createCatalog(config,roi=None,lon=None,lat=None):
    
    import ugali.observation.catalog
    if roi is None: roi = createROI(config,lon,lat)
    catalog = ugali.observation.catalog.Catalog(config,roi=roi)
    return catalog
1308160
def randomSizeAndLocation(cls, radius, widthLimits,
                              heightLimits, origin=None):
        '''
        
        '''

        r = cls(widthLimits, heightLimits, origin)

        r.origin = Point.randomLocation(radius, origin)
762832
def set_maxrad(self,newrad):
        
        if not isinstance(newrad, Quantity):
            newrad = newrad * u.arcsec
        #if 'Rsky' not in self.constraints:
        #    self.constraints.append('Rsky')
        for pop in self.poplist:
            if not pop.is_specific:
                try:
                    pop.maxrad = newrad
                except AttributeError:
                    pass
548804
def local_maxima(vector,min_distance = 4, brd_mode = "wrap"):
    
    fits = gaussian_filter(numpy.asarray(vector,dtype=numpy.float32),1., mode=brd_mode)
    for ii in range(len(fits)):
        if fits[ii] == fits[ii-1]:
            fits[ii-1] = 0.0
    maxfits     = maximum_filter(fits, size=min_distance, mode=brd_mode)
    maxima_mask = fits == maxfits
    maximum     = numpy.transpose(maxima_mask.nonzero())
    return numpy.asarray(maximum)
72181
def waverange(self):
        """"""
        if self.waveset is None:
            x = [None, None]
        else:
            x = u.Quantity([self.waveset.min(), self.waveset.max()])
        return x
484765
def nu_max(self, *args):
        
        return 3120.* (self.mass(*args) /
                        (self.radius(*args)**2 * np.sqrt(self.Teff(*args)/5777.)))
699782
private function buildLimit() {
        $this->getCriteria()->limit($this->getIndexCriteria()->getLimit(), $this->getIndexCriteria()->getOffset());
    }
324869
def within_radians(self, key, point, max_distance, min_distance=None):
        
        self.near(key, point)
        self._add_condition(key, '$maxDistance', max_distance)
        if min_distance is not None:
            self._add_condition(key, '$minDistance', min_distance)
        return self