sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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 ... | 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 where they do not.
Parameters
--... | entailment |
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
----------
... | 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
----------
data : 2d-array
Image array.
rmsimg : 2d-array
Noise image.
... | entailment |
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... | Estimates the number of sources in an island and returns initial parameters for the fit as well as
limits on those parameters.
Parameters
----------
data : 2d-array
(sub) image of flux values. Background should be subtracted.
rmsimg : 2d-array
Image of 1... | entailment |
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.
... | Convert fitting results into a set of components
Parameters
----------
result : lmfit.MinimizerResult
The fitting results.
model : lmfit.Parameters
The model that was fit.
island_data : :class:`AegeanTools.models.IslandFittingData`
Data abou... | entailment |
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... | Populate the global_data object by loading or calculating the various components
Parameters
----------
filename : str or HDUList
Main image which source finding is run on
hdu_index : int
HDU index of the image within the fits file, default is 0 (first)
... | entailment |
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... | Generate and save the background and RMS maps as FITS files.
They are saved in the current directly as aegean-background.fits and aegean-rms.fits.
Parameters
----------
image_filename : str or HDUList
Input image.
hdu_index : int
If fits file has more th... | entailment |
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... | Save the image data.
This is probably only useful if the image data has been blanked.
Parameters
----------
outname : str
Name for the output file. | entailment |
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.
... | 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.
If None: calculate the rms level (default).
Otherwise assume a constant rms.
... | entailment |
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... | 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 bounding region over which the bkg/rms will be calculated.
Retu... | entailment |
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.
... | 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.
auxfile : str or HDUList
The auxiliary file t... | entailment |
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.
... | Do island refitting (priorized fitting) on a group of islands.
Parameters
----------
group : list
A list of components grouped by island.
stage : int
Refitting stage.
outerclip : float
Ignored, placed holder for future development.
... | entailment |
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
... | 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
The sources that were fit. | entailment |
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 :... | 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 :class:`AegeanTools.models.IslandFittingData`
... | entailment |
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... | Run the Aegean source finder.
Parameters
----------
filename : str or HDUList
Image filename or HDUList.
hdu_index : int
The index of the FITS HDU (extension).
outfile : str
file for printing catalog (NOT a table, just a text file of my own... | entailment |
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):
... | Take an input catalog, and image, and optional background/noise images
fit the flux and ra/dec for each of the given sources, keeping the morphology fixed
if doregroup is true the groups will be recreated based on a matching radius/probability.
if doregroup is false then the islands of the inpu... | entailment |
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 =... | 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 | entailment |
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",
... | Print a list of all the file formats that are supported for writing.
The file formats are determined by their extensions.
Returns
-------
None | entailment |
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... | 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. | entailment |
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... | 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_isle.ext :class:`AegeanTools.models.IslandSource`
- base_simp.ext :cla... | entailment |
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), ...]
"""
... | 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), ...] | entailment |
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 =... | 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. | entailment |
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... | Write a table to a file.
Parameters
----------
table : Table
Table to be written
filename : str
Destination for saving table.
Returns
-------
None | entailment |
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... | 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
----------
... | entailment |
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... | 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 ... | entailment |
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 ... | 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` ... | entailment |
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.... | 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... | entailment |
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... | 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... | entailment |
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
... | 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... | entailment |
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.... | 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... | entailment |
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.
... | 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... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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 ... | 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 ... | entailment |
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... | 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 | entailment |
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... | 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
... | entailment |
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.
... | 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 ... | entailment |
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()... | 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. | entailment |
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... | Returns a string in ASCII Armor format, for the given binary data. The
output of this is compatiple with pgcrypto's armor/dearmor functions. | entailment |
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.
... | 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. | entailment |
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... | 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). | entailment |
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... | 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. | entailment |
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... | 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). | entailment |
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... | Deconstruct the field for Django 1.7+ migrations. | entailment |
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... | 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. | entailment |
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... | Better than excluding everything that is not needed,
collect only what is needed. | entailment |
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:
... | 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
... | entailment |
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... | 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... | entailment |
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... | 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]
... | entailment |
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... | Calculate the slopes and directions based on the 8 sections from
Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf | entailment |
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 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. | entailment |
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... | 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 | entailment |
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... | 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 | entailment |
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]) | Assigns data on the i'th tile to the data 'field' of the 'side'
edge of that tile | entailment |
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 on the 'key' tile to all the edges | entailment |
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.
"""
... | 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. | entailment |
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... | Given they 'key' tile's data, assigns this information to all
neighboring tiles | entailment |
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 left to do on each tile | entailment |
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 and record the number of edge pixels that are done one each
tile. | entailment |
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_... | Calculate the percentage of edge pixels that would be done if the tile
was reprocessed. This is done for each tile. | entailment |
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']:
... | Given a full array (for the while image), fill it with the data on
the edges. | entailment |
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... | Fixes the shape of the data fields on edges. Left edges should be
column vectors, and top edges should be row vectors, for example. | entailment |
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... | 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. | entailment |
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'. ... | 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... | entailment |
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 upstream contributing area to a file | entailment |
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 topographic wetness index to a file | entailment |
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 magnitude of the slope to a file | entailment |
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 the direction of the slope to a file | entailment |
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) | Saves TWI, UCA, magnitude and direction of slope to files. | entailment |
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')
... | 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' | entailment |
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
... | 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
... | entailment |
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... | 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... | entailment |
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:
... | Calculates the magnitude and direction of slopes and fills
self.mag, self.direction | entailment |
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... | Wrapper to pick between various algorithms | entailment |
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,
... | Calculate the slopes and directions based on the 8 sections from
Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf | entailment |
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')
... | Calculates magnitude/direction of slopes using central difference | entailment |
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
"""
... | 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 | entailment |
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
... | 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,... | entailment |
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... | 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
... | entailment |
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 due to contributions from
the edges only. | entailment |
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.
"""
... | Calculates the upstream contributing area for the interior, and
includes edge contributions if they are provided through area_edges. | entailment |
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... | 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. | entailment |
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... | Given the direction, figure out which nodes the drainage will go
toward, and what proportion of the drainage goes to which node | entailment |
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... | 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. | entailment |
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. 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. | entailment |
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 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. | entailment |
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 ... | 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... | entailment |
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()
... | Calculates the topographic wetness index and saves the result in
self.twi.
Returns
-------
twi : array
Array giving the topographic wetness index at each pixel | entailment |
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.
This is really just a light wrapper around _plot_connectivity_helper | entailment |
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 used to plot the adjacency/connectivity matrix. | entailment |
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'... | A debug function to plot the direction calculated in various ways. | entailment |
def clean(ctx, dry_run=False):
"""Cleanup generated document artifacts."""
basedir = ctx.sphinx.destdir or "build/docs"
cleanup_dirs([basedir], dry_run=dry_run) | Cleanup generated document artifacts. | entailment |
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 ... | Build docs with sphinx-build | entailment |
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... | Open documentation in web browser. | entailment |
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... | Save/update docs under destination directory. | entailment |
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
... | 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:... | entailment |
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'}
... | From the elevation filename, we can figure out and load the data and
done arrays. | entailment |
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) | Can figure out how to update the todo based on the elev filename | entailment |
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... | After finishing a calculation, this will update the neighbors and the
todo for that tile | entailment |
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... | Creates the initialization data from the edge structure | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.