INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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.
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: ...
Pops a message for a subscribed client.
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...
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.
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...
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/faculty/dtarb/96wr03137.pdf """ shp = np.array(data.shape) - 1 direction = np.full(data.shape, FLAT_ID_INT, 'float64') m...
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, 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...
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 direction of the slope based on Tarboton's D_\infty method. This is a helper-function to _tarboton_slopes_directions """ data0 = data[slc0] data...
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 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...
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.slice])
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 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. """ ...
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 the topleft gets # it's data from the left neighbor, which should have already bee...
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 xrange(self.n_chunks): self.n_todo.ravel()[i] = np.sum([left....
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.bottom for i in xrange(self.n_chunks): self.n_done.ravel()[i] = ...
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. """ left = self.left right = self.right top = self.top bottom = self.bottom for i in xrange(self.n_...
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(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: ...
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 example. """ for i in xrange(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: edge = get...
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 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...
Standard array saving routine
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'. ...
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 = self.twi.filled() self.twi[self.flats] = 0...
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.save_direction(rootpath, raw)
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 'name' from file Valid names are 'mag', 'direction', 'uca', 'twi' """ if os.path.exists(fn + '.npz'): array = np.load(fn + '.npz') ...
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 Number of pixels chunks will overlap Returns ------- start_id: array The startin...
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 ...
Assign data from a chunk to the full array. The data in overlap regions will not be assigned to the full array
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...
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 nans? # fill/interpolate flats first if self.fill_flats: ...
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': return self._central_slopes_dire...
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/cee/faculty/dtarb/96wr03137.pdf """ return _tarboton_slopes_directions(data, dX, dY, ...
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') mag = np.full(direction, 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 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 """ ...
Calculates the upstream contributing area.
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 ...
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.
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...
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, plotflag=False): """ Calculates the upstream contributing area due t...
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 upstream contributing area for the interior, and includes edge contributions if they are provided through area_edges. """ ...
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 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...
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 proportion of the drainage goes to which node """ shp = np.array(data.shape) - 1 facets = self.facets adj...
Calculates the adjacency of connectivity matrix. This matrix tells which pixels drain to which.
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...
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. 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...
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, 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...
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 surroundings on the flat. If the border ...
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 ...
Calculates the topographic wetness index and saves the result in self. twi.
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() ...
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 light wrapper around _plot_connectivity_helper """ if data is None: data = self.data B = A.tocoo() ...
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 = ~np.isnan(mat_datai) & (ji != -1) & (mat_datai >= 0) mat_...
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.direction / np.pi * 180); colorbar(); clim(0, 360) title('Direction'...
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(".").relpathto(destdir) command ...
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.platform.startswith("win"): o...
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.destdir)/format Path(dest).rmtree_p() sour...
Find the tile neighbors based on filenames
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 ...
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 = self.build_interpolator(dem_proc) opp = {'top': 'bottom', 'left': 'right'} ...
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_proc.edge_todo)
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) self.update_edge_todo(elev_fn, dem_proc) self.set_neighbor_data(elev_fn, 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()} edge_init_done = {key: self.edges[fn][key].get('do...
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): """ 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 pr...
Processes the TWI along with any dependencies ( like the slope and UCA )
def process_twi(self, index=None, do_edges=False, skip_uca_twi=False): """ 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, ...
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.
def process(self, index=None): """ 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...
Calculates twi for supplied elevation file
def calculate_twi(self, esfile, save_path, use_cache=True, do_edges=False, skip_uca_twi=False): """ Calculates twi for supplied elevation file Parameters ----------- esfile : str Path to elevation file to be processed save_path: str ...
Processes the hillshading
def process_command(self, command, save_name='custom', index=None): """ Processes the hillshading Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of ...
Given a list of file paths for elevation files this function will rename those files to the format required by the pyDEM package.
def rename_files(files, name=None): """ 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 elevat...
This parses the file name and returns the coordinates of the tile
def parse_fn(fn): """ 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] """ try: parts = os.path.splitext(os.path.split(fn)[-1])[0].r...
Determines the standard filename for a given GeoTIFF Layer.
def get_fn(elev, name=None): """ 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 ...
Given a set of coordinates returns the standard filename.
def get_fn_from_coords(coords, name=None): """ 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 ...
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'} ellipsoid = ELLIPSOID_MAP[geotif.grid_coordinates.wkt] d = distance(ellipsoid=ellipsoid) dx = geotif...
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
def mk_geotiff_obj(raster, fn, bands=1, gdal_data_type=gdal.GDT_Float32, lat=[46, 45], lon=[-73, -72]): """ 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 ------------ ...
Sorts array a by columns i
def sortrows(a, i=0, index_out=False, recurse=True): """ 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) ...
Find indices 2d - adjacent to those in I. Helper function for get_border *.
def get_adjacent_index(I, shape, size): """ 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 (technical...
Get flattened indices for the border of the region I.
def get_border_index(I, shape, size): """ 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) ...
Get border of the region as a boolean array mask.
def get_border_mask(region): """ 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 includi...
Compute within - region distances from the src pixels.
def get_distance(region, src): """ 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. Ret...
Grow a slice object by 1 in each direction without overreaching the list.
def grow_slice(slc, size): """ 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 """ return slice(max(0, s...
Check if a 2d object is on the edge of the array.
def is_edge(obj, shape): """ 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 ...
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.
def find_centroid(region): """ 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 t...
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 ).
def _tobytes(self): """Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object. """ if not self._has_view: # fast path optimization if len(self._deque) == 0: return b"" elif len(self._dequ...
Pops a chunk of the given max size.
def pop_chunk(self, chunk_max_size): """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. """ if self...
Return a new path with the file name changed.
def with_name(self, name): """Return a new path with the file name changed.""" if not self.name: raise ValueError("%r has an empty name" % (self,)) return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
Return a new path with the file suffix changed ( or added if none ).
def with_suffix(self, suffix): """Return a new path with the file suffix changed (or added, if none).""" # XXX if suffix is None, should the current suffix be removed? drv, root, parts = self._flavour.parse_parts((suffix,)) if drv or root or len(parts) != 1: raise ValueError(...
Open the file pointed by this path and return a file descriptor as os. open () does.
def _raw_open(self, flags, mode=0o777): """ Open the file pointed by this path and return a file descriptor, as os.open() does. """ return self._accessor.open(self, flags, mode)
Iterate over the files in this directory. Does not yield any result for the special paths. and...
def iterdir(self): """Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'. """ for name in self._accessor.listdir(self): if name in ('.', '..'): # Yielding a path object for these makes little sense ...
Return an absolute version of this path. This function works even if the path doesn t point to anything.
def absolute(self): """Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. all '.' and '..' will be kept along. Use resolve() to get the canonical path to a file. """ # XXX untested yet!...
Make the path absolute resolving all symlinks on the way and also normalizing it ( for example turning slashes into backslashes under Windows ).
def resolve(self): """ Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows). """ s = self._flavour.resolve(self) if s is None: # No symlink resolution => for cons...
Open the file pointed by this path and return a file object as the built - in open () function does.
def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None): """ Open the file pointed by this path and return a file object, as the built-in open() function does. """ if sys.version_info >= (3, 3): return io.open(str(self), mode, buf...
Rename this path to the given path clobbering the existing destination if it exists.
def replace(self, target): """ Rename this path to the given path, clobbering the existing destination if it exists. """ if sys.version_info < (3, 3): raise NotImplementedError("replace() is only available " "with Python 3.3 and l...
Make this path a symlink pointing to the given path. Note the order of arguments ( self target ) is the reverse of os. symlink s.
def symlink_to(self, target, target_is_directory=False): """ Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's. """ self._accessor.symlink(target, self, target_is_directory)
Whether this path is a symbolic link.
def is_symlink(self): """ Whether this path is a symbolic link. """ try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist return False
Whether this path is a block device.
def is_block_device(self): """ Whether this path is a block device. """ try: return S_ISBLK(self.stat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist or is a broken symlink # (see htt...
Whether this path is a character device.
def is_char_device(self): """ Whether this path is a character device. """ try: return S_ISCHR(self.stat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist or is a broken symlink # (see ...
Points are the outer edges of the UL and LR pixels. Size is rows columns. GC projection type is taken from Points.
def grid_coords_from_corners(upper_left_corner, lower_right_corner, size): ''' Points are the outer edges of the UL and LR pixels. Size is rows, columns. GC projection type is taken from Points. ''' assert upper_left_corner.wkt == lower_right_corner.wkt geotransform = np.array([upper_left_corner.lon, -(...
returns True if the GC s overlap.
def intersects(self, other_grid_coordinates): """ returns True if the GC's overlap. """ ogc = other_grid_coordinates # alias # for explanation: http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other # Note the flipped y-coord in this coord system. ...
A string that ( ideally ) uniquely represents this GC object. This helps with naming files for caching. Unique is defined as If GC1 ! = GC2 then GC1. unique_str () ! = GC2. unique_str () ; conversely If GC1 == GC2 then GC1. unique_str () == GC2. unique_str ().
def unique_str(self): """ A string that (ideally) uniquely represents this GC object. This helps with naming files for caching. 'Unique' is defined as 'If GC1 != GC2, then GC1.unique_str() != GC2.unique_str()'; conversely, 'If GC1 == GC2, then GC1.unique_str() == GC2.unique_str()'. ...
See http:// www. gdal. org/ gdal_datamodel. html for details.
def _get_x_axis(self): """See http://www.gdal.org/gdal_datamodel.html for details.""" # 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5). x_centers = np.linspace(.5, self.x_size - .5, self.x_size) y_centers = x_centers * 0 return (self.geotransform[0...
See http:// www. gdal. org/ gdal_datamodel. html for details.
def _get_y_axis(self): """See http://www.gdal.org/gdal_datamodel.html for details.""" # 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5). y_centers = np.linspace(.5, self.y_size - .5, self.y_size) x_centers = y_centers * 0 return (self.geotransform[3...
Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for details.
def raster_to_projection_coords(self, pixel_x, pixel_y): """ Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for details. """ h_px_py = np.array([1, pixel_x, pixel_y]) gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]) ...
Returns pixel centers. See documentation for the GDAL function GetGeoTransform for details.
def projection_to_raster_coords(self, lat, lon): """ Returns pixel centers. See documentation for the GDAL function GetGeoTransform for details. """ r_px_py = np.array([1, lon, lat]) tg = inv(np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]])) return np.inner(t...
Reprojects data in this layer to match that in the GridCoordinates object.
def reproject_to_grid_coordinates(self, grid_coordinates, interp=gdalconst.GRA_NearestNeighbour): """ Reprojects data in this layer to match that in the GridCoordinates object. """ source_dataset = self.grid_coordinates._as_gdal_dataset() dest_dataset = grid_coordinates._as_gdal_dataset(...
Replace masked - out elements in an array using an iterative image inpainting algorithm.
def inpaint(self): """ Replace masked-out elements in an array using an iterative image inpainting algorithm. """ import inpaint filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2) self.raster_data = np.ma.masked_invalid(filled)
Lookup a pixel value in the raster data performing linear interpolation if necessary. Indexed == > nearest neighbor ( * fast * ).
def interp_value(self, lat, lon, indexed=False): """ Lookup a pixel value in the raster data, performing linear interpolation if necessary. Indexed ==> nearest neighbor (*fast*). """ (px, py) = self.grid_coordinates.projection_to_raster_coords(lat, lon) if indexed: return sel...
Gets a connected Client object.
def get_connected_client(self): """Gets a connected Client object. If max_size is reached, this method will block until a new client object is available. Returns: A Future object with connected Client instance as a result (or ClientError if there was a conne...
Gets a Client object ( not necessary connected ).
def get_client_nowait(self): """Gets a Client object (not necessary connected). If max_size is reached, this method will return None (and won't block). Returns: A Client instance (not necessary connected) as result (or None). """ if self.__sem is not None: ...