INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Compute the mean fracdet within circular aperture (radius specified in decimal degrees) lon, lat, and radius are taken to be arrays of the same length
def meanFracdet(map_fracdet, lon_population, lat_population, radius_population): """ Compute the mean fracdet within circular aperture (radius specified in decimal degrees) lon, lat, and radius are taken to be arrays of the same length """ nside_fracdet = hp.npix2nside(len(map_fracdet)) map_fra...
Self-consistently train the classifier
def trainClassifier(self): """ Self-consistently train the classifier """ self.loadPopulationMetadata() self.loadSimResults() cut_geometry, flags_geometry = self.applyGeometry(self.data_population['RA'], self.data_population['DEC']) cut_...
Make some diagnostic plots
def validateClassifier(self, cut_detect, cut_train, cut_geometry, y_pred): """ Make some diagnostic plots """ color = {'detect': 'Red', 'nondetect': 'Gold', 'why_not': 'none', 'actual': 'DodgerBlue', 'hsc': 'lime'} ...
We want to enforce minimum fracdet for a satellite to be considered detectable True is passes fracdet cut
def applyFracdet(self, lon, lat): """ We want to enforce minimum fracdet for a satellite to be considered detectable True is passes fracdet cut """ self.loadFracdet() fracdet_core = meanFracdet(self.m_fracdet, lon, lat, np.tile(0.1, len(lon))) fracdet_wide = mean...
Exclude objects that are too close to hotspot True if passes hotspot cut
def applyHotspot(self, lon, lat): """ Exclude objects that are too close to hotspot True if passes hotspot cut """ self.loadRealResults() cut_detect_real = (self.data_real['SIG'] >= self.config[self.algorithm]['sig_threshold']) lon_real = self.data_real['RA'][cut...
distance, abs_mag, r_physical
def predict(self, lon, lat, **kwargs): """ distance, abs_mag, r_physical """ assert self.classifier is not None, 'ERROR' pred = np.zeros(len(lon)) cut_geometry, flags_geometry = self.applyGeometry(lon, lat) x_test = [] for key, operation ...
Factory for various catalogs.
def catalogFactory(name, **kwargs): """ Factory for various catalogs. """ fn = lambda member: inspect.isclass(member) and member.__module__==__name__ catalogs = odict(inspect.getmembers(sys.modules[__name__], fn)) if name not in list(catalogs.keys()): msg = "%s not found in catalogs:\n ...
Compute the average surface brightness [mag arcsec^-2] within the half-light radius abs_mag = absolute magnitude [mag] r_physical = half-light radius [kpc] distance = [kpc] The factor 2 in the c_v equation below account for half the luminosity within the half-light radius. The 3600.**2 is conver...
def surfaceBrightness(abs_mag, r_physical, distance): """ Compute the average surface brightness [mag arcsec^-2] within the half-light radius abs_mag = absolute magnitude [mag] r_physical = half-light radius [kpc] distance = [kpc] The factor 2 in the c_v equation below account for half the lu...
Create an MCMC instance
def createResults(config,srcfile,section='source',samples=None): """ Create an MCMC instance """ source = ugali.analysis.source.Source() source.load(srcfile,section=section) loglike = ugali.analysis.loglike.createLoglike(config,source) results = Results(config,loglike,samples) if samples is no...
Package everything nicely
def write_results(filename,config,srcfile,samples): """ Package everything nicely """ results = createResults(config,srcfile,samples=samples) results.write(filename)
Estimate parameter value and uncertainties
def estimate(self,param,burn=None,clip=10.0,alpha=0.32): """ Estimate parameter value and uncertainties """ # FIXME: Need to add age and metallicity to composite isochrone params (currently properties) if param not in list(self.samples.names) + list(self.source.params) + ['age','metallicity']: ...
Estimate all source parameters
def estimate_params(self,burn=None,clip=10.0,alpha=0.32): """ Estimate all source parameters """ mle = self.get_mle() out = odict() for param in mle.keys(): out[param] = self.estimate(param,burn=burn,clip=clip,alpha=alpha) return out
Estimate the position angle from the posterior dealing with periodicity.
def estimate_position_angle(self,param='position_angle',burn=None,clip=10.0,alpha=0.32): """ Estimate the position angle from the posterior dealing with periodicity. """ # Transform so peak in the middle of the distribution pa = self.samples.get(param,burn=burn,clip=clip) ...
Get the start and end formatted for query or the last hour if none specified. Unlike reports, this does not aggregate periods and so it is possible to just query a range and parse out the individual hours.
def date_range_for_webtrends(cls, start_at=None, end_at=None): """ Get the start and end formatted for query or the last hour if none specified. Unlike reports, this does not aggregate periods and so it is possible to just query a range and parse out the individual hours....
Get the path to the ugali data directory from the environment
def get_ugali_dir(): """Get the path to the ugali data directory from the environment""" dirname = os.getenv('UGALIDIR') # Get the HOME directory if not dirname: dirname=os.path.join(os.getenv('HOME'),'.ugali') if not os.path.exists(dirname): from ugali.utils.logger import logger ...
Get the ugali isochrone directory.
def get_iso_dir(): """Get the ugali isochrone directory.""" dirname = os.path.join(get_ugali_dir(),'isochrones') if not os.path.exists(dirname): from ugali.utils.logger import logger msg = "Isochrone directory not found:\n%s"%dirname logger.warning(msg) return dirname
Registers a parser to parse configuration inputs.
def registerParser(self, parser): """ Registers a parser to parse configuration inputs. """ if not isinstance(parser, Subparser): raise TypeError("%s is not an instance of a subparser." % parser) self.parsers.append(parser)
Adds the given configuration option to the ConfigManager. Inputs: name - The configuration name to accept. required - A boolean indicating whether or not the configuration option is required or not. cast - A type (or function accepting 1 argument and returning a...
def addConfig(self, name, default=None, cast=None, required=False, description=None): """ Adds the given configuration option to the ConfigManager. Inputs: name - The configuration name to accept. required - A boolean indicating whether or not the configuration option ...
Executes the registered parsers to parse input configurations.
def parse(self): """ Executes the registered parsers to parse input configurations. """ self._config = _Config() self._setDefaults() for parser in self.parsers: for key, value in parser.parse(self, self._config).items(): key = self._sanitize...
Sets all the expected configuration options on the config object as either the requested default value, or None.
def _setDefaults(self): """ Sets all the expected configuration options on the config object as either the requested default value, or None. """ for configName, configDict in self.configs.items(): self._setConfig(configName, configDict['default'])
Ensures that all configuration options marked as being required have been passed (ie are non-None). Raises a MissingConfigurationException if a required configuration option was not passed.
def _ensureRequired(self): """ Ensures that all configuration options marked as being required have been passed (ie are non-None). Raises a MissingConfigurationException if a required configuration option was not passed. """ for configName, configDict in self.configs.items(): ...
Iterates through our parsed configuration options and cast any options with marked cast types.
def _cast(self): """ Iterates through our parsed configuration options and cast any options with marked cast types. """ for configName, configDict in self.configs.items(): if configDict['cast'] is not None: configValue = getattr(self._config, configName) ...
Get the logged in user's models from the JIMM controller. @param macaroons The discharged JIMM macaroons. @return The json decoded list of environments.
def list_models(self, macaroons): """ Get the logged in user's models from the JIMM controller. @param macaroons The discharged JIMM macaroons. @return The json decoded list of environments. """ return make_request("{}model".format(self.url), timeout=self.timeout, ...
Composes chapters and writes the novel to a text file
def write(self, novel_title='novel', filetype='txt'): """ Composes chapters and writes the novel to a text file """ self._compose_chapters() self._write_to_file(novel_title, filetype)
Creates a chapters and appends them to list
def _compose_chapters(self): """ Creates a chapters and appends them to list """ for count in range(self.chapter_count): chapter_num = count + 1 c = Chapter(self.markov, chapter_num) self.chapters.append(c)
Determines whether the specified address string is valid.
def valid_address(address): """ Determines whether the specified address string is valid. """ if not address: return False components = str(address).split(':') if len(components) > 2 or not valid_hostname(components[0]): return False if len(components) == 2 and not valid_po...
Returns whether the specified string is a valid hostname.
def valid_hostname(host): """ Returns whether the specified string is a valid hostname. """ if len(host) > 255: return False if host[-1:] == '.': host = host[:-1] return all(_hostname_re.match(c) for c in host.split('.'))
Numerical Riemannn integral of the IMF (stupid simple). Parameters: ----------- mass_min: minimum mass bound for integration (solar masses) mass_max: maximum mass bound for integration (solar masses) log_mode[True]: use logarithmic steps in stellar mass as oppose to linear ...
def integrate(self, mass_min, mass_max, log_mode=True, weight=False, steps=1e4): """ Numerical Riemannn integral of the IMF (stupid simple). Parameters: ----------- mass_min: minimum mass bound for integration (solar masses) mass_max: maximum mass bound for integration (solar ma...
Sample initial mass values between mass_min and mass_max, following the IMF distribution. ADW: Should this be `sample` or `simulate`? Parameters: ----------- n : number of samples to draw mass_min : minimum mass to sample from mass_max : maximum mass to sample f...
def sample(self, n, mass_min=0.1, mass_max=10., steps=10000, seed=None): """ Sample initial mass values between mass_min and mass_max, following the IMF distribution. ADW: Should this be `sample` or `simulate`? Parameters: ----------- n : number of samples to dr...
PDF for the Chabrier IMF. The functional form and coefficients are described in Eq 17 and Tab 1 of Chabrier (2003): m <= 1 Msun: E(log m) = A1*exp(-(log m - log m_c)^2 / 2 sigma^2) m > 1 Msun: E(log m) = A2 * m^-x A1 = 1.58 : normalization [ log(Msun)^...
def pdf(cls, mass, log_mode=True): """ PDF for the Chabrier IMF. The functional form and coefficients are described in Eq 17 and Tab 1 of Chabrier (2003): m <= 1 Msun: E(log m) = A1*exp(-(log m - log m_c)^2 / 2 sigma^2) m > 1 Msun: E(log m) = A2 * m^-x ...
PDF for the Kroupa IMF. Normalization is set over the mass range from 0.1 Msun to 100 Msun
def pdf(cls, mass, log_mode=True): """ PDF for the Kroupa IMF. Normalization is set over the mass range from 0.1 Msun to 100 Msun """ log_mass = np.log10(mass) # From Eq 2 mb = mbreak = [0.08, 0.5] # Msun a = alpha = [0.3, 1.3, 2.3] # alpha # Normalizat...
PDF for the Salpeter IMF. Value of 'a' is set to normalize the IMF to 1 between 0.1 and 100 Msun
def pdf(cls, mass, log_mode=True): """ PDF for the Salpeter IMF. Value of 'a' is set to normalize the IMF to 1 between 0.1 and 100 Msun """ alpha = 2.35 a = 0.060285569480482866 dn_dm = a * mass**(-alpha) if log_mode: # Number per logarithmic mass ...
Retrieves a file descriptor to a configuration file to process. Inputs: config - The _Config object which is being populated. Outputs: An open file descriptor to the configuration file to parse in read mode if successful, else None.
def _getConfigFile(self, config): """ Retrieves a file descriptor to a configuration file to process. Inputs: config - The _Config object which is being populated. Outputs: An open file descriptor to the configuration file to parse in read mode if successful, else None. """ ...
Counts the citations in an aux-file. @return: defaultdict(int) - {citation_name: number, ...}
def _count_citations(aux_file): ''' Counts the citations in an aux-file. @return: defaultdict(int) - {citation_name: number, ...} ''' counter = defaultdict(int) with open(aux_file) as fobj: content = fobj.read() for match in CITE_PATTERN.finditer(content): name = match.grou...
Set up "optparse" and pass the options to a new instance of L{LatexMaker}.
def main(): ''' Set up "optparse" and pass the options to a new instance of L{LatexMaker}. ''' prog = 'latexmk.py' version = __version__ usage = '%prog [options] [filename]' # Read description from doc doc_text = '' for line in __doc__.splitlines(): if line.find('#') == ...
Set up a logger.
def _setup_logger(self): '''Set up a logger.''' log = logging.getLogger('latexmk.py') handler = logging.StreamHandler() log.addHandler(handler) if self.opt.verbose: log.setLevel(logging.INFO) return log
Read the project name from the texlipse config file ".texlipse".
def _parse_texlipse_config(self): ''' Read the project name from the texlipse config file ".texlipse". ''' # If Eclipse's workspace refresh, the # ".texlipse"-File will be newly created, # so try again after short sleep if # the file is still missing. ...
Check if some latex output files exist before first latex run, process them and return the generated data. - Parsing *.aux for citations counter and existing glossaries. - Getting content of files to detect changes. - *.toc file - al...
def _read_latex_files(self): ''' Check if some latex output files exist before first latex run, process them and return the generated data. - Parsing *.aux for citations counter and existing glossaries. - Getting content of files to detect changes. ...
Test if the *.toc file has changed during the first latex run.
def _is_toc_changed(self, toc_file): ''' Test if the *.toc file has changed during the first latex run. ''' fname = '%s.toc' % self.project_name if os.path.isfile(fname): with open(fname) as fobj: if fobj.read() != toc_file: ...
Determine if you need to run "bibtex". 1. Check if *.bib exists. 2. Check latex output for hints. 3. Test if the numbers of citations changed during first latex run. 4. Examine *.bib for changes.
def _need_bib_run(self, old_cite_counter): ''' Determine if you need to run "bibtex". 1. Check if *.bib exists. 2. Check latex output for hints. 3. Test if the numbers of citations changed during first latex run. 4. Examine *.bib for changes. ''' ...
Read all existing glossaries in the main aux-file.
def read_glossaries(self): ''' Read all existing glossaries in the main aux-file. ''' filename = '%s.aux' % self.project_name with open(filename) as fobj: main_aux = fobj.read() pattern = r'\\@newglossary\{(.*)\}\{.*\}\{(.*)\}\{(.*)\}' for match in re...
Check if errors occured during a latex run by scanning the output.
def check_errors(self): ''' Check if errors occured during a latex run by scanning the output. ''' errors = ERROR_PATTTERN.findall(self.out) # "errors" is a list of tuples if errors: self.log.error('! Errors occurred:') self.log.error('\n'...
Generate dictionary with the number of citations in all included files. If this changes after the first latex run, you have to run "bibtex".
def generate_citation_counter(self): ''' Generate dictionary with the number of citations in all included files. If this changes after the first latex run, you have to run "bibtex". ''' cite_counter = dict() filename = '%s.aux' % self.project_name with ope...
Start latex run.
def latex_run(self): ''' Start latex run. ''' self.log.info('Running %s...' % self.latex_cmd) cmd = [self.latex_cmd] cmd.extend(LATEX_FLAGS) cmd.append('%s.tex' % self.project_name) try: with open(os.devnull, 'w') as null: Popen...
Start bibtex run.
def bibtex_run(self): ''' Start bibtex run. ''' self.log.info('Running bibtex...') try: with open(os.devnull, 'w') as null: Popen(['bibtex', self.project_name], stdout=null).wait() except OSError: self.log.error(NO_LATEX_ERROR % 'bi...
Check for each glossary if it has to be regenerated with "makeindex". @return: True if "makeindex" was called.
def makeindex_runs(self, gloss_files): ''' Check for each glossary if it has to be regenerated with "makeindex". @return: True if "makeindex" was called. ''' gloss_changed = False for gloss in self.glossaries: make_gloss = False ext_i, ext...
Try to open a preview of the generated document. Currently only supported on Windows.
def open_preview(self): ''' Try to open a preview of the generated document. Currently only supported on Windows. ''' self.log.info('Opening preview...') if self.opt.pdf: ext = 'pdf' else: ext = 'dvi' filename = '%s.%s' % (self.proj...
Test for all rerun patterns if they match the output.
def need_latex_rerun(self): ''' Test for all rerun patterns if they match the output. ''' for pattern in LATEX_RERUN_PATTERNS: if pattern.search(self.out): return True return False
Run the LaTeX compilation.
def run(self): '''Run the LaTeX compilation.''' # store files self.old_dir = [] if self.opt.clean: self.old_dir = os.listdir('.') cite_counter, toc_file, gloss_files = self._read_latex_files() self.latex_run() self.read_glossaries() gloss_ch...
Generate the command for running the likelihood scan.
def command(self, outfile, configfile, pix): """ Generate the command for running the likelihood scan. """ params = dict(script=self.config['scan']['script'], config=configfile, outfile=outfile, nside=self.nside_likelihood, pix=pix, ...
UNTESTED. Should return a boolean array representing the pixels in the footprint.
def footprint(self, nside=None): """ UNTESTED. Should return a boolean array representing the pixels in the footprint. """ if nside is None: nside = self.nside_pixel elif nside < self.nside_catalog: raise Exception('Requested nside=%i is less than...
Open each valid filename for the set of pixels and determine the set of subpixels with valid data.
def inFootprint(self, pixels, nside=None): """ Open each valid filename for the set of pixels and determine the set of subpixels with valid data. """ if np.isscalar(pixels): pixels = np.array([pixels]) if nside is None: nside = self.nside_likelihood inside = np....
Submit likelihood analyses on a set of coordinates. If coords is `None`, submit all coordinates in the footprint. Inputs: coords : Array of target locations in Galactic coordinates. queue : Overwrite submit queue. debug : Don't run.
def submit_all(self, coords=None, queue=None, debug=False): """ Submit likelihood analyses on a set of coordinates. If coords is `None`, submit all coordinates in the footprint. Inputs: coords : Array of target locations in Galactic coordinates. queue : Overwrite submi...
Submit the likelihood job for the given pixel(s).
def submit(self, pixels, queue=None, debug=False, configfile=None): """ Submit the likelihood job for the given pixel(s). """ # For backwards compatibility batch = self.config['scan'].get('batch',self.config['batch']) queue = batch['cluster'] if queue is None else queue ...
Class method to check every settings. Will raise an ``ImproperlyConfigured`` exception with explanation.
def check(cls): """ Class method to check every settings. Will raise an ``ImproperlyConfigured`` exception with explanation. """ if cls == AppSettings: return None exceptions = [] for setting in cls.settings.values(): try: ...
Return a new record array with field names populated with data from arrays in *arrs*. If appending a single field, then *names*, *arrs* and *dtypes* do not have to be lists. They can just be the values themselves.
def rec_append_fields(rec, names, arrs, dtypes=None): """ Return a new record array with field names populated with data from arrays in *arrs*. If appending a single field, then *names*, *arrs* and *dtypes* do not have to be lists. They can just be the values themselves. """ if (not isstrin...
Parse command line argument for a collector Returns an argparse.Namespace with 'config' and 'query' options
def parse_args(name="", args=None): """Parse command line argument for a collector Returns an argparse.Namespace with 'config' and 'query' options""" def _load_json_file(path): with open(path) as f: json_data = json.load(f) json_data['path_to_json_file'] = path r...
Parse configuration options out of a YAML configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options populated thus far. Outputs: A dictionary of new configur...
def parse(self, configManager, config): """ Parse configuration options out of a YAML configuration file. Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object. config - The _Config object containing configuration options popula...
Sets the time_index parameter from a datetime using start/end/interval/units information from the service configuration. If best_fit is True, the method will match the closest time index for the given value, otherwise it will raise a ValueError for any value which doesn't exactly match a time index.
def set_time_index_from_datetime(self, value, best_fit=True): """ Sets the time_index parameter from a datetime using start/end/interval/units information from the service configuration. If best_fit is True, the method will match the closest time index for the given value, otherwise it w...
Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only.
def hash(self): """ Returns a hash of this render configuration from the variable, renderer, and time_index parameters. Used for caching the full-extent, native projection render so that subsequent requests can be served by a warp operation only. """ renderer_str = "{}|{...
Factory for creating objects. Arguments are passed directly to the constructor of the chosen class.
def factory(type, module=None, **kwargs): """ Factory for creating objects. Arguments are passed directly to the constructor of the chosen class. """ cls = type if module is None: module = __name__ fn = lambda member: inspect.isclass(member) and member.__module__==module classes = odict(...
NAME: JPRECESS PURPOSE: Precess astronomical coordinates from B1950 to J2000 EXPLANATION: Calculate the mean place of a star at J2000.0 on the FK5 system from the mean place at B1950.0 on the FK4 system. Use BPRECESS for the reverse direction J2000 ==> B1950 ...
def jprecess(ra, dec, mu_radec=None, parallax=None, rad_vel=None, epoch=None): """ NAME: JPRECESS PURPOSE: Precess astronomical coordinates from B1950 to J2000 EXPLANATION: Calculate the mean place of a star at J2000.0 on the FK5 system from the mean place at B1950.0 o...
NAME: BPRECESS PURPOSE: Precess positions from J2000.0 (FK5) to B1950.0 (FK4) EXPLANATION: Calculates the mean place of a star at B1950.0 on the FK4 system from the mean place at J2000.0 on the FK5 system. CALLING SEQUENCE: bprecess, ra, dec, ra_1950, de...
def bprecess(ra0, dec0, mu_radec=None, parallax=None, rad_vel=None, epoch=None): """ NAME: BPRECESS PURPOSE: Precess positions from J2000.0 (FK5) to B1950.0 (FK4) EXPLANATION: Calculates the mean place of a star at B1950.0 on the FK4 system from the mean place at J...
Returns a renderer object based on the configuration (as a dictionary)
def get_renderer_from_definition(config): """Returns a renderer object based on the configuration (as a dictionary)""" options = config.get('options', {}) try: renderer_type = config['type'] renderer_colors = [(float(x[0]), hex_to_color(x[1])) for x in config['colors']] fill_value ...
Returns a dictionary definition of the given renderer
def get_definition_from_renderer(renderer): """Returns a dictionary definition of the given renderer""" config = { 'colors': [[x[0], x[1].to_hex()] for x in renderer.colormap], 'options': {} } if renderer.fill_value: config['options']['fill_value'] = renderer.fill_value if...
Return a *copy* (we hope) of the parameters. DANGER: Altering properties directly doesn't call model._cache
def params(self): """ Return a *copy* (we hope) of the parameters. DANGER: Altering properties directly doesn't call model._cache """ params = odict([]) for key,model in self.models.items(): params.update(model.params) return params
Set a model. Parameters ---------- name : name of the model -- e.g., richness, kernel, isochrone, etc. model : the model instance Returns ------- None
def set_model(self, name, model): """ Set a model. Parameters ---------- name : name of the model -- e.g., richness, kernel, isochrone, etc. model : the model instance Returns ------- None """ # Careful to not use `hasattr` # htt...
Set the parameter values
def set_params(self,**kwargs): """ Set the parameter values """ for key,value in list(kwargs.items()): setattr(self,key,value)
Get an odict of the parameter names and values
def get_params(self): """ Get an odict of the parameter names and values """ return odict([(key,param.value) for key,param in self.params.items()])
Get an odict of free parameter names and values
def get_free_params(self): """ Get an odict of free parameter names and values """ return odict([(key,param.value) for key,param in self.params.items() if param.free])
Generate all matches found within a string for a regex and yield each match as a string
def iter_finds(regex_obj, s): """Generate all matches found within a string for a regex and yield each match as a string""" if isinstance(regex_obj, str): for m in re.finditer(regex_obj, s): yield m.group() else: for m in regex_obj.finditer(s): yield m.group()
r"""Wrap a string (tyically a regex) with a prefix and suffix (usually a nonconuming word break) Arguments: prefix, suffix (str): strings to append to the front and back of the provided string grouper (2-len str or 2-tuple): characters or strings to separate prefix and suffix from the middle >>> wra...
def wrap(s, prefix=r'\b', suffix=r'\b', grouper='()'): r"""Wrap a string (tyically a regex) with a prefix and suffix (usually a nonconuming word break) Arguments: prefix, suffix (str): strings to append to the front and back of the provided string grouper (2-len str or 2-tuple): characters or string...
Decorator for wrapping functions that calculate a weighted sum
def composite_decorator(func): """ Decorator for wrapping functions that calculate a weighted sum """ @wraps(func) def wrapper(self, *args, **kwargs): total = [] for weight,iso in zip(self.weights,self.isochrones): subfunc = getattr(iso,fun...
Merge a list of Catalogs. Parameters: ----------- catalog_list : List of Catalog objects. Returns: -------- catalog : Combined Catalog object
def mergeCatalogs(catalog_list): """ Merge a list of Catalogs. Parameters: ----------- catalog_list : List of Catalog objects. Returns: -------- catalog : Combined Catalog object """ # Check the columns for c in catalog_list: if c.data.dtype.names != catalog_l...
Return a new catalog which is a subset of objects selected using the input cut array. NOTE: This is really a *selection* (i.e., objects are retained if the value of 'cut' is True)
def applyCut(self, cut): """ Return a new catalog which is a subset of objects selected using the input cut array. NOTE: This is really a *selection* (i.e., objects are retained if the value of 'cut' is True) """ return Catalog(self.config, data=self.data[cut])
Return a random catalog by boostrapping the colors of the objects in the current catalog.
def bootstrap(self, mc_bit=0x10, seed=None): """ Return a random catalog by boostrapping the colors of the objects in the current catalog. """ if seed is not None: np.random.seed(seed) data = copy.deepcopy(self.data) idx = np.random.randint(0,len(data),len(data)) ...
Project coordinates on sphere to image plane using Projector class.
def project(self, projector = None): """ Project coordinates on sphere to image plane using Projector class. """ msg = "'%s.project': ADW 2018-05-05"%self.__class__.__name__ DeprecationWarning(msg) if projector is None: try: self.projector = ug...
Calculate indices of ROI pixels corresponding to object locations.
def spatialBin(self, roi): """ Calculate indices of ROI pixels corresponding to object locations. """ if hasattr(self,'pixel_roi_index') and hasattr(self,'pixel'): logger.warning('Catalog alread spatially binned') return # ADW: Not safe to set index = -1...
Write the current object catalog to FITS file. Parameters: ----------- filename : the FITS file to write. clobber : remove existing file kwargs : passed to fitsio.write Returns: -------- None
def write(self, outfile, clobber=True, **kwargs): """ Write the current object catalog to FITS file. Parameters: ----------- filename : the FITS file to write. clobber : remove existing file kwargs : passed to fitsio.write Returns: -------- ...
Parse catalog FITS files into recarray. Parameters: ----------- roi : The region of interest; if 'roi=None', read all catalog files Returns: -------- None
def _parse(self, roi=None, filenames=None): """ Parse catalog FITS files into recarray. Parameters: ----------- roi : The region of interest; if 'roi=None', read all catalog files Returns: -------- None """ if (roi is not None) an...
Helper funtion to define pertinent variables from catalog data. ADW (20170627): This has largely been replaced by properties.
def _defineVariables(self): """ Helper funtion to define pertinent variables from catalog data. ADW (20170627): This has largely been replaced by properties. """ logger.info('Catalog contains %i objects'%(len(self.data))) mc_source_id_field = self.config['catalog']['mc_...
Adds a node to the workflow. :param node_id: A unique identifier for the new node. :param task: The task to run. :param inputs: A mapping of inputs from workflow inputs, or outputs from other nodes. The format should be `{input_name: (source, value), ...}` where `input_name` is the ...
def add_node(self, node_id, task, inputs): """ Adds a node to the workflow. :param node_id: A unique identifier for the new node. :param task: The task to run. :param inputs: A mapping of inputs from workflow inputs, or outputs from other nodes. The format should be ...
Maps the output from a node to a workflow output. :param node_id: The id of the node to map from. :param node_output_name: The output parameter name for the node task to map to the workflow output. :param parameter_name: The workflow output parameter name.
def map_output(self, node_id, node_output_name, parameter_name): """ Maps the output from a node to a workflow output. :param node_id: The id of the node to map from. :param node_output_name: The output parameter name for the node task to map to the workflow output. :param param...
Serialize this workflow to JSON
def to_json(self, indent=None): """Serialize this workflow to JSON""" inputs = ParameterCollection(self.inputs) d = { 'meta': { 'name': self.name, 'description': self.description }, 'inputs': [], 'workflow': [], ...
Return a new workflow, deserialized from a JSON string
def from_json(cls, text): """Return a new workflow, deserialized from a JSON string""" d = json.loads(text) meta = d.get('meta', {}) workflow = cls(name=meta.get('name'), description=meta.get('description')) for workflow_input in d.get('inputs', []): parameter_cls ...
Return the static files serving handler wrapping the default handler, if static files should be served. Otherwise return the default handler.
def get_handler(self, *args, **options): ''' Return the static files serving handler wrapping the default handler, if static files should be served. Otherwise return the default handler. ''' handler = super().get_handler(*args, **options) use_static_handler = options['use...
Return the set of HEALPix pixels that cover the given coordinates at resolution nside. Optionally return the set of subpixels within those pixels at resolution nside_subpix
def surveyPixel(lon, lat, nside_pix, nside_subpix = None): """ Return the set of HEALPix pixels that cover the given coordinates at resolution nside. Optionally return the set of subpixels within those pixels at resolution nside_subpix """ pix = np.unique(ang2pix(nside_pix, lon, lat)) if nside_s...
Open each valid filename for the set of pixels and determine the set of subpixels with valid data.
def inFootprint(config, pixels, nside=None): """ Open each valid filename for the set of pixels and determine the set of subpixels with valid data. """ config = Config(config) nside_catalog = config['coords']['nside_catalog'] nside_likelihood = config['coords']['nside_likelihood'] ns...
UNTESTED. Should return a boolean array representing the pixels in the footprint.
def footprint(config, nside=None): """ UNTESTED. Should return a boolean array representing the pixels in the footprint. """ config = Config(config) if nside is None: nside = config['coords']['nside_pixel'] elif nside < config['coords']['nside_catalog']: raise Exception('Requ...
Generate a set of coordinates at the centers of pixels of resolutions nside across the full sky.
def allSkyCoordinates(nside): """ Generate a set of coordinates at the centers of pixels of resolutions nside across the full sky. """ lon,lat = pix2ang(nside, np.arange(0, hp.nside2npix(nside))) return lon, lat
Generate n random positions within a full HEALPix mask of booleans, or a set of (lon, lat) coordinates. Parameters: ----------- input : (1) full HEALPix mask of booleans, or (2) a set of (lon, lat) coordinates for catalog objects that define the occupied pixels. nside_pix : nside_pix is meant to be...
def randomPositions(input, nside_pix, n=1): """ Generate n random positions within a full HEALPix mask of booleans, or a set of (lon, lat) coordinates. Parameters: ----------- input : (1) full HEALPix mask of booleans, or (2) a set of (lon, lat) coordinates for catalog objects that define the o...
Generate n random positions within a HEALPix mask of booleans. KCB: Likely superceded by the randomPositions function, but more generic.
def randomPositionsMask(mask, nside_pix, n): """ Generate n random positions within a HEALPix mask of booleans. KCB: Likely superceded by the randomPositions function, but more generic. """ npix = len(mask) nside = hp.npix2nside(npix) # Estimate the number of points that need to be th...
Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a variable in the source model and bias is the linear bias associated with v. source_quadrat...
def embed_ising(source_linear, source_quadratic, embedding, target_adjacency, chain_strength=1.0): """Embeds a logical Ising model onto another graph via an embedding. Args: source_linear (dict): The linear biases to be embedded. Should be a dict of the form {v: bias, ...} where v is a vari...
Determines the frequency of chain breaks in the given samples. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadr...
def chain_break_frequency(samples, embedding): """Determines the frequency of chain breaks in the given samples. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target graph and val is the associ...
Return samples over the variables in the source graph. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target model and val is the associated value as determined by a binary quadratic mod...
def unembed_samples(samples, embedding, chain_break_method=None): """Return samples over the variables in the source graph. Args: samples (iterable): An iterable of samples where each sample is a dict of the form {v: val, ...} where v is a variable in the target model and val is...
Discards the sample if broken. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The mapping from the source graph to the targ...
def discard(sample, embedding): """Discards the sample if broken. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The ma...
Determines the sample values by majority vote. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The mapping from the source g...
def majority_vote(sample, embedding): """Determines the sample values by majority vote. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. em...
Determines the sample values by weighed random choice. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. embedding (dict): The mapping from the ...
def weighted_random(sample, embedding): """Determines the sample values by weighed random choice. Args: sample (dict): A sample of the form {v: val, ...} where v is a variable in the target graph and val is the associated value as determined by a binary quadratic model sampler. ...
True if all values in `iterable` are equal, else False.
def _all_equal(iterable): """True if all values in `iterable` are equal, else False.""" iterator = iter(iterable) first = next(iterator) return all(first == rest for rest in iterator)
Returns the most common element in `iterable`.
def _most_common(iterable): """Returns the most common element in `iterable`.""" data = Counter(iterable) return max(data, key=data.__getitem__)