text
stringlengths
81
112k
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:`AegeanTools.models.IslandSource`. Parameters ---------- ...
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.IslandSource`. Parameters ---------- filename : str Base name for file ...
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 `float32` are converted to `int64` and `float64` ...
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.IslandSource` will have contours drawn. fmt : str Outp...
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:`AegeanTools.models.IslandSource` will have contours drawn. 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 unless there are none, in which case :class:`Aeg...
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.models.SimpleSource`, or :class:`AegeanTools.models.Isl...
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. For ellipses that touch at a single poi...
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 degrees. Returns ------- d...
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: ra,dec,a,b,pa) eps : float Normalised distance constrain...
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 Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b...
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 read into a source list, or a list of objects with the following ...
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 def load_file_or_hdu(filename): """ Load a file from disk and return...
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. Default = None, which means don't write a file. Returns ...
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. Parameters ---------- datafile : str or ...
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. def change_autocommit_mode(self, switch): """ Strip and make a string case insensitive and ensure it is...
Returns a string in ASCII Armor format, for the given binary data. The output of this is compatiple with pgcrypto's armor/dearmor functions. 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/dea...
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 dearmor(text, verify=True): """ ...
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 unpad(text, block_size): """ ...
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. def pad(text, block_size, zero=False): """ Given a text string...
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). 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...
Deconstruct the field for Django 1.7+ migrations. 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': ...
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. def get_cipher(self): """ Return a new Cipher object ...
Better than excluding everything that is not needed, collect only what is needed. 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_p...
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: A configuration file, like: .. code-block:: INI ...
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 object in case of connection errors or Clien...
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 ----------- assigned : ndarray[ndim=2, dtype=int] ...
Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf 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/fac...
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 calculating the magnitude and directions of slopes. def _get_d1_d2(dX, dY, i...
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 def _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2): """ This function gives the magnitude and direc...
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 def get(self, key, side): """ Returns an edge given a particular key...
Assigns data on the i'th tile to the data 'field' of the 'side' edge of that tile 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.sl...
Assign data on the 'key' tile to all the edges 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)
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_neighbor_data(self, neighbor_side, data, key, field): """ Assign data from ...
Given they 'key' tile's data, assigns this information to all neighboring tiles 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 t...
Calculate and record the number of edge pixels left to do on each tile 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 x...
Calculate and record the number of edge pixels that are done one each tile. 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...
Calculate the percentage of edge pixels that would be done if the tile was reprocessed. This is done for each tile. 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. """ le...
Given a full array (for the while image), fill it with the data on the edges. 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(se...
Fixes the shape of the data fields on edges. Left edges should be column vectors, and top edges should be row vectors, for example. 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 exampl...
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. def find_best_candidate(self): """ Determine which tile, when processed, would complete the largest percentage ...
Standard array saving routine Parameters ----------- array : array Array to save to file name : str, optional Default 'array.tif'. Filename of array to save. Over-writes partname. partname : str, optional Part of the filename to sa...
Saves the upstream contributing area to a file 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)
Saves the topographic wetness index to a file 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 = sel...
Saves the magnitude of the slope to a file 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)
Saves the direction of the slope to a file 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)
Saves TWI, UCA, magnitude and direction of slope to files. 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.sav...
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' def load_array(self, fn, name): """ Can only load files that were saved in the 'raw' format. Loads previously computed field...
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 Nominal size of chunks (chunk_size < NN) chunk_overlap : int ...
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) that has size of full tile arr1 : array Full size array to which data will b...
Calculates the magnitude and direction of slopes and fills self.mag, self.direction 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 ...
Wrapper to pick between various algorithms 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': ...
Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf 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/ce...
Calculates magnitude/direction of slopes using central difference 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')...
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 _find_flats_edges(self, data, mag, direction): """ Extend flats 1 squa...
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 edge_init_data : list, optional edge_init_data = [uca_data, done_data,...
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) then this data is used. This is a bit of hack to take care of the edge-values. It could ...
Calculates the upstream contributing area due to contributions from the edges only. 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, ...
Calculates the upstream contributing area for the interior, and includes edge contributions if they are provided through area_edges. def _calc_uca_chunk(self, data, dX, dY, direction, mag, flats, area_edges, plotflag=False, edge_todo_i_no_mask=True): """ Calculates the u...
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. def _drain_step(self, A, ids, area, done, edge_todo): """ Does a single step of t...
Given the direction, figure out which nodes the drainage will go toward, and what proportion of the drainage goes to which node 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 p...
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, :]. So, the row gives the pixel drain to, and the columns the pixels drained from. def _...
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 neighbors. def _mk_connectivity(self, section, i12, j1, j2): """ ...
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 these pits and flats so that the TWI can be computed. def _mk_connectivity_pits(self...
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 region to a single pixel. All that area is then drained from that pixel to the surround...
Calculates the topographic wetness index and saves the result in self.twi. Returns ------- twi : array Array giving the topographic wetness index at each pixel def calc_twi(self): """ Calculates the topographic wetness index and saves the result in s...
A debug function used to plot the adjacency/connectivity matrix. This is really just a light wrapper around _plot_connectivity_helper 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...
A debug function used to plot the adjacency/connectivity matrix. 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 =...
A debug function to plot the direction calculated in various ways. 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.directio...
Cleanup generated document artifacts. def clean(ctx, dry_run=False): """Cleanup generated document artifacts.""" basedir = ctx.sphinx.destdir or "build/docs" cleanup_dirs([basedir], dry_run=dry_run)
Build docs with sphinx-build 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(".").relpa...
Open documentation in web browser. 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.p...
Save/update docs under destination directory. 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.des...
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 List of coordinates determined from the filename. See :py:...
From the elevation filename, we can figure out and load the data and done arrays. 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 ...
Can figure out how to update the todo based on the elev filename 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_...
After finishing a calculation, this will update the neighbors and the todo for that tile 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)...
Creates the initialization data from the edge structure 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()} ...
Heuristically determines which tile should be recalculated based on updated edge information. Presently does not check if that tile is locked, which could lead to a parallel thread closing while one thread continues to process tiles. def find_best_candidate(self, elev_source_files=None): ...
Processes the TWI, along with any dependencies (like the slope and UCA) Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of the files as listed in self.el...
This will completely process a directory of elevation tiles (as supplied in the constructor). Both phases of the calculation, the single tile and edge resolution phases are run. Parameters ----------- index : int/slice (optional) Default None - processes all tiles in...
Calculates twi for supplied elevation file Parameters ----------- esfile : str Path to elevation file to be processed save_path: str Root path to location where TWI will be saved. TWI will be saved in a subdirectory 'twi'. use_cache : bool (op...
Processes the hillshading Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of the files as listed in self.elev_source_files def process_command(self, com...
Given a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM package. This assumes a .tif extension. Parameters ----------- files : list A list of strings of the paths to the elevation files that will be renamed name ...
This parses the file name and returns the coordinates of the tile Parameters ----------- fn : str Filename of a GEOTIFF Returns -------- coords = [LLC.lat, LLC.lon, URC.lat, URC.lon] def parse_fn(fn): """ This parses the file name and returns the coordinates of the tile Param...
Determines the standard filename for a given GeoTIFF Layer. Parameters ----------- elev : GdalReader.raster_layer A raster layer from the GdalReader object. name : str (optional) An optional suffix to the filename. Returns ------- fn : str The standard <filename>_<na...
Given a set of coordinates, returns the standard filename. Parameters ----------- coords : list [LLC.lat, LLC.lon, URC.lat, URC.lon] name : str (optional) An optional suffix to the filename. Returns ------- fn : str The standard <filename>_<name>.tif with suffix (if...
Extracts the change in x and y coordinates from the geotiff file. Presently only supports WGS-84 files. def mk_dx_dy_from_geotif_layer(geotif): """ Extracts the change in x and y coordinates from the geotiff file. Presently only supports WGS-84 files. """ ELLIPSOID_MAP = {'WGS84': 'WGS-84'} ...
Creates a new geotiff file objects using the WGS84 coordinate system, saves it to disk, and returns a handle to the python file object and driver Parameters ------------ raster : array Numpy array of the raster data to be added to the object fn : str Name of the geotiff file ban...
Sorts array "a" by columns i Parameters ------------ a : np.ndarray array to be sorted i : int (optional) column to be sorted by, taken as 0 by default index_out : bool (optional) return the index I such that a(I) = sortrows(a,i). Default = False recurse : bool (optional...
Find indices 2d-adjacent to those in I. Helper function for get_border*. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region shape : tuple(int, int) region shape size : int region size (technically computable from shape) Returns ------- ...
Get flattened indices for the border of the region I. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region. size : int region size (technically computable from shape argument) shape : tuple(int, int) region shape Returns ------- J : np...
Get border of the region as a boolean array mask. Parameters ---------- region : np.ndarray(shape=(m, n), dtype=bool) mask of the region Returns ------- border : np.ndarray(shape=(m, n), dtype=bool) mask of the region border (not including region) def get_border_mask(region): ...
Compute within-region distances from the src pixels. Parameters ---------- region : np.ndarray(shape=(m, n), dtype=bool) mask of the region src : np.ndarray(shape=(m, n), dtype=bool) mask of the source pixels to compute distances from. Returns ------- d : np.ndarray(shape=(...
Grow a slice object by 1 in each direction without overreaching the list. Parameters ---------- slc: slice slice object to grow size: int list length Returns ------- slc: slice extended slice def grow_slice(slc, size): """ Grow a slice object by 1 in each di...
Check if a 2d object is on the edge of the array. Parameters ---------- obj : tuple(slice, slice) Pair of slices (e.g. from scipy.ndimage.measurements.find_objects) shape : tuple(int, int) Array shape. Returns ------- b : boolean True if the object touches any edge ...
Finds an approximate centroid for a region that is within the region. Parameters ---------- region : np.ndarray(shape=(m, n), dtype='bool') mask of the region. Returns ------- i, j : tuple(int, int) 2d index within the region nearest the center of mass. def find_centroid(r...
Resets the object at its initial (empty) state. def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object. def _tobytes(self): """Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object. """ if not self._has_view: # fast ...
Pops a chunk of the given max size. Optimized to avoid too much string copies. Args: chunk_max_size (int): max size of the returned chunk. Returns: string (bytes) with a size <= chunk_max_size. def pop_chunk(self, chunk_max_size): """Pops a chunk of the given ...