Search is not available for this dataset
text
stringlengths
75
104k
def get_aux_files(basename): """ Look for and return all the aux files that are associated witht this filename. Will look for: background (_bkg.fits) rms (_rms.fits) mask (.mim) catalogue (_comp.fits) psf map (_psf.fits) will return filenames if they exist, or None ...
def _gen_flood_wrap(self, data, rmsimg, innerclip, outerclip=None, domask=False): """ Generator function. Segment an image into islands and return one island at a time. Needs to work for entire image, and also for components within an island. Parameters ---------- ...
def estimate_lmfit_parinfo(self, data, rmsimg, curve, beam, innerclip, outerclip=None, offsets=(0, 0), max_summits=None): """ Estimates the number of sources in an island and returns initial parameters for the fit as well as limits on those parameters. Par...
def result_to_components(self, result, model, island_data, isflags): """ Convert fitting results into a set of components Parameters ---------- result : lmfit.MinimizerResult The fitting results. model : lmfit.Parameters The model that was fit. ...
def load_globals(self, filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, verb=False, rms=None, bkg=None, cores=1, do_curve=True, mask=None, lat=None, psf=None, blank=False, docov=True, cube_index=None): """ Populate the global_data object by loading or calculating the variou...
def save_background_files(self, image_filename, hdu_index=0, bkgin=None, rmsin=None, beam=None, rms=None, bkg=None, cores=1, outbase=None): """ Generate and save the background and RMS maps as FITS files. They are saved in the current directly as aegean-background.f...
def save_image(self, outname): """ Save the image data. This is probably only useful if the image data has been blanked. Parameters ---------- outname : str Name for the output file. """ hdu = self.global_data.img.hdu hdu.data = self.g...
def _make_bkg_rms(self, mesh_size=20, forced_rms=None, forced_bkg=None, cores=None): """ Calculate an rms image and a bkg image. Parameters ---------- mesh_size : int Number of beams per box default = 20 forced_rms : float The rms of the image. ...
def _estimate_bkg_rms(self, xmin, xmax, ymin, ymax): """ Estimate the background noise mean and RMS. The mean is estimated as the median of data. The RMS is estimated as the IQR of data / 1.34896. Parameters ---------- xmin, xmax, ymin, ymax : int The...
def _load_aux_image(self, image, auxfile): """ Load a fits file (bkg/rms/curve) and make sure that it is the same shape as the main image. Parameters ---------- image : :class:`AegeanTools.fits_image.FitsImage` The main image that has already been loaded. ...
def _refit_islands(self, group, stage, outerclip=None, istart=0): """ Do island refitting (priorized fitting) on a group of islands. Parameters ---------- group : list A list of components grouped by island. stage : int Refitting stage. ...
def _fit_island(self, island_data): """ Take an Island, do all the parameter estimation and fitting. Parameters ---------- island_data : :class:`AegeanTools.models.IslandFittingData` The island to be fit. Returns ------- sources : list ...
def _fit_islands(self, islands): """ Execute fitting on a list of islands This function just wraps around fit_island, so that when we do multiprocesing a single process will fit multiple islands before returning results. Parameters ---------- islands : list of :...
def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5, outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False, nopositive=False, nonegative=False, mask=None, lat=None, img...
def priorized_fit_islands(self, filename, catalogue, hdu_index=0, outfile=None, bkgin=None, rmsin=None, cores=1, rms=None, bkg=None, beam=None, lat=None, imgpsf=None, catpsf=None, stage=3, ratio=None, outerclip=3, doregroup=True, docov=True, cube_index=None): ...
def check_table_formats(files): """ Determine whether a list of files are of a recognizable output type. Parameters ---------- files : str A list of file names Returns ------- result : bool True if *all* the file names are supported """ cont = True formats =...
def show_formats(): """ Print a list of all the file formats that are supported for writing. The file formats are determined by their extensions. Returns ------- None """ fmts = { "ann": "Kvis annotation", "reg": "DS9 regions file", "fits": "FITS Binary Table", ...
def update_meta_data(meta=None): """ Modify the metadata dictionary. DATE, PROGRAM, and PROGVER are added/modified. Parameters ---------- meta : dict The dictionary to be modified, default = None (empty) Returns ------- An updated dictionary. """ if meta is None...
def save_catalog(filename, catalog, meta=None, prefix=None): """ Save a catalogue of sources using filename as a model. Meta data can be written to some file types (fits, votable). Each type of source will be in a separate file: - base_comp.ext :class:`AegeanTools.models.OutputSource` - base_i...
def load_catalog(filename): """ Load a catalogue and extract the source positions (only) Parameters ---------- filename : str Filename to read. Supported types are csv, tab, tex, vo, vot, and xml. Returns ------- catalogue : list A list of [ (ra, dec), ...] """ ...
def load_table(filename): """ Load a table from a given file. Supports csv, tab, tex, vo, vot, xml, fits, and hdf5. Parameters ---------- filename : str File to read Returns ------- table : Table Table of data. """ supported = get_table_formats() fmt =...
def write_table(table, filename): """ Write a table to a file. Parameters ---------- table : Table Table to be written filename : str Destination for saving table. Returns ------- None """ try: if os.path.exists(filename): os.remove(file...
def table_to_source_list(table, src_type=OutputSource): """ Convert a table of data into a list of sources. A single table must have consistent source types given by src_type. src_type should be one of :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`Ae...
def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None): """ Write a catalog (list of sources) to a file with format determined by extension. Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSo...
def writeFITSTable(filename, table): """ Convert a table into a FITSTable and then write to disk. Parameters ---------- filename : str Filename to write. table : Table Table to write. Returns ------- None Notes ----- Due to a bug in numpy, `int32` and ...
def writeIslandContours(filename, catalog, fmt='reg'): """ Write an output file in ds9 .reg format that outlines the boundaries of each island. Parameters ---------- filename : str Filename to write. catalog : list List of sources. Only those of type :class:`AegeanTools.models....
def writeIslandBoxes(filename, catalog, fmt): """ Write an output file in ds9 .reg, or kvis .ann format that contains bounding boxes for all the islands. Parameters ---------- filename : str Filename to write. catalog : list List of sources. Only those of type :class:`AegeanToo...
def writeAnn(filename, catalog, fmt): """ Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg). Uses ra/dec from catalog. Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30" circles otherwise. Only :class:`AegeanTools.models.OutputSource` will appear in the annotation file ...
def writeDB(filename, catalog, meta=None): """ Output an sqlite3 database containing one table for each source type Parameters ---------- filename : str Output filename catalog : list List of sources of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools....
def norm_dist(src1, src2): """ Calculate the normalised distance between two sources. Sources are elliptical Gaussians. The normalised distance is calculated as the GCD distance between the centers, divided by quadrature sum of the radius of each ellipse along a line joining the two ellipses. ...
def sky_dist(src1, src2): """ Great circle distance between two sources. A check is made to determine if the two sources are the same object, in this case the distance is zero. Parameters ---------- src1, src2 : object Two sources to check. Objects must have parameters (ra,dec) in d...
def pairwise_ellpitical_binary(sources, eps, far=None): """ Do a pairwise comparison of all sources and determine if they have a normalized distance within eps. Form this into a matrix of shape NxN. Parameters ---------- sources : list A list of sources (objects with parameters: r...
def regroup_vectorized(srccat, eps, far=None, dist=norm_dist): """ Regroup the islands of a catalog according to their normalised distance. Assumes srccat is recarray-like for efficiency. Return a list of island groups. Parameters ---------- srccat : np.rec.arry or pd.DataFrame Sho...
def regroup(catalog, eps, far=None, dist=norm_dist): """ Regroup the islands of a catalog according to their normalised distance. Return a list of island groups. Sources have their (island,source) parameters relabeled. Parameters ---------- catalog : str or object Either a filename to ...
def load_file_or_hdu(filename): """ Load a file from disk and return an HDUList If filename is already an HDUList return that instead Parameters ---------- filename : str or HDUList File or HDU to be loaded Returns ------- hdulist : HDUList """ if isinstance(filenam...
def compress(datafile, factor, outfile=None): """ Compress a file using decimation. Parameters ---------- datafile : str or HDUList Input data to be loaded. (HDUList will be modified if passed). factor : int Decimation factor. outfile : str File to be written. Defa...
def expand(datafile, outfile=None): """ Expand and interpolate the given data file using the given method. Datafile can be a filename or an HDUList It is assumed that the file has been compressed and that there are `BN_?` keywords in the fits header that describe how the compression was done. ...
def change_autocommit_mode(self, switch): """ Strip and make a string case insensitive and ensure it is either 'true' or 'false'. If neither, prompt user for either value. When 'true', return True, and when 'false' return False. """ parsed_switch = switch.strip().lower()...
def armor(data, versioned=True): """ Returns a string in ASCII Armor format, for the given binary data. The output of this is compatiple with pgcrypto's armor/dearmor functions. """ template = '-----BEGIN PGP MESSAGE-----\n%(headers)s%(body)s\n=%(crc)s\n-----END PGP MESSAGE-----' body = base64.b...
def dearmor(text, verify=True): """ Given a string in ASCII Armor format, returns the decoded binary data. If verify=True (the default), the CRC is decoded and checked against that of the decoded data, otherwise it is ignored. If the checksum does not match, a BadChecksumError exception is raised. ...
def unpad(text, block_size): """ Takes the last character of the text, and if it is less than the block_size, assumes the text is padded, and removes any trailing zeros or bytes with the value of the pad character. See http://www.di-mgt.com.au/cryptopad.html for more information (methods 1, 3, and 4...
def pad(text, block_size, zero=False): """ Given a text string and a block size, pads the text with bytes of the same value as the number of padding bytes. This is the recommended method, and the one used by pgcrypto. See http://www.di-mgt.com.au/cryptopad.html for more information. """ num = bl...
def aes_pad_key(key): """ AES keys must be either 16, 24, or 32 bytes long. If a key is provided that is not one of these lengths, pad it with zeroes (this is what pgcrypto does). """ if len(key) in (16, 24, 32): return key if len(key) < 16: return pad(key, 16, zero=True) eli...
def deconstruct(self): """ Deconstruct the field for Django 1.7+ migrations. """ name, path, args, kwargs = super(BaseEncryptedField, self).deconstruct() kwargs.update({ #'key': self.cipher_key, 'cipher': self.cipher_name, 'charset': self.chars...
def get_cipher(self): """ Return a new Cipher object for each time we want to encrypt/decrypt. This is because pgcrypto expects a zeroed block for IV (initial value), but the IV on the cipher object is cumulatively updated each time encrypt/decrypt is called. """ return s...
def find_packages_by_root_package(where): """Better than excluding everything that is not needed, collect only what is needed. """ root_package = os.path.basename(where) packages = [ "%s.%s" % (root_package, sub_package) for sub_package in find_packages(where)] packages.insert(0...
def make_long_description(marker=None, intro=None): """ click_ is a framework to simplify writing composable commands for command-line tools. This package extends the click_ functionality by adding support for commands that use configuration files. .. _click: https://click.pocoo.org/ EXAMPLE: ...
def pubsub_pop_message(self, deadline=None): """Pops a message for a subscribed client. Args: deadline (int): max number of seconds to wait (None => no timeout) Returns: Future with the popped message as result (or None if timeout or ConnectionError obje...
def _get_flat_ids(assigned): """ This is a helper function to recover the coordinates of regions that have been labeled within an image. This function efficiently computes the coordinate of all regions and returns the information in a memory-efficient manner. Parameters ----------- assi...
def _tarboton_slopes_directions(data, dX, dY, facets, ang_adj): """ Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf """ shp = np.array(data.shape) - 1 direction = np.full(data.shape, FLAT_ID_INT, 'float64') m...
def _get_d1_d2(dX, dY, ind, e1, e2, shp, topbot=None): """ This finds the distances along the patch (within the eight neighboring pixels around a central pixel) given the difference in x and y coordinates of the real image. This is the function that allows real coordinates to be used when calculatin...
def _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2): """ This function gives the magnitude and direction of the slope based on Tarboton's D_\infty method. This is a helper-function to _tarboton_slopes_directions """ data0 = data[slc0] data...
def get(self, key, side): """ Returns an edge given a particular key Parmeters ---------- key : tuple (te, be, le, re) tuple that identifies a tile side : str top, bottom, left, or right, which edge to return """ return getattr(self...
def set_i(self, i, data, field, side): """ Assigns data on the i'th tile to the data 'field' of the 'side' edge of that tile """ edge = self.get_i(i, side) setattr(edge, field, data[edge.slice])
def set_sides(self, key, data, field, local=False): """ Assign data on the 'key' tile to all the edges """ for side in ['left', 'right', 'top', 'bottom']: self.set(key, data, field, side, local)
def set_neighbor_data(self, neighbor_side, data, key, field): """ Assign data from the 'key' tile to the edge on the neighboring tile which is on the 'neighbor_side' of the 'key' tile. The data is assigned to the 'field' attribute of the neihboring tile's edge. """ ...
def set_all_neighbors_data(self, data, done, key): """ Given they 'key' tile's data, assigns this information to all neighboring tiles """ # The order of this for loop is important because the topleft gets # it's data from the left neighbor, which should have already bee...
def fill_n_todo(self): """ Calculate and record the number of edge pixels left to do on each tile """ left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_chunks): self.n_todo.ravel()[i] = np.sum([left....
def fill_n_done(self): """ Calculate and record the number of edge pixels that are done one each tile. """ left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_chunks): self.n_done.ravel()[i] = ...
def fill_percent_done(self): """ Calculate the percentage of edge pixels that would be done if the tile was reprocessed. This is done for each tile. """ left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_...
def fill_array(self, array, field, add=False, maximize=False): """ Given a full array (for the while image), fill it with the data on the edges. """ self.fix_shapes() for i in xrange(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: ...
def fix_shapes(self): """ Fixes the shape of the data fields on edges. Left edges should be column vectors, and top edges should be row vectors, for example. """ for i in xrange(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: edge = get...
def find_best_candidate(self): """ Determine which tile, when processed, would complete the largest percentage of unresolved edge pixels. This is a heuristic function and does not give the optimal tile. """ self.fill_percent_done() i_b = np.argmax(self.percent_don...
def save_array(self, array, name=None, partname=None, rootpath='.', raw=False, as_int=True): """ Standard array saving routine Parameters ----------- array : array Array to save to file name : str, optional Default 'array.tif'. ...
def save_uca(self, rootpath, raw=False, as_int=False): """ Saves the upstream contributing area to a file """ self.save_array(self.uca, None, 'uca', rootpath, raw, as_int=as_int)
def save_twi(self, rootpath, raw=False, as_int=True): """ Saves the topographic wetness index to a file """ self.twi = np.ma.masked_array(self.twi, mask=self.twi <= 0, fill_value=-9999) # self.twi = self.twi.filled() self.twi[self.flats] = 0...
def save_slope(self, rootpath, raw=False, as_int=False): """ Saves the magnitude of the slope to a file """ self.save_array(self.mag, None, 'mag', rootpath, raw, as_int=as_int)
def save_direction(self, rootpath, raw=False, as_int=False): """ Saves the direction of the slope to a file """ self.save_array(self.direction, None, 'ang', rootpath, raw, as_int=as_int)
def save_outputs(self, rootpath='.', raw=False): """Saves TWI, UCA, magnitude and direction of slope to files. """ self.save_twi(rootpath, raw) self.save_uca(rootpath, raw) self.save_slope(rootpath, raw) self.save_direction(rootpath, raw)
def load_array(self, fn, name): """ Can only load files that were saved in the 'raw' format. Loads previously computed field 'name' from file Valid names are 'mag', 'direction', 'uca', 'twi' """ if os.path.exists(fn + '.npz'): array = np.load(fn + '.npz') ...
def _get_chunk_edges(self, NN, chunk_size, chunk_overlap): """ Given the size of the array, calculate and array that gives the edges of chunks of nominal size, with specified overlap Parameters ---------- NN : int Size of array chunk_size : int ...
def _assign_chunk(self, data, arr1, arr2, te, be, le, re, ovr, add=False): """ Assign data from a chunk to the full array. The data in overlap regions will not be assigned to the full array Parameters ----------- data : array Unused array (except for shape) t...
def calc_slopes_directions(self, plotflag=False): """ Calculates the magnitude and direction of slopes and fills self.mag, self.direction """ # TODO minimum filter behavior with nans? # fill/interpolate flats first if self.fill_flats: ...
def _slopes_directions(self, data, dX, dY, method='tarboton'): """ Wrapper to pick between various algorithms """ # %% if method == 'tarboton': return self._tarboton_slopes_directions(data, dX, dY) elif method == 'central': return self._central_slopes_dire...
def _tarboton_slopes_directions(self, data, dX, dY): """ Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf """ return _tarboton_slopes_directions(data, dX, dY, ...
def _central_slopes_directions(self, data, dX, dY): """ Calculates magnitude/direction of slopes using central difference """ shp = np.array(data.shape) - 1 direction = np.full(data.shape, FLAT_ID_INT, 'float64') mag = np.full(direction, FLAT_ID_INT, 'float64') ...
def _find_flats_edges(self, data, mag, direction): """ Extend flats 1 square downstream Flats on the downstream side of the flat might find a valid angle, but that doesn't mean that it's a correct angle. We have to find these and then set them equal to a flat """ ...
def calc_uca(self, plotflag=False, edge_init_data=None, uca_init=None): """Calculates the upstream contributing area. Parameters ---------- plotflag : bool, optional Default False. If true will plot debugging plots. For large files, this will be very slow ...
def fix_edge_pixels(self, edge_init_data, edge_init_done, edge_init_todo): """ This function fixes the pixels on the very edge of the tile. Drainage is calculated if the edge is downstream from the interior. If there is data available on the edge (from edge_init_data, for eg) the...
def _calc_uca_chunk_update(self, data, dX, dY, direction, mag, flats, tile_edge=None, i=None, area_edges=None, edge_todo=None, edge_done=None, plotflag=False): """ Calculates the upstream contributing area due t...
def _calc_uca_chunk(self, data, dX, dY, direction, mag, flats, area_edges, plotflag=False, edge_todo_i_no_mask=True): """ Calculates the upstream contributing area for the interior, and includes edge contributions if they are provided through area_edges. """ ...
def _drain_step(self, A, ids, area, done, edge_todo): """ Does a single step of the upstream contributing area calculation. Here the pixels in ids are drained downstream, the areas are updated and the next set of pixels to drain are determined for the next round. """ # On...
def _calc_uca_section_proportion(self, data, dX, dY, direction, flats): """ Given the direction, figure out which nodes the drainage will go toward, and what proportion of the drainage goes to which node """ shp = np.array(data.shape) - 1 facets = self.facets adj...
def _mk_adjacency_matrix(self, section, proportion, flats, elev, mag, dX, dY): """ Calculates the adjacency of connectivity matrix. This matrix tells which pixels drain to which. For example, the pixel i, will recieve area from np.nonzero(A[i, :]) at the proportions given in A[i...
def _mk_connectivity(self, section, i12, j1, j2): """ Helper function for _mk_adjacency_matrix. Calculates the drainage neighbors and proportions based on the direction. This deals with non-flat regions in the image. In this case, each pixel can only drain to either 1 or two neig...
def _mk_connectivity_pits(self, i12, flats, elev, mag, dX, dY): """ Helper function for _mk_adjacency_matrix. This is a more general version of _mk_adjacency_flats which drains pits and flats to nearby but non-adjacent pixels. The slope magnitude (and flats mask) is updated for t...
def _mk_connectivity_flats(self, i12, j1, j2, mat_data, flats, elev, mag): """ Helper function for _mk_adjacency_matrix. This calcualtes the connectivity for flat regions. Every pixel in the flat will drain to a random pixel in the flat. This accumulates all the area in the flat ...
def calc_twi(self): """ Calculates the topographic wetness index and saves the result in self.twi. Returns ------- twi : array Array giving the topographic wetness index at each pixel """ if self.uca is None: self.calc_uca() ...
def _plot_connectivity(self, A, data=None, lims=[None, None]): """ A debug function used to plot the adjacency/connectivity matrix. This is really just a light wrapper around _plot_connectivity_helper """ if data is None: data = self.data B = A.tocoo() ...
def _plot_connectivity_helper(self, ii, ji, mat_datai, data, lims=[1, 8]): """ A debug function used to plot the adjacency/connectivity matrix. """ from matplotlib.pyplot import quiver, colorbar, clim, matshow I = ~np.isnan(mat_datai) & (ji != -1) & (mat_datai >= 0) mat_...
def _plot_debug_slopes_directions(self): """ A debug function to plot the direction calculated in various ways. """ # %% from matplotlib.pyplot import matshow, colorbar, clim, title matshow(self.direction / np.pi * 180); colorbar(); clim(0, 360) title('Direction'...
def clean(ctx, dry_run=False): """Cleanup generated document artifacts.""" basedir = ctx.sphinx.destdir or "build/docs" cleanup_dirs([basedir], dry_run=dry_run)
def build(ctx, builder="html", options=""): """Build docs with sphinx-build""" sourcedir = ctx.config.sphinx.sourcedir destdir = Path(ctx.config.sphinx.destdir or "build")/builder destdir = destdir.abspath() with cd(sourcedir): destdir_relative = Path(".").relpathto(destdir) command ...
def browse(ctx): """Open documentation in web browser.""" page_html = Path(ctx.config.sphinx.destdir)/"html"/"index.html" if not page_html.exists(): build(ctx, builder="html") assert page_html.exists() open_cmd = "open" # -- WORKS ON: MACOSX if sys.platform.startswith("win"): o...
def save(ctx, dest="docs.html", format="html"): """Save/update docs under destination directory.""" print("STEP: Generate docs in HTML format") build(ctx, builder=format) print("STEP: Save docs under %s/" % dest) source_dir = Path(ctx.config.sphinx.destdir)/format Path(dest).rmtree_p() sour...
def find_neighbors(neighbors, coords, I, source_files, f, sides): """Find the tile neighbors based on filenames Parameters ----------- neighbors : dict Dictionary that stores the neighbors. Format is neighbors["source_file_name"]["side"] = "neighbor_source_file_name" coords : list ...
def set_neighbor_data(self, elev_fn, dem_proc, interp=None): """ From the elevation filename, we can figure out and load the data and done arrays. """ if interp is None: interp = self.build_interpolator(dem_proc) opp = {'top': 'bottom', 'left': 'right'} ...
def update_edge_todo(self, elev_fn, dem_proc): """ Can figure out how to update the todo based on the elev filename """ for key in self.edges[elev_fn].keys(): self.edges[elev_fn][key].set_data('todo', data=dem_proc.edge_todo)
def update_edges(self, elev_fn, dem_proc): """ After finishing a calculation, this will update the neighbors and the todo for that tile """ interp = self.build_interpolator(dem_proc) self.update_edge_todo(elev_fn, dem_proc) self.set_neighbor_data(elev_fn, dem_proc...
def get_edge_init_data(self, fn, save_path=None): """ Creates the initialization data from the edge structure """ edge_init_data = {key: self.edges[fn][key].get('data') for key in self.edges[fn].keys()} edge_init_done = {key: self.edges[fn][key].get('do...