repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
PaulHancock/Aegean
AegeanTools/catalogs.py
table_to_source_list
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:`AegeanTools.models.IslandSource`. Parameters ---------- table : Table Table of sources src_type : class Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. Returns ------- sources : list A list of objects of the given type. """ source_list = [] if table is None: return source_list for row in table: # Initialise our object src = src_type() # look for the columns required by our source object for param in src_type.names: if param in table.colnames: # copy the value to our object val = row[param] # hack around float32's broken-ness if isinstance(val, np.float32): val = np.float64(val) setattr(src, param, val) # save this object to our list of sources source_list.append(src) return source_list
python
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:`AegeanTools.models.IslandSource`. Parameters ---------- table : Table Table of sources src_type : class Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. Returns ------- sources : list A list of objects of the given type. """ source_list = [] if table is None: return source_list for row in table: # Initialise our object src = src_type() # look for the columns required by our source object for param in src_type.names: if param in table.colnames: # copy the value to our object val = row[param] # hack around float32's broken-ness if isinstance(val, np.float32): val = np.float64(val) setattr(src, param, val) # save this object to our list of sources source_list.append(src) return source_list
[ "def", "table_to_source_list", "(", "table", ",", "src_type", "=", "OutputSource", ")", ":", "source_list", "=", "[", "]", "if", "table", "is", "None", ":", "return", "source_list", "for", "row", "in", "table", ":", "# Initialise our object", "src", "=", "sr...
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 ---------- table : Table Table of sources src_type : class Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. Returns ------- sources : list A list of objects of the given type.
[ "Convert", "a", "table", "of", "data", "into", "a", "list", "of", "sources", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L302-L343
train
PaulHancock/Aegean
AegeanTools/catalogs.py
write_catalog
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.IslandSource`. Parameters ---------- filename : str Base name for file to write. `_simp`, `_comp`, or `_isle` will be added to differentiate the different types of sources that are being written. catalog : list A list of source objects. Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. fmt : str The file format extension. prefix : str Prepend each column name with "prefix_". Default is to prepend nothing. meta : dict A dictionary to be used as metadata for some file types (fits, VOTable). Returns ------- None """ if meta is None: meta = {} if prefix is None: pre='' else: pre = prefix + '_' def writer(filename, catalog, fmt=None): """ construct a dict of the data this method preserves the data types in the VOTable """ tab_dict = {} name_list = [] for name in catalog[0].names: col_name = name if catalog[0].galactic: if name.startswith('ra'): col_name = 'lon'+name[2:] elif name.endswith('ra'): col_name = name[:-2] + 'lon' elif name.startswith('dec'): col_name = 'lat'+name[3:] elif name.endswith('dec'): col_name = name[:-3] + 'lat' col_name = pre + col_name tab_dict[col_name] = [getattr(c, name, None) for c in catalog] name_list.append(col_name) t = Table(tab_dict, meta=meta) # re-order the columns t = t[[n for n in name_list]] if fmt is not None: if fmt in ["vot", "vo", "xml"]: vot = from_table(t) # description of this votable vot.description = repr(meta) writetoVO(vot, filename) elif fmt in ['hdf5']: t.write(filename, path='data', overwrite=True) elif fmt in ['fits']: writeFITSTable(filename, t) else: ascii.write(t, filename, fmt, overwrite=True) else: ascii.write(t, filename, overwrite=True) return # sort the sources into types and then write them out individually components, islands, simples = classify_catalog(catalog) if len(components) > 0: new_name = "{1}{0}{2}".format('_comp', *os.path.splitext(filename)) writer(new_name, components, fmt) log.info("wrote {0}".format(new_name)) if len(islands) > 0: new_name = "{1}{0}{2}".format('_isle', *os.path.splitext(filename)) writer(new_name, islands, fmt) log.info("wrote {0}".format(new_name)) if len(simples) > 0: new_name = "{1}{0}{2}".format('_simp', *os.path.splitext(filename)) writer(new_name, simples, fmt) log.info("wrote {0}".format(new_name)) return
python
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.IslandSource`. Parameters ---------- filename : str Base name for file to write. `_simp`, `_comp`, or `_isle` will be added to differentiate the different types of sources that are being written. catalog : list A list of source objects. Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. fmt : str The file format extension. prefix : str Prepend each column name with "prefix_". Default is to prepend nothing. meta : dict A dictionary to be used as metadata for some file types (fits, VOTable). Returns ------- None """ if meta is None: meta = {} if prefix is None: pre='' else: pre = prefix + '_' def writer(filename, catalog, fmt=None): """ construct a dict of the data this method preserves the data types in the VOTable """ tab_dict = {} name_list = [] for name in catalog[0].names: col_name = name if catalog[0].galactic: if name.startswith('ra'): col_name = 'lon'+name[2:] elif name.endswith('ra'): col_name = name[:-2] + 'lon' elif name.startswith('dec'): col_name = 'lat'+name[3:] elif name.endswith('dec'): col_name = name[:-3] + 'lat' col_name = pre + col_name tab_dict[col_name] = [getattr(c, name, None) for c in catalog] name_list.append(col_name) t = Table(tab_dict, meta=meta) # re-order the columns t = t[[n for n in name_list]] if fmt is not None: if fmt in ["vot", "vo", "xml"]: vot = from_table(t) # description of this votable vot.description = repr(meta) writetoVO(vot, filename) elif fmt in ['hdf5']: t.write(filename, path='data', overwrite=True) elif fmt in ['fits']: writeFITSTable(filename, t) else: ascii.write(t, filename, fmt, overwrite=True) else: ascii.write(t, filename, overwrite=True) return # sort the sources into types and then write them out individually components, islands, simples = classify_catalog(catalog) if len(components) > 0: new_name = "{1}{0}{2}".format('_comp', *os.path.splitext(filename)) writer(new_name, components, fmt) log.info("wrote {0}".format(new_name)) if len(islands) > 0: new_name = "{1}{0}{2}".format('_isle', *os.path.splitext(filename)) writer(new_name, islands, fmt) log.info("wrote {0}".format(new_name)) if len(simples) > 0: new_name = "{1}{0}{2}".format('_simp', *os.path.splitext(filename)) writer(new_name, simples, fmt) log.info("wrote {0}".format(new_name)) return
[ "def", "write_catalog", "(", "filename", ",", "catalog", ",", "fmt", "=", "None", ",", "meta", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "meta", "is", "None", ":", "meta", "=", "{", "}", "if", "prefix", "is", "None", ":", "pre", "=...
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 to write. `_simp`, `_comp`, or `_isle` will be added to differentiate the different types of sources that are being written. catalog : list A list of source objects. Sources must be of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. fmt : str The file format extension. prefix : str Prepend each column name with "prefix_". Default is to prepend nothing. meta : dict A dictionary to be used as metadata for some file types (fits, VOTable). Returns ------- None
[ "Write", "a", "catalog", "(", "list", "of", "sources", ")", "to", "a", "file", "with", "format", "determined", "by", "extension", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L346-L440
train
PaulHancock/Aegean
AegeanTools/catalogs.py
writeFITSTable
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 `float32` are converted to `int64` and `float64` before writing. """ def FITSTableType(val): """ Return the FITSTable type corresponding to each named parameter in obj """ if isinstance(val, bool): types = "L" elif isinstance(val, (int, np.int64, np.int32)): types = "J" elif isinstance(val, (float, np.float64, np.float32)): types = "E" elif isinstance(val, six.string_types): types = "{0}A".format(len(val)) else: log.warning("Column {0} is of unknown type {1}".format(val, type(val))) log.warning("Using 5A") types = "5A" return types cols = [] for name in table.colnames: cols.append(fits.Column(name=name, format=FITSTableType(table[name][0]), array=table[name])) cols = fits.ColDefs(cols) tbhdu = fits.BinTableHDU.from_columns(cols) for k in table.meta: tbhdu.header['HISTORY'] = ':'.join((k, table.meta[k])) tbhdu.writeto(filename, overwrite=True)
python
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 `float32` are converted to `int64` and `float64` before writing. """ def FITSTableType(val): """ Return the FITSTable type corresponding to each named parameter in obj """ if isinstance(val, bool): types = "L" elif isinstance(val, (int, np.int64, np.int32)): types = "J" elif isinstance(val, (float, np.float64, np.float32)): types = "E" elif isinstance(val, six.string_types): types = "{0}A".format(len(val)) else: log.warning("Column {0} is of unknown type {1}".format(val, type(val))) log.warning("Using 5A") types = "5A" return types cols = [] for name in table.colnames: cols.append(fits.Column(name=name, format=FITSTableType(table[name][0]), array=table[name])) cols = fits.ColDefs(cols) tbhdu = fits.BinTableHDU.from_columns(cols) for k in table.meta: tbhdu.header['HISTORY'] = ':'.join((k, table.meta[k])) tbhdu.writeto(filename, overwrite=True)
[ "def", "writeFITSTable", "(", "filename", ",", "table", ")", ":", "def", "FITSTableType", "(", "val", ")", ":", "\"\"\"\n Return the FITSTable type corresponding to each named parameter in obj\n \"\"\"", "if", "isinstance", "(", "val", ",", "bool", ")", ":",...
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` before writing.
[ "Convert", "a", "table", "into", "a", "FITSTable", "and", "then", "write", "to", "disk", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L443-L488
train
PaulHancock/Aegean
AegeanTools/catalogs.py
writeIslandContours
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.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' is supported (default) Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandBoxes` """ if fmt != 'reg': log.warning("Format {0} not yet supported".format(fmt)) log.warning("not writing anything") return out = open(filename, 'w') print("#Aegean island contours", file=out) print("#AegeanTools.catalogs version {0}-({1})".format(__version__, __date__), file=out) line_fmt = 'image;line({0},{1},{2},{3})' text_fmt = 'fk5; text({0},{1}) # text={{{2}}}' mas_fmt = 'image; line({1},{0},{3},{2}) #color = yellow' x_fmt = 'image; point({1},{0}) # point=x' for c in catalog: contour = c.contour if len(contour) > 1: for p1, p2 in zip(contour[:-1], contour[1:]): print(line_fmt.format(p1[1] + 0.5, p1[0] + 0.5, p2[1] + 0.5, p2[0] + 0.5), file=out) print(line_fmt.format(contour[-1][1] + 0.5, contour[-1][0] + 0.5, contour[0][1] + 0.5, contour[0][0] + 0.5), file=out) # comment out lines that have invalid ra/dec (WCS problems) if np.nan in [c.ra, c.dec]: print('#', end=' ', file=out) # some islands may not have anchors because they don't have any contours if len(c.max_angular_size_anchors) == 4: print(text_fmt.format(c.ra, c.dec, c.island), file=out) print(mas_fmt.format(*[a + 0.5 for a in c.max_angular_size_anchors]), file=out) for p1, p2 in c.pix_mask: # DS9 uses 1-based instead of 0-based indexing print(x_fmt.format(p1 + 1, p2 + 1), file=out) out.close() return
python
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.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' is supported (default) Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandBoxes` """ if fmt != 'reg': log.warning("Format {0} not yet supported".format(fmt)) log.warning("not writing anything") return out = open(filename, 'w') print("#Aegean island contours", file=out) print("#AegeanTools.catalogs version {0}-({1})".format(__version__, __date__), file=out) line_fmt = 'image;line({0},{1},{2},{3})' text_fmt = 'fk5; text({0},{1}) # text={{{2}}}' mas_fmt = 'image; line({1},{0},{3},{2}) #color = yellow' x_fmt = 'image; point({1},{0}) # point=x' for c in catalog: contour = c.contour if len(contour) > 1: for p1, p2 in zip(contour[:-1], contour[1:]): print(line_fmt.format(p1[1] + 0.5, p1[0] + 0.5, p2[1] + 0.5, p2[0] + 0.5), file=out) print(line_fmt.format(contour[-1][1] + 0.5, contour[-1][0] + 0.5, contour[0][1] + 0.5, contour[0][0] + 0.5), file=out) # comment out lines that have invalid ra/dec (WCS problems) if np.nan in [c.ra, c.dec]: print('#', end=' ', file=out) # some islands may not have anchors because they don't have any contours if len(c.max_angular_size_anchors) == 4: print(text_fmt.format(c.ra, c.dec, c.island), file=out) print(mas_fmt.format(*[a + 0.5 for a in c.max_angular_size_anchors]), file=out) for p1, p2 in c.pix_mask: # DS9 uses 1-based instead of 0-based indexing print(x_fmt.format(p1 + 1, p2 + 1), file=out) out.close() return
[ "def", "writeIslandContours", "(", "filename", ",", "catalog", ",", "fmt", "=", "'reg'", ")", ":", "if", "fmt", "!=", "'reg'", ":", "log", ".", "warning", "(", "\"Format {0} not yet supported\"", ".", "format", "(", "fmt", ")", ")", "log", ".", "warning", ...
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 Output format type. Currently only 'reg' is supported (default) Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandBoxes`
[ "Write", "an", "output", "file", "in", "ds9", ".", "reg", "format", "that", "outlines", "the", "boundaries", "of", "each", "island", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L491-L544
train
PaulHancock/Aegean
AegeanTools/catalogs.py
writeIslandBoxes
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:`AegeanTools.models.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' and 'ann' are supported. Default = 'reg'. Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandContours` """ if fmt not in ['reg', 'ann']: log.warning("Format not supported for island boxes{0}".format(fmt)) return # fmt not supported out = open(filename, 'w') print("#Aegean Islands", file=out) print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) if fmt == 'reg': print("IMAGE", file=out) box_fmt = 'box({0},{1},{2},{3}) #{4}' else: print("COORD P", file=out) box_fmt = 'box P {0} {1} {2} {3} #{4}' for c in catalog: # x/y swap for pyfits/numpy translation ymin, ymax, xmin, xmax = c.extent # +1 for array/image offset xcen = (xmin + xmax) / 2.0 + 1 # + 0.5 in each direction to make lines run 'between' DS9 pixels xwidth = xmax - xmin + 1 ycen = (ymin + ymax) / 2.0 + 1 ywidth = ymax - ymin + 1 print(box_fmt.format(xcen, ycen, xwidth, ywidth, c.island), file=out) out.close() return
python
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:`AegeanTools.models.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' and 'ann' are supported. Default = 'reg'. Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandContours` """ if fmt not in ['reg', 'ann']: log.warning("Format not supported for island boxes{0}".format(fmt)) return # fmt not supported out = open(filename, 'w') print("#Aegean Islands", file=out) print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) if fmt == 'reg': print("IMAGE", file=out) box_fmt = 'box({0},{1},{2},{3}) #{4}' else: print("COORD P", file=out) box_fmt = 'box P {0} {1} {2} {3} #{4}' for c in catalog: # x/y swap for pyfits/numpy translation ymin, ymax, xmin, xmax = c.extent # +1 for array/image offset xcen = (xmin + xmax) / 2.0 + 1 # + 0.5 in each direction to make lines run 'between' DS9 pixels xwidth = xmax - xmin + 1 ycen = (ymin + ymax) / 2.0 + 1 ywidth = ymax - ymin + 1 print(box_fmt.format(xcen, ycen, xwidth, ywidth, c.island), file=out) out.close() return
[ "def", "writeIslandBoxes", "(", "filename", ",", "catalog", ",", "fmt", ")", ":", "if", "fmt", "not", "in", "[", "'reg'", ",", "'ann'", "]", ":", "log", ".", "warning", "(", "\"Format not supported for island boxes{0}\"", ".", "format", "(", "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:`AegeanTools.models.IslandSource` will have contours drawn. fmt : str Output format type. Currently only 'reg' and 'ann' are supported. Default = 'reg'. Returns ------- None See Also -------- :func:`AegeanTools.catalogs.writeIslandContours`
[ "Write", "an", "output", "file", "in", "ds9", ".", "reg", "or", "kvis", ".", "ann", "format", "that", "contains", "bounding", "boxes", "for", "all", "the", "islands", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L547-L596
train
PaulHancock/Aegean
AegeanTools/catalogs.py
writeAnn
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 unless there are none, in which case :class:`AegeanTools.models.SimpleSource` (if present) will be written. If any :class:`AegeanTools.models.IslandSource` objects are present then an island contours file will be written. Parameters ---------- filename : str Output filename base. catalog : list List of sources. fmt : ['ann', 'reg'] Output file type. Returns ------- None See Also -------- AegeanTools.catalogs.writeIslandContours """ if fmt not in ['reg', 'ann']: log.warning("Format not supported for island boxes{0}".format(fmt)) return # fmt not supported components, islands, simples = classify_catalog(catalog) if len(components) > 0: cat = sorted(components) suffix = "comp" elif len(simples) > 0: cat = simples suffix = "simp" else: cat = [] if len(cat) > 0: ras = [a.ra for a in cat] decs = [a.dec for a in cat] if not hasattr(cat[0], 'a'): # a being the variable that I used for bmaj. bmajs = [30 / 3600.0 for a in cat] bmins = bmajs pas = [0 for a in cat] else: bmajs = [a.a / 3600.0 for a in cat] bmins = [a.b / 3600.0 for a in cat] pas = [a.pa for a in cat] names = [a.__repr__() for a in cat] if fmt == 'ann': new_file = re.sub('.ann$', '_{0}.ann'.format(suffix), filename) out = open(new_file, 'w') print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) print('PA SKY', file=out) print('FONT hershey12', file=out) print('COORD W', file=out) formatter = "ELLIPSE W {0} {1} {2} {3} {4:+07.3f} #{5}\nTEXT W {0} {1} {5}" else: # reg new_file = re.sub('.reg$', '_{0}.reg'.format(suffix), filename) out = open(new_file, 'w') print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) print("fk5", file=out) formatter = 'ellipse {0} {1} {2:.9f}d {3:.9f}d {4:+07.3f}d # text="{5}"' # DS9 has some strange ideas about position angle pas = [a - 90 for a in pas] for ra, dec, bmaj, bmin, pa, name in zip(ras, decs, bmajs, bmins, pas, names): # comment out lines that have invalid or stupid entries if np.nan in [ra, dec, bmaj, bmin, pa] or bmaj >= 180: print('#', end=' ', file=out) print(formatter.format(ra, dec, bmaj, bmin, pa, name), file=out) out.close() log.info("wrote {0}".format(new_file)) if len(islands) > 0: if fmt == 'reg': new_file = re.sub('.reg$', '_isle.reg', filename) elif fmt == 'ann': log.warning('kvis islands are currently not working') return else: log.warning('format {0} not supported for island annotations'.format(fmt)) return writeIslandContours(new_file, islands, fmt) log.info("wrote {0}".format(new_file)) return
python
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 unless there are none, in which case :class:`AegeanTools.models.SimpleSource` (if present) will be written. If any :class:`AegeanTools.models.IslandSource` objects are present then an island contours file will be written. Parameters ---------- filename : str Output filename base. catalog : list List of sources. fmt : ['ann', 'reg'] Output file type. Returns ------- None See Also -------- AegeanTools.catalogs.writeIslandContours """ if fmt not in ['reg', 'ann']: log.warning("Format not supported for island boxes{0}".format(fmt)) return # fmt not supported components, islands, simples = classify_catalog(catalog) if len(components) > 0: cat = sorted(components) suffix = "comp" elif len(simples) > 0: cat = simples suffix = "simp" else: cat = [] if len(cat) > 0: ras = [a.ra for a in cat] decs = [a.dec for a in cat] if not hasattr(cat[0], 'a'): # a being the variable that I used for bmaj. bmajs = [30 / 3600.0 for a in cat] bmins = bmajs pas = [0 for a in cat] else: bmajs = [a.a / 3600.0 for a in cat] bmins = [a.b / 3600.0 for a in cat] pas = [a.pa for a in cat] names = [a.__repr__() for a in cat] if fmt == 'ann': new_file = re.sub('.ann$', '_{0}.ann'.format(suffix), filename) out = open(new_file, 'w') print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) print('PA SKY', file=out) print('FONT hershey12', file=out) print('COORD W', file=out) formatter = "ELLIPSE W {0} {1} {2} {3} {4:+07.3f} #{5}\nTEXT W {0} {1} {5}" else: # reg new_file = re.sub('.reg$', '_{0}.reg'.format(suffix), filename) out = open(new_file, 'w') print("#Aegean version {0}-({1})".format(__version__, __date__), file=out) print("fk5", file=out) formatter = 'ellipse {0} {1} {2:.9f}d {3:.9f}d {4:+07.3f}d # text="{5}"' # DS9 has some strange ideas about position angle pas = [a - 90 for a in pas] for ra, dec, bmaj, bmin, pa, name in zip(ras, decs, bmajs, bmins, pas, names): # comment out lines that have invalid or stupid entries if np.nan in [ra, dec, bmaj, bmin, pa] or bmaj >= 180: print('#', end=' ', file=out) print(formatter.format(ra, dec, bmaj, bmin, pa, name), file=out) out.close() log.info("wrote {0}".format(new_file)) if len(islands) > 0: if fmt == 'reg': new_file = re.sub('.reg$', '_isle.reg', filename) elif fmt == 'ann': log.warning('kvis islands are currently not working') return else: log.warning('format {0} not supported for island annotations'.format(fmt)) return writeIslandContours(new_file, islands, fmt) log.info("wrote {0}".format(new_file)) return
[ "def", "writeAnn", "(", "filename", ",", "catalog", ",", "fmt", ")", ":", "if", "fmt", "not", "in", "[", "'reg'", ",", "'ann'", "]", ":", "log", ".", "warning", "(", "\"Format not supported for island boxes{0}\"", ".", "format", "(", "fmt", ")", ")", "re...
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:`AegeanTools.models.SimpleSource` (if present) will be written. If any :class:`AegeanTools.models.IslandSource` objects are present then an island contours file will be written. Parameters ---------- filename : str Output filename base. catalog : list List of sources. fmt : ['ann', 'reg'] Output file type. Returns ------- None See Also -------- AegeanTools.catalogs.writeIslandContours
[ "Write", "an", "annotation", "file", "that", "can", "be", "read", "by", "Kvis", "(", ".", "ann", ")", "or", "DS9", "(", ".", "reg", ")", ".", "Uses", "ra", "/", "dec", "from", "catalog", ".", "Draws", "ellipses", "if", "bmaj", "/", "bmin", "/", "...
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L599-L692
train
PaulHancock/Aegean
AegeanTools/catalogs.py
writeDB
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.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. meta : dict Meta data to be written to table `meta` Returns ------- None """ def sqlTypes(obj, names): """ Return the sql type corresponding to each named parameter in obj """ types = [] for n in names: val = getattr(obj, n) if isinstance(val, bool): types.append("BOOL") elif isinstance(val, (int, np.int64, np.int32)): types.append("INT") elif isinstance(val, (float, np.float64, np.float32)): # float32 is bugged and claims not to be a float types.append("FLOAT") elif isinstance(val, six.string_types): types.append("VARCHAR") else: log.warning("Column {0} is of unknown type {1}".format(n, type(n))) log.warning("Using VARCHAR") types.append("VARCHAR") return types if os.path.exists(filename): log.warning("overwriting {0}".format(filename)) os.remove(filename) conn = sqlite3.connect(filename) db = conn.cursor() # determine the column names by inspecting the catalog class for t, tn in zip(classify_catalog(catalog), ["components", "islands", "simples"]): if len(t) < 1: continue #don't write empty tables col_names = t[0].names col_types = sqlTypes(t[0], col_names) stmnt = ','.join(["{0} {1}".format(a, b) for a, b in zip(col_names, col_types)]) db.execute('CREATE TABLE {0} ({1})'.format(tn, stmnt)) stmnt = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(tn, ','.join(col_names), ','.join(['?' for i in col_names])) # expend the iterators that are created by python 3+ data = list(map(nulls, list(r.as_list() for r in t))) db.executemany(stmnt, data) log.info("Created table {0}".format(tn)) # metadata add some meta data db.execute("CREATE TABLE meta (key VARCHAR, val VARCHAR)") for k in meta: db.execute("INSERT INTO meta (key, val) VALUES (?,?)", (k, meta[k])) conn.commit() log.info(db.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()) conn.close() log.info("Wrote file {0}".format(filename)) return
python
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.models.SimpleSource`, or :class:`AegeanTools.models.IslandSource`. meta : dict Meta data to be written to table `meta` Returns ------- None """ def sqlTypes(obj, names): """ Return the sql type corresponding to each named parameter in obj """ types = [] for n in names: val = getattr(obj, n) if isinstance(val, bool): types.append("BOOL") elif isinstance(val, (int, np.int64, np.int32)): types.append("INT") elif isinstance(val, (float, np.float64, np.float32)): # float32 is bugged and claims not to be a float types.append("FLOAT") elif isinstance(val, six.string_types): types.append("VARCHAR") else: log.warning("Column {0} is of unknown type {1}".format(n, type(n))) log.warning("Using VARCHAR") types.append("VARCHAR") return types if os.path.exists(filename): log.warning("overwriting {0}".format(filename)) os.remove(filename) conn = sqlite3.connect(filename) db = conn.cursor() # determine the column names by inspecting the catalog class for t, tn in zip(classify_catalog(catalog), ["components", "islands", "simples"]): if len(t) < 1: continue #don't write empty tables col_names = t[0].names col_types = sqlTypes(t[0], col_names) stmnt = ','.join(["{0} {1}".format(a, b) for a, b in zip(col_names, col_types)]) db.execute('CREATE TABLE {0} ({1})'.format(tn, stmnt)) stmnt = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(tn, ','.join(col_names), ','.join(['?' for i in col_names])) # expend the iterators that are created by python 3+ data = list(map(nulls, list(r.as_list() for r in t))) db.executemany(stmnt, data) log.info("Created table {0}".format(tn)) # metadata add some meta data db.execute("CREATE TABLE meta (key VARCHAR, val VARCHAR)") for k in meta: db.execute("INSERT INTO meta (key, val) VALUES (?,?)", (k, meta[k])) conn.commit() log.info(db.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()) conn.close() log.info("Wrote file {0}".format(filename)) return
[ "def", "writeDB", "(", "filename", ",", "catalog", ",", "meta", "=", "None", ")", ":", "def", "sqlTypes", "(", "obj", ",", "names", ")", ":", "\"\"\"\n Return the sql type corresponding to each named parameter in obj\n \"\"\"", "types", "=", "[", "]", ...
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.IslandSource`. meta : dict Meta data to be written to table `meta` Returns ------- None
[ "Output", "an", "sqlite3", "database", "containing", "one", "table", "for", "each", "source", "type" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L714-L782
train
PaulHancock/Aegean
AegeanTools/cluster.py
norm_dist
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. For ellipses that touch at a single point, the normalized distance will be 1/sqrt(2). Parameters ---------- src1, src2 : object The two positions to compare. Objects must have the following parameters: (ra, dec, a, b, pa). Returns ------- dist: float The normalised distance. """ if np.all(src1 == src2): return 0 dist = gcd(src1.ra, src1.dec, src2.ra, src2.dec) # degrees # the angle between the ellipse centers phi = bear(src1.ra, src1.dec, src2.ra, src2.dec) # Degrees # Calculate the radius of each ellipse along a line that joins their centers. r1 = src1.a*src1.b / np.hypot(src1.a * np.sin(np.radians(phi - src1.pa)), src1.b * np.cos(np.radians(phi - src1.pa))) r2 = src2.a*src2.b / np.hypot(src2.a * np.sin(np.radians(180 + phi - src2.pa)), src2.b * np.cos(np.radians(180 + phi - src2.pa))) R = dist / (np.hypot(r1, r2) / 3600) return R
python
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. For ellipses that touch at a single point, the normalized distance will be 1/sqrt(2). Parameters ---------- src1, src2 : object The two positions to compare. Objects must have the following parameters: (ra, dec, a, b, pa). Returns ------- dist: float The normalised distance. """ if np.all(src1 == src2): return 0 dist = gcd(src1.ra, src1.dec, src2.ra, src2.dec) # degrees # the angle between the ellipse centers phi = bear(src1.ra, src1.dec, src2.ra, src2.dec) # Degrees # Calculate the radius of each ellipse along a line that joins their centers. r1 = src1.a*src1.b / np.hypot(src1.a * np.sin(np.radians(phi - src1.pa)), src1.b * np.cos(np.radians(phi - src1.pa))) r2 = src2.a*src2.b / np.hypot(src2.a * np.sin(np.radians(180 + phi - src2.pa)), src2.b * np.cos(np.radians(180 + phi - src2.pa))) R = dist / (np.hypot(r1, r2) / 3600) return R
[ "def", "norm_dist", "(", "src1", ",", "src2", ")", ":", "if", "np", ".", "all", "(", "src1", "==", "src2", ")", ":", "return", "0", "dist", "=", "gcd", "(", "src1", ".", "ra", ",", "src1", ".", "dec", ",", "src2", ".", "ra", ",", "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. For ellipses that touch at a single point, the normalized distance will be 1/sqrt(2). Parameters ---------- src1, src2 : object The two positions to compare. Objects must have the following parameters: (ra, dec, a, b, pa). Returns ------- dist: float The normalised distance.
[ "Calculate", "the", "normalised", "distance", "between", "two", "sources", ".", "Sources", "are", "elliptical", "Gaussians", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/cluster.py#L27-L60
train
PaulHancock/Aegean
AegeanTools/cluster.py
sky_dist
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 degrees. Returns ------- distance : float The distance between the two sources. See Also -------- :func:`AegeanTools.angle_tools.gcd` """ if np.all(src1 == src2): return 0 return gcd(src1.ra, src1.dec, src2.ra, src2.dec)
python
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 degrees. Returns ------- distance : float The distance between the two sources. See Also -------- :func:`AegeanTools.angle_tools.gcd` """ if np.all(src1 == src2): return 0 return gcd(src1.ra, src1.dec, src2.ra, src2.dec)
[ "def", "sky_dist", "(", "src1", ",", "src2", ")", ":", "if", "np", ".", "all", "(", "src1", "==", "src2", ")", ":", "return", "0", "return", "gcd", "(", "src1", ".", "ra", ",", "src1", ".", "dec", ",", "src2", ".", "ra", ",", "src2", ".", "de...
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 ------- distance : float The distance between the two sources. See Also -------- :func:`AegeanTools.angle_tools.gcd`
[ "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", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/cluster.py#L63-L86
train
PaulHancock/Aegean
AegeanTools/cluster.py
pairwise_ellpitical_binary
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: ra,dec,a,b,pa) eps : float Normalised distance constraint. far : float If sources have a dec that differs by more than this amount then they are considered to be not matched. This is a short-cut around performing GCD calculations. Returns ------- prob : numpy.ndarray A 2d array of True/False. See Also -------- :func:`AegeanTools.cluster.norm_dist` """ if far is None: far = max(a.a/3600 for a in sources) l = len(sources) distances = np.zeros((l, l), dtype=bool) for i in range(l): for j in range(i, l): if i == j: distances[i, j] = False continue src1 = sources[i] src2 = sources[j] if src2.dec - src1.dec > far: break if abs(src2.ra - src1.ra)*np.cos(np.radians(src1.dec)) > far: continue distances[i, j] = norm_dist(src1, src2) > eps distances[j, i] = distances[i, j] return distances
python
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: ra,dec,a,b,pa) eps : float Normalised distance constraint. far : float If sources have a dec that differs by more than this amount then they are considered to be not matched. This is a short-cut around performing GCD calculations. Returns ------- prob : numpy.ndarray A 2d array of True/False. See Also -------- :func:`AegeanTools.cluster.norm_dist` """ if far is None: far = max(a.a/3600 for a in sources) l = len(sources) distances = np.zeros((l, l), dtype=bool) for i in range(l): for j in range(i, l): if i == j: distances[i, j] = False continue src1 = sources[i] src2 = sources[j] if src2.dec - src1.dec > far: break if abs(src2.ra - src1.ra)*np.cos(np.radians(src1.dec)) > far: continue distances[i, j] = norm_dist(src1, src2) > eps distances[j, i] = distances[i, j] return distances
[ "def", "pairwise_ellpitical_binary", "(", "sources", ",", "eps", ",", "far", "=", "None", ")", ":", "if", "far", "is", "None", ":", "far", "=", "max", "(", "a", ".", "a", "/", "3600", "for", "a", "in", "sources", ")", "l", "=", "len", "(", "sourc...
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 constraint. far : float If sources have a dec that differs by more than this amount then they are considered to be not matched. This is a short-cut around performing GCD calculations. Returns ------- prob : numpy.ndarray A 2d array of True/False. See Also -------- :func:`AegeanTools.cluster.norm_dist`
[ "Do", "a", "pairwise", "comparison", "of", "all", "sources", "and", "determine", "if", "they", "have", "a", "normalized", "distance", "within", "eps", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/cluster.py#L89-L135
train
PaulHancock/Aegean
AegeanTools/cluster.py
regroup_vectorized
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 Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance apart will not be grouped, and will not be tested. Default = 0.5. dist : func a function that calculates the distance between a source and each element of an array of sources. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list of lists Each island contians integer indices for members from srccat (in descending dec order). """ if far is None: far = 0.5 # 10*max(a.a/3600 for a in srccat) # most negative declination first # XXX: kind='mergesort' ensures stable sorting for determinism. # Do we need this? order = np.argsort(srccat.dec, kind='mergesort')[::-1] # TODO: is it better to store groups as arrays even if appends are more # costly? groups = [[order[0]]] for idx in order[1:]: rec = srccat[idx] # TODO: Find out if groups are big enough for this to give us a speed # gain. If not, get distance to all entries in groups above # decmin simultaneously. decmin = rec.dec - far for group in reversed(groups): # when an island's largest (last) declination is smaller than # decmin, we don't need to look at any more islands if srccat.dec[group[-1]] < decmin: # new group groups.append([idx]) rafar = far / np.cos(np.radians(rec.dec)) group_recs = np.take(srccat, group, mode='clip') group_recs = group_recs[abs(rec.ra - group_recs.ra) <= rafar] if len(group_recs) and dist(rec, group_recs).min() < eps: group.append(idx) break else: # new group groups.append([idx]) # TODO?: a more numpy-like interface would return only an array providing # the mapping: # group_idx = np.empty(len(srccat), dtype=int) # for i, group in enumerate(groups): # group_idx[group] = i # return group_idx return groups
python
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 Should have the following fields[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance apart will not be grouped, and will not be tested. Default = 0.5. dist : func a function that calculates the distance between a source and each element of an array of sources. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list of lists Each island contians integer indices for members from srccat (in descending dec order). """ if far is None: far = 0.5 # 10*max(a.a/3600 for a in srccat) # most negative declination first # XXX: kind='mergesort' ensures stable sorting for determinism. # Do we need this? order = np.argsort(srccat.dec, kind='mergesort')[::-1] # TODO: is it better to store groups as arrays even if appends are more # costly? groups = [[order[0]]] for idx in order[1:]: rec = srccat[idx] # TODO: Find out if groups are big enough for this to give us a speed # gain. If not, get distance to all entries in groups above # decmin simultaneously. decmin = rec.dec - far for group in reversed(groups): # when an island's largest (last) declination is smaller than # decmin, we don't need to look at any more islands if srccat.dec[group[-1]] < decmin: # new group groups.append([idx]) rafar = far / np.cos(np.radians(rec.dec)) group_recs = np.take(srccat, group, mode='clip') group_recs = group_recs[abs(rec.ra - group_recs.ra) <= rafar] if len(group_recs) and dist(rec, group_recs).min() < eps: group.append(idx) break else: # new group groups.append([idx]) # TODO?: a more numpy-like interface would return only an array providing # the mapping: # group_idx = np.empty(len(srccat), dtype=int) # for i, group in enumerate(groups): # group_idx[group] = i # return group_idx return groups
[ "def", "regroup_vectorized", "(", "srccat", ",", "eps", ",", "far", "=", "None", ",", "dist", "=", "norm_dist", ")", ":", "if", "far", "is", "None", ":", "far", "=", "0.5", "# 10*max(a.a/3600 for a in srccat)", "# most negative declination first", "# XXX: kind='me...
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[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance apart will not be grouped, and will not be tested. Default = 0.5. dist : func a function that calculates the distance between a source and each element of an array of sources. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list of lists Each island contians integer indices for members from srccat (in descending dec order).
[ "Regroup", "the", "islands", "of", "a", "catalog", "according", "to", "their", "normalised", "distance", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/cluster.py#L138-L206
train
PaulHancock/Aegean
AegeanTools/cluster.py
regroup
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 read into a source list, or a list of objects with the following properties[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance appart will not be grouped, and will not be tested. Default = None. dist : func a function that calculates the distance between two sources must accept two SimpleSource objects. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list A list of islands. Each island is a list of sources. See Also -------- :func:`AegeanTools.cluster.norm_dist` """ if isinstance(catalog, str): table = load_table(catalog) srccat = table_to_source_list(table) else: try: srccat = catalog _ = catalog[0].ra, catalog[0].dec, catalog[0].a, catalog[0].b, catalog[0].pa, catalog[0].peak_flux except AttributeError as e: log.error("catalog is not understood.") log.error("catalog: Should be a list of objects with the following properties[units]:\n" + "ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any]") raise e log.info("Regrouping islands within catalog") log.debug("Calculating distances") if far is None: far = 0.5 # 10*max(a.a/3600 for a in srccat) srccat_array = np.rec.fromrecords( [(s.ra, s.dec, s.a, s.b, s.pa, s.peak_flux) for s in srccat], names=['ra', 'dec', 'a', 'b', 'pa', 'peak_flux']) groups = regroup_vectorized(srccat_array, eps=eps, far=far, dist=dist) groups = [[srccat[idx] for idx in group] for group in groups] islands = [] # now that we have the groups, we relabel the sources to have (island,component) in flux order # note that the order of sources within an island list is not changed - just their labels for isle, group in enumerate(groups): for comp, src in enumerate(sorted(group, key=lambda x: -1*x.peak_flux)): src.island = isle src.source = comp islands.append(group) return islands
python
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 read into a source list, or a list of objects with the following properties[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance appart will not be grouped, and will not be tested. Default = None. dist : func a function that calculates the distance between two sources must accept two SimpleSource objects. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list A list of islands. Each island is a list of sources. See Also -------- :func:`AegeanTools.cluster.norm_dist` """ if isinstance(catalog, str): table = load_table(catalog) srccat = table_to_source_list(table) else: try: srccat = catalog _ = catalog[0].ra, catalog[0].dec, catalog[0].a, catalog[0].b, catalog[0].pa, catalog[0].peak_flux except AttributeError as e: log.error("catalog is not understood.") log.error("catalog: Should be a list of objects with the following properties[units]:\n" + "ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any]") raise e log.info("Regrouping islands within catalog") log.debug("Calculating distances") if far is None: far = 0.5 # 10*max(a.a/3600 for a in srccat) srccat_array = np.rec.fromrecords( [(s.ra, s.dec, s.a, s.b, s.pa, s.peak_flux) for s in srccat], names=['ra', 'dec', 'a', 'b', 'pa', 'peak_flux']) groups = regroup_vectorized(srccat_array, eps=eps, far=far, dist=dist) groups = [[srccat[idx] for idx in group] for group in groups] islands = [] # now that we have the groups, we relabel the sources to have (island,component) in flux order # note that the order of sources within an island list is not changed - just their labels for isle, group in enumerate(groups): for comp, src in enumerate(sorted(group, key=lambda x: -1*x.peak_flux)): src.island = isle src.source = comp islands.append(group) return islands
[ "def", "regroup", "(", "catalog", ",", "eps", ",", "far", "=", "None", ",", "dist", "=", "norm_dist", ")", ":", "if", "isinstance", "(", "catalog", ",", "str", ")", ":", "table", "=", "load_table", "(", "catalog", ")", "srccat", "=", "table_to_source_l...
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 properties[units]: ra[deg],dec[deg], a[arcsec],b[arcsec],pa[deg], peak_flux[any] eps : float maximum normalised distance within which sources are considered to be grouped far : float (degrees) sources that are further than this distance appart will not be grouped, and will not be tested. Default = None. dist : func a function that calculates the distance between two sources must accept two SimpleSource objects. Default = :func:`AegeanTools.cluster.norm_dist` Returns ------- islands : list A list of islands. Each island is a list of sources. See Also -------- :func:`AegeanTools.cluster.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", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/cluster.py#L209-L278
train
PaulHancock/Aegean
AegeanTools/fits_interp.py
load_file_or_hdu
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(filename, fits.HDUList): hdulist = filename else: hdulist = fits.open(filename, ignore_missing_end=True) return hdulist
python
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(filename, fits.HDUList): hdulist = filename else: hdulist = fits.open(filename, ignore_missing_end=True) return hdulist
[ "def", "load_file_or_hdu", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "fits", ".", "HDUList", ")", ":", "hdulist", "=", "filename", "else", ":", "hdulist", "=", "fits", ".", "open", "(", "filename", ",", "ignore_missing_end", "=",...
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
[ "Load", "a", "file", "from", "disk", "and", "return", "an", "HDUList", "If", "filename", "is", "already", "an", "HDUList", "return", "that", "instead" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fits_interp.py#L16-L34
train
PaulHancock/Aegean
AegeanTools/fits_interp.py
compress
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. Default = None, which means don't write a file. Returns ------- hdulist : HDUList A decimated HDUList See Also -------- :func:`AegeanTools.fits_interp.expand` """ if not (factor > 0 and isinstance(factor, int)): logging.error("factor must be a positive integer") return None hdulist = load_file_or_hdu(datafile) header = hdulist[0].header data = np.squeeze(hdulist[0].data) cx, cy = data.shape[0], data.shape[1] nx = cx // factor ny = cy // factor # check to see if we will have some residual data points lcx = cx % factor lcy = cy % factor if lcx > 0: nx += 1 if lcy > 0: ny += 1 # decimate the data new_data = np.empty((nx + 1, ny + 1)) new_data[:nx, :ny] = data[::factor, ::factor] # copy the last row/col across new_data[-1, :ny] = data[-1, ::factor] new_data[:nx, -1] = data[::factor, -1] new_data[-1, -1] = data[-1, -1] # TODO: Figure out what to do when CD2_1 and CD1_2 are non-zero if 'CDELT1' in header: header['CDELT1'] *= factor elif 'CD1_1' in header: header['CD1_1'] *= factor else: logging.error("Error: Can't find CDELT1 or CD1_1") return None if 'CDELT2' in header: header['CDELT2'] *= factor elif "CD2_2" in header: header['CD2_2'] *= factor else: logging.error("Error: Can't find CDELT2 or CD2_2") return None # Move the reference pixel so that the WCS is correct header['CRPIX1'] = (header['CRPIX1'] + factor - 1) / factor header['CRPIX2'] = (header['CRPIX2'] + factor - 1) / factor # Update the header so that we can do the correct interpolation later on header['BN_CFAC'] = (factor, "Compression factor (grid size) used by BANE") header['BN_NPX1'] = (header['NAXIS1'], 'original NAXIS1 value') header['BN_NPX2'] = (header['NAXIS2'], 'original NAXIS2 value') header['BN_RPX1'] = (lcx, 'Residual on axis 1') header['BN_RPX2'] = (lcy, 'Residual on axis 2') header['HISTORY'] = "Compressed by a factor of {0}".format(factor) # save the changes hdulist[0].data = np.array(new_data, dtype=np.float32) hdulist[0].header = header if outfile is not None: hdulist.writeto(outfile, overwrite=True) logging.info("Wrote: {0}".format(outfile)) return hdulist
python
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. Default = None, which means don't write a file. Returns ------- hdulist : HDUList A decimated HDUList See Also -------- :func:`AegeanTools.fits_interp.expand` """ if not (factor > 0 and isinstance(factor, int)): logging.error("factor must be a positive integer") return None hdulist = load_file_or_hdu(datafile) header = hdulist[0].header data = np.squeeze(hdulist[0].data) cx, cy = data.shape[0], data.shape[1] nx = cx // factor ny = cy // factor # check to see if we will have some residual data points lcx = cx % factor lcy = cy % factor if lcx > 0: nx += 1 if lcy > 0: ny += 1 # decimate the data new_data = np.empty((nx + 1, ny + 1)) new_data[:nx, :ny] = data[::factor, ::factor] # copy the last row/col across new_data[-1, :ny] = data[-1, ::factor] new_data[:nx, -1] = data[::factor, -1] new_data[-1, -1] = data[-1, -1] # TODO: Figure out what to do when CD2_1 and CD1_2 are non-zero if 'CDELT1' in header: header['CDELT1'] *= factor elif 'CD1_1' in header: header['CD1_1'] *= factor else: logging.error("Error: Can't find CDELT1 or CD1_1") return None if 'CDELT2' in header: header['CDELT2'] *= factor elif "CD2_2" in header: header['CD2_2'] *= factor else: logging.error("Error: Can't find CDELT2 or CD2_2") return None # Move the reference pixel so that the WCS is correct header['CRPIX1'] = (header['CRPIX1'] + factor - 1) / factor header['CRPIX2'] = (header['CRPIX2'] + factor - 1) / factor # Update the header so that we can do the correct interpolation later on header['BN_CFAC'] = (factor, "Compression factor (grid size) used by BANE") header['BN_NPX1'] = (header['NAXIS1'], 'original NAXIS1 value') header['BN_NPX2'] = (header['NAXIS2'], 'original NAXIS2 value') header['BN_RPX1'] = (lcx, 'Residual on axis 1') header['BN_RPX2'] = (lcy, 'Residual on axis 2') header['HISTORY'] = "Compressed by a factor of {0}".format(factor) # save the changes hdulist[0].data = np.array(new_data, dtype=np.float32) hdulist[0].header = header if outfile is not None: hdulist.writeto(outfile, overwrite=True) logging.info("Wrote: {0}".format(outfile)) return hdulist
[ "def", "compress", "(", "datafile", ",", "factor", ",", "outfile", "=", "None", ")", ":", "if", "not", "(", "factor", ">", "0", "and", "isinstance", "(", "factor", ",", "int", ")", ")", ":", "logging", ".", "error", "(", "\"factor must be a positive inte...
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 ------- hdulist : HDUList A decimated HDUList See Also -------- :func:`AegeanTools.fits_interp.expand`
[ "Compress", "a", "file", "using", "decimation", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fits_interp.py#L37-L121
train
PaulHancock/Aegean
AegeanTools/fits_interp.py
expand
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. Parameters ---------- datafile : str or HDUList filename or HDUList of file to work on outfile : str filename to write to (default = None) Returns ------- hdulist : HDUList HDUList of the expanded data. See Also -------- :func:`AegeanTools.fits_interp.compress` """ hdulist = load_file_or_hdu(datafile) header = hdulist[0].header data = hdulist[0].data # Check for the required key words, only expand if they exist if not all(a in header for a in ['BN_CFAC', 'BN_NPX1', 'BN_NPX2', 'BN_RPX1', 'BN_RPX2']): return hdulist factor = header['BN_CFAC'] (gx, gy) = np.mgrid[0:header['BN_NPX2'], 0:header['BN_NPX1']] # fix the last column of the grid to account for residuals lcx = header['BN_RPX2'] lcy = header['BN_RPX1'] rows = (np.arange(data.shape[0]) + int(lcx/factor))*factor cols = (np.arange(data.shape[1]) + int(lcy/factor))*factor # Do the interpolation hdulist[0].data = np.array(RegularGridInterpolator((rows,cols), data)((gx, gy)), dtype=np.float32) # update the fits keywords so that the WCS is correct header['CRPIX1'] = (header['CRPIX1'] - 1) * factor + 1 header['CRPIX2'] = (header['CRPIX2'] - 1) * factor + 1 if 'CDELT1' in header: header['CDELT1'] /= factor elif 'CD1_1' in header: header['CD1_1'] /= factor else: logging.error("Error: Can't find CD1_1 or CDELT1") return None if 'CDELT2' in header: header['CDELT2'] /= factor elif "CD2_2" in header: header['CD2_2'] /= factor else: logging.error("Error: Can't find CDELT2 or CD2_2") return None header['HISTORY'] = 'Expanded by factor {0}'.format(factor) # don't need these any more so delete them. del header['BN_CFAC'], header['BN_NPX1'], header['BN_NPX2'], header['BN_RPX1'], header['BN_RPX2'] hdulist[0].header = header if outfile is not None: hdulist.writeto(outfile, overwrite=True) logging.info("Wrote: {0}".format(outfile)) return hdulist
python
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. Parameters ---------- datafile : str or HDUList filename or HDUList of file to work on outfile : str filename to write to (default = None) Returns ------- hdulist : HDUList HDUList of the expanded data. See Also -------- :func:`AegeanTools.fits_interp.compress` """ hdulist = load_file_or_hdu(datafile) header = hdulist[0].header data = hdulist[0].data # Check for the required key words, only expand if they exist if not all(a in header for a in ['BN_CFAC', 'BN_NPX1', 'BN_NPX2', 'BN_RPX1', 'BN_RPX2']): return hdulist factor = header['BN_CFAC'] (gx, gy) = np.mgrid[0:header['BN_NPX2'], 0:header['BN_NPX1']] # fix the last column of the grid to account for residuals lcx = header['BN_RPX2'] lcy = header['BN_RPX1'] rows = (np.arange(data.shape[0]) + int(lcx/factor))*factor cols = (np.arange(data.shape[1]) + int(lcy/factor))*factor # Do the interpolation hdulist[0].data = np.array(RegularGridInterpolator((rows,cols), data)((gx, gy)), dtype=np.float32) # update the fits keywords so that the WCS is correct header['CRPIX1'] = (header['CRPIX1'] - 1) * factor + 1 header['CRPIX2'] = (header['CRPIX2'] - 1) * factor + 1 if 'CDELT1' in header: header['CDELT1'] /= factor elif 'CD1_1' in header: header['CD1_1'] /= factor else: logging.error("Error: Can't find CD1_1 or CDELT1") return None if 'CDELT2' in header: header['CDELT2'] /= factor elif "CD2_2" in header: header['CD2_2'] /= factor else: logging.error("Error: Can't find CDELT2 or CD2_2") return None header['HISTORY'] = 'Expanded by factor {0}'.format(factor) # don't need these any more so delete them. del header['BN_CFAC'], header['BN_NPX1'], header['BN_NPX2'], header['BN_RPX1'], header['BN_RPX2'] hdulist[0].header = header if outfile is not None: hdulist.writeto(outfile, overwrite=True) logging.info("Wrote: {0}".format(outfile)) return hdulist
[ "def", "expand", "(", "datafile", ",", "outfile", "=", "None", ")", ":", "hdulist", "=", "load_file_or_hdu", "(", "datafile", ")", "header", "=", "hdulist", "[", "0", "]", ".", "header", "data", "=", "hdulist", "[", "0", "]", ".", "data", "# Check for ...
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 HDUList filename or HDUList of file to work on outfile : str filename to write to (default = None) Returns ------- hdulist : HDUList HDUList of the expanded data. See Also -------- :func:`AegeanTools.fits_interp.compress`
[ "Expand", "and", "interpolate", "the", "given", "data", "file", "using", "the", "given", "method", ".", "Datafile", "can", "be", "a", "filename", "or", "an", "HDUList" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fits_interp.py#L124-L198
train
bgschiller/postgres_kernel
postgres_kernel/kernel.py
PostgresKernel.change_autocommit_mode
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() if not parsed_switch in ['true', 'false']: self.send_response( self.iopub_socket, 'stream', { 'name': 'stderr', 'text': 'autocommit must be true or false.\n\n' } ) switch_bool = (parsed_switch == 'true') committed = self.switch_autocommit(switch_bool) message = ( 'committed current transaction & ' if committed else '' + 'switched autocommit mode to ' + str(self._autocommit) ) self.send_response( self.iopub_socket, 'stream', { 'name': 'stderr', 'text': message, } )
python
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() if not parsed_switch in ['true', 'false']: self.send_response( self.iopub_socket, 'stream', { 'name': 'stderr', 'text': 'autocommit must be true or false.\n\n' } ) switch_bool = (parsed_switch == 'true') committed = self.switch_autocommit(switch_bool) message = ( 'committed current transaction & ' if committed else '' + 'switched autocommit mode to ' + str(self._autocommit) ) self.send_response( self.iopub_socket, 'stream', { 'name': 'stderr', 'text': message, } )
[ "def", "change_autocommit_mode", "(", "self", ",", "switch", ")", ":", "parsed_switch", "=", "switch", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "not", "parsed_switch", "in", "[", "'true'", ",", "'false'", "]", ":", "self", ".", "send_respons...
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.
[ "Strip", "and", "make", "a", "string", "case", "insensitive", "and", "ensure", "it", "is", "either", "true", "or", "false", "." ]
523c4f3b7057ca165d7c0407fd8cc865c793be30
https://github.com/bgschiller/postgres_kernel/blob/523c4f3b7057ca165d7c0407fd8cc865c793be30/postgres_kernel/kernel.py#L125-L153
train
dcwatson/django-pgcrypto
pgcrypto/base.py
armor
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.b64encode(data) # The 24-bit CRC should be in big-endian, strip off the first byte (it's already masked in crc24). crc = base64.b64encode(struct.pack('>L', crc24(data))[1:]) return template % { 'headers': 'Version: django-pgcrypto %s\n\n' % __version__ if versioned else '\n', 'body': body.decode('ascii'), 'crc': crc.decode('ascii'), }
python
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.b64encode(data) # The 24-bit CRC should be in big-endian, strip off the first byte (it's already masked in crc24). crc = base64.b64encode(struct.pack('>L', crc24(data))[1:]) return template % { 'headers': 'Version: django-pgcrypto %s\n\n' % __version__ if versioned else '\n', 'body': body.decode('ascii'), 'crc': crc.decode('ascii'), }
[ "def", "armor", "(", "data", ",", "versioned", "=", "True", ")", ":", "template", "=", "'-----BEGIN PGP MESSAGE-----\\n%(headers)s%(body)s\\n=%(crc)s\\n-----END PGP MESSAGE-----'", "body", "=", "base64", ".", "b64encode", "(", "data", ")", "# The 24-bit CRC should be in big...
Returns a string in ASCII Armor format, for the given binary data. The output of this is compatiple with pgcrypto's armor/dearmor functions.
[ "Returns", "a", "string", "in", "ASCII", "Armor", "format", "for", "the", "given", "binary", "data", ".", "The", "output", "of", "this", "is", "compatiple", "with", "pgcrypto", "s", "armor", "/", "dearmor", "functions", "." ]
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/base.py#L33-L46
train
dcwatson/django-pgcrypto
pgcrypto/base.py
dearmor
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. """ lines = text.strip().split('\n') data_lines = [] check_data = None started = False in_body = False for line in lines: if line.startswith('-----BEGIN'): started = True elif line.startswith('-----END'): break elif started: if in_body: if line.startswith('='): # Once we get the checksum data, we're done. check_data = line[1:5].encode('ascii') break else: # This is part of the base64-encoded data. data_lines.append(line) else: if line.strip(): # This is a header line, which we basically ignore for now. pass else: # The data starts after an empty line. in_body = True b64_str = ''.join(data_lines) # Python 3's b64decode expects bytes, not a string. We know base64 is ASCII, though. data = base64.b64decode(b64_str.encode('ascii')) if verify and check_data: # The 24-bit CRC is in big-endian, so we add a null byte to the beginning. crc = struct.unpack('>L', b'\0' + base64.b64decode(check_data))[0] if crc != crc24(data): raise BadChecksumError() return data
python
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. """ lines = text.strip().split('\n') data_lines = [] check_data = None started = False in_body = False for line in lines: if line.startswith('-----BEGIN'): started = True elif line.startswith('-----END'): break elif started: if in_body: if line.startswith('='): # Once we get the checksum data, we're done. check_data = line[1:5].encode('ascii') break else: # This is part of the base64-encoded data. data_lines.append(line) else: if line.strip(): # This is a header line, which we basically ignore for now. pass else: # The data starts after an empty line. in_body = True b64_str = ''.join(data_lines) # Python 3's b64decode expects bytes, not a string. We know base64 is ASCII, though. data = base64.b64decode(b64_str.encode('ascii')) if verify and check_data: # The 24-bit CRC is in big-endian, so we add a null byte to the beginning. crc = struct.unpack('>L', b'\0' + base64.b64decode(check_data))[0] if crc != crc24(data): raise BadChecksumError() return data
[ "def", "dearmor", "(", "text", ",", "verify", "=", "True", ")", ":", "lines", "=", "text", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "data_lines", "=", "[", "]", "check_data", "=", "None", "started", "=", "False", "in_body", "=", "Fa...
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", "decod...
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/base.py#L49-L90
train
dcwatson/django-pgcrypto
pgcrypto/base.py
unpad
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). """ end = len(text) if end == 0: return text padch = ord_safe(text[end - 1]) if padch > block_size: # If the last byte value is larger than the block size, it's not padded. return text while end > 0 and ord_safe(text[end - 1]) in (0, padch): end -= 1 return text[:end]
python
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). """ end = len(text) if end == 0: return text padch = ord_safe(text[end - 1]) if padch > block_size: # If the last byte value is larger than the block size, it's not padded. return text while end > 0 and ord_safe(text[end - 1]) in (0, padch): end -= 1 return text[:end]
[ "def", "unpad", "(", "text", ",", "block_size", ")", ":", "end", "=", "len", "(", "text", ")", "if", "end", "==", "0", ":", "return", "text", "padch", "=", "ord_safe", "(", "text", "[", "end", "-", "1", "]", ")", "if", "padch", ">", "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", "...
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/base.py#L93-L109
train
dcwatson/django-pgcrypto
pgcrypto/base.py
pad
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 = block_size - (len(text) % block_size) ch = b'\0' if zero else chr(num).encode('latin-1') return text + (ch * num)
python
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 = block_size - (len(text) % block_size) ch = b'\0' if zero else chr(num).encode('latin-1') return text + (ch * num)
[ "def", "pad", "(", "text", ",", "block_size", ",", "zero", "=", "False", ")", ":", "num", "=", "block_size", "-", "(", "len", "(", "text", ")", "%", "block_size", ")", "ch", "=", "b'\\0'", "if", "zero", "else", "chr", "(", "num", ")", ".", "encod...
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.
[ "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", ...
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/base.py#L112-L120
train
dcwatson/django-pgcrypto
pgcrypto/base.py
aes_pad_key
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) elif len(key) < 24: return pad(key, 24, zero=True) else: return pad(key[:32], 32, zero=True)
python
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) elif len(key) < 24: return pad(key, 24, zero=True) else: return pad(key[:32], 32, zero=True)
[ "def", "aes_pad_key", "(", "key", ")", ":", "if", "len", "(", "key", ")", "in", "(", "16", ",", "24", ",", "32", ")", ":", "return", "key", "if", "len", "(", "key", ")", "<", "16", ":", "return", "pad", "(", "key", ",", "16", ",", "zero", "...
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).
[ "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...
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/base.py#L123-L135
train
dcwatson/django-pgcrypto
pgcrypto/fields.py
BaseEncryptedField.deconstruct
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.charset, 'check_armor': self.check_armor, 'versioned': self.versioned, }) return name, path, args, kwargs
python
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.charset, 'check_armor': self.check_armor, 'versioned': self.versioned, }) return name, path, args, kwargs
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", "BaseEncryptedField", ",", "self", ")", ".", "deconstruct", "(", ")", "kwargs", ".", "update", "(", "{", "#'key': self.cipher_key,", "'cipher'"...
Deconstruct the field for Django 1.7+ migrations.
[ "Deconstruct", "the", "field", "for", "Django", "1", ".", "7", "+", "migrations", "." ]
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/fields.py#L47-L59
train
dcwatson/django-pgcrypto
pgcrypto/fields.py
BaseEncryptedField.get_cipher
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 self.cipher_class.new(self.cipher_key, self.cipher_class.MODE_CBC, b'\0' * self.cipher_class.block_size)
python
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 self.cipher_class.new(self.cipher_key, self.cipher_class.MODE_CBC, b'\0' * self.cipher_class.block_size)
[ "def", "get_cipher", "(", "self", ")", ":", "return", "self", ".", "cipher_class", ".", "new", "(", "self", ".", "cipher_key", ",", "self", ".", "cipher_class", ".", "MODE_CBC", ",", "b'\\0'", "*", "self", ".", "cipher_class", ".", "block_size", ")" ]
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", "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", ...
02108795ec97f80af92ff6800a1c55eb958c3496
https://github.com/dcwatson/django-pgcrypto/blob/02108795ec97f80af92ff6800a1c55eb958c3496/pgcrypto/fields.py#L61-L67
train
click-contrib/click-configfile
setup.py
find_packages_by_root_package
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, root_package) return packages
python
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, root_package) return packages
[ "def", "find_packages_by_root_package", "(", "where", ")", ":", "root_package", "=", "os", ".", "path", ".", "basename", "(", "where", ")", "packages", "=", "[", "\"%s.%s\"", "%", "(", "root_package", ",", "sub_package", ")", "for", "sub_package", "in", "fin...
Better than excluding everything that is not needed, collect only what is needed.
[ "Better", "than", "excluding", "everything", "that", "is", "not", "needed", "collect", "only", "what", "is", "needed", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/setup.py#L25-L33
train
click-contrib/click-configfile
setup.py
make_long_description
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: A configuration file, like: .. code-block:: INI # -- FILE: foo.ini [foo] flag = yes name = Alice and Bob numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt [person.alice] name = Alice birthyear = 1995 [person.bob] name = Bob birthyear = 2001 can be processed with: .. code-block:: python # EXAMPLE: """ if intro is None: intro = inspect.getdoc(make_long_description) with open("README.rst", "r") as infile: line = infile.readline() while not line.strip().startswith(marker): line = infile.readline() # -- COLLECT REMAINING: Usage example contents = infile.read() text = intro +"\n" + contents return text
python
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: A configuration file, like: .. code-block:: INI # -- FILE: foo.ini [foo] flag = yes name = Alice and Bob numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt [person.alice] name = Alice birthyear = 1995 [person.bob] name = Bob birthyear = 2001 can be processed with: .. code-block:: python # EXAMPLE: """ if intro is None: intro = inspect.getdoc(make_long_description) with open("README.rst", "r") as infile: line = infile.readline() while not line.strip().startswith(marker): line = infile.readline() # -- COLLECT REMAINING: Usage example contents = infile.read() text = intro +"\n" + contents return text
[ "def", "make_long_description", "(", "marker", "=", "None", ",", "intro", "=", "None", ")", ":", "if", "intro", "is", "None", ":", "intro", "=", "inspect", ".", "getdoc", "(", "make_long_description", ")", "with", "open", "(", "\"README.rst\"", ",", "\"r\"...
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 # -- FILE: foo.ini [foo] flag = yes name = Alice and Bob numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt [person.alice] name = Alice birthyear = 1995 [person.bob] name = Bob birthyear = 2001 can be processed with: .. code-block:: python # 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", "...
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/setup.py#L35-L83
train
thefab/tornadis
tornadis/pubsub.py
PubSubClient.pubsub_pop_message
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 object in case of connection errors or ClientError object if you are not subscribed) """ if not self.subscribed: excep = ClientError("you must subscribe before using " "pubsub_pop_message") raise tornado.gen.Return(excep) reply = None try: reply = self._reply_list.pop(0) raise tornado.gen.Return(reply) except IndexError: pass if deadline is not None: td = timedelta(seconds=deadline) yield self._condition.wait(timeout=td) else: yield self._condition.wait() try: reply = self._reply_list.pop(0) except IndexError: pass raise tornado.gen.Return(reply)
python
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 object in case of connection errors or ClientError object if you are not subscribed) """ if not self.subscribed: excep = ClientError("you must subscribe before using " "pubsub_pop_message") raise tornado.gen.Return(excep) reply = None try: reply = self._reply_list.pop(0) raise tornado.gen.Return(reply) except IndexError: pass if deadline is not None: td = timedelta(seconds=deadline) yield self._condition.wait(timeout=td) else: yield self._condition.wait() try: reply = self._reply_list.pop(0) except IndexError: pass raise tornado.gen.Return(reply)
[ "def", "pubsub_pop_message", "(", "self", ",", "deadline", "=", "None", ")", ":", "if", "not", "self", ".", "subscribed", ":", "excep", "=", "ClientError", "(", "\"you must subscribe before using \"", "\"pubsub_pop_message\"", ")", "raise", "tornado", ".", "gen", ...
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 ClientError object if you are not subscribed)
[ "Pops", "a", "message", "for", "a", "subscribed", "client", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pubsub.py#L140-L170
train
creare-com/pydem
pydem/dem_processing.py
_get_flat_ids
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 ----------- assigned : ndarray[ndim=2, dtype=int] The labeled image. For example, the result of calling scipy.ndimage.label on a binary image Returns -------- I : ndarray[ndim=1, dtype=int] Array of 1d coordinate indices of all regions in the image region_ids : ndarray[shape=[n_features + 1], dtype=int] Indexing array used to separate the coordinates of the different regions. For example, region k has xy coordinates of xy[region_ids[k]:region_ids[k+1], :] labels : ndarray[ndim=1, dtype=int] The labels of the regions in the image corresponding to the coordinates For example, assigned.ravel()[I[k]] == labels[k] """ # MPU optimization: # Let's segment the regions and store in a sparse format # First, let's use where once to find all the information we want ids_labels = np.arange(len(assigned.ravel()), 'int64') I = ids_labels[assigned.ravel().astype(bool)] labels = assigned.ravel()[I] # Now sort these arrays by the label to figure out where to segment sort_id = np.argsort(labels) labels = labels[sort_id] I = I[sort_id] # this should be of size n_features-1 region_ids = np.where(labels[1:] - labels[:-1] > 0)[0] + 1 # This should be of size n_features + 1 region_ids = np.concatenate(([0], region_ids, [len(labels)])) return [I, region_ids, labels]
python
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 ----------- assigned : ndarray[ndim=2, dtype=int] The labeled image. For example, the result of calling scipy.ndimage.label on a binary image Returns -------- I : ndarray[ndim=1, dtype=int] Array of 1d coordinate indices of all regions in the image region_ids : ndarray[shape=[n_features + 1], dtype=int] Indexing array used to separate the coordinates of the different regions. For example, region k has xy coordinates of xy[region_ids[k]:region_ids[k+1], :] labels : ndarray[ndim=1, dtype=int] The labels of the regions in the image corresponding to the coordinates For example, assigned.ravel()[I[k]] == labels[k] """ # MPU optimization: # Let's segment the regions and store in a sparse format # First, let's use where once to find all the information we want ids_labels = np.arange(len(assigned.ravel()), 'int64') I = ids_labels[assigned.ravel().astype(bool)] labels = assigned.ravel()[I] # Now sort these arrays by the label to figure out where to segment sort_id = np.argsort(labels) labels = labels[sort_id] I = I[sort_id] # this should be of size n_features-1 region_ids = np.where(labels[1:] - labels[:-1] > 0)[0] + 1 # This should be of size n_features + 1 region_ids = np.concatenate(([0], region_ids, [len(labels)])) return [I, region_ids, labels]
[ "def", "_get_flat_ids", "(", "assigned", ")", ":", "# MPU optimization:", "# Let's segment the regions and store in a sparse format", "# First, let's use where once to find all the information we want", "ids_labels", "=", "np", ".", "arange", "(", "len", "(", "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 ----------- assigned : ndarray[ndim=2, dtype=int] The labeled image. For example, the result of calling scipy.ndimage.label on a binary image Returns -------- I : ndarray[ndim=1, dtype=int] Array of 1d coordinate indices of all regions in the image region_ids : ndarray[shape=[n_features + 1], dtype=int] Indexing array used to separate the coordinates of the different regions. For example, region k has xy coordinates of xy[region_ids[k]:region_ids[k+1], :] labels : ndarray[ndim=1, dtype=int] The labels of the regions in the image corresponding to the coordinates For example, assigned.ravel()[I[k]] == labels[k]
[ "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",...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2364-L2404
train
creare-com/pydem
pydem/dem_processing.py
_tarboton_slopes_directions
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') mag = np.full(data.shape, FLAT_ID_INT, 'float64') slc0 = [slice(1, -1), slice(1, -1)] for ind in xrange(8): e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(1 + e1[0], shp[0] + e1[0]), slice(1 + e1[1], shp[1] + e1[1])] slc2 = [slice(1 + e2[0], shp[0] + e2[0]), slice(1 + e2[1], shp[1] + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp) mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # %%Now do the edges # if the edge is lower than the interior, we need to copy the value # from the interior (as an approximation) ids1 = (direction[:, 1] > np.pi / 2) \ & (direction[:, 1] < 3 * np.pi / 2) direction[ids1, 0] = direction[ids1, 1] mag[ids1, 0] = mag[ids1, 1] ids1 = (direction[:, -2] < np.pi / 2) \ | (direction[:, -2] > 3 * np.pi / 2) direction[ids1, -1] = direction[ids1, -2] mag[ids1, -1] = mag[ids1, -2] ids1 = (direction[1, :] > 0) & (direction[1, :] < np.pi) direction[0, ids1] = direction[1, ids1] mag[0, ids1] = mag[1, ids1] ids1 = (direction[-2, :] > np.pi) & (direction[-2, :] < 2 * np.pi) direction[-1, ids1] = direction[-2, ids1] mag[-1, ids1] = mag[-2, ids1] # Now update the edges in case they are higher than the interior (i.e. # look at the downstream angle) # left edge slc0 = [slice(1, -1), slice(0, 1)] for ind in [0, 1, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(1 + e1[0], shp[0] + e1[0]), slice(e1[1], 1 + e1[1])] slc2 = [slice(1 + e2[0], shp[0] + e2[0]), slice(e2[1], 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp) mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # right edge slc0 = [slice(1, -1), slice(-1, None)] for ind in [2, 3, 4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(1 + e1[0], shp[0] + e1[0]), slice(shp[1] + e1[1], shp[1] + 1 + e1[1])] slc2 = [slice(1 + e2[0], shp[0] + e2[0]), slice(shp[1] + e2[1], shp[1] + 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp) mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # top edge slc0 = [slice(0, 1), slice(1, -1)] for ind in [4, 5, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(e1[0], 1 + e1[0]), slice(1 + e1[1], shp[1] + e1[1])] slc2 = [slice(e2[0], 1 + e2[0]), slice(1 + e2[1], shp[1] + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'top') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # bottom edge slc0 = [slice(-1, None), slice(1, -1)] for ind in [0, 1, 2, 3]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(shp[0] + e1[0], shp[0] + 1 + e1[0]), slice(1 + e1[1], shp[1] + e1[1])] slc2 = [slice(shp[0] + e2[0], shp[0] + 1 + e2[0]), slice(1 + e2[1], shp[1] + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'bot') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # top-left corner slc0 = [slice(0, 1), slice(0, 1)] for ind in [6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(e1[0], 1 + e1[0]), slice(e1[1], 1 + e1[1])] slc2 = [slice(e2[0], 1 + e2[0]), slice(e2[1], 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'top') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # top-right corner slc0 = [slice(0, 1), slice(-1, None)] for ind in [4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(e1[0], 1 + e1[0]), slice(shp[1] + e1[1], shp[1] + 1 + e1[1])] slc2 = [slice(e2[0], 1 + e2[0]), slice(shp[1] + e2[1], shp[1] + 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'top') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # bottom-left corner slc0 = [slice(-1, None), slice(0, 1)] for ind in [0, 1]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(shp[0] + e1[0], shp[0] + 1 + e1[0]), slice(e1[1], 1 + e1[1])] slc2 = [slice(shp[0] + e2[0], shp[0] + 1 + e2[0]), slice(e2[1], 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'bot') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # bottom-right corner slc0 = [slice(-1, None), slice(-1, None)] for ind in [3, 4]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(shp[0] + e1[0], shp[0] + 1 + e1[0]), slice(shp[1] + e1[1], shp[1] + 1 + e1[1])] slc2 = [slice(shp[0] + e2[0], shp[0] + 1 + e2[0]), slice(shp[1] + e2[1], shp[1] + 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'bot') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) mag[mag > 0] = np.sqrt(mag[mag > 0]) return mag, direction
python
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') mag = np.full(data.shape, FLAT_ID_INT, 'float64') slc0 = [slice(1, -1), slice(1, -1)] for ind in xrange(8): e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(1 + e1[0], shp[0] + e1[0]), slice(1 + e1[1], shp[1] + e1[1])] slc2 = [slice(1 + e2[0], shp[0] + e2[0]), slice(1 + e2[1], shp[1] + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp) mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # %%Now do the edges # if the edge is lower than the interior, we need to copy the value # from the interior (as an approximation) ids1 = (direction[:, 1] > np.pi / 2) \ & (direction[:, 1] < 3 * np.pi / 2) direction[ids1, 0] = direction[ids1, 1] mag[ids1, 0] = mag[ids1, 1] ids1 = (direction[:, -2] < np.pi / 2) \ | (direction[:, -2] > 3 * np.pi / 2) direction[ids1, -1] = direction[ids1, -2] mag[ids1, -1] = mag[ids1, -2] ids1 = (direction[1, :] > 0) & (direction[1, :] < np.pi) direction[0, ids1] = direction[1, ids1] mag[0, ids1] = mag[1, ids1] ids1 = (direction[-2, :] > np.pi) & (direction[-2, :] < 2 * np.pi) direction[-1, ids1] = direction[-2, ids1] mag[-1, ids1] = mag[-2, ids1] # Now update the edges in case they are higher than the interior (i.e. # look at the downstream angle) # left edge slc0 = [slice(1, -1), slice(0, 1)] for ind in [0, 1, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(1 + e1[0], shp[0] + e1[0]), slice(e1[1], 1 + e1[1])] slc2 = [slice(1 + e2[0], shp[0] + e2[0]), slice(e2[1], 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp) mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # right edge slc0 = [slice(1, -1), slice(-1, None)] for ind in [2, 3, 4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(1 + e1[0], shp[0] + e1[0]), slice(shp[1] + e1[1], shp[1] + 1 + e1[1])] slc2 = [slice(1 + e2[0], shp[0] + e2[0]), slice(shp[1] + e2[1], shp[1] + 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp) mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # top edge slc0 = [slice(0, 1), slice(1, -1)] for ind in [4, 5, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(e1[0], 1 + e1[0]), slice(1 + e1[1], shp[1] + e1[1])] slc2 = [slice(e2[0], 1 + e2[0]), slice(1 + e2[1], shp[1] + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'top') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # bottom edge slc0 = [slice(-1, None), slice(1, -1)] for ind in [0, 1, 2, 3]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(shp[0] + e1[0], shp[0] + 1 + e1[0]), slice(1 + e1[1], shp[1] + e1[1])] slc2 = [slice(shp[0] + e2[0], shp[0] + 1 + e2[0]), slice(1 + e2[1], shp[1] + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'bot') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # top-left corner slc0 = [slice(0, 1), slice(0, 1)] for ind in [6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(e1[0], 1 + e1[0]), slice(e1[1], 1 + e1[1])] slc2 = [slice(e2[0], 1 + e2[0]), slice(e2[1], 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'top') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # top-right corner slc0 = [slice(0, 1), slice(-1, None)] for ind in [4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(e1[0], 1 + e1[0]), slice(shp[1] + e1[1], shp[1] + 1 + e1[1])] slc2 = [slice(e2[0], 1 + e2[0]), slice(shp[1] + e2[1], shp[1] + 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'top') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # bottom-left corner slc0 = [slice(-1, None), slice(0, 1)] for ind in [0, 1]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(shp[0] + e1[0], shp[0] + 1 + e1[0]), slice(e1[1], 1 + e1[1])] slc2 = [slice(shp[0] + e2[0], shp[0] + 1 + e2[0]), slice(e2[1], 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'bot') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) # bottom-right corner slc0 = [slice(-1, None), slice(-1, None)] for ind in [3, 4]: e1 = facets[ind][1] e2 = facets[ind][2] ang = ang_adj[ind] slc1 = [slice(shp[0] + e1[0], shp[0] + 1 + e1[0]), slice(shp[1] + e1[1], shp[1] + 1 + e1[1])] slc2 = [slice(shp[0] + e2[0], shp[0] + 1 + e2[0]), slice(shp[1] + e2[1], shp[1] + 1 + e2[1])] d1, d2, theta = _get_d1_d2(dX, dY, ind, e1, e2, shp, 'bot') mag, direction = _calc_direction(data, mag, direction, ang, d1, d2, theta, slc0, slc1, slc2) mag[mag > 0] = np.sqrt(mag[mag > 0]) return mag, direction
[ "def", "_tarboton_slopes_directions", "(", "data", ",", "dX", ",", "dY", ",", "facets", ",", "ang_adj", ")", ":", "shp", "=", "np", ".", "array", "(", "data", ".", "shape", ")", "-", "1", "direction", "=", "np", ".", "full", "(", "data", ".", "shap...
Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
[ "Calculate", "the", "slopes", "and", "directions", "based", "on", "the", "8", "sections", "from", "Tarboton", "http", ":", "//", "www", ".", "neng", ".", "usu", ".", "edu", "/", "cee", "/", "faculty", "/", "dtarb", "/", "96wr03137", ".", "pdf" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2406-L2554
train
creare-com/pydem
pydem/dem_processing.py
_get_d1_d2
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 calculating the magnitude and directions of slopes. """ if topbot == None: if ind in [0, 3, 4, 7]: d1 = dX[slice((e2[0] + 1) / 2, shp[0] + (e2[0] - 1) / 2)] d2 = dY[slice((e2[0] + 1) / 2, shp[0] + (e2[0] - 1) / 2)] if d1.size == 0: d1 = np.array([dX[0]]) d2 = np.array([dY[0]]) else: d2 = dX[slice((e1[0] + 1) / 2, shp[0] + (e1[0] - 1) / 2)] d1 = dY[slice((e1[0] + 1) / 2, shp[0] + (e1[0] - 1) / 2)] if d1.size == 0: d2 = dX[0] d1 = dY[0] elif topbot == 'top': if ind in [0, 3, 4, 7]: d1, d2 = dX[0], dY[0] else: d2, d1 = dX[0], dY[0] elif topbot == 'bot': if ind in [0, 3, 4, 7]: d1, d2 = dX[-1], dY[-1] else: d2, d1 = dX[-1], dY[-1] theta = np.arctan2(d2, d1) return d1.reshape(d1.size, 1), d2.reshape(d2.size, 1), theta.reshape(theta.size, 1)
python
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 calculating the magnitude and directions of slopes. """ if topbot == None: if ind in [0, 3, 4, 7]: d1 = dX[slice((e2[0] + 1) / 2, shp[0] + (e2[0] - 1) / 2)] d2 = dY[slice((e2[0] + 1) / 2, shp[0] + (e2[0] - 1) / 2)] if d1.size == 0: d1 = np.array([dX[0]]) d2 = np.array([dY[0]]) else: d2 = dX[slice((e1[0] + 1) / 2, shp[0] + (e1[0] - 1) / 2)] d1 = dY[slice((e1[0] + 1) / 2, shp[0] + (e1[0] - 1) / 2)] if d1.size == 0: d2 = dX[0] d1 = dY[0] elif topbot == 'top': if ind in [0, 3, 4, 7]: d1, d2 = dX[0], dY[0] else: d2, d1 = dX[0], dY[0] elif topbot == 'bot': if ind in [0, 3, 4, 7]: d1, d2 = dX[-1], dY[-1] else: d2, d1 = dX[-1], dY[-1] theta = np.arctan2(d2, d1) return d1.reshape(d1.size, 1), d2.reshape(d2.size, 1), theta.reshape(theta.size, 1)
[ "def", "_get_d1_d2", "(", "dX", ",", "dY", ",", "ind", ",", "e1", ",", "e2", ",", "shp", ",", "topbot", "=", "None", ")", ":", "if", "topbot", "==", "None", ":", "if", "ind", "in", "[", "0", ",", "3", ",", "4", ",", "7", "]", ":", "d1", "...
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.
[ "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", ...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2556-L2589
train
creare-com/pydem
pydem/dem_processing.py
_calc_direction
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] data1 = data[slc1] data2 = data[slc2] s1 = (data0 - data1) / d1 s2 = (data1 - data2) / d2 s1_2 = s1**2 sd = (data0 - data2) / np.sqrt(d1**2 + d2**2) r = np.arctan2(s2, s1) rad2 = s1_2 + s2**2 # Handle special cases # should be on diagonal b_s1_lte0 = s1 <= 0 b_s2_lte0 = s2 <= 0 b_s1_gt0 = s1 > 0 b_s2_gt0 = s2 > 0 I1 = (b_s1_lte0 & b_s2_gt0) | (r > theta) if I1.any(): rad2[I1] = sd[I1] ** 2 r[I1] = theta.repeat(I1.shape[1], 1)[I1] I2 = (b_s1_gt0 & b_s2_lte0) | (r < 0) # should be on straight section if I2.any(): rad2[I2] = s1_2[I2] r[I2] = 0 I3 = b_s1_lte0 & (b_s2_lte0 | (b_s2_gt0 & (sd <= 0))) # upslope or flat rad2[I3] = -1 I4 = rad2 > mag[slc0] if I4.any(): mag[slc0][I4] = rad2[I4] direction[slc0][I4] = r[I4] * ang[1] + ang[0] * np.pi/2 return mag, direction
python
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] data1 = data[slc1] data2 = data[slc2] s1 = (data0 - data1) / d1 s2 = (data1 - data2) / d2 s1_2 = s1**2 sd = (data0 - data2) / np.sqrt(d1**2 + d2**2) r = np.arctan2(s2, s1) rad2 = s1_2 + s2**2 # Handle special cases # should be on diagonal b_s1_lte0 = s1 <= 0 b_s2_lte0 = s2 <= 0 b_s1_gt0 = s1 > 0 b_s2_gt0 = s2 > 0 I1 = (b_s1_lte0 & b_s2_gt0) | (r > theta) if I1.any(): rad2[I1] = sd[I1] ** 2 r[I1] = theta.repeat(I1.shape[1], 1)[I1] I2 = (b_s1_gt0 & b_s2_lte0) | (r < 0) # should be on straight section if I2.any(): rad2[I2] = s1_2[I2] r[I2] = 0 I3 = b_s1_lte0 & (b_s2_lte0 | (b_s2_gt0 & (sd <= 0))) # upslope or flat rad2[I3] = -1 I4 = rad2 > mag[slc0] if I4.any(): mag[slc0][I4] = rad2[I4] direction[slc0][I4] = r[I4] * ang[1] + ang[0] * np.pi/2 return mag, direction
[ "def", "_calc_direction", "(", "data", ",", "mag", ",", "direction", ",", "ang", ",", "d1", ",", "d2", ",", "theta", ",", "slc0", ",", "slc1", ",", "slc2", ")", ":", "data0", "=", "data", "[", "slc0", "]", "data1", "=", "data", "[", "slc1", "]", ...
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
[ "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" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2593-L2638
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.get
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, side).ravel()[self.keys[key]]
python
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, side).ravel()[self.keys[key]]
[ "def", "get", "(", "self", ",", "key", ",", "side", ")", ":", "return", "getattr", "(", "self", ",", "side", ")", ".", "ravel", "(", ")", "[", "self", ".", "keys", "[", "key", "]", "]" ]
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
[ "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",...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L234-L244
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.set_i
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])
python
def set_i(self, i, data, field, side): """ Assigns data on the i'th tile to the data 'field' of the 'side' edge of that tile """ edge = self.get_i(i, side) setattr(edge, field, data[edge.slice])
[ "def", "set_i", "(", "self", ",", "i", ",", "data", ",", "field", ",", "side", ")", ":", "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
[ "Assigns", "data", "on", "the", "i", "th", "tile", "to", "the", "data", "field", "of", "the", "side", "edge", "of", "that", "tile" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L265-L270
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.set_sides
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)
python
def set_sides(self, key, data, field, local=False): """ Assign data on the 'key' tile to all the edges """ for side in ['left', 'right', 'top', 'bottom']: self.set(key, data, field, side, local)
[ "def", "set_sides", "(", "self", ",", "key", ",", "data", ",", "field", ",", "local", "=", "False", ")", ":", "for", "side", "in", "[", "'left'", ",", "'right'", ",", "'top'", ",", "'bottom'", "]", ":", "self", ".", "set", "(", "key", ",", "data"...
Assign data on the 'key' tile to all the edges
[ "Assign", "data", "on", "the", "key", "tile", "to", "all", "the", "edges" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L272-L277
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.set_neighbor_data
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. """ i = self.keys[key] found = False sides = [] if 'left' in neighbor_side: if i % self.n_cols == 0: return None i -= 1 sides.append('right') found = True if 'right' in neighbor_side: if i % self.n_cols == self.n_cols - 1: return None i += 1 sides.append('left') found = True if 'top' in neighbor_side: sides.append('bottom') i -= self.n_cols found = True if 'bottom' in neighbor_side: sides.append('top') i += self.n_cols found = True if not found: print "Side '%s' not found" % neighbor_side # Check if i is in range if i < 0 or i >= self.n_chunks: return None # Otherwise, set the data for side in sides: self.set_i(i, data, field, side)
python
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. """ i = self.keys[key] found = False sides = [] if 'left' in neighbor_side: if i % self.n_cols == 0: return None i -= 1 sides.append('right') found = True if 'right' in neighbor_side: if i % self.n_cols == self.n_cols - 1: return None i += 1 sides.append('left') found = True if 'top' in neighbor_side: sides.append('bottom') i -= self.n_cols found = True if 'bottom' in neighbor_side: sides.append('top') i += self.n_cols found = True if not found: print "Side '%s' not found" % neighbor_side # Check if i is in range if i < 0 or i >= self.n_chunks: return None # Otherwise, set the data for side in sides: self.set_i(i, data, field, side)
[ "def", "set_neighbor_data", "(", "self", ",", "neighbor_side", ",", "data", ",", "key", ",", "field", ")", ":", "i", "=", "self", ".", "keys", "[", "key", "]", "found", "=", "False", "sides", "=", "[", "]", "if", "'left'", "in", "neighbor_side", ":",...
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...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L279-L316
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.set_all_neighbors_data
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 been # updated... for side in ['left', 'right', 'top', 'bottom', 'topleft', 'topright', 'bottomleft', 'bottomright']: self.set_neighbor_data(side, data, key, 'data') # self.set_neighbor_data(side, todo, key, 'todo') self.set_neighbor_data(side, done, key, 'done')
python
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 been # updated... for side in ['left', 'right', 'top', 'bottom', 'topleft', 'topright', 'bottomleft', 'bottomright']: self.set_neighbor_data(side, data, key, 'data') # self.set_neighbor_data(side, todo, key, 'todo') self.set_neighbor_data(side, done, key, 'done')
[ "def", "set_all_neighbors_data", "(", "self", ",", "data", ",", "done", ",", "key", ")", ":", "# The order of this for loop is important because the topleft gets", "# it's data from the left neighbor, which should have already been", "# updated...", "for", "side", "in", "[", "'...
Given they 'key' tile's data, assigns this information to all neighboring tiles
[ "Given", "they", "key", "tile", "s", "data", "assigns", "this", "information", "to", "all", "neighboring", "tiles" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L318-L330
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.fill_n_todo
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.ravel()[i].n_todo, right.ravel()[i].n_todo, top.ravel()[i].n_todo, bottom.ravel()[i].n_todo])
python
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.ravel()[i].n_todo, right.ravel()[i].n_todo, top.ravel()[i].n_todo, bottom.ravel()[i].n_todo])
[ "def", "fill_n_todo", "(", "self", ")", ":", "left", "=", "self", ".", "left", "right", "=", "self", ".", "right", "top", "=", "self", ".", "top", "bottom", "=", "self", ".", "bottom", "for", "i", "in", "xrange", "(", "self", ".", "n_chunks", ")", ...
Calculate and record the number of edge pixels left to do on each tile
[ "Calculate", "and", "record", "the", "number", "of", "edge", "pixels", "left", "to", "do", "on", "each", "tile" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L332-L344
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.fill_n_done
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] = np.sum([left.ravel()[i].n_done, right.ravel()[i].n_done, top.ravel()[i].n_done, bottom.ravel()[i].n_done])
python
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] = np.sum([left.ravel()[i].n_done, right.ravel()[i].n_done, top.ravel()[i].n_done, bottom.ravel()[i].n_done])
[ "def", "fill_n_done", "(", "self", ")", ":", "left", "=", "self", ".", "left", "right", "=", "self", ".", "right", "top", "=", "self", ".", "top", "bottom", "=", "self", ".", "bottom", "for", "i", "in", "xrange", "(", "self", ".", "n_chunks", ")", ...
Calculate and record the number of edge pixels that are done one each tile.
[ "Calculate", "and", "record", "the", "number", "of", "edge", "pixels", "that", "are", "done", "one", "each", "tile", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L346-L359
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.fill_percent_done
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_chunks): self.percent_done.ravel()[i] = \ np.sum([left.ravel()[i].percent_done, right.ravel()[i].percent_done, top.ravel()[i].percent_done, bottom.ravel()[i].percent_done]) self.percent_done.ravel()[i] /= \ np.sum([left.ravel()[i].percent_done > 0, right.ravel()[i].percent_done > 0, top.ravel()[i].percent_done > 0, bottom.ravel()[i].percent_done > 0, 1e-16])
python
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_chunks): self.percent_done.ravel()[i] = \ np.sum([left.ravel()[i].percent_done, right.ravel()[i].percent_done, top.ravel()[i].percent_done, bottom.ravel()[i].percent_done]) self.percent_done.ravel()[i] /= \ np.sum([left.ravel()[i].percent_done > 0, right.ravel()[i].percent_done > 0, top.ravel()[i].percent_done > 0, bottom.ravel()[i].percent_done > 0, 1e-16])
[ "def", "fill_percent_done", "(", "self", ")", ":", "left", "=", "self", ".", "left", "right", "=", "self", ".", "right", "top", "=", "self", ".", "top", "bottom", "=", "self", ".", "bottom", "for", "i", "in", "xrange", "(", "self", ".", "n_chunks", ...
Calculate the percentage of edge pixels that would be done if the tile was reprocessed. This is done for each tile.
[ "Calculate", "the", "percentage", "of", "edge", "pixels", "that", "would", "be", "done", "if", "the", "tile", "was", "reprocessed", ".", "This", "is", "done", "for", "each", "tile", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L361-L380
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.fill_array
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']: edge = getattr(self, side).ravel()[i] if add: array[edge.slice] += getattr(edge, field) elif maximize: array[edge.slice] = np.maximum(array[edge.slice], getattr(edge, field)) else: array[edge.slice] = getattr(edge, field) return array
python
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']: edge = getattr(self, side).ravel()[i] if add: array[edge.slice] += getattr(edge, field) elif maximize: array[edge.slice] = np.maximum(array[edge.slice], getattr(edge, field)) else: array[edge.slice] = getattr(edge, field) return array
[ "def", "fill_array", "(", "self", ",", "array", ",", "field", ",", "add", "=", "False", ",", "maximize", "=", "False", ")", ":", "self", ".", "fix_shapes", "(", ")", "for", "i", "in", "xrange", "(", "self", ".", "n_chunks", ")", ":", "for", "side",...
Given a full array (for the while image), fill it with the data on the edges.
[ "Given", "a", "full", "array", "(", "for", "the", "while", "image", ")", "fill", "it", "with", "the", "data", "on", "the", "edges", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L382-L398
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.fix_shapes
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 = getattr(self, side).ravel()[i] if side in ['left', 'right']: shp = [edge.todo.size, 1] else: shp = [1, edge.todo.size] edge.done = edge.done.reshape(shp) edge.data = edge.data.reshape(shp) edge.todo = edge.todo.reshape(shp)
python
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 = getattr(self, side).ravel()[i] if side in ['left', 'right']: shp = [edge.todo.size, 1] else: shp = [1, edge.todo.size] edge.done = edge.done.reshape(shp) edge.data = edge.data.reshape(shp) edge.todo = edge.todo.reshape(shp)
[ "def", "fix_shapes", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "n_chunks", ")", ":", "for", "side", "in", "[", "'left'", ",", "'right'", ",", "'top'", ",", "'bottom'", "]", ":", "edge", "=", "getattr", "(", "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.
[ "Fixes", "the", "shape", "of", "the", "data", "fields", "on", "edges", ".", "Left", "edges", "should", "be", "column", "vectors", "and", "top", "edges", "should", "be", "row", "vectors", "for", "example", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L400-L414
train
creare-com/pydem
pydem/dem_processing.py
TileEdge.find_best_candidate
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_done.ravel()) if self.percent_done.ravel()[i_b] <= 0: return None # check for ties I = self.percent_done.ravel() == self.percent_done.ravel()[i_b] if I.sum() == 1: return i_b else: I2 = np.argmax(self.max_elev.ravel()[I]) return I.nonzero()[0][I2]
python
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_done.ravel()) if self.percent_done.ravel()[i_b] <= 0: return None # check for ties I = self.percent_done.ravel() == self.percent_done.ravel()[i_b] if I.sum() == 1: return i_b else: I2 = np.argmax(self.max_elev.ravel()[I]) return I.nonzero()[0][I2]
[ "def", "find_best_candidate", "(", "self", ")", ":", "self", ".", "fill_percent_done", "(", ")", "i_b", "=", "np", ".", "argmax", "(", "self", ".", "percent_done", ".", "ravel", "(", ")", ")", "if", "self", ".", "percent_done", ".", "ravel", "(", ")", ...
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.
[ "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", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L416-L433
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.save_array
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'. Filename of array to save. Over-writes partname. partname : str, optional Part of the filename to save (with the coordinates appended) rootpath : str, optional Default '.'. Which directory to save file raw : bool, optional Default False. If true will save a .npz of the array. If false, will save a geotiff as_int : bool, optional Default True. If true will save array as an integer array ( excellent compression). If false will save as float array. """ if name is None and partname is not None: fnl_file = self.get_full_fn(partname, rootpath) tmp_file = os.path.join(rootpath, partname, self.get_fn(partname + '_tmp')) elif name is not None: fnl_file = name tmp_file = fnl_file + '_tmp.tiff' else: fnl_file = 'array.tif' if not raw: s_file = self.elev.clone_traits() s_file.raster_data = np.ma.masked_array(array) count = 10 while count > 0 and (s_file.raster_data.mask.sum() > 0 \ or np.isnan(s_file.raster_data).sum() > 0): s_file.inpaint() count -= 1 s_file.export_to_geotiff(tmp_file) if as_int: cmd = "gdalwarp -multi -wm 2000 -co BIGTIFF=YES -of GTiff -co compress=lzw -ot Int16 -co TILED=YES -wo OPTIMIZE_SIZE=YES -r near -t_srs %s %s %s" \ % (self.save_projection, tmp_file, fnl_file) else: cmd = "gdalwarp -multi -wm 2000 -co BIGTIFF=YES -of GTiff -co compress=lzw -co TILED=YES -wo OPTIMIZE_SIZE=YES -r near -t_srs %s %s %s" \ % (self.save_projection, tmp_file, fnl_file) print "<<"*4, cmd, ">>"*4 subprocess.call(cmd) os.remove(tmp_file) else: np.savez_compressed(fnl_file, array)
python
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'. Filename of array to save. Over-writes partname. partname : str, optional Part of the filename to save (with the coordinates appended) rootpath : str, optional Default '.'. Which directory to save file raw : bool, optional Default False. If true will save a .npz of the array. If false, will save a geotiff as_int : bool, optional Default True. If true will save array as an integer array ( excellent compression). If false will save as float array. """ if name is None and partname is not None: fnl_file = self.get_full_fn(partname, rootpath) tmp_file = os.path.join(rootpath, partname, self.get_fn(partname + '_tmp')) elif name is not None: fnl_file = name tmp_file = fnl_file + '_tmp.tiff' else: fnl_file = 'array.tif' if not raw: s_file = self.elev.clone_traits() s_file.raster_data = np.ma.masked_array(array) count = 10 while count > 0 and (s_file.raster_data.mask.sum() > 0 \ or np.isnan(s_file.raster_data).sum() > 0): s_file.inpaint() count -= 1 s_file.export_to_geotiff(tmp_file) if as_int: cmd = "gdalwarp -multi -wm 2000 -co BIGTIFF=YES -of GTiff -co compress=lzw -ot Int16 -co TILED=YES -wo OPTIMIZE_SIZE=YES -r near -t_srs %s %s %s" \ % (self.save_projection, tmp_file, fnl_file) else: cmd = "gdalwarp -multi -wm 2000 -co BIGTIFF=YES -of GTiff -co compress=lzw -co TILED=YES -wo OPTIMIZE_SIZE=YES -r near -t_srs %s %s %s" \ % (self.save_projection, tmp_file, fnl_file) print "<<"*4, cmd, ">>"*4 subprocess.call(cmd) os.remove(tmp_file) else: np.savez_compressed(fnl_file, array)
[ "def", "save_array", "(", "self", ",", "array", ",", "name", "=", "None", ",", "partname", "=", "None", ",", "rootpath", "=", "'.'", ",", "raw", "=", "False", ",", "as_int", "=", "True", ")", ":", "if", "name", "is", "None", "and", "partname", "is"...
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 save (with the coordinates appended) rootpath : str, optional Default '.'. Which directory to save file raw : bool, optional Default False. If true will save a .npz of the array. If false, will save a geotiff as_int : bool, optional Default True. If true will save array as an integer array ( excellent compression). If false will save as float array.
[ "Standard", "array", "saving", "routine" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L631-L684
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.save_uca
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)
python
def save_uca(self, rootpath, raw=False, as_int=False): """ Saves the upstream contributing area to a file """ self.save_array(self.uca, None, 'uca', rootpath, raw, as_int=as_int)
[ "def", "save_uca", "(", "self", ",", "rootpath", ",", "raw", "=", "False", ",", "as_int", "=", "False", ")", ":", "self", ".", "save_array", "(", "self", ".", "uca", ",", "None", ",", "'uca'", ",", "rootpath", ",", "raw", ",", "as_int", "=", "as_in...
Saves the upstream contributing area to a file
[ "Saves", "the", "upstream", "contributing", "area", "to", "a", "file" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L686-L689
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.save_twi
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 self.twi.mask[self.flats] = True # self.twi = self.flats self.save_array(self.twi, None, 'twi', rootpath, raw, as_int=as_int)
python
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 self.twi.mask[self.flats] = True # self.twi = self.flats self.save_array(self.twi, None, 'twi', rootpath, raw, as_int=as_int)
[ "def", "save_twi", "(", "self", ",", "rootpath", ",", "raw", "=", "False", ",", "as_int", "=", "True", ")", ":", "self", ".", "twi", "=", "np", ".", "ma", ".", "masked_array", "(", "self", ".", "twi", ",", "mask", "=", "self", ".", "twi", "<=", ...
Saves the topographic wetness index to a file
[ "Saves", "the", "topographic", "wetness", "index", "to", "a", "file" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L691-L700
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.save_slope
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)
python
def save_slope(self, rootpath, raw=False, as_int=False): """ Saves the magnitude of the slope to a file """ self.save_array(self.mag, None, 'mag', rootpath, raw, as_int=as_int)
[ "def", "save_slope", "(", "self", ",", "rootpath", ",", "raw", "=", "False", ",", "as_int", "=", "False", ")", ":", "self", ".", "save_array", "(", "self", ".", "mag", ",", "None", ",", "'mag'", ",", "rootpath", ",", "raw", ",", "as_int", "=", "as_...
Saves the magnitude of the slope to a file
[ "Saves", "the", "magnitude", "of", "the", "slope", "to", "a", "file" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L702-L705
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.save_direction
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)
python
def save_direction(self, rootpath, raw=False, as_int=False): """ Saves the direction of the slope to a file """ self.save_array(self.direction, None, 'ang', rootpath, raw, as_int=as_int)
[ "def", "save_direction", "(", "self", ",", "rootpath", ",", "raw", "=", "False", ",", "as_int", "=", "False", ")", ":", "self", ".", "save_array", "(", "self", ".", "direction", ",", "None", ",", "'ang'", ",", "rootpath", ",", "raw", ",", "as_int", "...
Saves the direction of the slope to a file
[ "Saves", "the", "direction", "of", "the", "slope", "to", "a", "file" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L707-L710
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.save_outputs
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)
python
def save_outputs(self, rootpath='.', raw=False): """Saves TWI, UCA, magnitude and direction of slope to files. """ self.save_twi(rootpath, raw) self.save_uca(rootpath, raw) self.save_slope(rootpath, raw) self.save_direction(rootpath, raw)
[ "def", "save_outputs", "(", "self", ",", "rootpath", "=", "'.'", ",", "raw", "=", "False", ")", ":", "self", ".", "save_twi", "(", "rootpath", ",", "raw", ")", "self", ".", "save_uca", "(", "rootpath", ",", "raw", ")", "self", ".", "save_slope", "(",...
Saves TWI, UCA, magnitude and direction of slope to files.
[ "Saves", "TWI", "UCA", "magnitude", "and", "direction", "of", "slope", "to", "files", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L712-L718
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.load_array
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') try: setattr(self, name, array['arr_0']) except Exception, e: print e finally: array.close() else: raise RuntimeError("File %s does not exist." % (fn + '.npz'))
python
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') try: setattr(self, name, array['arr_0']) except Exception, e: print e finally: array.close() else: raise RuntimeError("File %s does not exist." % (fn + '.npz'))
[ "def", "load_array", "(", "self", ",", "fn", ",", "name", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "fn", "+", "'.npz'", ")", ":", "array", "=", "np", ".", "load", "(", "fn", "+", "'.npz'", ")", "try", ":", "setattr", "(", "self", ...
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'
[ "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" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L720-L737
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._get_chunk_edges
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 Nominal size of chunks (chunk_size < NN) chunk_overlap : int Number of pixels chunks will overlap Returns ------- start_id : array The starting id of a chunk. start_id[i] gives the starting id of the i'th chunk end_id : array The ending id of a chunk. end_id[i] gives the ending id of the i'th chunk """ left_edge = np.arange(0, NN - chunk_overlap, chunk_size) left_edge[1:] -= chunk_overlap right_edge = np.arange(0, NN - chunk_overlap, chunk_size) right_edge[:-1] = right_edge[1:] + chunk_overlap right_edge[-1] = NN right_edge = np.minimum(right_edge, NN) return left_edge, right_edge
python
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 Nominal size of chunks (chunk_size < NN) chunk_overlap : int Number of pixels chunks will overlap Returns ------- start_id : array The starting id of a chunk. start_id[i] gives the starting id of the i'th chunk end_id : array The ending id of a chunk. end_id[i] gives the ending id of the i'th chunk """ left_edge = np.arange(0, NN - chunk_overlap, chunk_size) left_edge[1:] -= chunk_overlap right_edge = np.arange(0, NN - chunk_overlap, chunk_size) right_edge[:-1] = right_edge[1:] + chunk_overlap right_edge[-1] = NN right_edge = np.minimum(right_edge, NN) return left_edge, right_edge
[ "def", "_get_chunk_edges", "(", "self", ",", "NN", ",", "chunk_size", ",", "chunk_overlap", ")", ":", "left_edge", "=", "np", ".", "arange", "(", "0", ",", "NN", "-", "chunk_overlap", ",", "chunk_size", ")", "left_edge", "[", "1", ":", "]", "-=", "chun...
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 starting id of a chunk. start_id[i] gives the starting id of the i'th chunk end_id : array The ending id of a chunk. end_id[i] gives the ending id of the i'th chunk
[ "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_s...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L754-L781
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._assign_chunk
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) that has size of full tile arr1 : array Full size array to which data will be assigned arr2 : array Chunk-sized array from which data will be assigned te : int Top edge id be : int Bottom edge id le : int Left edge id re : int Right edge id ovr : int The number of pixels in the overlap add : bool, optional Default False. If true, the data in arr2 will be added to arr1, otherwise data in arr2 will overwrite data in arr1 """ if te == 0: i1 = 0 else: i1 = ovr if be == data.shape[0]: i2 = 0 i2b = None else: i2 = -ovr i2b = -ovr if le == 0: j1 = 0 else: j1 = ovr if re == data.shape[1]: j2 = 0 j2b = None else: j2 = -ovr j2b = -ovr if add: arr1[te+i1:be+i2, le+j1:re+j2] += arr2[i1:i2b, j1:j2b] else: arr1[te+i1:be+i2, le+j1:re+j2] = arr2[i1:i2b, j1:j2b]
python
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) that has size of full tile arr1 : array Full size array to which data will be assigned arr2 : array Chunk-sized array from which data will be assigned te : int Top edge id be : int Bottom edge id le : int Left edge id re : int Right edge id ovr : int The number of pixels in the overlap add : bool, optional Default False. If true, the data in arr2 will be added to arr1, otherwise data in arr2 will overwrite data in arr1 """ if te == 0: i1 = 0 else: i1 = ovr if be == data.shape[0]: i2 = 0 i2b = None else: i2 = -ovr i2b = -ovr if le == 0: j1 = 0 else: j1 = ovr if re == data.shape[1]: j2 = 0 j2b = None else: j2 = -ovr j2b = -ovr if add: arr1[te+i1:be+i2, le+j1:re+j2] += arr2[i1:i2b, j1:j2b] else: arr1[te+i1:be+i2, le+j1:re+j2] = arr2[i1:i2b, j1:j2b]
[ "def", "_assign_chunk", "(", "self", ",", "data", ",", "arr1", ",", "arr2", ",", "te", ",", "be", ",", "le", ",", "re", ",", "ovr", ",", "add", "=", "False", ")", ":", "if", "te", "==", "0", ":", "i1", "=", "0", "else", ":", "i1", "=", "ovr...
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 be assigned arr2 : array Chunk-sized array from which data will be assigned te : int Top edge id be : int Bottom edge id le : int Left edge id re : int Right edge id ovr : int The number of pixels in the overlap add : bool, optional Default False. If true, the data in arr2 will be added to arr1, otherwise data in arr2 will overwrite data in arr1
[ "Assign", "data", "from", "a", "chunk", "to", "the", "full", "array", ".", "The", "data", "in", "overlap", "regions", "will", "not", "be", "assigned", "to", "the", "full", "array" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L783-L838
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.calc_slopes_directions
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: data = np.ma.filled(self.data.astype('float64'), np.nan) filled = data.copy() edge = np.ones_like(data, bool) edge[1:-1, 1:-1] = False if self.fill_flats_below_sea: sea_mask = data != 0 else: sea_mask = data > 0 flat = (spndi.minimum_filter(data, (3, 3)) >= data) & sea_mask flats, n = spndi.label(flat, structure=FLATS_KERNEL3) objs = spndi.find_objects(flats) for i, _obj in enumerate(objs): obj = grow_obj(_obj, data.shape) self._fill_flat(data[obj], filled[obj], flats[obj]==i+1, edge[obj]) self.data = np.ma.masked_array(filled, mask=np.isnan(filled)).astype(self.data.dtype) # %% Calculate the slopes and directions based on the 8 sections from # Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf if self.data.shape[0] <= self.chunk_size_slp_dir and \ self.data.shape[1] <= self.chunk_size_slp_dir: print "starting slope/direction calculation" self.mag, self.direction = self._slopes_directions( self.data, self.dX, self.dY, 'tarboton') # Find the flat regions. This is mostly simple (look for mag < 0), # but the downstream pixel at the edge of a flat will have a # calcuable angle which will not be accurate. We have to also find # these edges and set their magnitude to -1 (that is, the flat_id) self.find_flats() else: self.direction = np.full(self.data.shape, FLAT_ID_INT, 'float64') self.mag = np.full(self.data.shape, FLAT_ID_INT, 'float64') self.flats = np.zeros(self.data.shape, bool) top_edge, bottom_edge = \ self._get_chunk_edges(self.data.shape[0], self.chunk_size_slp_dir, self.chunk_overlap_slp_dir) left_edge, right_edge = \ self._get_chunk_edges(self.data.shape[1], self.chunk_size_slp_dir, self.chunk_overlap_slp_dir) ovr = self.chunk_overlap_slp_dir count = 1 for te, be in zip(top_edge, bottom_edge): for le, re in zip(left_edge, right_edge): print "starting slope/direction calculation for chunk", \ count, "[%d:%d, %d:%d]" % (te, be, le, re) count += 1 mag, direction = \ self._slopes_directions(self.data[te:be, le:re], self.dX[te:be-1], self.dY[te:be-1]) flats = self._find_flats_edges(self.data[te:be, le:re], mag, direction) direction[flats] = FLAT_ID_INT mag[flats] = FLAT_ID_INT self._assign_chunk(self.data, self.mag, mag, te, be, le, re, ovr) self._assign_chunk(self.data, self.direction, direction, te, be, le, re, ovr) self._assign_chunk(self.data, self.flats, flats, te, be, le, re, ovr) if plotflag: self._plot_debug_slopes_directions() gc.collect() # Just in case return self.mag, self.direction
python
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: data = np.ma.filled(self.data.astype('float64'), np.nan) filled = data.copy() edge = np.ones_like(data, bool) edge[1:-1, 1:-1] = False if self.fill_flats_below_sea: sea_mask = data != 0 else: sea_mask = data > 0 flat = (spndi.minimum_filter(data, (3, 3)) >= data) & sea_mask flats, n = spndi.label(flat, structure=FLATS_KERNEL3) objs = spndi.find_objects(flats) for i, _obj in enumerate(objs): obj = grow_obj(_obj, data.shape) self._fill_flat(data[obj], filled[obj], flats[obj]==i+1, edge[obj]) self.data = np.ma.masked_array(filled, mask=np.isnan(filled)).astype(self.data.dtype) # %% Calculate the slopes and directions based on the 8 sections from # Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf if self.data.shape[0] <= self.chunk_size_slp_dir and \ self.data.shape[1] <= self.chunk_size_slp_dir: print "starting slope/direction calculation" self.mag, self.direction = self._slopes_directions( self.data, self.dX, self.dY, 'tarboton') # Find the flat regions. This is mostly simple (look for mag < 0), # but the downstream pixel at the edge of a flat will have a # calcuable angle which will not be accurate. We have to also find # these edges and set their magnitude to -1 (that is, the flat_id) self.find_flats() else: self.direction = np.full(self.data.shape, FLAT_ID_INT, 'float64') self.mag = np.full(self.data.shape, FLAT_ID_INT, 'float64') self.flats = np.zeros(self.data.shape, bool) top_edge, bottom_edge = \ self._get_chunk_edges(self.data.shape[0], self.chunk_size_slp_dir, self.chunk_overlap_slp_dir) left_edge, right_edge = \ self._get_chunk_edges(self.data.shape[1], self.chunk_size_slp_dir, self.chunk_overlap_slp_dir) ovr = self.chunk_overlap_slp_dir count = 1 for te, be in zip(top_edge, bottom_edge): for le, re in zip(left_edge, right_edge): print "starting slope/direction calculation for chunk", \ count, "[%d:%d, %d:%d]" % (te, be, le, re) count += 1 mag, direction = \ self._slopes_directions(self.data[te:be, le:re], self.dX[te:be-1], self.dY[te:be-1]) flats = self._find_flats_edges(self.data[te:be, le:re], mag, direction) direction[flats] = FLAT_ID_INT mag[flats] = FLAT_ID_INT self._assign_chunk(self.data, self.mag, mag, te, be, le, re, ovr) self._assign_chunk(self.data, self.direction, direction, te, be, le, re, ovr) self._assign_chunk(self.data, self.flats, flats, te, be, le, re, ovr) if plotflag: self._plot_debug_slopes_directions() gc.collect() # Just in case return self.mag, self.direction
[ "def", "calc_slopes_directions", "(", "self", ",", "plotflag", "=", "False", ")", ":", "# TODO minimum filter behavior with nans?", "# fill/interpolate flats first", "if", "self", ".", "fill_flats", ":", "data", "=", "np", ".", "ma", ".", "filled", "(", "self", "....
Calculates the magnitude and direction of slopes and fills self.mag, self.direction
[ "Calculates", "the", "magnitude", "and", "direction", "of", "slopes", "and", "fills", "self", ".", "mag", "self", ".", "direction" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L936-L1018
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._slopes_directions
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_directions(data, dX, dY)
python
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_directions(data, dX, dY)
[ "def", "_slopes_directions", "(", "self", ",", "data", ",", "dX", ",", "dY", ",", "method", "=", "'tarboton'", ")", ":", "# %%", "if", "method", "==", "'tarboton'", ":", "return", "self", ".", "_tarboton_slopes_directions", "(", "data", ",", "dX", ",", "...
Wrapper to pick between various algorithms
[ "Wrapper", "to", "pick", "between", "various", "algorithms" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1020-L1027
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._tarboton_slopes_directions
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, self.facets, self.ang_adj)
python
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, self.facets, self.ang_adj)
[ "def", "_tarboton_slopes_directions", "(", "self", ",", "data", ",", "dX", ",", "dY", ")", ":", "return", "_tarboton_slopes_directions", "(", "data", ",", "dX", ",", "dY", ",", "self", ".", "facets", ",", "self", ".", "ang_adj", ")" ]
Calculate the slopes and directions based on the 8 sections from Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
[ "Calculate", "the", "slopes", "and", "directions", "based", "on", "the", "8", "sections", "from", "Tarboton", "http", ":", "//", "www", ".", "neng", ".", "usu", ".", "edu", "/", "cee", "/", "faculty", "/", "dtarb", "/", "96wr03137", ".", "pdf" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1029-L1036
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._central_slopes_directions
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') ind = 0 d1, d2, theta = _get_d1_d2(dX, dY, ind, [0, 1], [1, 1], shp) s2 = (data[0:-2, 1:-1] - data[2:, 1:-1]) / d2 s1 = -(data[1:-1, 0:-2] - data[1:-1, 2:]) / d1 direction[1:-1, 1:-1] = np.arctan2(s2, s1) + np.pi mag = np.sqrt(s1**2 + s2**2) return mag, direction
python
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') ind = 0 d1, d2, theta = _get_d1_d2(dX, dY, ind, [0, 1], [1, 1], shp) s2 = (data[0:-2, 1:-1] - data[2:, 1:-1]) / d2 s1 = -(data[1:-1, 0:-2] - data[1:-1, 2:]) / d1 direction[1:-1, 1:-1] = np.arctan2(s2, s1) + np.pi mag = np.sqrt(s1**2 + s2**2) return mag, direction
[ "def", "_central_slopes_directions", "(", "self", ",", "data", ",", "dX", ",", "dY", ")", ":", "shp", "=", "np", ".", "array", "(", "data", ".", "shape", ")", "-", "1", "direction", "=", "np", ".", "full", "(", "data", ".", "shape", ",", "FLAT_ID_I...
Calculates magnitude/direction of slopes using central difference
[ "Calculates", "magnitude", "/", "direction", "of", "slopes", "using", "central", "difference" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1038-L1054
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._find_flats_edges
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 """ i12 = np.arange(data.size).reshape(data.shape) flat = mag == FLAT_ID_INT flats, n = spndi.label(flat, structure=FLATS_KERNEL3) objs = spndi.find_objects(flats) f = flat.ravel() d = data.ravel() for i, _obj in enumerate(objs): region = flats[_obj] == i+1 I = i12[_obj][region] J = get_adjacent_index(I, data.shape, data.size) f[J] = d[J] == d[I[0]] flat = f.reshape(data.shape) return flat
python
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 """ i12 = np.arange(data.size).reshape(data.shape) flat = mag == FLAT_ID_INT flats, n = spndi.label(flat, structure=FLATS_KERNEL3) objs = spndi.find_objects(flats) f = flat.ravel() d = data.ravel() for i, _obj in enumerate(objs): region = flats[_obj] == i+1 I = i12[_obj][region] J = get_adjacent_index(I, data.shape, data.size) f[J] = d[J] == d[I[0]] flat = f.reshape(data.shape) return flat
[ "def", "_find_flats_edges", "(", "self", ",", "data", ",", "mag", ",", "direction", ")", ":", "i12", "=", "np", ".", "arange", "(", "data", ".", "size", ")", ".", "reshape", "(", "data", ".", "shape", ")", "flat", "=", "mag", "==", "FLAT_ID_INT", "...
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", ...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1056-L1079
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.calc_uca
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 edge_init_data : list, optional edge_init_data = [uca_data, done_data, todo_data] uca_data : dict Dictionary with 'left', 'right', 'top', 'bottom' keys that gives the arrays filled with uca data on the edge corresponding to the key done_data : dict As uca_data, but bool array indicating if neighboring tiles have computed a finished value for that edge pixel todo_data : dict As uca_data, but bool array indicating if edges on tile still have to be computed uca_init : array, optional Array with pre-computed upstream contributing area (without edge contributions) Notes ------- if edge_init_data is given, then the initialized area will be modified such that the edges are equal to the edge_init_data. If uca_init is given, then the interior of the upstream area will not be calculated. Only the information from the edges will be updated. Unless the tile is too large so that the calculation is chunked. In that case, the whole tile is re-computed. """ if self.direction is None: self.calc_slopes_directions() # Initialize the upstream area uca_edge_init = np.zeros(self.data.shape, 'float64') uca_edge_done = np.zeros(self.data.shape, bool) uca_edge_todo = np.zeros(self.data.shape, bool) edge_init_done, edge_init_todo = None, None if edge_init_data is not None: edge_init_data, edge_init_done, edge_init_todo = edge_init_data slices = {'left': [slice(None), slice(0, 1)], 'right': [slice(None), slice(-1, None)], 'top': [slice(0, 1), slice(None)], 'bottom': [slice(-1, None), slice(None)]} for key, val in slices.iteritems(): # To initialize and edge it needs to have data and be finished uca_edge_done[val] += \ edge_init_done[key].reshape(uca_edge_init[val].shape) uca_edge_init[val] = \ edge_init_data[key].reshape(uca_edge_init[val].shape) uca_edge_init[val][~uca_edge_done[val]] = 0 uca_edge_todo[val] += \ edge_init_todo[key].reshape(uca_edge_init[val].shape) if uca_init is None: self.uca = np.full(self.data.shape, FLAT_ID_INT, 'float64') else: self.uca = uca_init.astype('float64') if self.data.shape[0] <= self.chunk_size_uca and \ self.data.shape[1] <= self.chunk_size_uca: if uca_init is None: print "Starting uca calculation" res = self._calc_uca_chunk(self.data, self.dX, self.dY, self.direction, self.mag, self.flats, area_edges=uca_edge_init, plotflag=plotflag) self.edge_todo = res[1] self.edge_done = res[2] self.uca = res[0] else: print "Starting edge resolution round: ", # last return value will be None: edge_ area, e2doi, edone, _ = \ self._calc_uca_chunk_update(self.data, self.dX, self.dY, self.direction, self.mag, self.flats, area_edges=uca_edge_init, edge_todo=uca_edge_todo, edge_done=uca_edge_done) self.uca += area self.edge_todo = e2doi self.edge_done = edone else: top_edge, bottom_edge = \ self._get_chunk_edges(self.data.shape[0], self.chunk_size_uca, self.chunk_overlap_uca) left_edge, right_edge = \ self._get_chunk_edges(self.data.shape[1], self.chunk_size_uca, self.chunk_overlap_uca) ovr = self.chunk_overlap_uca # Initialize the edge_todo and done arrays edge_todo = np.zeros(self.data.shape, bool) edge_todo_tile = np.zeros(self.data.shape, bool) edge_not_done_tile = np.zeros(self.data.shape, bool) edge_done = np.zeros(self.data.shape, bool) tile_edge = TileEdge(top_edge, bottom_edge, left_edge, right_edge, ovr, self.elev.grid_coordinates.x_axis, self.elev.grid_coordinates.y_axis, self.data) count = 1 # Mask out the edges because we're just trying to resolve the # internal edge conflicts self.data.mask[:, 0] = True self.data.mask[:, -1] = True self.data.mask[0, :] = True self.data.mask[-1, :] = True # if 1: # uca_init == None: print "Starting uca calculation for chunk: ", # %% for te, be in zip(top_edge, bottom_edge): for le, re in zip(left_edge, right_edge): print count, "[%d:%d, %d:%d]" % (te, be, le, re), count += 1 area, e2doi, edone, e2doi_no_mask, e2o_no_mask = \ self._calc_uca_chunk(self.data[te:be, le:re], self.dX[te:be-1], self.dY[te:be-1], self.direction[te:be, le:re], self.mag[te:be, le:re], self.flats[te:be, le:re], area_edges=uca_edge_init[te:be, le:re], plotflag=plotflag, edge_todo_i_no_mask=uca_edge_todo[te:be, le:re]) self._assign_chunk(self.data, self.uca, area, te, be, le, re, ovr) edge_todo[te:be, le:re] += e2doi edge_not_done_tile[te:be, le:re] += e2o_no_mask # if this tile is on the edge of the domain, we actually # want to keep the edge information # UPDATE: I don't think we actually need this here as it # will be handled by chunk update ??? self._assign_chunk(self.data, edge_todo_tile, e2doi_no_mask, te, be, le, re, ovr) # if te == top_edge[0] or be == bottom_edge[-1] \ # or le == left_edge[0] or re == right_edge[-1]: # edge_todo_tile[te:be, le:re] = e2doi self._assign_chunk(self.data, edge_done, edone, te, be, le, re, ovr) tile_edge.set_all_neighbors_data(self.uca, edge_done, (te, be, le, re)) tile_edge.set_sides((te, be, le, re), e2doi, 'todo', local=True) # %% print '..Done' # This needs to be much more sophisticated because we have to # follow the tile's edge value through the interior. # Since we have to do that anyway, we might as well recompute # the UCA from scratch. So the above branch does that. The branch # below would be more efficient if we can get it working. if 0: # else: # need to populate tile_edge somehow edge_todo_tile = uca_edge_todo & ~uca_edge_done edge_not_done_tile = edge_todo_tile.copy() for te, be in zip(top_edge, bottom_edge): for le, re in zip( [left_edge[0], left_edge[-1]], [right_edge[0], right_edge[-1]]): e2doi = uca_edge_todo[te:be, le:re] tiledata = uca_edge_init[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledata, 'data', local=True) tiledone = uca_edge_done[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledone, 'done', local=True) for te, be in zip([top_edge[0], top_edge[-1]], [bottom_edge[0], bottom_edge[-1]]): for le, re in zip(left_edge, right_edge): e2doi = uca_edge_todo[te:be, le:re] tiledata = uca_edge_init[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledata, 'data', local=True) tiledone = uca_edge_done[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledone, 'done', local=True) if not self.resolve_edges: # This branch is probably horribly broken (but it might have # always been that way) self.tile_edge = tile_edge self.edge_todo = edge_todo self.edge_done = edge_done return self.uca # ## RESOLVING EDGES ## # # Get a good starting tile for the iteration i = tile_edge.find_best_candidate() tile_edge.fix_shapes() # dbug = np.zeros_like(self.uca) print "Starting edge resolution round: ", count = 0 i_old = -1 while i is not None and i != i_old: count += 1 print count, '(%d) .' % i, # %% te, be, le, re = tile_edge.coords[i] data, dX, dY, direction, mag, flats = \ [self.data[te:be, le:re], self.dX[te:be-1], self.dY[te:be-1], self.direction[te:be, le:re], self.mag[te:be, le:re], self.flats[te:be, le:re]] area, e2doi, edone, e2doi_tile = self._calc_uca_chunk_update( data, dX, dY, direction, mag, flats, tile_edge, i, edge_todo=edge_not_done_tile[te:be, le:re]) self._assign_chunk(self.data, self.uca, area, te, be, le, re, ovr, add=True) self._assign_chunk(self.data, edge_done, edone, te, be, le, re, ovr) tile_edge.set_all_neighbors_data(self.uca, edge_done, (te, be, le, re)) try: edge_not_done_tile[te:be, le:re] += e2doi_tile except: import ipdb; ipdb.set_trace() # BREAKPOINT tile_edge.set_sides((te, be, le, re), e2doi, 'todo', local=True) i_old = i i = tile_edge.find_best_candidate() # Debugging plots below. Feel free to uncomment for debugging # def drawgrid(): # ax = gca(); # ax.set_xticks(np.linspace(-0.5, 63.5, 9)) # ax.set_yticks(np.linspace(-0.5, 63.5, 9)) # grid(lw=2, ls='-', c=(0.5, 0.5, 0.5)) # figure(1);clf();imshow((self.uca), interpolation='none');colorbar(); title("uca" + str(i_old) + " " + str(i));drawgrid() # figure(2);clf();imshow(area, interpolation='none');colorbar(); title("local area" + str(i_old) + " " + str(i)) ## edge_todo[:] = 0 ## edge_todo = tile_edge.fill_array(edge_todo, 'todo', add=True) # figure(3);clf();imshow(edge_todo*1.0 + edge_done*2.0, interpolation='none');colorbar(); title("todo" + str(i_old) + " " + str(i));clim(0, 3) # edge_todo[:] = 0 # edge_todo = tile_edge.fill_array(edge_todo, 'coulddo', add=True) # figure(3);clf();imshow(edge_todo*1.0 + edge_done*2.0, interpolation='none');colorbar(); title("todo" + str(i_old) + " " + str(i));clim(0, 3);drawgrid() # figure(4);clf();imshow(tile_edge.percent_done, interpolation='none');colorbar(); title("percent done" + str(i_old) + " " + str(i));clim(0, 1) # dbug[:] = 0 # dbug = tile_edge.fill_array(dbug, 'coulddo', maximize=False) # dbug[dbug > 0] -= (self.uca - ref_area)[dbug > 0] # figure(5);clf();imshow(dbug, interpolation='none');colorbar(); title("data diff" + str(i_old) + " " + str(i));drawgrid() # dbug = (self.uca - area1) # figure(6);clf();imshow(np.log10(np.abs(dbug)), interpolation='none');colorbar(); title("uca diff" + str(i_old) + " " + str(i));drawgrid() # %% self.tile_edge = tile_edge self.edge_todo = edge_todo_tile self.edge_done = ~edge_not_done_tile print '..Done' # Fix the very last pixel on the edges self.fix_edge_pixels(edge_init_data, edge_init_done, edge_init_todo) gc.collect() # Just in case return self.uca
python
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 edge_init_data : list, optional edge_init_data = [uca_data, done_data, todo_data] uca_data : dict Dictionary with 'left', 'right', 'top', 'bottom' keys that gives the arrays filled with uca data on the edge corresponding to the key done_data : dict As uca_data, but bool array indicating if neighboring tiles have computed a finished value for that edge pixel todo_data : dict As uca_data, but bool array indicating if edges on tile still have to be computed uca_init : array, optional Array with pre-computed upstream contributing area (without edge contributions) Notes ------- if edge_init_data is given, then the initialized area will be modified such that the edges are equal to the edge_init_data. If uca_init is given, then the interior of the upstream area will not be calculated. Only the information from the edges will be updated. Unless the tile is too large so that the calculation is chunked. In that case, the whole tile is re-computed. """ if self.direction is None: self.calc_slopes_directions() # Initialize the upstream area uca_edge_init = np.zeros(self.data.shape, 'float64') uca_edge_done = np.zeros(self.data.shape, bool) uca_edge_todo = np.zeros(self.data.shape, bool) edge_init_done, edge_init_todo = None, None if edge_init_data is not None: edge_init_data, edge_init_done, edge_init_todo = edge_init_data slices = {'left': [slice(None), slice(0, 1)], 'right': [slice(None), slice(-1, None)], 'top': [slice(0, 1), slice(None)], 'bottom': [slice(-1, None), slice(None)]} for key, val in slices.iteritems(): # To initialize and edge it needs to have data and be finished uca_edge_done[val] += \ edge_init_done[key].reshape(uca_edge_init[val].shape) uca_edge_init[val] = \ edge_init_data[key].reshape(uca_edge_init[val].shape) uca_edge_init[val][~uca_edge_done[val]] = 0 uca_edge_todo[val] += \ edge_init_todo[key].reshape(uca_edge_init[val].shape) if uca_init is None: self.uca = np.full(self.data.shape, FLAT_ID_INT, 'float64') else: self.uca = uca_init.astype('float64') if self.data.shape[0] <= self.chunk_size_uca and \ self.data.shape[1] <= self.chunk_size_uca: if uca_init is None: print "Starting uca calculation" res = self._calc_uca_chunk(self.data, self.dX, self.dY, self.direction, self.mag, self.flats, area_edges=uca_edge_init, plotflag=plotflag) self.edge_todo = res[1] self.edge_done = res[2] self.uca = res[0] else: print "Starting edge resolution round: ", # last return value will be None: edge_ area, e2doi, edone, _ = \ self._calc_uca_chunk_update(self.data, self.dX, self.dY, self.direction, self.mag, self.flats, area_edges=uca_edge_init, edge_todo=uca_edge_todo, edge_done=uca_edge_done) self.uca += area self.edge_todo = e2doi self.edge_done = edone else: top_edge, bottom_edge = \ self._get_chunk_edges(self.data.shape[0], self.chunk_size_uca, self.chunk_overlap_uca) left_edge, right_edge = \ self._get_chunk_edges(self.data.shape[1], self.chunk_size_uca, self.chunk_overlap_uca) ovr = self.chunk_overlap_uca # Initialize the edge_todo and done arrays edge_todo = np.zeros(self.data.shape, bool) edge_todo_tile = np.zeros(self.data.shape, bool) edge_not_done_tile = np.zeros(self.data.shape, bool) edge_done = np.zeros(self.data.shape, bool) tile_edge = TileEdge(top_edge, bottom_edge, left_edge, right_edge, ovr, self.elev.grid_coordinates.x_axis, self.elev.grid_coordinates.y_axis, self.data) count = 1 # Mask out the edges because we're just trying to resolve the # internal edge conflicts self.data.mask[:, 0] = True self.data.mask[:, -1] = True self.data.mask[0, :] = True self.data.mask[-1, :] = True # if 1: # uca_init == None: print "Starting uca calculation for chunk: ", # %% for te, be in zip(top_edge, bottom_edge): for le, re in zip(left_edge, right_edge): print count, "[%d:%d, %d:%d]" % (te, be, le, re), count += 1 area, e2doi, edone, e2doi_no_mask, e2o_no_mask = \ self._calc_uca_chunk(self.data[te:be, le:re], self.dX[te:be-1], self.dY[te:be-1], self.direction[te:be, le:re], self.mag[te:be, le:re], self.flats[te:be, le:re], area_edges=uca_edge_init[te:be, le:re], plotflag=plotflag, edge_todo_i_no_mask=uca_edge_todo[te:be, le:re]) self._assign_chunk(self.data, self.uca, area, te, be, le, re, ovr) edge_todo[te:be, le:re] += e2doi edge_not_done_tile[te:be, le:re] += e2o_no_mask # if this tile is on the edge of the domain, we actually # want to keep the edge information # UPDATE: I don't think we actually need this here as it # will be handled by chunk update ??? self._assign_chunk(self.data, edge_todo_tile, e2doi_no_mask, te, be, le, re, ovr) # if te == top_edge[0] or be == bottom_edge[-1] \ # or le == left_edge[0] or re == right_edge[-1]: # edge_todo_tile[te:be, le:re] = e2doi self._assign_chunk(self.data, edge_done, edone, te, be, le, re, ovr) tile_edge.set_all_neighbors_data(self.uca, edge_done, (te, be, le, re)) tile_edge.set_sides((te, be, le, re), e2doi, 'todo', local=True) # %% print '..Done' # This needs to be much more sophisticated because we have to # follow the tile's edge value through the interior. # Since we have to do that anyway, we might as well recompute # the UCA from scratch. So the above branch does that. The branch # below would be more efficient if we can get it working. if 0: # else: # need to populate tile_edge somehow edge_todo_tile = uca_edge_todo & ~uca_edge_done edge_not_done_tile = edge_todo_tile.copy() for te, be in zip(top_edge, bottom_edge): for le, re in zip( [left_edge[0], left_edge[-1]], [right_edge[0], right_edge[-1]]): e2doi = uca_edge_todo[te:be, le:re] tiledata = uca_edge_init[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledata, 'data', local=True) tiledone = uca_edge_done[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledone, 'done', local=True) for te, be in zip([top_edge[0], top_edge[-1]], [bottom_edge[0], bottom_edge[-1]]): for le, re in zip(left_edge, right_edge): e2doi = uca_edge_todo[te:be, le:re] tiledata = uca_edge_init[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledata, 'data', local=True) tiledone = uca_edge_done[te:be, le:re] tile_edge.set_sides((te, be, le, re), tiledone, 'done', local=True) if not self.resolve_edges: # This branch is probably horribly broken (but it might have # always been that way) self.tile_edge = tile_edge self.edge_todo = edge_todo self.edge_done = edge_done return self.uca # ## RESOLVING EDGES ## # # Get a good starting tile for the iteration i = tile_edge.find_best_candidate() tile_edge.fix_shapes() # dbug = np.zeros_like(self.uca) print "Starting edge resolution round: ", count = 0 i_old = -1 while i is not None and i != i_old: count += 1 print count, '(%d) .' % i, # %% te, be, le, re = tile_edge.coords[i] data, dX, dY, direction, mag, flats = \ [self.data[te:be, le:re], self.dX[te:be-1], self.dY[te:be-1], self.direction[te:be, le:re], self.mag[te:be, le:re], self.flats[te:be, le:re]] area, e2doi, edone, e2doi_tile = self._calc_uca_chunk_update( data, dX, dY, direction, mag, flats, tile_edge, i, edge_todo=edge_not_done_tile[te:be, le:re]) self._assign_chunk(self.data, self.uca, area, te, be, le, re, ovr, add=True) self._assign_chunk(self.data, edge_done, edone, te, be, le, re, ovr) tile_edge.set_all_neighbors_data(self.uca, edge_done, (te, be, le, re)) try: edge_not_done_tile[te:be, le:re] += e2doi_tile except: import ipdb; ipdb.set_trace() # BREAKPOINT tile_edge.set_sides((te, be, le, re), e2doi, 'todo', local=True) i_old = i i = tile_edge.find_best_candidate() # Debugging plots below. Feel free to uncomment for debugging # def drawgrid(): # ax = gca(); # ax.set_xticks(np.linspace(-0.5, 63.5, 9)) # ax.set_yticks(np.linspace(-0.5, 63.5, 9)) # grid(lw=2, ls='-', c=(0.5, 0.5, 0.5)) # figure(1);clf();imshow((self.uca), interpolation='none');colorbar(); title("uca" + str(i_old) + " " + str(i));drawgrid() # figure(2);clf();imshow(area, interpolation='none');colorbar(); title("local area" + str(i_old) + " " + str(i)) ## edge_todo[:] = 0 ## edge_todo = tile_edge.fill_array(edge_todo, 'todo', add=True) # figure(3);clf();imshow(edge_todo*1.0 + edge_done*2.0, interpolation='none');colorbar(); title("todo" + str(i_old) + " " + str(i));clim(0, 3) # edge_todo[:] = 0 # edge_todo = tile_edge.fill_array(edge_todo, 'coulddo', add=True) # figure(3);clf();imshow(edge_todo*1.0 + edge_done*2.0, interpolation='none');colorbar(); title("todo" + str(i_old) + " " + str(i));clim(0, 3);drawgrid() # figure(4);clf();imshow(tile_edge.percent_done, interpolation='none');colorbar(); title("percent done" + str(i_old) + " " + str(i));clim(0, 1) # dbug[:] = 0 # dbug = tile_edge.fill_array(dbug, 'coulddo', maximize=False) # dbug[dbug > 0] -= (self.uca - ref_area)[dbug > 0] # figure(5);clf();imshow(dbug, interpolation='none');colorbar(); title("data diff" + str(i_old) + " " + str(i));drawgrid() # dbug = (self.uca - area1) # figure(6);clf();imshow(np.log10(np.abs(dbug)), interpolation='none');colorbar(); title("uca diff" + str(i_old) + " " + str(i));drawgrid() # %% self.tile_edge = tile_edge self.edge_todo = edge_todo_tile self.edge_done = ~edge_not_done_tile print '..Done' # Fix the very last pixel on the edges self.fix_edge_pixels(edge_init_data, edge_init_done, edge_init_todo) gc.collect() # Just in case return self.uca
[ "def", "calc_uca", "(", "self", ",", "plotflag", "=", "False", ",", "edge_init_data", "=", "None", ",", "uca_init", "=", "None", ")", ":", "if", "self", ".", "direction", "is", "None", ":", "self", ".", "calc_slopes_directions", "(", ")", "# Initialize the...
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, todo_data] uca_data : dict Dictionary with 'left', 'right', 'top', 'bottom' keys that gives the arrays filled with uca data on the edge corresponding to the key done_data : dict As uca_data, but bool array indicating if neighboring tiles have computed a finished value for that edge pixel todo_data : dict As uca_data, but bool array indicating if edges on tile still have to be computed uca_init : array, optional Array with pre-computed upstream contributing area (without edge contributions) Notes ------- if edge_init_data is given, then the initialized area will be modified such that the edges are equal to the edge_init_data. If uca_init is given, then the interior of the upstream area will not be calculated. Only the information from the edges will be updated. Unless the tile is too large so that the calculation is chunked. In that case, the whole tile is re-computed.
[ "Calculates", "the", "upstream", "contributing", "area", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1081-L1344
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.fix_edge_pixels
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) then this data is used. This is a bit of hack to take care of the edge-values. It could possibly be handled through the main algorithm, but at least here the treatment is explicit. """ data, dX, dY, direction, flats = \ self.data, self.dX, self.dY, self.direction, self.flats sides = ['left', 'right', 'top', 'bottom'] slices_o = [[slice(None), slice(1, 2)], [slice(None), slice(-2, -1)], [slice(1, 2), slice(None)], [slice(-2, -1), slice(None)]] slices_d = [[slice(None), slice(0, 1)], [slice(None), slice(-1, None)], [slice(0, 1), slice(None)], [slice(-1, None), slice(None)]] # The first set of edges will have contributions from two nodes whereas # the second set of edges will only have contributinos from one node indices = {'left': [[3, 4], [2, 5]], 'right': [[0, 7], [1, 6]], 'top': [[1, 2], [0, 3]], 'bottom': [[5, 6], [4, 7]]} # Figure out which section the drainage goes towards, and what # proportion goes to the straight-sided (as opposed to diagonal) node. for side, slice_o, slice_d in zip(sides, slices_o, slices_d): section, proportion = \ self._calc_uca_section_proportion(data[slice_o], dX[slice_o[0]], dY[slice_o[0]], direction[slice_o], flats[slice_o]) # self-initialize: if side in ['left', 'right']: self.uca[slice_d] = \ np.concatenate(([dX[slice_d[0]][0] * dY[slice_d[0]][0]], dX[slice_d[0]] * dY[slice_d[0]]))\ .reshape(self.uca[slice_d].shape) else: self.uca[slice_d] = dX[slice_d[0]][0] * dY[slice_d[0]][0] for e in range(2): for i in indices[side][e]: ed = self.facets[i][2] ids = section == i if e == 0: self.uca[slice_d][ids] += self.uca[slice_o][ids] \ * proportion[ids] self.uca[slice_d][ids] += \ np.roll(np.roll(self.uca[slice_o] * (1 - proportion), ed[0], 0), ed[1], 1)[ids] if e == 1: self.uca[slice_d][ids] += \ np.roll(np.roll(self.uca[slice_o] * (proportion), ed[0], 0), ed[1], 1)[ids] # Finally, add the edge data from adjacent tiles if edge_init_done is not None: ids = edge_init_done[side] # > 0 if side in ['left', 'right']: self.uca[slice_d][ids, :] = \ edge_init_data[side][ids][:, None] else: self.uca[slice_d][:, ids] = edge_init_data[side][ids]
python
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) then this data is used. This is a bit of hack to take care of the edge-values. It could possibly be handled through the main algorithm, but at least here the treatment is explicit. """ data, dX, dY, direction, flats = \ self.data, self.dX, self.dY, self.direction, self.flats sides = ['left', 'right', 'top', 'bottom'] slices_o = [[slice(None), slice(1, 2)], [slice(None), slice(-2, -1)], [slice(1, 2), slice(None)], [slice(-2, -1), slice(None)]] slices_d = [[slice(None), slice(0, 1)], [slice(None), slice(-1, None)], [slice(0, 1), slice(None)], [slice(-1, None), slice(None)]] # The first set of edges will have contributions from two nodes whereas # the second set of edges will only have contributinos from one node indices = {'left': [[3, 4], [2, 5]], 'right': [[0, 7], [1, 6]], 'top': [[1, 2], [0, 3]], 'bottom': [[5, 6], [4, 7]]} # Figure out which section the drainage goes towards, and what # proportion goes to the straight-sided (as opposed to diagonal) node. for side, slice_o, slice_d in zip(sides, slices_o, slices_d): section, proportion = \ self._calc_uca_section_proportion(data[slice_o], dX[slice_o[0]], dY[slice_o[0]], direction[slice_o], flats[slice_o]) # self-initialize: if side in ['left', 'right']: self.uca[slice_d] = \ np.concatenate(([dX[slice_d[0]][0] * dY[slice_d[0]][0]], dX[slice_d[0]] * dY[slice_d[0]]))\ .reshape(self.uca[slice_d].shape) else: self.uca[slice_d] = dX[slice_d[0]][0] * dY[slice_d[0]][0] for e in range(2): for i in indices[side][e]: ed = self.facets[i][2] ids = section == i if e == 0: self.uca[slice_d][ids] += self.uca[slice_o][ids] \ * proportion[ids] self.uca[slice_d][ids] += \ np.roll(np.roll(self.uca[slice_o] * (1 - proportion), ed[0], 0), ed[1], 1)[ids] if e == 1: self.uca[slice_d][ids] += \ np.roll(np.roll(self.uca[slice_o] * (proportion), ed[0], 0), ed[1], 1)[ids] # Finally, add the edge data from adjacent tiles if edge_init_done is not None: ids = edge_init_done[side] # > 0 if side in ['left', 'right']: self.uca[slice_d][ids, :] = \ edge_init_data[side][ids][:, None] else: self.uca[slice_d][:, ids] = edge_init_data[side][ids]
[ "def", "fix_edge_pixels", "(", "self", ",", "edge_init_data", ",", "edge_init_done", ",", "edge_init_todo", ")", ":", "data", ",", "dX", ",", "dY", ",", "direction", ",", "flats", "=", "self", ".", "data", ",", "self", ".", "dX", ",", "self", ".", "dY"...
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 possibly be handled through the main algorithm, but at least here the treatment is explicit.
[ "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", ...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1346-L1412
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._calc_uca_chunk_update
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 to contributions from the edges only. """ # %% sides = ['left', 'right', 'top', 'bottom'] slices = [[slice(None), slice(0, 1)], [slice(None), slice(-1, None)], [slice(0, 1), slice(None)], [slice(-1, None), slice(None)]] # Figure out which section the drainage goes towards, and what # proportion goes to the straight-sided (as opposed to diagonal) node. section, proportion = self._calc_uca_section_proportion( data, dX, dY, direction, flats) # Build the drainage or adjacency matrix A = self._mk_adjacency_matrix(section, proportion, flats, data, mag, dX, dY) if CYTHON: B = A C = A.tocsr() if not CYTHON: A = A.tocoo() ids = np.zeros(data.shape, bool) area = np.zeros(data.shape, 'float64') # Set the ids to the edges that are now done, and initialize the # edge area if tile_edge is not None: if edge_todo is not None: edge_todo_tile = edge_todo else: edge_todo_tile = None edge_todo = np.zeros(data.shape, bool) for side, slice0 in zip(sides, slices): edge = getattr(tile_edge, side).ravel()[i] ids[slice0] = edge.done & edge.coulddo # only add area from the finished edges area[slice0] = edge.data * edge.done * edge.coulddo edge_todo[slice0] = edge.todo & ~edge.done elif area_edges is not None and edge_todo is not None \ and edge_done is not None: area[:, 0] = area_edges[:, 0] area[:, -1] = area_edges[:, -1] area[-1, :] = area_edges[-1, :] area[0, :] = area_edges[0, :] # Initialize starting ids ids = edge_done & edge_todo edge_todo = edge_todo & ~edge_done edge_todo_tile = None else: raise RuntimeError("Need to specify either tile_edge or area_edges" "in _calc_uca_chunk_update") ids = ids.ravel() ids0 = ids.copy() area[flats] = np.nan edge_done = ~edge_todo edge_todo_i = edge_todo.copy() ids_old = np.zeros_like(ids) # I need this to keep track of when I have to add the area, and when # I have to replace the area. ids_i = np.arange(ids.size) done = np.ones(data.shape, bool) done.ravel()[ids] = False # Now we have to advance done through the mesh to figure out which # contributions matter (i.e. what's done already) def drain_pixels_done(ids, arr, rows_A, cols_A): ids_old = ids.copy() ids_old[:] = False # If I use ids.sum() > 0 then I might get stuck in circular # references. while (ids - ids_old).sum() > 0: # %% print "x", ids_old = ids.copy() ids_todo = ids_i[ids.ravel()] ids[:] = False for id_todo in ids_todo: rows = cols_A == id_todo rows_id = rows_A[rows] ids[rows_id] += arr.ravel()[rows_id] is True arr.ravel()[rows_id] = False # Set second arrival new id return arr if CYTHON: a = cyutils.drain_connections( done.ravel(), ids, B.indptr, B.indices, set_to=False) done = a.reshape(done.shape).astype(bool) else: done = drain_pixels_done(ids, done, A.row, A.col) done[data.mask] = True # deal with no-data values # ids = ids0.copy() # Set all the edges to "done" for ids0. This ensures that no edges # will ever be updated, whether they are done or not. ids0 = ids0.reshape(data.shape) ids0[:, 0] = True ids0[:, -1] = True ids0[0, :] = True ids0[-1, :] = True ids0 = ids0.ravel() ids_old[:] = 0 # %% def drain_area(ids, area, done, rows_A, cols_A, data_A, edge_todo_tile): ids_old = ids.copy() ids_old[:] = False # If I use ids.sum() > 0 then I might get stuck in # circular references. while (ids - ids_old).sum() > 0: # %% print "o", ids_old = ids.copy() done.ravel()[ids] = True ids_todo = ids_i[ids.ravel()] ids[:] = False for id_todo in ids_todo: rows = cols_A == id_todo rows_id = rows_A[rows] factor = data_A[rows] # not allowed to modify edge values edge_filter_ids = ~ids0[rows_id] factor = factor[edge_filter_ids] rows_id = rows_id[edge_filter_ids] area.ravel()[rows_id] += area.ravel()[id_todo] * factor if edge_todo_tile is not None: edge_todo_tile.ravel()[rows_id] += \ edge_todo_tile.ravel()[id_todo] * factor # Figure out of this cell that just received a contribution # should give its contribution to what's next... i.e. make # sure all inputs have been added together for row_id in rows_id: # this is the 'waiting' part cols = cols_A[rows_A == row_id] ids[row_id] += (~(done.ravel()[cols])).sum() == 0 # for col in cols: # print 'row', row_id, 'col', col, 'done', done.ravel()[col] # Follow the drainage along. New candidates are cells that # just changed #ids = (track_id_old.ravel() == -1) \ # & (track_id_old.ravel() != track_id.ravel()) # done.ravel()[ids] = True # figure(7);clf();imshow(ids.reshape(mag.shape), interpolation='none') # figure(8);clf();imshow(area, interpolation='none');colorbar() # figure(9);clf();imshow(done, interpolation='none');colorbar() # figure(10);clf();imshow(a + area - b, interpolation='none');colorbar() #%% # self._plot_connectivity(A, data=data) return area, done, edge_todo_tile if CYTHON: if edge_todo_tile is not None: a, b, c, d = cyutils.drain_area(area.ravel(), done.ravel(), ids, B.indptr, B.indices, B.data, C.indptr, C.indices, area.shape[0], area.shape[1], edge_todo_tile.astype('float64').ravel(), skip_edge=True) edge_todo_tile = c.reshape(edge_todo_tile.shape) else: a, b, c, d = cyutils.drain_area(area.ravel(), done.ravel(), ids, B.indptr, B.indices, B.data, C.indptr, C.indices, area.shape[0], area.shape[1], skip_edge=True) area = a.reshape(area.shape) done = b.reshape(done.shape) else: area, done, edge_todo_tile = \ drain_area(ids, area, done, A.row, A.col, A.data, edge_todo_tile) # Rather unfortunately, we still have to follow through the boolean # edge_todo matrix... ids = edge_todo.copy().ravel() # %% def drain_pixels_todo(ids, arr, rows_A, cols_A): ids_old = ids.copy() ids_old[:] = False # If I use ids.sum() > 0 then I might get stuck in # circular references. while (ids - ids_old).sum() > 0: # %% print "x", ids_old = ids.copy() # edge_todo_old = arr.copy() ids_todo = ids_i[ids.ravel()] ids[:] = False for id_todo in ids_todo: rows = cols_A == id_todo rows_id = rows_A[rows] ids[rows_id] += arr.ravel()[rows_id] == False arr.ravel()[rows_id] = True # Set new id of second arrival # #Follow the drainage along. New candidates are cells that just changed # ids = (edge_todo_old.ravel() != arr.ravel()) return arr if CYTHON: a = cyutils.drain_connections(edge_todo.ravel(), ids, B.indptr, B.indices, set_to=True) edge_todo = a.reshape(edge_todo.shape).astype(bool) else: edge_todo = drain_pixels_todo(ids, edge_todo, A.row, A.col) area[flats] = np.nan edge_done = ~edge_todo return area, edge_todo_i, edge_done, edge_todo_tile
python
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 to contributions from the edges only. """ # %% sides = ['left', 'right', 'top', 'bottom'] slices = [[slice(None), slice(0, 1)], [slice(None), slice(-1, None)], [slice(0, 1), slice(None)], [slice(-1, None), slice(None)]] # Figure out which section the drainage goes towards, and what # proportion goes to the straight-sided (as opposed to diagonal) node. section, proportion = self._calc_uca_section_proportion( data, dX, dY, direction, flats) # Build the drainage or adjacency matrix A = self._mk_adjacency_matrix(section, proportion, flats, data, mag, dX, dY) if CYTHON: B = A C = A.tocsr() if not CYTHON: A = A.tocoo() ids = np.zeros(data.shape, bool) area = np.zeros(data.shape, 'float64') # Set the ids to the edges that are now done, and initialize the # edge area if tile_edge is not None: if edge_todo is not None: edge_todo_tile = edge_todo else: edge_todo_tile = None edge_todo = np.zeros(data.shape, bool) for side, slice0 in zip(sides, slices): edge = getattr(tile_edge, side).ravel()[i] ids[slice0] = edge.done & edge.coulddo # only add area from the finished edges area[slice0] = edge.data * edge.done * edge.coulddo edge_todo[slice0] = edge.todo & ~edge.done elif area_edges is not None and edge_todo is not None \ and edge_done is not None: area[:, 0] = area_edges[:, 0] area[:, -1] = area_edges[:, -1] area[-1, :] = area_edges[-1, :] area[0, :] = area_edges[0, :] # Initialize starting ids ids = edge_done & edge_todo edge_todo = edge_todo & ~edge_done edge_todo_tile = None else: raise RuntimeError("Need to specify either tile_edge or area_edges" "in _calc_uca_chunk_update") ids = ids.ravel() ids0 = ids.copy() area[flats] = np.nan edge_done = ~edge_todo edge_todo_i = edge_todo.copy() ids_old = np.zeros_like(ids) # I need this to keep track of when I have to add the area, and when # I have to replace the area. ids_i = np.arange(ids.size) done = np.ones(data.shape, bool) done.ravel()[ids] = False # Now we have to advance done through the mesh to figure out which # contributions matter (i.e. what's done already) def drain_pixels_done(ids, arr, rows_A, cols_A): ids_old = ids.copy() ids_old[:] = False # If I use ids.sum() > 0 then I might get stuck in circular # references. while (ids - ids_old).sum() > 0: # %% print "x", ids_old = ids.copy() ids_todo = ids_i[ids.ravel()] ids[:] = False for id_todo in ids_todo: rows = cols_A == id_todo rows_id = rows_A[rows] ids[rows_id] += arr.ravel()[rows_id] is True arr.ravel()[rows_id] = False # Set second arrival new id return arr if CYTHON: a = cyutils.drain_connections( done.ravel(), ids, B.indptr, B.indices, set_to=False) done = a.reshape(done.shape).astype(bool) else: done = drain_pixels_done(ids, done, A.row, A.col) done[data.mask] = True # deal with no-data values # ids = ids0.copy() # Set all the edges to "done" for ids0. This ensures that no edges # will ever be updated, whether they are done or not. ids0 = ids0.reshape(data.shape) ids0[:, 0] = True ids0[:, -1] = True ids0[0, :] = True ids0[-1, :] = True ids0 = ids0.ravel() ids_old[:] = 0 # %% def drain_area(ids, area, done, rows_A, cols_A, data_A, edge_todo_tile): ids_old = ids.copy() ids_old[:] = False # If I use ids.sum() > 0 then I might get stuck in # circular references. while (ids - ids_old).sum() > 0: # %% print "o", ids_old = ids.copy() done.ravel()[ids] = True ids_todo = ids_i[ids.ravel()] ids[:] = False for id_todo in ids_todo: rows = cols_A == id_todo rows_id = rows_A[rows] factor = data_A[rows] # not allowed to modify edge values edge_filter_ids = ~ids0[rows_id] factor = factor[edge_filter_ids] rows_id = rows_id[edge_filter_ids] area.ravel()[rows_id] += area.ravel()[id_todo] * factor if edge_todo_tile is not None: edge_todo_tile.ravel()[rows_id] += \ edge_todo_tile.ravel()[id_todo] * factor # Figure out of this cell that just received a contribution # should give its contribution to what's next... i.e. make # sure all inputs have been added together for row_id in rows_id: # this is the 'waiting' part cols = cols_A[rows_A == row_id] ids[row_id] += (~(done.ravel()[cols])).sum() == 0 # for col in cols: # print 'row', row_id, 'col', col, 'done', done.ravel()[col] # Follow the drainage along. New candidates are cells that # just changed #ids = (track_id_old.ravel() == -1) \ # & (track_id_old.ravel() != track_id.ravel()) # done.ravel()[ids] = True # figure(7);clf();imshow(ids.reshape(mag.shape), interpolation='none') # figure(8);clf();imshow(area, interpolation='none');colorbar() # figure(9);clf();imshow(done, interpolation='none');colorbar() # figure(10);clf();imshow(a + area - b, interpolation='none');colorbar() #%% # self._plot_connectivity(A, data=data) return area, done, edge_todo_tile if CYTHON: if edge_todo_tile is not None: a, b, c, d = cyutils.drain_area(area.ravel(), done.ravel(), ids, B.indptr, B.indices, B.data, C.indptr, C.indices, area.shape[0], area.shape[1], edge_todo_tile.astype('float64').ravel(), skip_edge=True) edge_todo_tile = c.reshape(edge_todo_tile.shape) else: a, b, c, d = cyutils.drain_area(area.ravel(), done.ravel(), ids, B.indptr, B.indices, B.data, C.indptr, C.indices, area.shape[0], area.shape[1], skip_edge=True) area = a.reshape(area.shape) done = b.reshape(done.shape) else: area, done, edge_todo_tile = \ drain_area(ids, area, done, A.row, A.col, A.data, edge_todo_tile) # Rather unfortunately, we still have to follow through the boolean # edge_todo matrix... ids = edge_todo.copy().ravel() # %% def drain_pixels_todo(ids, arr, rows_A, cols_A): ids_old = ids.copy() ids_old[:] = False # If I use ids.sum() > 0 then I might get stuck in # circular references. while (ids - ids_old).sum() > 0: # %% print "x", ids_old = ids.copy() # edge_todo_old = arr.copy() ids_todo = ids_i[ids.ravel()] ids[:] = False for id_todo in ids_todo: rows = cols_A == id_todo rows_id = rows_A[rows] ids[rows_id] += arr.ravel()[rows_id] == False arr.ravel()[rows_id] = True # Set new id of second arrival # #Follow the drainage along. New candidates are cells that just changed # ids = (edge_todo_old.ravel() != arr.ravel()) return arr if CYTHON: a = cyutils.drain_connections(edge_todo.ravel(), ids, B.indptr, B.indices, set_to=True) edge_todo = a.reshape(edge_todo.shape).astype(bool) else: edge_todo = drain_pixels_todo(ids, edge_todo, A.row, A.col) area[flats] = np.nan edge_done = ~edge_todo return area, edge_todo_i, edge_done, edge_todo_tile
[ "def", "_calc_uca_chunk_update", "(", "self", ",", "data", ",", "dX", ",", "dY", ",", "direction", ",", "mag", ",", "flats", ",", "tile_edge", "=", "None", ",", "i", "=", "None", ",", "area_edges", "=", "None", ",", "edge_todo", "=", "None", ",", "ed...
Calculates the upstream contributing area due to contributions from the edges only.
[ "Calculates", "the", "upstream", "contributing", "area", "due", "to", "contributions", "from", "the", "edges", "only", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1414-L1642
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._calc_uca_chunk
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. """ # %% # Figure out which section the drainage goes towards, and what # proportion goes to the straight-sided (as opposed to diagonal) node. section, proportion = self._calc_uca_section_proportion( data, dX, dY, direction, flats) # Build the drainage or adjacency matrix A = self._mk_adjacency_matrix(section, proportion, flats, data, mag, dX, dY) if CYTHON: B = A.tocsr() colsum = np.array(A.sum(1)).ravel() ids = colsum == 0 # If no one drains into me area = (dX * dY) # Record minimum area min_area = np.nanmin(area) self.twi_min_area = min(self.twi_min_area, min_area) area = np.concatenate((area[0:1], area)).reshape(area.size+1, 1) area = area.repeat(data.shape[1], 1) # Set the edge areas to zero, will add those contributions later area[:, 0] = area_edges[:, 0] area[:, -1] = area_edges[:, -1] area[-1, :] = area_edges[-1, :] area[0, :] = area_edges[0, :] # These edges are done, they have been drained already ids[area_edges.ravel() > 0] = True done = np.zeros(data.shape, bool) done.ravel()[ids] = True # deal with no-data values done[1:-1, 1:-1] = done[1:-1, 1:-1] | data.mask[1:-1, 1:-1] # Check the inlet edges edge_todo = np.zeros_like(done) ids_ed = np.arange(data.size).reshape(data.shape) # left edge_todo[:, 0] = (A[:, ids_ed[:, 0]].sum(0) > 0) \ & (area_edges[:, 0] == 0) edge_todo[:, -1] = (A[:, ids_ed[:, -1]].sum(0) > 0) \ & (area_edges[:, -1] == 0) edge_todo[0, :] = (A[:, ids_ed[0, :]].sum(0) > 0) \ & (area_edges[0, :] == 0) edge_todo[-1, :] = (A[:, ids_ed[-1, :]].sum(0) > 0) \ & (area_edges[-1, :] == 0) # Will do the tile-level doneness edge_todo_i_no_mask = edge_todo.copy() & edge_todo_i_no_mask edge_todo_no_mask = edge_todo_i_no_mask.copy() # tile-level doneness edge_todo[data.mask] = False # Don't do masked areas # Initialize done edges edge_todo_i = edge_todo.copy() ids_old = np.zeros_like(ids) # %% count = 1 if CYTHON: area_ = area.ravel() done_ = done.ravel() edge_todo_ = edge_todo.astype('float64').ravel() edge_todo_no_mask_ = edge_todo_no_mask.astype('float64').ravel() data_ = data.ravel() while (np.any(~done) and count < self.circular_ref_maxcount): print ".", count += 1 if CYTHON: area_, done_, edge_todo_, edge_todo_no_mask_ = cyutils.drain_area(area_, done_, ids, A.indptr, A.indices, A.data, B.indptr, B.indices, area.shape[0], area.shape[1], edge_todo_, edge_todo_no_mask_) else: # If I use ids.sum() > 0 then I might get stuck in # circular references. while (ids - ids_old).sum() > 0: # %% ids_old = ids.copy() ids, area, done, edge_todo = \ self._drain_step(A, ids, area, done, edge_todo) # figure(1);clf();imshow(area, interpolation='none');colorbar() # figure(2);clf();imshow(ids.reshape(area.shape), interpolation='none');colorbar() # figure(3);clf();imshow(done, interpolation='none');colorbar() done_ = done.ravel() #%% ids[:] = False max_elev = (data_ * (~done_)).max() ids[((data_ * (~done_) - max_elev) / max_elev > -0.01)] = True if CYTHON: area = area_.reshape(area.shape) done = done_.reshape(done.shape) edge_todo = edge_todo_.reshape(edge_todo.shape).astype(bool) edge_todo_no_mask = edge_todo_no_mask_.reshape(edge_todo_no_mask.shape).astype(bool) area[flats] = np.nan edge_done = ~edge_todo edge_done[data.mask] = True # Don't do masked areas if self.apply_uca_limit_edges: # 2x because of bifurcations (maybe should be more than 2x, but # should be ok edge_done[area > self.uca_saturation_limit * 2 * min_area] = True # %% if plotflag: # TODO DTYPE self._plot_connectivity(A, (done.astype('float64') is False) + flats.astype('float64') * 2, [0, 3]) return area, edge_todo_i, edge_done, edge_todo_i_no_mask, edge_todo_no_mask
python
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. """ # %% # Figure out which section the drainage goes towards, and what # proportion goes to the straight-sided (as opposed to diagonal) node. section, proportion = self._calc_uca_section_proportion( data, dX, dY, direction, flats) # Build the drainage or adjacency matrix A = self._mk_adjacency_matrix(section, proportion, flats, data, mag, dX, dY) if CYTHON: B = A.tocsr() colsum = np.array(A.sum(1)).ravel() ids = colsum == 0 # If no one drains into me area = (dX * dY) # Record minimum area min_area = np.nanmin(area) self.twi_min_area = min(self.twi_min_area, min_area) area = np.concatenate((area[0:1], area)).reshape(area.size+1, 1) area = area.repeat(data.shape[1], 1) # Set the edge areas to zero, will add those contributions later area[:, 0] = area_edges[:, 0] area[:, -1] = area_edges[:, -1] area[-1, :] = area_edges[-1, :] area[0, :] = area_edges[0, :] # These edges are done, they have been drained already ids[area_edges.ravel() > 0] = True done = np.zeros(data.shape, bool) done.ravel()[ids] = True # deal with no-data values done[1:-1, 1:-1] = done[1:-1, 1:-1] | data.mask[1:-1, 1:-1] # Check the inlet edges edge_todo = np.zeros_like(done) ids_ed = np.arange(data.size).reshape(data.shape) # left edge_todo[:, 0] = (A[:, ids_ed[:, 0]].sum(0) > 0) \ & (area_edges[:, 0] == 0) edge_todo[:, -1] = (A[:, ids_ed[:, -1]].sum(0) > 0) \ & (area_edges[:, -1] == 0) edge_todo[0, :] = (A[:, ids_ed[0, :]].sum(0) > 0) \ & (area_edges[0, :] == 0) edge_todo[-1, :] = (A[:, ids_ed[-1, :]].sum(0) > 0) \ & (area_edges[-1, :] == 0) # Will do the tile-level doneness edge_todo_i_no_mask = edge_todo.copy() & edge_todo_i_no_mask edge_todo_no_mask = edge_todo_i_no_mask.copy() # tile-level doneness edge_todo[data.mask] = False # Don't do masked areas # Initialize done edges edge_todo_i = edge_todo.copy() ids_old = np.zeros_like(ids) # %% count = 1 if CYTHON: area_ = area.ravel() done_ = done.ravel() edge_todo_ = edge_todo.astype('float64').ravel() edge_todo_no_mask_ = edge_todo_no_mask.astype('float64').ravel() data_ = data.ravel() while (np.any(~done) and count < self.circular_ref_maxcount): print ".", count += 1 if CYTHON: area_, done_, edge_todo_, edge_todo_no_mask_ = cyutils.drain_area(area_, done_, ids, A.indptr, A.indices, A.data, B.indptr, B.indices, area.shape[0], area.shape[1], edge_todo_, edge_todo_no_mask_) else: # If I use ids.sum() > 0 then I might get stuck in # circular references. while (ids - ids_old).sum() > 0: # %% ids_old = ids.copy() ids, area, done, edge_todo = \ self._drain_step(A, ids, area, done, edge_todo) # figure(1);clf();imshow(area, interpolation='none');colorbar() # figure(2);clf();imshow(ids.reshape(area.shape), interpolation='none');colorbar() # figure(3);clf();imshow(done, interpolation='none');colorbar() done_ = done.ravel() #%% ids[:] = False max_elev = (data_ * (~done_)).max() ids[((data_ * (~done_) - max_elev) / max_elev > -0.01)] = True if CYTHON: area = area_.reshape(area.shape) done = done_.reshape(done.shape) edge_todo = edge_todo_.reshape(edge_todo.shape).astype(bool) edge_todo_no_mask = edge_todo_no_mask_.reshape(edge_todo_no_mask.shape).astype(bool) area[flats] = np.nan edge_done = ~edge_todo edge_done[data.mask] = True # Don't do masked areas if self.apply_uca_limit_edges: # 2x because of bifurcations (maybe should be more than 2x, but # should be ok edge_done[area > self.uca_saturation_limit * 2 * min_area] = True # %% if plotflag: # TODO DTYPE self._plot_connectivity(A, (done.astype('float64') is False) + flats.astype('float64') * 2, [0, 3]) return area, edge_todo_i, edge_done, edge_todo_i_no_mask, edge_todo_no_mask
[ "def", "_calc_uca_chunk", "(", "self", ",", "data", ",", "dX", ",", "dY", ",", "direction", ",", "mag", ",", "flats", ",", "area_edges", ",", "plotflag", "=", "False", ",", "edge_todo_i_no_mask", "=", "True", ")", ":", "# %%", "# Figure out which section the...
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", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1644-L1761
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._drain_step
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. """ # Only drain to cells that have a contribution A_todo = A[:, ids.ravel()] colsum = np.array(A_todo.sum(1)).ravel() # Only touch cells that actually receive a contribution # during this stage ids_new = colsum != 0 # Is it possible that I may drain twice from my own cell? # -- No, I don't think so... # Is it possible that other cells may drain into me in # multiple iterations -- yes # Then say I check for when I'm done ensures that I don't drain until # everyone has drained into me area.ravel()[ids_new] += (A_todo[ids_new, :] * (area.ravel()[ids].ravel())) edge_todo.ravel()[ids_new] += (A_todo[ids_new, :] * (edge_todo.ravel()[ids].ravel())) # Figure out what's left to do. done.ravel()[ids] = True colsum = A * (~done.ravel()) ids = colsum == 0 # Figure out the new-undrained ids ids = ids & (~done.ravel()) return ids, area, done, edge_todo
python
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. """ # Only drain to cells that have a contribution A_todo = A[:, ids.ravel()] colsum = np.array(A_todo.sum(1)).ravel() # Only touch cells that actually receive a contribution # during this stage ids_new = colsum != 0 # Is it possible that I may drain twice from my own cell? # -- No, I don't think so... # Is it possible that other cells may drain into me in # multiple iterations -- yes # Then say I check for when I'm done ensures that I don't drain until # everyone has drained into me area.ravel()[ids_new] += (A_todo[ids_new, :] * (area.ravel()[ids].ravel())) edge_todo.ravel()[ids_new] += (A_todo[ids_new, :] * (edge_todo.ravel()[ids].ravel())) # Figure out what's left to do. done.ravel()[ids] = True colsum = A * (~done.ravel()) ids = colsum == 0 # Figure out the new-undrained ids ids = ids & (~done.ravel()) return ids, area, done, edge_todo
[ "def", "_drain_step", "(", "self", ",", "A", ",", "ids", ",", "area", ",", "done", ",", "edge_todo", ")", ":", "# Only drain to cells that have a contribution", "A_todo", "=", "A", "[", ":", ",", "ids", ".", "ravel", "(", ")", "]", "colsum", "=", "np", ...
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.
[ "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", "...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1763-L1793
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._calc_uca_section_proportion
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 adjust = self.ang_adj[:, 1] d1, d2, theta = _get_d1_d2(dX, dY, 0, facets[0][1], facets[0][2], shp) if dX.size > 1: theta = np.row_stack((theta[0, :], theta, theta[-1, :])) # Which quadrant am I in? section = ((direction / np.pi * 2.0) // 1).astype('int8') # TODO DTYPE # Gets me in the quadrant quadrant = (direction - np.pi / 2.0 * section) proportion = np.full_like(quadrant, np.nan) # Now which section within the quadrant section = section * 2 \ + (quadrant > theta.repeat(data.shape[1], 1)) * (section % 2 == 0) \ + (quadrant > (np.pi/2 - theta.repeat(data.shape[1], 1))) \ * (section % 2 == 1) # greater than because of ties resolution b4 # %% Calculate proportion # As a side note, it's crazy to me how: # _get_d1_d2 needs to use indices 0, 3, 4, 7, # section uses even/odd (i.e. % 2) # proportion uses indices (0, 1, 4, 5) {ALl of them different! ARG!} I1 = (section == 0) | (section == 1) | (section == 4) | (section == 5) # I1 = section % 2 == 0 I = I1 & (quadrant <= theta.repeat(data.shape[1], 1)) proportion[I] = quadrant[I] / theta.repeat(data.shape[1], 1)[I] I = I1 & (quadrant > theta.repeat(data.shape[1], 1)) proportion[I] = (quadrant[I] - theta.repeat(data.shape[1], 1)[I]) \ / (np.pi / 2 - theta.repeat(data.shape[1], 1)[I]) I = (~I1) & (quadrant <= (np.pi / 2 - theta.repeat(data.shape[1], 1))) proportion[I] = (quadrant[I]) \ / (np.pi / 2 - theta.repeat(data.shape[1], 1)[I]) I = (~I1) & (quadrant > (np.pi / 2 - theta.repeat(data.shape[1], 1))) proportion[I] = (quadrant[I] - (np.pi / 2 - theta.repeat(data.shape[1], 1)[I])) \ / (theta.repeat(data.shape[1], 1)[I]) # %%Finish Proportion Calculation section[flats] = FLAT_ID_INT proportion[flats] = FLAT_ID section[section == 8] = 0 # Fence-post error correction proportion = (1 + adjust[section]) / 2.0 - adjust[section] * proportion return section, proportion
python
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 adjust = self.ang_adj[:, 1] d1, d2, theta = _get_d1_d2(dX, dY, 0, facets[0][1], facets[0][2], shp) if dX.size > 1: theta = np.row_stack((theta[0, :], theta, theta[-1, :])) # Which quadrant am I in? section = ((direction / np.pi * 2.0) // 1).astype('int8') # TODO DTYPE # Gets me in the quadrant quadrant = (direction - np.pi / 2.0 * section) proportion = np.full_like(quadrant, np.nan) # Now which section within the quadrant section = section * 2 \ + (quadrant > theta.repeat(data.shape[1], 1)) * (section % 2 == 0) \ + (quadrant > (np.pi/2 - theta.repeat(data.shape[1], 1))) \ * (section % 2 == 1) # greater than because of ties resolution b4 # %% Calculate proportion # As a side note, it's crazy to me how: # _get_d1_d2 needs to use indices 0, 3, 4, 7, # section uses even/odd (i.e. % 2) # proportion uses indices (0, 1, 4, 5) {ALl of them different! ARG!} I1 = (section == 0) | (section == 1) | (section == 4) | (section == 5) # I1 = section % 2 == 0 I = I1 & (quadrant <= theta.repeat(data.shape[1], 1)) proportion[I] = quadrant[I] / theta.repeat(data.shape[1], 1)[I] I = I1 & (quadrant > theta.repeat(data.shape[1], 1)) proportion[I] = (quadrant[I] - theta.repeat(data.shape[1], 1)[I]) \ / (np.pi / 2 - theta.repeat(data.shape[1], 1)[I]) I = (~I1) & (quadrant <= (np.pi / 2 - theta.repeat(data.shape[1], 1))) proportion[I] = (quadrant[I]) \ / (np.pi / 2 - theta.repeat(data.shape[1], 1)[I]) I = (~I1) & (quadrant > (np.pi / 2 - theta.repeat(data.shape[1], 1))) proportion[I] = (quadrant[I] - (np.pi / 2 - theta.repeat(data.shape[1], 1)[I])) \ / (theta.repeat(data.shape[1], 1)[I]) # %%Finish Proportion Calculation section[flats] = FLAT_ID_INT proportion[flats] = FLAT_ID section[section == 8] = 0 # Fence-post error correction proportion = (1 + adjust[section]) / 2.0 - adjust[section] * proportion return section, proportion
[ "def", "_calc_uca_section_proportion", "(", "self", ",", "data", ",", "dX", ",", "dY", ",", "direction", ",", "flats", ")", ":", "shp", "=", "np", ".", "array", "(", "data", ".", "shape", ")", "-", "1", "facets", "=", "self", ".", "facets", "adjust",...
Given the direction, figure out which nodes the drainage will go toward, and what proportion of the drainage goes to which node
[ "Given", "the", "direction", "figure", "out", "which", "nodes", "the", "drainage", "will", "go", "toward", "and", "what", "proportion", "of", "the", "drainage", "goes", "to", "which", "node" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1795-L1844
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._mk_adjacency_matrix
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, :]. So, the row gives the pixel drain to, and the columns the pixels drained from. """ shp = section.shape mat_data = np.row_stack((proportion, 1 - proportion)) NN = np.prod(shp) i12 = np.arange(NN).reshape(shp) j1 = - np.ones_like(i12) j2 = - np.ones_like(i12) # make the connectivity for the non-flats/pits j1, j2 = self._mk_connectivity(section, i12, j1, j2) j = np.row_stack((j1, j2)) i = np.row_stack((i12, i12)) # connectivity for flats/pits if self.drain_pits: pit_i, pit_j, pit_prop, flats, mag = \ self._mk_connectivity_pits(i12, flats, elev, mag, dX, dY) j = np.concatenate([j.ravel(), pit_j]).astype('int64') i = np.concatenate([i.ravel(), pit_i]).astype('int64') mat_data = np.concatenate([mat_data.ravel(), pit_prop]) elif self.drain_flats: j1, j2, mat_data, flat_i, flat_j, flat_prop = \ self._mk_connectivity_flats( i12, j1, j2, mat_data, flats, elev, mag) j = np.concatenate([j.ravel(), flat_j]).astype('int64') i = np.concatenate([i.ravel(), flat_j]).astype('int64') mat_data = np.concatenate([mat_data.ravel(), flat_prop]) # This prevents no-data values, remove connections when not present, # and makes sure that floating point precision errors do not # create circular references where a lower elevation cell drains # to a higher elevation cell I = ~np.isnan(mat_data) & (j != -1) & (mat_data > 1e-8) \ & (elev.ravel()[j] <= elev.ravel()[i]) mat_data = mat_data[I] j = j[I] i = i[I] # %%Make the matrix and initialize # What is A? The row i area receives area contributions from the # entries in its columns. If all the entries in my columns have # drained, then I can drain. A = sps.csc_matrix((mat_data.ravel(), np.row_stack((j.ravel(), i.ravel()))), shape=(NN, NN)) normalize = np.array(A.sum(0) + 1e-16).squeeze() A = np.dot(A, sps.diags(1/normalize, 0)) return A
python
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, :]. So, the row gives the pixel drain to, and the columns the pixels drained from. """ shp = section.shape mat_data = np.row_stack((proportion, 1 - proportion)) NN = np.prod(shp) i12 = np.arange(NN).reshape(shp) j1 = - np.ones_like(i12) j2 = - np.ones_like(i12) # make the connectivity for the non-flats/pits j1, j2 = self._mk_connectivity(section, i12, j1, j2) j = np.row_stack((j1, j2)) i = np.row_stack((i12, i12)) # connectivity for flats/pits if self.drain_pits: pit_i, pit_j, pit_prop, flats, mag = \ self._mk_connectivity_pits(i12, flats, elev, mag, dX, dY) j = np.concatenate([j.ravel(), pit_j]).astype('int64') i = np.concatenate([i.ravel(), pit_i]).astype('int64') mat_data = np.concatenate([mat_data.ravel(), pit_prop]) elif self.drain_flats: j1, j2, mat_data, flat_i, flat_j, flat_prop = \ self._mk_connectivity_flats( i12, j1, j2, mat_data, flats, elev, mag) j = np.concatenate([j.ravel(), flat_j]).astype('int64') i = np.concatenate([i.ravel(), flat_j]).astype('int64') mat_data = np.concatenate([mat_data.ravel(), flat_prop]) # This prevents no-data values, remove connections when not present, # and makes sure that floating point precision errors do not # create circular references where a lower elevation cell drains # to a higher elevation cell I = ~np.isnan(mat_data) & (j != -1) & (mat_data > 1e-8) \ & (elev.ravel()[j] <= elev.ravel()[i]) mat_data = mat_data[I] j = j[I] i = i[I] # %%Make the matrix and initialize # What is A? The row i area receives area contributions from the # entries in its columns. If all the entries in my columns have # drained, then I can drain. A = sps.csc_matrix((mat_data.ravel(), np.row_stack((j.ravel(), i.ravel()))), shape=(NN, NN)) normalize = np.array(A.sum(0) + 1e-16).squeeze() A = np.dot(A, sps.diags(1/normalize, 0)) return A
[ "def", "_mk_adjacency_matrix", "(", "self", ",", "section", ",", "proportion", ",", "flats", ",", "elev", ",", "mag", ",", "dX", ",", "dY", ")", ":", "shp", "=", "section", ".", "shape", "mat_data", "=", "np", ".", "row_stack", "(", "(", "proportion", ...
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.
[ "Calculates", "the", "adjacency", "of", "connectivity", "matrix", ".", "This", "matrix", "tells", "which", "pixels", "drain", "to", "which", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1846-L1908
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._mk_connectivity
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 neighbors. """ shp = np.array(section.shape) - 1 facets = self.facets for ii, facet in enumerate(facets): e1 = facet[1] e2 = facet[2] I = section[1:-1, 1:-1] == ii j1[1:-1, 1:-1][I] = i12[1 + e1[0]:shp[0] + e1[0], 1 + e1[1]:shp[1] + e1[1]][I] j2[1:-1, 1:-1][I] = i12[1 + e2[0]:shp[0] + e2[0], 1 + e2[1]:shp[1] + e2[1]][I] # Now do the edges # left edge slc0 = [slice(1, -1), slice(0, 1)] for ind in [0, 1, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[1 + e1[0]:shp[0] + e1[0], e1[1]][I.ravel()] j2[slc0][I] = i12[1 + e2[0]:shp[0] + e2[0], e2[1]][I.ravel()] # right edge slc0 = [slice(1, -1), slice(-1, None)] for ind in [2, 3, 4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[1 + e1[0]:shp[0] + e1[0], shp[1] + e1[1]][I.ravel()] j2[slc0][I] = i12[1 + e2[0]:shp[0] + e2[0], shp[1] + e2[1]][I.ravel()] # top edge slc0 = [slice(0, 1), slice(1, -1)] for ind in [4, 5, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[e1[0], 1 + e1[1]:shp[1] + e1[1]][I.ravel()] j2[slc0][I] = i12[e2[0], 1 + e2[1]:shp[1] + e2[1]][I.ravel()] # bottom edge slc0 = [slice(-1, None), slice(1, -1)] for ind in [0, 1, 2, 3]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[shp[0] + e1[0], 1 + e1[1]:shp[1] + e1[1]][I.ravel()] j2[slc0][I] = i12[shp[0] + e2[0], 1 + e2[1]:shp[1] + e2[1]][I.ravel()] # top-left corner slc0 = [slice(0, 1), slice(0, 1)] for ind in [6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[e1[0], e1[1]] j2[slc0] = i12[e2[0], e2[1]] # top-right corner slc0 = [slice(0, 1), slice(-1, None)] for ind in [4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[e1[0], shp[1] + e1[1]] j2[slc0] = i12[e2[0], shp[1] + e2[1]] # bottom-left corner slc0 = [slice(-1, None), slice(0, 1)] for ind in [0, 1]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[shp[0] + e1[0], e1[1]] j2[slc0] = i12[shp[0] + e2[0], e2[1]] # bottom-right corner slc0 = [slice(-1, None), slice(-1, None)] for ind in [2, 3]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[e1[0] + shp[0], shp[1] + e1[1]] j2[slc0] = i12[e2[0] + shp[0], shp[1] + e2[1]] return j1, j2
python
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 neighbors. """ shp = np.array(section.shape) - 1 facets = self.facets for ii, facet in enumerate(facets): e1 = facet[1] e2 = facet[2] I = section[1:-1, 1:-1] == ii j1[1:-1, 1:-1][I] = i12[1 + e1[0]:shp[0] + e1[0], 1 + e1[1]:shp[1] + e1[1]][I] j2[1:-1, 1:-1][I] = i12[1 + e2[0]:shp[0] + e2[0], 1 + e2[1]:shp[1] + e2[1]][I] # Now do the edges # left edge slc0 = [slice(1, -1), slice(0, 1)] for ind in [0, 1, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[1 + e1[0]:shp[0] + e1[0], e1[1]][I.ravel()] j2[slc0][I] = i12[1 + e2[0]:shp[0] + e2[0], e2[1]][I.ravel()] # right edge slc0 = [slice(1, -1), slice(-1, None)] for ind in [2, 3, 4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[1 + e1[0]:shp[0] + e1[0], shp[1] + e1[1]][I.ravel()] j2[slc0][I] = i12[1 + e2[0]:shp[0] + e2[0], shp[1] + e2[1]][I.ravel()] # top edge slc0 = [slice(0, 1), slice(1, -1)] for ind in [4, 5, 6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[e1[0], 1 + e1[1]:shp[1] + e1[1]][I.ravel()] j2[slc0][I] = i12[e2[0], 1 + e2[1]:shp[1] + e2[1]][I.ravel()] # bottom edge slc0 = [slice(-1, None), slice(1, -1)] for ind in [0, 1, 2, 3]: e1 = facets[ind][1] e2 = facets[ind][2] I = section[slc0] == ind j1[slc0][I] = i12[shp[0] + e1[0], 1 + e1[1]:shp[1] + e1[1]][I.ravel()] j2[slc0][I] = i12[shp[0] + e2[0], 1 + e2[1]:shp[1] + e2[1]][I.ravel()] # top-left corner slc0 = [slice(0, 1), slice(0, 1)] for ind in [6, 7]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[e1[0], e1[1]] j2[slc0] = i12[e2[0], e2[1]] # top-right corner slc0 = [slice(0, 1), slice(-1, None)] for ind in [4, 5]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[e1[0], shp[1] + e1[1]] j2[slc0] = i12[e2[0], shp[1] + e2[1]] # bottom-left corner slc0 = [slice(-1, None), slice(0, 1)] for ind in [0, 1]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[shp[0] + e1[0], e1[1]] j2[slc0] = i12[shp[0] + e2[0], e2[1]] # bottom-right corner slc0 = [slice(-1, None), slice(-1, None)] for ind in [2, 3]: e1 = facets[ind][1] e2 = facets[ind][2] if section[slc0] == ind: j1[slc0] = i12[e1[0] + shp[0], shp[1] + e1[1]] j2[slc0] = i12[e2[0] + shp[0], shp[1] + e2[1]] return j1, j2
[ "def", "_mk_connectivity", "(", "self", ",", "section", ",", "i12", ",", "j1", ",", "j2", ")", ":", "shp", "=", "np", ".", "array", "(", "section", ".", "shape", ")", "-", "1", "facets", "=", "self", ".", "facets", "for", "ii", ",", "facet", "in"...
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.
[ "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...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L1910-L2007
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._mk_connectivity_pits
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 these pits and flats so that the TWI can be computed. """ e = elev.data.ravel() pit_i = [] pit_j = [] pit_prop = [] warn_pits = [] pits = i12[flats & (elev > 0)] I = np.argsort(e[pits]) for pit in pits[I]: # find drains pit_area = np.array([pit], 'int64') drain = None epit = e[pit] for it in range(self.drain_pits_max_iter): border = get_border_index(pit_area, elev.shape, elev.size) eborder = e[border] emin = eborder.min() if emin < epit: drain = border[eborder < epit] break pit_area = np.concatenate([pit_area, border[eborder == emin]]) if drain is None: warn_pits.append(pit) continue ipit, jpit = np.unravel_index(pit, elev.shape) Idrain, Jdrain = np.unravel_index(drain, elev.shape) # filter by drain distance in coordinate space if self.drain_pits_max_dist: dij = np.sqrt((ipit - Idrain)**2 + (jpit-Jdrain)**2) b = dij <= self.drain_pits_max_dist if not b.any(): warn_pits.append(pit) continue drain = drain[b] Idrain = Idrain[b] Jdrain = Jdrain[b] # calculate real distances dx = [_get_dX_mean(dX, ipit, idrain) * (jpit - jdrain) for idrain, jdrain in zip(Idrain, Jdrain)] dy = [dY[make_slice(ipit, idrain)].sum() for idrain in Idrain] dxy = np.sqrt(np.array(dx)**2 + np.array(dy)**2) # filter by drain distance in real space if self.drain_pits_max_dist_XY: b = dxy <= self.drain_pits_max_dist_XY if not b.any(): warn_pits.append(pit) continue drain = drain[b] dxy = dxy[b] # calculate magnitudes s = (e[pit]-e[drain]) / dxy # connectivity info # TODO proportion calculation (_mk_connectivity_flats used elev?) pit_i += [pit for i in drain] pit_j += drain.tolist() pit_prop += s.tolist() # update pit magnitude and flats mask mag[ipit, jpit] = np.mean(s) flats[ipit, jpit] = False if warn_pits: warnings.warn("Warning %d pits had no place to drain to in this " "chunk" % len(warn_pits)) # Note: returning flats and mag here is not strictly necessary return (np.array(pit_i, 'int64'), np.array(pit_j, 'int64'), np.array(pit_prop, 'float64'), flats, mag)
python
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 these pits and flats so that the TWI can be computed. """ e = elev.data.ravel() pit_i = [] pit_j = [] pit_prop = [] warn_pits = [] pits = i12[flats & (elev > 0)] I = np.argsort(e[pits]) for pit in pits[I]: # find drains pit_area = np.array([pit], 'int64') drain = None epit = e[pit] for it in range(self.drain_pits_max_iter): border = get_border_index(pit_area, elev.shape, elev.size) eborder = e[border] emin = eborder.min() if emin < epit: drain = border[eborder < epit] break pit_area = np.concatenate([pit_area, border[eborder == emin]]) if drain is None: warn_pits.append(pit) continue ipit, jpit = np.unravel_index(pit, elev.shape) Idrain, Jdrain = np.unravel_index(drain, elev.shape) # filter by drain distance in coordinate space if self.drain_pits_max_dist: dij = np.sqrt((ipit - Idrain)**2 + (jpit-Jdrain)**2) b = dij <= self.drain_pits_max_dist if not b.any(): warn_pits.append(pit) continue drain = drain[b] Idrain = Idrain[b] Jdrain = Jdrain[b] # calculate real distances dx = [_get_dX_mean(dX, ipit, idrain) * (jpit - jdrain) for idrain, jdrain in zip(Idrain, Jdrain)] dy = [dY[make_slice(ipit, idrain)].sum() for idrain in Idrain] dxy = np.sqrt(np.array(dx)**2 + np.array(dy)**2) # filter by drain distance in real space if self.drain_pits_max_dist_XY: b = dxy <= self.drain_pits_max_dist_XY if not b.any(): warn_pits.append(pit) continue drain = drain[b] dxy = dxy[b] # calculate magnitudes s = (e[pit]-e[drain]) / dxy # connectivity info # TODO proportion calculation (_mk_connectivity_flats used elev?) pit_i += [pit for i in drain] pit_j += drain.tolist() pit_prop += s.tolist() # update pit magnitude and flats mask mag[ipit, jpit] = np.mean(s) flats[ipit, jpit] = False if warn_pits: warnings.warn("Warning %d pits had no place to drain to in this " "chunk" % len(warn_pits)) # Note: returning flats and mag here is not strictly necessary return (np.array(pit_i, 'int64'), np.array(pit_j, 'int64'), np.array(pit_prop, 'float64'), flats, mag)
[ "def", "_mk_connectivity_pits", "(", "self", ",", "i12", ",", "flats", ",", "elev", ",", "mag", ",", "dX", ",", "dY", ")", ":", "e", "=", "elev", ".", "data", ".", "ravel", "(", ")", "pit_i", "=", "[", "]", "pit_j", "=", "[", "]", "pit_prop", "...
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.
[ "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", "ma...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2009-L2098
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._mk_connectivity_flats
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 region to a single pixel. All that area is then drained from that pixel to the surroundings on the flat. If the border of the flat has a single pixel with a much lower elevation, all the area will go towards that pixel. If the border has pixels with similar elevation, then the area will be distributed amongst all the border pixels proportional to their elevation. """ nn, mm = flats.shape NN = np.prod(flats.shape) # Label the flats assigned, n_flats = spndi.label(flats, FLATS_KERNEL3) flat_ids, flat_coords, flat_labelsf = _get_flat_ids(assigned) flat_j = [None] * n_flats flat_prop = [None] * n_flats flat_i = [None] * n_flats # Temporary array to find the flats edges = np.zeros_like(flats) # %% Calcute the flat drainage warn_flats = [] for ii in xrange(n_flats): ids_flats = flat_ids[flat_coords[ii]:flat_coords[ii+1]] edges[:] = 0 j = ids_flats % mm i = ids_flats // mm for iii in [-1, 0, 1]: for jjj in [-1, 0, 1]: i_2 = i + iii j_2 = j + jjj ids_tmp = (i_2 >= 0) & (j_2 >= 0) & (i_2 < nn) & (j_2 < mm) edges[i_2[ids_tmp], j_2[ids_tmp]] += \ FLATS_KERNEL3[iii+1, jjj+1] edges.ravel()[ids_flats] = 0 ids_edge = np.argwhere(edges.ravel()).squeeze() flat_elev_loc = elev.ravel()[ids_flats] # It is possble for the edges to merge 2 flats, so we need to # take the lower elevation to avoid large circular regions flat_elev = flat_elev_loc.min() loc_elev = elev.ravel()[ids_edge] # Filter out any elevations larger than the flat elevation # TODO: Figure out if this should be <= or < I_filt = loc_elev < flat_elev try: loc_elev = loc_elev[I_filt] loc_slope = mag.ravel()[ids_edge][I_filt] except: # If this is fully masked out (i.e. inside a no-data area) loc_elev = np.array([]) loc_slope = np.array([]) loc_dx = self.dX.mean() # Now I have to figure out if I should just use the minimum or # distribute amongst many pixels on the flat boundary n = len(loc_slope) if n == 0: # Flat does not have anywhere to drain # Let's see if the flat goes to the edge. If yes, we'll just # distribute the area along the edge. ids_flat_on_edge = ((ids_flats % mag.shape[1]) == 0) | \ ((ids_flats % mag.shape[1]) == (mag.shape[1] - 1)) | \ (ids_flats <= mag.shape[1]) | \ (ids_flats >= (mag.shape[1] * (mag.shape[0] - 1))) if ids_flat_on_edge.sum() == 0: warn_flats.append(ii) continue drain_ids = ids_flats[ids_flat_on_edge] loc_proportions = mag.ravel()[ids_flats[ids_flat_on_edge]] loc_proportions /= loc_proportions.sum() ids_flats = ids_flats[~ids_flat_on_edge] # This flat is entirely on the edge of the image if len(ids_flats) == 0: # therefore, whatever drains into it is done. continue flat_elev_loc = flat_elev_loc[~ids_flat_on_edge] else: # Flat has a place to drain to min_edges = np.zeros(loc_slope.shape, bool) min_edges[np.argmin(loc_slope)] = True # Add to the min edges any edge that is within an error # tolerance as small as the minimum min_edges = (loc_slope + loc_slope * loc_dx / 2) \ >= loc_slope[min_edges] drain_ids = ids_edge[I_filt][min_edges] loc_proportions = loc_slope[min_edges] loc_proportions /= loc_proportions.sum() # Now distribute the connectivity amongst the chosen elevations # proportional to their slopes # First, let all the the ids in the flats drain to 1 # flat id (for ease) one_id = np.zeros(ids_flats.size, bool) one_id[np.argmin(flat_elev_loc)] = True j1.ravel()[ids_flats[~one_id]] = ids_flats[one_id] mat_data.ravel()[ids_flats[~one_id]] = 1 # Negative indices will be eliminated before making the matix j2.ravel()[ids_flats[~one_id]] = -1 mat_data.ravel()[ids_flats[~one_id] + NN] = 0 # Now drain the 1 flat to the drains j1.ravel()[ids_flats[one_id]] = drain_ids[0] mat_data.ravel()[ids_flats[one_id]] = loc_proportions[0] if len(drain_ids) > 1: j2.ravel()[ids_flats[one_id]] = drain_ids[1] mat_data.ravel()[ids_flats[one_id] + NN] = loc_proportions[1] if len(loc_proportions > 2): flat_j[ii] = drain_ids[2:] flat_prop[ii] = loc_proportions[2:] flat_i[ii] = np.ones(drain_ids[2:].size, 'int64') * ids_flats[one_id] try: flat_j = np.concatenate([fj for fj in flat_j if fj is not None]) flat_prop = \ np.concatenate([fp for fp in flat_prop if fp is not None]) flat_i = np.concatenate([fi for fi in flat_i if fi is not None]) except: flat_j = np.array([], 'int64') flat_prop = np.array([], 'float64') flat_i = np.array([], 'int64') if len(warn_flats) > 0: warnings.warn("Warning %d flats had no place" % len(warn_flats) + " to drain to --> these are pits (check pit-remove" "algorithm).") return j1, j2, mat_data, flat_i, flat_j, flat_prop
python
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 region to a single pixel. All that area is then drained from that pixel to the surroundings on the flat. If the border of the flat has a single pixel with a much lower elevation, all the area will go towards that pixel. If the border has pixels with similar elevation, then the area will be distributed amongst all the border pixels proportional to their elevation. """ nn, mm = flats.shape NN = np.prod(flats.shape) # Label the flats assigned, n_flats = spndi.label(flats, FLATS_KERNEL3) flat_ids, flat_coords, flat_labelsf = _get_flat_ids(assigned) flat_j = [None] * n_flats flat_prop = [None] * n_flats flat_i = [None] * n_flats # Temporary array to find the flats edges = np.zeros_like(flats) # %% Calcute the flat drainage warn_flats = [] for ii in xrange(n_flats): ids_flats = flat_ids[flat_coords[ii]:flat_coords[ii+1]] edges[:] = 0 j = ids_flats % mm i = ids_flats // mm for iii in [-1, 0, 1]: for jjj in [-1, 0, 1]: i_2 = i + iii j_2 = j + jjj ids_tmp = (i_2 >= 0) & (j_2 >= 0) & (i_2 < nn) & (j_2 < mm) edges[i_2[ids_tmp], j_2[ids_tmp]] += \ FLATS_KERNEL3[iii+1, jjj+1] edges.ravel()[ids_flats] = 0 ids_edge = np.argwhere(edges.ravel()).squeeze() flat_elev_loc = elev.ravel()[ids_flats] # It is possble for the edges to merge 2 flats, so we need to # take the lower elevation to avoid large circular regions flat_elev = flat_elev_loc.min() loc_elev = elev.ravel()[ids_edge] # Filter out any elevations larger than the flat elevation # TODO: Figure out if this should be <= or < I_filt = loc_elev < flat_elev try: loc_elev = loc_elev[I_filt] loc_slope = mag.ravel()[ids_edge][I_filt] except: # If this is fully masked out (i.e. inside a no-data area) loc_elev = np.array([]) loc_slope = np.array([]) loc_dx = self.dX.mean() # Now I have to figure out if I should just use the minimum or # distribute amongst many pixels on the flat boundary n = len(loc_slope) if n == 0: # Flat does not have anywhere to drain # Let's see if the flat goes to the edge. If yes, we'll just # distribute the area along the edge. ids_flat_on_edge = ((ids_flats % mag.shape[1]) == 0) | \ ((ids_flats % mag.shape[1]) == (mag.shape[1] - 1)) | \ (ids_flats <= mag.shape[1]) | \ (ids_flats >= (mag.shape[1] * (mag.shape[0] - 1))) if ids_flat_on_edge.sum() == 0: warn_flats.append(ii) continue drain_ids = ids_flats[ids_flat_on_edge] loc_proportions = mag.ravel()[ids_flats[ids_flat_on_edge]] loc_proportions /= loc_proportions.sum() ids_flats = ids_flats[~ids_flat_on_edge] # This flat is entirely on the edge of the image if len(ids_flats) == 0: # therefore, whatever drains into it is done. continue flat_elev_loc = flat_elev_loc[~ids_flat_on_edge] else: # Flat has a place to drain to min_edges = np.zeros(loc_slope.shape, bool) min_edges[np.argmin(loc_slope)] = True # Add to the min edges any edge that is within an error # tolerance as small as the minimum min_edges = (loc_slope + loc_slope * loc_dx / 2) \ >= loc_slope[min_edges] drain_ids = ids_edge[I_filt][min_edges] loc_proportions = loc_slope[min_edges] loc_proportions /= loc_proportions.sum() # Now distribute the connectivity amongst the chosen elevations # proportional to their slopes # First, let all the the ids in the flats drain to 1 # flat id (for ease) one_id = np.zeros(ids_flats.size, bool) one_id[np.argmin(flat_elev_loc)] = True j1.ravel()[ids_flats[~one_id]] = ids_flats[one_id] mat_data.ravel()[ids_flats[~one_id]] = 1 # Negative indices will be eliminated before making the matix j2.ravel()[ids_flats[~one_id]] = -1 mat_data.ravel()[ids_flats[~one_id] + NN] = 0 # Now drain the 1 flat to the drains j1.ravel()[ids_flats[one_id]] = drain_ids[0] mat_data.ravel()[ids_flats[one_id]] = loc_proportions[0] if len(drain_ids) > 1: j2.ravel()[ids_flats[one_id]] = drain_ids[1] mat_data.ravel()[ids_flats[one_id] + NN] = loc_proportions[1] if len(loc_proportions > 2): flat_j[ii] = drain_ids[2:] flat_prop[ii] = loc_proportions[2:] flat_i[ii] = np.ones(drain_ids[2:].size, 'int64') * ids_flats[one_id] try: flat_j = np.concatenate([fj for fj in flat_j if fj is not None]) flat_prop = \ np.concatenate([fp for fp in flat_prop if fp is not None]) flat_i = np.concatenate([fi for fi in flat_i if fi is not None]) except: flat_j = np.array([], 'int64') flat_prop = np.array([], 'float64') flat_i = np.array([], 'int64') if len(warn_flats) > 0: warnings.warn("Warning %d flats had no place" % len(warn_flats) + " to drain to --> these are pits (check pit-remove" "algorithm).") return j1, j2, mat_data, flat_i, flat_j, flat_prop
[ "def", "_mk_connectivity_flats", "(", "self", ",", "i12", ",", "j1", ",", "j2", ",", "mat_data", ",", "flats", ",", "elev", ",", "mag", ")", ":", "nn", ",", "mm", "=", "flats", ".", "shape", "NN", "=", "np", ".", "prod", "(", "flats", ".", "shape...
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 of the flat has a single pixel with a much lower elevation, all the area will go towards that pixel. If the border has pixels with similar elevation, then the area will be distributed amongst all the border pixels proportional to their elevation.
[ "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", "acc...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2100-L2235
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor.calc_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() gc.collect() # Just in case min_area = self.twi_min_area min_slope = self.twi_min_slope twi = self.uca.copy() if self.apply_twi_limits_on_uca: twi[twi > self.uca_saturation_limit * min_area] = \ self.uca_saturation_limit * min_area gc.collect() # Just in case twi = np.log((twi) / (self.mag + min_slope)) # apply the cap if self.apply_twi_limits: twi_sat_value = \ np.log(self.uca_saturation_limit * min_area / min_slope) twi[twi > twi_sat_value] = twi_sat_value # multiply by 10 for better integer resolution when storing self.twi = twi * 10 gc.collect() # Just in case return twi
python
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() gc.collect() # Just in case min_area = self.twi_min_area min_slope = self.twi_min_slope twi = self.uca.copy() if self.apply_twi_limits_on_uca: twi[twi > self.uca_saturation_limit * min_area] = \ self.uca_saturation_limit * min_area gc.collect() # Just in case twi = np.log((twi) / (self.mag + min_slope)) # apply the cap if self.apply_twi_limits: twi_sat_value = \ np.log(self.uca_saturation_limit * min_area / min_slope) twi[twi > twi_sat_value] = twi_sat_value # multiply by 10 for better integer resolution when storing self.twi = twi * 10 gc.collect() # Just in case return twi
[ "def", "calc_twi", "(", "self", ")", ":", "if", "self", ".", "uca", "is", "None", ":", "self", ".", "calc_uca", "(", ")", "gc", ".", "collect", "(", ")", "# Just in case", "min_area", "=", "self", ".", "twi_min_area", "min_slope", "=", "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
[ "Calculates", "the", "topographic", "wetness", "index", "and", "saves", "the", "result", "in", "self", ".", "twi", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2237-L2267
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._plot_connectivity
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() self._plot_connectivity_helper(B.col, B.row, B.data, data, lims)
python
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() self._plot_connectivity_helper(B.col, B.row, B.data, data, lims)
[ "def", "_plot_connectivity", "(", "self", ",", "A", ",", "data", "=", "None", ",", "lims", "=", "[", "None", ",", "None", "]", ")", ":", "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
[ "A", "debug", "function", "used", "to", "plot", "the", "adjacency", "/", "connectivity", "matrix", ".", "This", "is", "really", "just", "a", "light", "wrapper", "around", "_plot_connectivity_helper" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2269-L2279
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._plot_connectivity_helper
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_data = mat_datai[I] j = ji[I] i = ii[I] x = i.astype(float) % data.shape[1] y = i.astype(float) // data.shape[1] x1 = (j.astype(float) % data.shape[1]).ravel() y1 = (j.astype(float) // data.shape[1]).ravel() nx = (x1 - x) ny = (y1 - y) matshow(data, cmap='gist_rainbow'); colorbar(); clim(lims) quiver(x, y, nx, ny, mat_data.ravel(), angles='xy', scale_units='xy', scale=1, cmap='bone') colorbar(); clim([0, 1])
python
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_data = mat_datai[I] j = ji[I] i = ii[I] x = i.astype(float) % data.shape[1] y = i.astype(float) // data.shape[1] x1 = (j.astype(float) % data.shape[1]).ravel() y1 = (j.astype(float) // data.shape[1]).ravel() nx = (x1 - x) ny = (y1 - y) matshow(data, cmap='gist_rainbow'); colorbar(); clim(lims) quiver(x, y, nx, ny, mat_data.ravel(), angles='xy', scale_units='xy', scale=1, cmap='bone') colorbar(); clim([0, 1])
[ "def", "_plot_connectivity_helper", "(", "self", ",", "ii", ",", "ji", ",", "mat_datai", ",", "data", ",", "lims", "=", "[", "1", ",", "8", "]", ")", ":", "from", "matplotlib", ".", "pyplot", "import", "quiver", ",", "colorbar", ",", "clim", ",", "ma...
A debug function used to plot the adjacency/connectivity matrix.
[ "A", "debug", "function", "used", "to", "plot", "the", "adjacency", "/", "connectivity", "matrix", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2281-L2299
train
creare-com/pydem
pydem/dem_processing.py
DEMProcessor._plot_debug_slopes_directions
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') mag2, direction2 = self._central_slopes_directions() matshow(direction2 / np.pi * 180.0); colorbar(); clim(0, 360) title('Direction (central difference)') matshow(self.mag); colorbar() title('Magnitude') matshow(mag2); colorbar(); title("Magnitude (Central difference)") # %% # Compare to Taudem filename = self.file_name os.chdir('testtiff') try: os.remove('test_ang.tif') os.remove('test_slp.tif') except: pass cmd = ('dinfflowdir -fel "%s" -ang "%s" -slp "%s"' % (os.path.split(filename)[-1], 'test_ang.tif', 'test_slp.tif')) taudem._run(cmd) td_file = GdalReader(file_name='test_ang.tif') td_ang, = td_file.raster_layers td_file2 = GdalReader(file_name='test_slp.tif') td_mag, = td_file2.raster_layers os.chdir('..') matshow(td_ang.raster_data / np.pi*180); clim(0, 360); colorbar() title('Taudem direction') matshow(td_mag.raster_data); colorbar() title('Taudem magnitude') matshow(self.data); colorbar() title('The test data (elevation)') diff = (td_ang.raster_data - self.direction) / np.pi * 180.0 diff[np.abs(diff) > 300] = np.nan matshow(diff); colorbar(); clim([-1, 1]) title('Taudem direction - calculated Direction') # normalize magnitudes mag2 = td_mag.raster_data mag2 /= np.nanmax(mag2) mag = self.mag.copy() mag /= np.nanmax(mag) matshow(mag - mag2); colorbar() title('Taudem magnitude - calculated magnitude') del td_file del td_file2 del td_ang del td_mag
python
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') mag2, direction2 = self._central_slopes_directions() matshow(direction2 / np.pi * 180.0); colorbar(); clim(0, 360) title('Direction (central difference)') matshow(self.mag); colorbar() title('Magnitude') matshow(mag2); colorbar(); title("Magnitude (Central difference)") # %% # Compare to Taudem filename = self.file_name os.chdir('testtiff') try: os.remove('test_ang.tif') os.remove('test_slp.tif') except: pass cmd = ('dinfflowdir -fel "%s" -ang "%s" -slp "%s"' % (os.path.split(filename)[-1], 'test_ang.tif', 'test_slp.tif')) taudem._run(cmd) td_file = GdalReader(file_name='test_ang.tif') td_ang, = td_file.raster_layers td_file2 = GdalReader(file_name='test_slp.tif') td_mag, = td_file2.raster_layers os.chdir('..') matshow(td_ang.raster_data / np.pi*180); clim(0, 360); colorbar() title('Taudem direction') matshow(td_mag.raster_data); colorbar() title('Taudem magnitude') matshow(self.data); colorbar() title('The test data (elevation)') diff = (td_ang.raster_data - self.direction) / np.pi * 180.0 diff[np.abs(diff) > 300] = np.nan matshow(diff); colorbar(); clim([-1, 1]) title('Taudem direction - calculated Direction') # normalize magnitudes mag2 = td_mag.raster_data mag2 /= np.nanmax(mag2) mag = self.mag.copy() mag /= np.nanmax(mag) matshow(mag - mag2); colorbar() title('Taudem magnitude - calculated magnitude') del td_file del td_file2 del td_ang del td_mag
[ "def", "_plot_debug_slopes_directions", "(", "self", ")", ":", "# %%", "from", "matplotlib", ".", "pyplot", "import", "matshow", ",", "colorbar", ",", "clim", ",", "title", "matshow", "(", "self", ".", "direction", "/", "np", ".", "pi", "*", "180", ")", ...
A debug function to plot the direction calculated in various ways.
[ "A", "debug", "function", "to", "plot", "the", "direction", "calculated", "in", "various", "ways", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2301-L2361
train
click-contrib/click-configfile
tasks/docs.py
clean
def clean(ctx, dry_run=False): """Cleanup generated document artifacts.""" basedir = ctx.sphinx.destdir or "build/docs" cleanup_dirs([basedir], dry_run=dry_run)
python
def clean(ctx, dry_run=False): """Cleanup generated document artifacts.""" basedir = ctx.sphinx.destdir or "build/docs" cleanup_dirs([basedir], dry_run=dry_run)
[ "def", "clean", "(", "ctx", ",", "dry_run", "=", "False", ")", ":", "basedir", "=", "ctx", ".", "sphinx", ".", "destdir", "or", "\"build/docs\"", "cleanup_dirs", "(", "[", "basedir", "]", ",", "dry_run", "=", "dry_run", ")" ]
Cleanup generated document artifacts.
[ "Cleanup", "generated", "document", "artifacts", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/docs.py#L20-L23
train
click-contrib/click-configfile
tasks/docs.py
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 = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \ .format(builder=builder, sourcedir=".", destdir=destdir_relative, opts=options) ctx.run(command)
python
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 = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \ .format(builder=builder, sourcedir=".", destdir=destdir_relative, opts=options) ctx.run(command)
[ "def", "build", "(", "ctx", ",", "builder", "=", "\"html\"", ",", "options", "=", "\"\"", ")", ":", "sourcedir", "=", "ctx", ".", "config", ".", "sphinx", ".", "sourcedir", "destdir", "=", "Path", "(", "ctx", ".", "config", ".", "sphinx", ".", "destd...
Build docs with sphinx-build
[ "Build", "docs", "with", "sphinx", "-", "build" ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/docs.py#L30-L40
train
click-contrib/click-configfile
tasks/docs.py
browse
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"): open_cmd = "start" ctx.run("{open} {page_html}".format(open=open_cmd, page_html=page_html))
python
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"): open_cmd = "start" ctx.run("{open} {page_html}".format(open=open_cmd, page_html=page_html))
[ "def", "browse", "(", "ctx", ")", ":", "page_html", "=", "Path", "(", "ctx", ".", "config", ".", "sphinx", ".", "destdir", ")", "/", "\"html\"", "/", "\"index.html\"", "if", "not", "page_html", ".", "exists", "(", ")", ":", "build", "(", "ctx", ",", ...
Open documentation in web browser.
[ "Open", "documentation", "in", "web", "browser", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/docs.py#L48-L57
train
click-contrib/click-configfile
tasks/docs.py
save
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() source_dir.copytree(dest) # -- POST-PROCESSING: Polish up. for part in [ ".buildinfo", ".doctrees" ]: partpath = Path(dest)/part if partpath.isdir(): partpath.rmtree_p() elif partpath.exists(): partpath.remove_p()
python
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() source_dir.copytree(dest) # -- POST-PROCESSING: Polish up. for part in [ ".buildinfo", ".doctrees" ]: partpath = Path(dest)/part if partpath.isdir(): partpath.rmtree_p() elif partpath.exists(): partpath.remove_p()
[ "def", "save", "(", "ctx", ",", "dest", "=", "\"docs.html\"", ",", "format", "=", "\"html\"", ")", ":", "print", "(", "\"STEP: Generate docs in HTML format\"", ")", "build", "(", "ctx", ",", "builder", "=", "format", ")", "print", "(", "\"STEP: Save docs under...
Save/update docs under destination directory.
[ "Save", "/", "update", "docs", "under", "destination", "directory", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/docs.py#L65-L81
train
creare-com/pydem
pydem/processing_manager.py
find_neighbors
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 List of coordinates determined from the filename. See :py:func:`utils.parse_fn` I : array Sort index. Different sorting schemes will speed up when neighbors are found source_files : list List of strings of source file names f : callable Function that determines if two tiles are neighbors based on their coordinates. f(c1, c2) returns True if tiles are neighbors sides : list List of 2 strings that give the "side" where tiles are neighbors. Returns ------- neighbors : dict Dictionary of neighbors Notes ------- For example, if Tile1 is to the left of Tile2, then neighbors['Tile1']['right'] = 'Tile2' neighbors['Tile2']['left'] = 'Tile1' """ for i, c1 in enumerate(coords): me = source_files[I[i]] # If the left neighbor has already been found... if neighbors[me][sides[0]] != '': continue # could try coords[i:] (+ fixes) for speed if it becomes a problem for j, c2 in enumerate(coords): if f(c1, c2): # then tiles are neighbors neighbors neigh = source_files[I[j]] neighbors[me][sides[0]] = neigh neighbors[neigh][sides[1]] = me break return neighbors
python
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 List of coordinates determined from the filename. See :py:func:`utils.parse_fn` I : array Sort index. Different sorting schemes will speed up when neighbors are found source_files : list List of strings of source file names f : callable Function that determines if two tiles are neighbors based on their coordinates. f(c1, c2) returns True if tiles are neighbors sides : list List of 2 strings that give the "side" where tiles are neighbors. Returns ------- neighbors : dict Dictionary of neighbors Notes ------- For example, if Tile1 is to the left of Tile2, then neighbors['Tile1']['right'] = 'Tile2' neighbors['Tile2']['left'] = 'Tile1' """ for i, c1 in enumerate(coords): me = source_files[I[i]] # If the left neighbor has already been found... if neighbors[me][sides[0]] != '': continue # could try coords[i:] (+ fixes) for speed if it becomes a problem for j, c2 in enumerate(coords): if f(c1, c2): # then tiles are neighbors neighbors neigh = source_files[I[j]] neighbors[me][sides[0]] = neigh neighbors[neigh][sides[1]] = me break return neighbors
[ "def", "find_neighbors", "(", "neighbors", ",", "coords", ",", "I", ",", "source_files", ",", "f", ",", "sides", ")", ":", "for", "i", ",", "c1", "in", "enumerate", "(", "coords", ")", ":", "me", "=", "source_files", "[", "I", "[", "i", "]", "]", ...
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:func:`utils.parse_fn` I : array Sort index. Different sorting schemes will speed up when neighbors are found source_files : list List of strings of source file names f : callable Function that determines if two tiles are neighbors based on their coordinates. f(c1, c2) returns True if tiles are neighbors sides : list List of 2 strings that give the "side" where tiles are neighbors. Returns ------- neighbors : dict Dictionary of neighbors Notes ------- For example, if Tile1 is to the left of Tile2, then neighbors['Tile1']['right'] = 'Tile2' neighbors['Tile2']['left'] = 'Tile1'
[ "Find", "the", "tile", "neighbors", "based", "on", "filenames" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L74-L120
train
creare-com/pydem
pydem/processing_manager.py
TileEdgeFile.set_neighbor_data
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'} for key in self.neighbors[elev_fn].keys(): tile = self.neighbors[elev_fn][key] if tile == '': continue oppkey = key for me, neigh in opp.iteritems(): if me in key: oppkey = oppkey.replace(me, neigh) else: oppkey = oppkey.replace(neigh, me) opp_edge = self.neighbors[tile][oppkey] if opp_edge == '': continue interp.values = dem_proc.uca[::-1, :] # interp.values[:, 0] = np.ravel(dem_proc.uca) # for other interp. # for the top-left tile we have to set the bottom and right edges # of that tile, so two edges for those tiles for key_ed in oppkey.split('-'): self.edges[tile][key_ed].set_data('data', interp) interp.values = dem_proc.edge_done[::-1, :].astype(float) # interp.values[:, 0] = np.ravel(dem_proc.edge_done) for key_ed in oppkey.split('-'): self.edges[tile][key_ed].set_data('done', interp)
python
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'} for key in self.neighbors[elev_fn].keys(): tile = self.neighbors[elev_fn][key] if tile == '': continue oppkey = key for me, neigh in opp.iteritems(): if me in key: oppkey = oppkey.replace(me, neigh) else: oppkey = oppkey.replace(neigh, me) opp_edge = self.neighbors[tile][oppkey] if opp_edge == '': continue interp.values = dem_proc.uca[::-1, :] # interp.values[:, 0] = np.ravel(dem_proc.uca) # for other interp. # for the top-left tile we have to set the bottom and right edges # of that tile, so two edges for those tiles for key_ed in oppkey.split('-'): self.edges[tile][key_ed].set_data('data', interp) interp.values = dem_proc.edge_done[::-1, :].astype(float) # interp.values[:, 0] = np.ravel(dem_proc.edge_done) for key_ed in oppkey.split('-'): self.edges[tile][key_ed].set_data('done', interp)
[ "def", "set_neighbor_data", "(", "self", ",", "elev_fn", ",", "dem_proc", ",", "interp", "=", "None", ")", ":", "if", "interp", "is", "None", ":", "interp", "=", "self", ".", "build_interpolator", "(", "dem_proc", ")", "opp", "=", "{", "'top'", ":", "'...
From the elevation filename, we can figure out and load the data and done arrays.
[ "From", "the", "elevation", "filename", "we", "can", "figure", "out", "and", "load", "the", "data", "and", "done", "arrays", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L453-L485
train
creare-com/pydem
pydem/processing_manager.py
TileEdgeFile.update_edge_todo
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)
python
def update_edge_todo(self, elev_fn, dem_proc): """ Can figure out how to update the todo based on the elev filename """ for key in self.edges[elev_fn].keys(): self.edges[elev_fn][key].set_data('todo', data=dem_proc.edge_todo)
[ "def", "update_edge_todo", "(", "self", ",", "elev_fn", ",", "dem_proc", ")", ":", "for", "key", "in", "self", ".", "edges", "[", "elev_fn", "]", ".", "keys", "(", ")", ":", "self", ".", "edges", "[", "elev_fn", "]", "[", "key", "]", ".", "set_data...
Can figure out how to update the todo based on the elev filename
[ "Can", "figure", "out", "how", "to", "update", "the", "todo", "based", "on", "the", "elev", "filename" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L487-L492
train
creare-com/pydem
pydem/processing_manager.py
TileEdgeFile.update_edges
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, interp)
python
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, interp)
[ "def", "update_edges", "(", "self", ",", "elev_fn", ",", "dem_proc", ")", ":", "interp", "=", "self", ".", "build_interpolator", "(", "dem_proc", ")", "self", ".", "update_edge_todo", "(", "elev_fn", ",", "dem_proc", ")", "self", ".", "set_neighbor_data", "(...
After finishing a calculation, this will update the neighbors and the todo for that tile
[ "After", "finishing", "a", "calculation", "this", "will", "update", "the", "neighbors", "and", "the", "todo", "for", "that", "tile" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L494-L501
train
creare-com/pydem
pydem/processing_manager.py
TileEdgeFile.get_edge_init_data
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('done') for key in self.edges[fn].keys()} edge_init_todo = {key: self.edges[fn][key].get('todo') for key in self.edges[fn].keys()} return edge_init_data, edge_init_done, edge_init_todo
python
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('done') for key in self.edges[fn].keys()} edge_init_todo = {key: self.edges[fn][key].get('todo') for key in self.edges[fn].keys()} return edge_init_data, edge_init_done, edge_init_todo
[ "def", "get_edge_init_data", "(", "self", ",", "fn", ",", "save_path", "=", "None", ")", ":", "edge_init_data", "=", "{", "key", ":", "self", ".", "edges", "[", "fn", "]", "[", "key", "]", ".", "get", "(", "'data'", ")", "for", "key", "in", "self",...
Creates the initialization data from the edge structure
[ "Creates", "the", "initialization", "data", "from", "the", "edge", "structure" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L503-L514
train
creare-com/pydem
pydem/processing_manager.py
TileEdgeFile.find_best_candidate
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 process tiles. """ self.fill_percent_done() i_b = np.argmax(self.percent_done.values()) if self.percent_done.values()[i_b] <= 0: return None # check for ties I = np.array(self.percent_done.values()) == \ self.percent_done.values()[i_b] if I.sum() == 1: pass # no ties else: I2 = np.argmax(np.array(self.max_elev.values())[I]) i_b = I.nonzero()[0][I2] # Make sure the apples are still apples assert(np.array(self.max_elev.keys())[I][I2] == np.array(self.percent_done.keys())[I][I2]) if elev_source_files is not None: fn = self.percent_done.keys()[i_b] lckfn = _get_lockfile_name(fn) if os.path.exists(lckfn): # another process is working on it # Find a different Candidate i_alt = np.argsort(self.percent_done.values())[::-1] for i in i_alt: fn = self.percent_done.keys()[i] lckfn = _get_lockfile_name(fn) if not os.path.exists(lckfn): break # Get and return the index i_b = elev_source_files.index(fn) return i_b
python
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 process tiles. """ self.fill_percent_done() i_b = np.argmax(self.percent_done.values()) if self.percent_done.values()[i_b] <= 0: return None # check for ties I = np.array(self.percent_done.values()) == \ self.percent_done.values()[i_b] if I.sum() == 1: pass # no ties else: I2 = np.argmax(np.array(self.max_elev.values())[I]) i_b = I.nonzero()[0][I2] # Make sure the apples are still apples assert(np.array(self.max_elev.keys())[I][I2] == np.array(self.percent_done.keys())[I][I2]) if elev_source_files is not None: fn = self.percent_done.keys()[i_b] lckfn = _get_lockfile_name(fn) if os.path.exists(lckfn): # another process is working on it # Find a different Candidate i_alt = np.argsort(self.percent_done.values())[::-1] for i in i_alt: fn = self.percent_done.keys()[i] lckfn = _get_lockfile_name(fn) if not os.path.exists(lckfn): break # Get and return the index i_b = elev_source_files.index(fn) return i_b
[ "def", "find_best_candidate", "(", "self", ",", "elev_source_files", "=", "None", ")", ":", "self", ".", "fill_percent_done", "(", ")", "i_b", "=", "np", ".", "argmax", "(", "self", ".", "percent_done", ".", "values", "(", ")", ")", "if", "self", ".", ...
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.
[ "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", "t...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L516-L555
train
creare-com/pydem
pydem/processing_manager.py
ProcessManager.process_twi
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, will only process the index/indices of the files as listed in self.elev_source_files do_edges : bool (optional) Default False. When false, the UCA will be calculated with available edge information if the UCA was not previously computed. If the UCA was previously computed and do_edges == False, the UCA will not be updated. If do_edges == True, the UCA will also be recalculated. skip_uca_twi : bool (optional) Skips the calculation of the UCA and TWI (only calculates the magnitude and direction) Notes ------ do_edges = False for the first round of the processing, but it is True for the second round. """ if index is not None: elev_source_files = [self.elev_source_files[index]] else: elev_source_files = self.elev_source_files for i, esfile in enumerate(elev_source_files): try: fn, status = self.calculate_twi(esfile, save_path=self.save_path, do_edges=do_edges, skip_uca_twi=skip_uca_twi) if index is None: self.twi_status[i] = status else: self.twi_status[index] = status except: lckfn = _get_lockfile_name(esfile) try: os.remove(lckfn) except: pass traceback.print_exc() print traceback.format_exc() if index is None: self.twi_status[i] = "Error " + traceback.format_exc() else: self.twi_status[index] = "Error " + traceback.format_exc()
python
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, will only process the index/indices of the files as listed in self.elev_source_files do_edges : bool (optional) Default False. When false, the UCA will be calculated with available edge information if the UCA was not previously computed. If the UCA was previously computed and do_edges == False, the UCA will not be updated. If do_edges == True, the UCA will also be recalculated. skip_uca_twi : bool (optional) Skips the calculation of the UCA and TWI (only calculates the magnitude and direction) Notes ------ do_edges = False for the first round of the processing, but it is True for the second round. """ if index is not None: elev_source_files = [self.elev_source_files[index]] else: elev_source_files = self.elev_source_files for i, esfile in enumerate(elev_source_files): try: fn, status = self.calculate_twi(esfile, save_path=self.save_path, do_edges=do_edges, skip_uca_twi=skip_uca_twi) if index is None: self.twi_status[i] = status else: self.twi_status[index] = status except: lckfn = _get_lockfile_name(esfile) try: os.remove(lckfn) except: pass traceback.print_exc() print traceback.format_exc() if index is None: self.twi_status[i] = "Error " + traceback.format_exc() else: self.twi_status[index] = "Error " + traceback.format_exc()
[ "def", "process_twi", "(", "self", ",", "index", "=", "None", ",", "do_edges", "=", "False", ",", "skip_uca_twi", "=", "False", ")", ":", "if", "index", "is", "not", "None", ":", "elev_source_files", "=", "[", "self", ".", "elev_source_files", "[", "inde...
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.elev_source_files do_edges : bool (optional) Default False. When false, the UCA will be calculated with available edge information if the UCA was not previously computed. If the UCA was previously computed and do_edges == False, the UCA will not be updated. If do_edges == True, the UCA will also be recalculated. skip_uca_twi : bool (optional) Skips the calculation of the UCA and TWI (only calculates the magnitude and direction) Notes ------ do_edges = False for the first round of the processing, but it is True for the second round.
[ "Processes", "the", "TWI", "along", "with", "any", "dependencies", "(", "like", "the", "slope", "and", "UCA", ")" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L614-L663
train
creare-com/pydem
pydem/processing_manager.py
ProcessManager.process
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) Default None - processes all tiles in a directory. See :py:func:`process_twi` for additional options. """ # Round 0 of twi processing, process the magnitude and directions of # slopes print "Starting slope calculation round" self.process_twi(index, do_edges=False, skip_uca_twi=True) # Round 1 of twi processing print "Starting self-area calculation round" self.process_twi(index, do_edges=False) # Round 2 of twi processing: edge resolution i = self.tile_edge.find_best_candidate(self.elev_source_files) print "Starting edge resolution round: ", count = 0 i_old = -1 same_count = 0 while i is not None and same_count < 3: count += 1 print '*' * 10 print count, '(%d -- > %d) .' % (i_old, i) # %% self.process_twi(i, do_edges=True) i_old = i i = self.tile_edge.find_best_candidate(self.elev_source_files) if i_old == i: same_count += 1 else: same_count = 0 print '*'*79 print '******* PROCESSING COMPLETED *******' print '*'*79 return self
python
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) Default None - processes all tiles in a directory. See :py:func:`process_twi` for additional options. """ # Round 0 of twi processing, process the magnitude and directions of # slopes print "Starting slope calculation round" self.process_twi(index, do_edges=False, skip_uca_twi=True) # Round 1 of twi processing print "Starting self-area calculation round" self.process_twi(index, do_edges=False) # Round 2 of twi processing: edge resolution i = self.tile_edge.find_best_candidate(self.elev_source_files) print "Starting edge resolution round: ", count = 0 i_old = -1 same_count = 0 while i is not None and same_count < 3: count += 1 print '*' * 10 print count, '(%d -- > %d) .' % (i_old, i) # %% self.process_twi(i, do_edges=True) i_old = i i = self.tile_edge.find_best_candidate(self.elev_source_files) if i_old == i: same_count += 1 else: same_count = 0 print '*'*79 print '******* PROCESSING COMPLETED *******' print '*'*79 return self
[ "def", "process", "(", "self", ",", "index", "=", "None", ")", ":", "# Round 0 of twi processing, process the magnitude and directions of", "# slopes", "print", "\"Starting slope calculation round\"", "self", ".", "process_twi", "(", "index", ",", "do_edges", "=", "False"...
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 a directory. See :py:func:`process_twi` for additional options.
[ "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", ...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L665-L709
train
creare-com/pydem
pydem/processing_manager.py
ProcessManager.calculate_twi
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 Root path to location where TWI will be saved. TWI will be saved in a subdirectory 'twi'. use_cache : bool (optional) Default True. If a temporary file exists (from a previous run), the cached file will be used. Otherwise, if False, existing files will be recomputed do_edges : bool (optional) See :py:func:`process_twi` for details on this argument. skip_uca_twi : bool (optional) Skips the calculation of the UCA and TWI (only calculates the magnitude and direction) """ if os.path.exists(os.path.join(save_path, 'tile_edge.pkl')) and \ self.tile_edge is None: with open(os.path.join(save_path, 'tile_edge.pkl'), 'r') as fid: self.tile_edge = cPickle.load(fid) elif self.tile_edge is None: self.tile_edge = TileEdgeFile(self.elev_source_files, save_path) with open(os.path.join(save_path, 'tile_edge.pkl'), 'wb') as fid: cPickle.dump(self.tile_edge, fid) status = 'Success' # optimism # Check if file is locked lckfn = _get_lockfile_name(esfile) coords = parse_fn(esfile) fn = get_fn_from_coords(coords, 'twi') print '*'*79 if skip_uca_twi: print '*'*10, fn, 'Slope Calculation starting...:', '*'*10 else: print '*'*10, fn, 'TWI Calculation starting...:', '*'*10 print '*'*79 if os.path.exists(lckfn): # another process is working on it print fn, 'is locked' return fn, "Locked" else: # lock this tile fid = file(lckfn, 'w') fid.close() dem_proc = DEMProcessor(esfile) # check if the slope already exists for the file. If yes, we should # move on to the next tile without doing anything else if skip_uca_twi \ and os.path.exists(dem_proc.get_full_fn('mag', save_path) + '.npz') \ and os.path.exists(dem_proc.get_full_fn('ang', save_path) + '.npz'): print dem_proc.get_full_fn('mag', save_path) + '.npz', 'already exists' print dem_proc.get_full_fn('ang', save_path) + '.npz', 'already exists' # remove lock file os.remove(lckfn) return fn, 'Cached: Slope' # check if the twi already exists for the file. If not in the edge # resolution round, we should move on to the next tile if os.path.exists(dem_proc.get_full_fn('twi', save_path)) \ and (do_edges is False): print dem_proc.get_full_fn('twi', save_path), 'already exists' # remove lock file os.remove(lckfn) return fn, 'Cached' # only calculate the slopes and direction if they do not exist in cache fn_ang = dem_proc.get_full_fn('ang', save_path) fn_mag = dem_proc.get_full_fn('mag', save_path) if os.path.exists(fn_ang + '.npz') and os.path.exists(fn_mag + '.npz')\ and not self.overwrite_cache: dem_proc.load_direction(fn_ang) dem_proc.load_slope(fn_mag) dem_proc.find_flats() else: if os.path.exists(fn_ang + '.npz') and os.path_exists(fn_mag + '.npz')\ and self.overwrite_cache: os.remove(fn_ang) os.remove(fn_mag) dem_proc.calc_slopes_directions() dem_proc.save_slope(save_path, raw=True) dem_proc.save_direction(save_path, raw=True) if self._DEBUG: dem_proc.save_slope(save_path, as_int=False) dem_proc.save_direction(save_path, as_int=False) if skip_uca_twi: # remove lock file os.remove(lckfn) return fn, status + ":mag-dir-only" fn_uca = dem_proc.get_full_fn('uca', save_path) fn_uca_ec = dem_proc.get_full_fn('uca_edge_corrected', save_path) fn_twi = dem_proc.get_full_fn('twi', save_path) # check if edge structure exists for this tile and initialize edge_init_data, edge_init_done, edge_init_todo = \ self.tile_edge.get_edge_init_data(esfile, save_path) # Check if uca data exists (if yes, we are in the # edge-resolution round) uca_init = None if os.path.exists(fn_uca + '.npz'): if os.path.exists(fn_uca_ec + '.npz'): dem_proc.load_uca(fn_uca_ec) else: dem_proc.load_uca(fn_uca) uca_init = dem_proc.uca if do_edges or uca_init is None: dem_proc.calc_uca(uca_init=uca_init, edge_init_data=[edge_init_data, edge_init_done, edge_init_todo]) if uca_init is None: dem_proc.save_uca(save_path, raw=True) if self._DEBUG: # Also save a geotiff for debugging dem_proc.save_uca(save_path, as_int=False) else: if os.path.exists(fn_uca_ec): os.remove(fn_uca_ec) dem_proc.save_array(dem_proc.uca, None, 'uca_edge_corrected', save_path, raw=True) if self._DEBUG: dem_proc.save_array(dem_proc.uca, None, 'uca_edge_corrected', save_path, as_int=False) # Saving Edge Data, and updating edges self.tile_edge.update_edges(esfile, dem_proc) dem_proc.calc_twi() if os.path.exists(fn_twi): os.remove(fn_twi) dem_proc.save_twi(save_path, raw=False) # clean up for in case gc.collect() # remove lock file os.remove(lckfn) # Save last-used dem_proc for debugging purposes if self._DEBUG: self.dem_proc = dem_proc return fn, status
python
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 Root path to location where TWI will be saved. TWI will be saved in a subdirectory 'twi'. use_cache : bool (optional) Default True. If a temporary file exists (from a previous run), the cached file will be used. Otherwise, if False, existing files will be recomputed do_edges : bool (optional) See :py:func:`process_twi` for details on this argument. skip_uca_twi : bool (optional) Skips the calculation of the UCA and TWI (only calculates the magnitude and direction) """ if os.path.exists(os.path.join(save_path, 'tile_edge.pkl')) and \ self.tile_edge is None: with open(os.path.join(save_path, 'tile_edge.pkl'), 'r') as fid: self.tile_edge = cPickle.load(fid) elif self.tile_edge is None: self.tile_edge = TileEdgeFile(self.elev_source_files, save_path) with open(os.path.join(save_path, 'tile_edge.pkl'), 'wb') as fid: cPickle.dump(self.tile_edge, fid) status = 'Success' # optimism # Check if file is locked lckfn = _get_lockfile_name(esfile) coords = parse_fn(esfile) fn = get_fn_from_coords(coords, 'twi') print '*'*79 if skip_uca_twi: print '*'*10, fn, 'Slope Calculation starting...:', '*'*10 else: print '*'*10, fn, 'TWI Calculation starting...:', '*'*10 print '*'*79 if os.path.exists(lckfn): # another process is working on it print fn, 'is locked' return fn, "Locked" else: # lock this tile fid = file(lckfn, 'w') fid.close() dem_proc = DEMProcessor(esfile) # check if the slope already exists for the file. If yes, we should # move on to the next tile without doing anything else if skip_uca_twi \ and os.path.exists(dem_proc.get_full_fn('mag', save_path) + '.npz') \ and os.path.exists(dem_proc.get_full_fn('ang', save_path) + '.npz'): print dem_proc.get_full_fn('mag', save_path) + '.npz', 'already exists' print dem_proc.get_full_fn('ang', save_path) + '.npz', 'already exists' # remove lock file os.remove(lckfn) return fn, 'Cached: Slope' # check if the twi already exists for the file. If not in the edge # resolution round, we should move on to the next tile if os.path.exists(dem_proc.get_full_fn('twi', save_path)) \ and (do_edges is False): print dem_proc.get_full_fn('twi', save_path), 'already exists' # remove lock file os.remove(lckfn) return fn, 'Cached' # only calculate the slopes and direction if they do not exist in cache fn_ang = dem_proc.get_full_fn('ang', save_path) fn_mag = dem_proc.get_full_fn('mag', save_path) if os.path.exists(fn_ang + '.npz') and os.path.exists(fn_mag + '.npz')\ and not self.overwrite_cache: dem_proc.load_direction(fn_ang) dem_proc.load_slope(fn_mag) dem_proc.find_flats() else: if os.path.exists(fn_ang + '.npz') and os.path_exists(fn_mag + '.npz')\ and self.overwrite_cache: os.remove(fn_ang) os.remove(fn_mag) dem_proc.calc_slopes_directions() dem_proc.save_slope(save_path, raw=True) dem_proc.save_direction(save_path, raw=True) if self._DEBUG: dem_proc.save_slope(save_path, as_int=False) dem_proc.save_direction(save_path, as_int=False) if skip_uca_twi: # remove lock file os.remove(lckfn) return fn, status + ":mag-dir-only" fn_uca = dem_proc.get_full_fn('uca', save_path) fn_uca_ec = dem_proc.get_full_fn('uca_edge_corrected', save_path) fn_twi = dem_proc.get_full_fn('twi', save_path) # check if edge structure exists for this tile and initialize edge_init_data, edge_init_done, edge_init_todo = \ self.tile_edge.get_edge_init_data(esfile, save_path) # Check if uca data exists (if yes, we are in the # edge-resolution round) uca_init = None if os.path.exists(fn_uca + '.npz'): if os.path.exists(fn_uca_ec + '.npz'): dem_proc.load_uca(fn_uca_ec) else: dem_proc.load_uca(fn_uca) uca_init = dem_proc.uca if do_edges or uca_init is None: dem_proc.calc_uca(uca_init=uca_init, edge_init_data=[edge_init_data, edge_init_done, edge_init_todo]) if uca_init is None: dem_proc.save_uca(save_path, raw=True) if self._DEBUG: # Also save a geotiff for debugging dem_proc.save_uca(save_path, as_int=False) else: if os.path.exists(fn_uca_ec): os.remove(fn_uca_ec) dem_proc.save_array(dem_proc.uca, None, 'uca_edge_corrected', save_path, raw=True) if self._DEBUG: dem_proc.save_array(dem_proc.uca, None, 'uca_edge_corrected', save_path, as_int=False) # Saving Edge Data, and updating edges self.tile_edge.update_edges(esfile, dem_proc) dem_proc.calc_twi() if os.path.exists(fn_twi): os.remove(fn_twi) dem_proc.save_twi(save_path, raw=False) # clean up for in case gc.collect() # remove lock file os.remove(lckfn) # Save last-used dem_proc for debugging purposes if self._DEBUG: self.dem_proc = dem_proc return fn, status
[ "def", "calculate_twi", "(", "self", ",", "esfile", ",", "save_path", ",", "use_cache", "=", "True", ",", "do_edges", "=", "False", ",", "skip_uca_twi", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "joi...
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 (optional) Default True. If a temporary file exists (from a previous run), the cached file will be used. Otherwise, if False, existing files will be recomputed do_edges : bool (optional) See :py:func:`process_twi` for details on this argument. skip_uca_twi : bool (optional) Skips the calculation of the UCA and TWI (only calculates the magnitude and direction)
[ "Calculates", "twi", "for", "supplied", "elevation", "file" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L711-L860
train
creare-com/pydem
pydem/processing_manager.py
ProcessManager.process_command
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 the files as listed in self.elev_source_files """ if index is not None: elev_source_files = [self.elev_source_files[index]] else: elev_source_files = self.elev_source_files save_root = os.path.join(self.save_path, save_name) if not os.path.exists(save_root): os.makedirs(save_root) for i, esfile in enumerate(elev_source_files): try: status = 'Success' # optimism # Check if file is locked lckfn = _get_lockfile_name(esfile) coords = parse_fn(esfile) fn = get_fn_from_coords(coords, save_name) fn = os.path.join(save_root, fn) if os.path.exists(lckfn): # another process is working on it print fn, 'is locked' status = 'locked' elif os.path.exists(fn): print fn, 'already exists' status = 'cached' else: # lock this tile print fn, '... calculating ', save_name fid = file(lckfn, 'w') fid.close() # Calculate the custom process for this tile status = command(esfile, fn) os.remove(lckfn) if index is None: self.custom_status[i] = status else: self.custom_status[index] = status except: lckfn = _get_lockfile_name(esfile) try: os.remove(lckfn) except: pass traceback.print_exc() print traceback.format_exc() if index is None: self.custom_status[i] = "Error " + traceback.format_exc() else: self.custom_status[index] = "Error " + traceback.format_exc()
python
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 the files as listed in self.elev_source_files """ if index is not None: elev_source_files = [self.elev_source_files[index]] else: elev_source_files = self.elev_source_files save_root = os.path.join(self.save_path, save_name) if not os.path.exists(save_root): os.makedirs(save_root) for i, esfile in enumerate(elev_source_files): try: status = 'Success' # optimism # Check if file is locked lckfn = _get_lockfile_name(esfile) coords = parse_fn(esfile) fn = get_fn_from_coords(coords, save_name) fn = os.path.join(save_root, fn) if os.path.exists(lckfn): # another process is working on it print fn, 'is locked' status = 'locked' elif os.path.exists(fn): print fn, 'already exists' status = 'cached' else: # lock this tile print fn, '... calculating ', save_name fid = file(lckfn, 'w') fid.close() # Calculate the custom process for this tile status = command(esfile, fn) os.remove(lckfn) if index is None: self.custom_status[i] = status else: self.custom_status[index] = status except: lckfn = _get_lockfile_name(esfile) try: os.remove(lckfn) except: pass traceback.print_exc() print traceback.format_exc() if index is None: self.custom_status[i] = "Error " + traceback.format_exc() else: self.custom_status[index] = "Error " + traceback.format_exc()
[ "def", "process_command", "(", "self", ",", "command", ",", "save_name", "=", "'custom'", ",", "index", "=", "None", ")", ":", "if", "index", "is", "not", "None", ":", "elev_source_files", "=", "[", "self", ".", "elev_source_files", "[", "index", "]", "]...
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
[ "Processes", "the", "hillshading" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/processing_manager.py#L873-L932
train
creare-com/pydem
pydem/utils.py
rename_files
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 elevation files that will be renamed name : str (optional) Default = None. A suffix to the filename. For example <filename>_suffix.tif Notes ------ The files are renamed in the same directory as the original file locations """ for fil in files: elev_file = GdalReader(file_name=fil) elev, = elev_file.raster_layers fn = get_fn(elev, name) del elev_file del elev fn = os.path.join(os.path.split(fil)[0], fn) os.rename(fil, fn) print "Renamed", fil, "to", fn
python
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 elevation files that will be renamed name : str (optional) Default = None. A suffix to the filename. For example <filename>_suffix.tif Notes ------ The files are renamed in the same directory as the original file locations """ for fil in files: elev_file = GdalReader(file_name=fil) elev, = elev_file.raster_layers fn = get_fn(elev, name) del elev_file del elev fn = os.path.join(os.path.split(fil)[0], fn) os.rename(fil, fn) print "Renamed", fil, "to", fn
[ "def", "rename_files", "(", "files", ",", "name", "=", "None", ")", ":", "for", "fil", "in", "files", ":", "elev_file", "=", "GdalReader", "(", "file_name", "=", "fil", ")", "elev", ",", "=", "elev_file", ".", "raster_layers", "fn", "=", "get_fn", "(",...
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 : str (optional) Default = None. A suffix to the filename. For example <filename>_suffix.tif Notes ------ The files are renamed in the same directory as the original file locations
[ "Given", "a", "list", "of", "file", "paths", "for", "elevation", "files", "this", "function", "will", "rename", "those", "files", "to", "the", "format", "required", "by", "the", "pyDEM", "package", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L46-L74
train
creare-com/pydem
pydem/utils.py
parse_fn
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].replace('o', '.')\ .split('_')[:2] coords = [float(crds) for crds in re.split('[NSEW]', parts[0] + parts[1])[1:]] except: coords = [np.nan] * 4 return coords
python
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].replace('o', '.')\ .split('_')[:2] coords = [float(crds) for crds in re.split('[NSEW]', parts[0] + parts[1])[1:]] except: coords = [np.nan] * 4 return coords
[ "def", "parse_fn", "(", "fn", ")", ":", "try", ":", "parts", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "fn", ")", "[", "-", "1", "]", ")", "[", "0", "]", ".", "replace", "(", "'o'", ",", "'.'", ")",...
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]
[ "This", "parses", "the", "file", "name", "and", "returns", "the", "coordinates", "of", "the", "tile" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L77-L96
train
creare-com/pydem
pydem/utils.py
get_fn
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 : str The standard <filename>_<name>.tif with suffix (if supplied) """ gcs = elev.grid_coordinates coords = [gcs.LLC.lat, gcs.LLC.lon, gcs.URC.lat, gcs.URC.lon] return get_fn_from_coords(coords, name)
python
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 : str The standard <filename>_<name>.tif with suffix (if supplied) """ gcs = elev.grid_coordinates coords = [gcs.LLC.lat, gcs.LLC.lon, gcs.URC.lat, gcs.URC.lon] return get_fn_from_coords(coords, name)
[ "def", "get_fn", "(", "elev", ",", "name", "=", "None", ")", ":", "gcs", "=", "elev", ".", "grid_coordinates", "coords", "=", "[", "gcs", ".", "LLC", ".", "lat", ",", "gcs", ".", "LLC", ".", "lon", ",", "gcs", ".", "URC", ".", "lat", ",", "gcs"...
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>_<name>.tif with suffix (if supplied)
[ "Determines", "the", "standard", "filename", "for", "a", "given", "GeoTIFF", "Layer", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L99-L116
train
creare-com/pydem
pydem/utils.py
get_fn_from_coords
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 The standard <filename>_<name>.tif with suffix (if supplied) """ NS1 = ["S", "N"][coords[0] > 0] EW1 = ["W", "E"][coords[1] > 0] NS2 = ["S", "N"][coords[2] > 0] EW2 = ["W", "E"][coords[3] > 0] new_name = "%s%0.3g%s%0.3g_%s%0.3g%s%0.3g" % \ (NS1, coords[0], EW1, coords[1], NS2, coords[2], EW2, coords[3]) if name is not None: new_name += '_' + name return new_name.replace('.', 'o') + '.tif'
python
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 The standard <filename>_<name>.tif with suffix (if supplied) """ NS1 = ["S", "N"][coords[0] > 0] EW1 = ["W", "E"][coords[1] > 0] NS2 = ["S", "N"][coords[2] > 0] EW2 = ["W", "E"][coords[3] > 0] new_name = "%s%0.3g%s%0.3g_%s%0.3g%s%0.3g" % \ (NS1, coords[0], EW1, coords[1], NS2, coords[2], EW2, coords[3]) if name is not None: new_name += '_' + name return new_name.replace('.', 'o') + '.tif'
[ "def", "get_fn_from_coords", "(", "coords", ",", "name", "=", "None", ")", ":", "NS1", "=", "[", "\"S\"", ",", "\"N\"", "]", "[", "coords", "[", "0", "]", ">", "0", "]", "EW1", "=", "[", "\"W\"", ",", "\"E\"", "]", "[", "coords", "[", "1", "]",...
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 supplied)
[ "Given", "a", "set", "of", "coordinates", "returns", "the", "standard", "filename", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L119-L142
train
creare-com/pydem
pydem/utils.py
mk_dx_dy_from_geotif_layer
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.grid_coordinates.x_axis dy = geotif.grid_coordinates.y_axis dX = np.zeros((dy.shape[0]-1)) for j in xrange(len(dX)): dX[j] = d.measure((dy[j+1], dx[1]), (dy[j+1], dx[0])) * 1000 # km2m dY = np.zeros((dy.shape[0]-1)) for i in xrange(len(dY)): dY[i] = d.measure((dy[i], 0), (dy[i+1], 0)) * 1000 # km2m return dX, dY
python
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.grid_coordinates.x_axis dy = geotif.grid_coordinates.y_axis dX = np.zeros((dy.shape[0]-1)) for j in xrange(len(dX)): dX[j] = d.measure((dy[j+1], dx[1]), (dy[j+1], dx[0])) * 1000 # km2m dY = np.zeros((dy.shape[0]-1)) for i in xrange(len(dY)): dY[i] = d.measure((dy[i], 0), (dy[i+1], 0)) * 1000 # km2m return dX, dY
[ "def", "mk_dx_dy_from_geotif_layer", "(", "geotif", ")", ":", "ELLIPSOID_MAP", "=", "{", "'WGS84'", ":", "'WGS-84'", "}", "ellipsoid", "=", "ELLIPSOID_MAP", "[", "geotif", ".", "grid_coordinates", ".", "wkt", "]", "d", "=", "distance", "(", "ellipsoid", "=", ...
Extracts the change in x and y coordinates from the geotiff file. Presently only supports WGS-84 files.
[ "Extracts", "the", "change", "in", "x", "and", "y", "coordinates", "from", "the", "geotiff", "file", ".", "Presently", "only", "supports", "WGS", "-", "84", "files", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L145-L161
train
creare-com/pydem
pydem/utils.py
mk_geotiff_obj
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 ------------ raster : array Numpy array of the raster data to be added to the object fn : str Name of the geotiff file bands : int (optional) See :py:func:`gdal.GetDriverByName('Gtiff').Create gdal_data : gdal.GDT_<type> Gdal data type (see gdal.GDT_...) lat : list northern lat, southern lat lon : list [western lon, eastern lon] """ NNi, NNj = raster.shape driver = gdal.GetDriverByName('GTiff') obj = driver.Create(fn, NNj, NNi, bands, gdal_data_type) pixel_height = -np.abs(lat[0] - lat[1]) / (NNi - 1.0) pixel_width = np.abs(lon[0] - lon[1]) / (NNj - 1.0) obj.SetGeoTransform([lon[0], pixel_width, 0, lat[0], 0, pixel_height]) srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS84') obj.SetProjection(srs.ExportToWkt()) obj.GetRasterBand(1).WriteArray(raster) return obj, driver
python
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 ------------ raster : array Numpy array of the raster data to be added to the object fn : str Name of the geotiff file bands : int (optional) See :py:func:`gdal.GetDriverByName('Gtiff').Create gdal_data : gdal.GDT_<type> Gdal data type (see gdal.GDT_...) lat : list northern lat, southern lat lon : list [western lon, eastern lon] """ NNi, NNj = raster.shape driver = gdal.GetDriverByName('GTiff') obj = driver.Create(fn, NNj, NNi, bands, gdal_data_type) pixel_height = -np.abs(lat[0] - lat[1]) / (NNi - 1.0) pixel_width = np.abs(lon[0] - lon[1]) / (NNj - 1.0) obj.SetGeoTransform([lon[0], pixel_width, 0, lat[0], 0, pixel_height]) srs = osr.SpatialReference() srs.SetWellKnownGeogCS('WGS84') obj.SetProjection(srs.ExportToWkt()) obj.GetRasterBand(1).WriteArray(raster) return obj, driver
[ "def", "mk_geotiff_obj", "(", "raster", ",", "fn", ",", "bands", "=", "1", ",", "gdal_data_type", "=", "gdal", ".", "GDT_Float32", ",", "lat", "=", "[", "46", ",", "45", "]", ",", "lon", "=", "[", "-", "73", ",", "-", "72", "]", ")", ":", "NNi"...
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 bands : int (optional) See :py:func:`gdal.GetDriverByName('Gtiff').Create gdal_data : gdal.GDT_<type> Gdal data type (see gdal.GDT_...) lat : list northern lat, southern lat lon : list [western lon, eastern lon]
[ "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" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L164-L195
train
creare-com/pydem
pydem/utils.py
sortrows
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) = sortrows(a,i). Default = False recurse : bool (optional) recursively sort by each of the columns. i.e. once column i is sort, we sort the smallest column number etc. True by default. Returns -------- a : np.ndarray The array 'a' sorted in descending order by column i I : np.ndarray (optional) The index such that a[I, :] = sortrows(a, i). Only return if index_out = True Examples --------- >>> a = array([[1,2],[3,1],[2,3]]) >>> b = sortrows(a,0) >>> b array([[1, 2], [2, 3], [3, 1]]) c, I = sortrows(a,1,True) >>> c array([[3, 1], [1, 2], [2, 3]]) >>> I array([1, 0, 2]) >>> a[I,:] - c array([[0, 0], [0, 0], [0, 0]]) """ I = np.argsort(a[:, i]) a = a[I, :] # We recursively call sortrows to make sure it is sorted best by every # column if recurse & (len(a[0]) > i + 1): for b in np.unique(a[:, i]): ids = a[:, i] == b colids = range(i) + range(i+1, len(a[0])) a[np.ix_(ids, colids)], I2 = sortrows(a[np.ix_(ids, colids)], 0, True, True) I[ids] = I[np.nonzero(ids)[0][I2]] if index_out: return a, I else: return a
python
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) = sortrows(a,i). Default = False recurse : bool (optional) recursively sort by each of the columns. i.e. once column i is sort, we sort the smallest column number etc. True by default. Returns -------- a : np.ndarray The array 'a' sorted in descending order by column i I : np.ndarray (optional) The index such that a[I, :] = sortrows(a, i). Only return if index_out = True Examples --------- >>> a = array([[1,2],[3,1],[2,3]]) >>> b = sortrows(a,0) >>> b array([[1, 2], [2, 3], [3, 1]]) c, I = sortrows(a,1,True) >>> c array([[3, 1], [1, 2], [2, 3]]) >>> I array([1, 0, 2]) >>> a[I,:] - c array([[0, 0], [0, 0], [0, 0]]) """ I = np.argsort(a[:, i]) a = a[I, :] # We recursively call sortrows to make sure it is sorted best by every # column if recurse & (len(a[0]) > i + 1): for b in np.unique(a[:, i]): ids = a[:, i] == b colids = range(i) + range(i+1, len(a[0])) a[np.ix_(ids, colids)], I2 = sortrows(a[np.ix_(ids, colids)], 0, True, True) I[ids] = I[np.nonzero(ids)[0][I2]] if index_out: return a, I else: return a
[ "def", "sortrows", "(", "a", ",", "i", "=", "0", ",", "index_out", "=", "False", ",", "recurse", "=", "True", ")", ":", "I", "=", "np", ".", "argsort", "(", "a", "[", ":", ",", "i", "]", ")", "a", "=", "a", "[", "I", ",", ":", "]", "# We ...
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) recursively sort by each of the columns. i.e. once column i is sort, we sort the smallest column number etc. True by default. Returns -------- a : np.ndarray The array 'a' sorted in descending order by column i I : np.ndarray (optional) The index such that a[I, :] = sortrows(a, i). Only return if index_out = True Examples --------- >>> a = array([[1,2],[3,1],[2,3]]) >>> b = sortrows(a,0) >>> b array([[1, 2], [2, 3], [3, 1]]) c, I = sortrows(a,1,True) >>> c array([[3, 1], [1, 2], [2, 3]]) >>> I array([1, 0, 2]) >>> a[I,:] - c array([[0, 0], [0, 0], [0, 0]])
[ "Sorts", "array", "a", "by", "columns", "i" ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L198-L258
train
creare-com/pydem
pydem/utils.py
get_adjacent_index
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 (technically computable from shape) Returns ------- J : np.ndarray(dtype=int) indices orthogonally and diagonally adjacent to I """ m, n = shape In = I % n bL = In != 0 bR = In != n-1 J = np.concatenate([ # orthonally adjacent I - n, I[bL] - 1, I[bR] + 1, I + n, # diagonally adjacent I[bL] - n-1, I[bR] - n+1, I[bL] + n-1, I[bR] + n+1]) # remove indices outside the array J = J[(J>=0) & (J<size)] return J
python
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 (technically computable from shape) Returns ------- J : np.ndarray(dtype=int) indices orthogonally and diagonally adjacent to I """ m, n = shape In = I % n bL = In != 0 bR = In != n-1 J = np.concatenate([ # orthonally adjacent I - n, I[bL] - 1, I[bR] + 1, I + n, # diagonally adjacent I[bL] - n-1, I[bR] - n+1, I[bL] + n-1, I[bR] + n+1]) # remove indices outside the array J = J[(J>=0) & (J<size)] return J
[ "def", "get_adjacent_index", "(", "I", ",", "shape", ",", "size", ")", ":", "m", ",", "n", "=", "shape", "In", "=", "I", "%", "n", "bL", "=", "In", "!=", "0", "bR", "=", "In", "!=", "n", "-", "1", "J", "=", "np", ".", "concatenate", "(", "[...
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 ------- J : np.ndarray(dtype=int) indices orthogonally and diagonally adjacent to I
[ "Find", "indices", "2d", "-", "adjacent", "to", "those", "in", "I", ".", "Helper", "function", "for", "get_border", "*", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L260-L301
train
creare-com/pydem
pydem/utils.py
get_border_index
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) region shape Returns ------- J : np.ndarray(dtype=int) indices orthogonally and diagonally bordering I """ J = get_adjacent_index(I, shape, size) # instead of setdiff? # border = np.zeros(size) # border[J] = 1 # border[I] = 0 # J, = np.where(border) return np.setdiff1d(J, I)
python
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) region shape Returns ------- J : np.ndarray(dtype=int) indices orthogonally and diagonally bordering I """ J = get_adjacent_index(I, shape, size) # instead of setdiff? # border = np.zeros(size) # border[J] = 1 # border[I] = 0 # J, = np.where(border) return np.setdiff1d(J, I)
[ "def", "get_border_index", "(", "I", ",", "shape", ",", "size", ")", ":", "J", "=", "get_adjacent_index", "(", "I", ",", "shape", ",", "size", ")", "# instead of setdiff?", "# border = np.zeros(size)", "# border[J] = 1", "# border[I] = 0", "# J, = np.where(border)", ...
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.ndarray(dtype=int) indices orthogonally and diagonally bordering I
[ "Get", "flattened", "indices", "for", "the", "border", "of", "the", "region", "I", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L303-L330
train
creare-com/pydem
pydem/utils.py
get_border_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 including region) """ # common special case (for efficiency) internal = region[1:-1, 1:-1] if internal.all() and internal.any(): return ~region I, = np.where(region.ravel()) J = get_adjacent_index(I, region.shape, region.size) border = np.zeros(region.size, dtype='bool') border[J] = 1 border[I] = 0 border = border.reshape(region.shape) return border
python
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 including region) """ # common special case (for efficiency) internal = region[1:-1, 1:-1] if internal.all() and internal.any(): return ~region I, = np.where(region.ravel()) J = get_adjacent_index(I, region.shape, region.size) border = np.zeros(region.size, dtype='bool') border[J] = 1 border[I] = 0 border = border.reshape(region.shape) return border
[ "def", "get_border_mask", "(", "region", ")", ":", "# common special case (for efficiency)", "internal", "=", "region", "[", "1", ":", "-", "1", ",", "1", ":", "-", "1", "]", "if", "internal", ".", "all", "(", ")", "and", "internal", ".", "any", "(", "...
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)
[ "Get", "border", "of", "the", "region", "as", "a", "boolean", "array", "mask", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L332-L360
train
creare-com/pydem
pydem/utils.py
get_distance
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. Returns ------- d : np.ndarray(shape=(m, n), dtype=float) approximate within-region distance from the nearest src pixel; (distances outside of the region are arbitrary). """ dmax = float(region.size) d = np.full(region.shape, dmax) d[src] = 0 for n in range(region.size): d_orth = minimum_filter(d, footprint=_ORTH2) + 1 d_diag = minimum_filter(d, (3, 3)) + _SQRT2 d_adj = np.minimum(d_orth[region], d_diag[region]) d[region] = np.minimum(d_adj, d[region]) if (d[region] < dmax).all(): break return d
python
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. Returns ------- d : np.ndarray(shape=(m, n), dtype=float) approximate within-region distance from the nearest src pixel; (distances outside of the region are arbitrary). """ dmax = float(region.size) d = np.full(region.shape, dmax) d[src] = 0 for n in range(region.size): d_orth = minimum_filter(d, footprint=_ORTH2) + 1 d_diag = minimum_filter(d, (3, 3)) + _SQRT2 d_adj = np.minimum(d_orth[region], d_diag[region]) d[region] = np.minimum(d_adj, d[region]) if (d[region] < dmax).all(): break return d
[ "def", "get_distance", "(", "region", ",", "src", ")", ":", "dmax", "=", "float", "(", "region", ".", "size", ")", "d", "=", "np", ".", "full", "(", "region", ".", "shape", ",", "dmax", ")", "d", "[", "src", "]", "=", "0", "for", "n", "in", "...
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=(m, n), dtype=float) approximate within-region distance from the nearest src pixel; (distances outside of the region are arbitrary).
[ "Compute", "within", "-", "region", "distances", "from", "the", "src", "pixels", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L364-L392
train
creare-com/pydem
pydem/utils.py
grow_slice
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, slc.start-1), min(size, slc.stop+1))
python
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, slc.start-1), min(size, slc.stop+1))
[ "def", "grow_slice", "(", "slc", ",", "size", ")", ":", "return", "slice", "(", "max", "(", "0", ",", "slc", ".", "start", "-", "1", ")", ",", "min", "(", "size", ",", "slc", ".", "stop", "+", "1", ")", ")" ]
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
[ "Grow", "a", "slice", "object", "by", "1", "in", "each", "direction", "without", "overreaching", "the", "list", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L400-L418
train
creare-com/pydem
pydem/utils.py
is_edge
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 True if the object touches any edge of the array, else False. """ if obj[0].start == 0: return True if obj[1].start == 0: return True if obj[0].stop == shape[0]: return True if obj[1].stop == shape[1]: return True return False
python
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 True if the object touches any edge of the array, else False. """ if obj[0].start == 0: return True if obj[1].start == 0: return True if obj[0].stop == shape[0]: return True if obj[1].stop == shape[1]: return True return False
[ "def", "is_edge", "(", "obj", ",", "shape", ")", ":", "if", "obj", "[", "0", "]", ".", "start", "==", "0", ":", "return", "True", "if", "obj", "[", "1", "]", ".", "start", "==", "0", ":", "return", "True", "if", "obj", "[", "0", "]", ".", "...
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 of the array, else False.
[ "Check", "if", "a", "2d", "object", "is", "on", "the", "edge", "of", "the", "array", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L439-L460
train
creare-com/pydem
pydem/utils.py
find_centroid
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 the center of mass. """ x, y = center_of_mass(region) w = np.argwhere(region) i, j = w[np.argmin(np.linalg.norm(w - (x, y), axis=1))] return i, j
python
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 the center of mass. """ x, y = center_of_mass(region) w = np.argwhere(region) i, j = w[np.argmin(np.linalg.norm(w - (x, y), axis=1))] return i, j
[ "def", "find_centroid", "(", "region", ")", ":", "x", ",", "y", "=", "center_of_mass", "(", "region", ")", "w", "=", "np", ".", "argwhere", "(", "region", ")", "i", ",", "j", "=", "w", "[", "np", ".", "argmin", "(", "np", ".", "linalg", ".", "n...
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.
[ "Finds", "an", "approximate", "centroid", "for", "a", "region", "that", "is", "within", "the", "region", ".", "Parameters", "----------", "region", ":", "np", ".", "ndarray", "(", "shape", "=", "(", "m", "n", ")", "dtype", "=", "bool", ")", "mask", "of...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L462-L480
train
thefab/tornadis
tornadis/write_buffer.py
WriteBuffer.clear
def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
python
def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_deque", ".", "clear", "(", ")", "self", ".", "_total_length", "=", "0", "self", ".", "_has_view", "=", "False" ]
Resets the object at its initial (empty) state.
[ "Resets", "the", "object", "at", "its", "initial", "(", "empty", ")", "state", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/write_buffer.py#L39-L43
train
thefab/tornadis
tornadis/write_buffer.py
WriteBuffer._tobytes
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._deque) == 1: # no copy return self._deque[0] else: return b"".join(self._deque) else: tmp = [x.tobytes() if isinstance(x, memoryview) else x for x in self._deque] return b"".join(tmp)
python
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._deque) == 1: # no copy return self._deque[0] else: return b"".join(self._deque) else: tmp = [x.tobytes() if isinstance(x, memoryview) else x for x in self._deque] return b"".join(tmp)
[ "def", "_tobytes", "(", "self", ")", ":", "if", "not", "self", ".", "_has_view", ":", "# fast path optimization", "if", "len", "(", "self", ".", "_deque", ")", "==", "0", ":", "return", "b\"\"", "elif", "len", "(", "self", ".", "_deque", ")", "==", "...
Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object.
[ "Serializes", "the", "write", "buffer", "into", "a", "single", "string", "(", "bytes", ")", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/write_buffer.py#L54-L72
train
thefab/tornadis
tornadis/write_buffer.py
WriteBuffer.pop_chunk
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._total_length < chunk_max_size: # fastpath (the whole queue fit in a single chunk) res = self._tobytes() self.clear() return res first_iteration = True while True: try: data = self._deque.popleft() data_length = len(data) self._total_length -= data_length if first_iteration: # first iteration if data_length == chunk_max_size: # we are lucky ! return data elif data_length > chunk_max_size: # we have enough data at first iteration # => fast path optimization view = self._get_pointer_or_memoryview(data, data_length) self.appendleft(view[chunk_max_size:]) return view[:chunk_max_size] else: # no single iteration fast path optimization :-( # let's use a WriteBuffer to build the result chunk chunk_write_buffer = WriteBuffer() else: # not first iteration if chunk_write_buffer._total_length + data_length \ > chunk_max_size: view = self._get_pointer_or_memoryview(data, data_length) limit = chunk_max_size - \ chunk_write_buffer._total_length - data_length self.appendleft(view[limit:]) data = view[:limit] chunk_write_buffer.append(data) if chunk_write_buffer._total_length >= chunk_max_size: break except IndexError: # the buffer is empty (so no memoryview inside) self._has_view = False break first_iteration = False return chunk_write_buffer._tobytes()
python
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._total_length < chunk_max_size: # fastpath (the whole queue fit in a single chunk) res = self._tobytes() self.clear() return res first_iteration = True while True: try: data = self._deque.popleft() data_length = len(data) self._total_length -= data_length if first_iteration: # first iteration if data_length == chunk_max_size: # we are lucky ! return data elif data_length > chunk_max_size: # we have enough data at first iteration # => fast path optimization view = self._get_pointer_or_memoryview(data, data_length) self.appendleft(view[chunk_max_size:]) return view[:chunk_max_size] else: # no single iteration fast path optimization :-( # let's use a WriteBuffer to build the result chunk chunk_write_buffer = WriteBuffer() else: # not first iteration if chunk_write_buffer._total_length + data_length \ > chunk_max_size: view = self._get_pointer_or_memoryview(data, data_length) limit = chunk_max_size - \ chunk_write_buffer._total_length - data_length self.appendleft(view[limit:]) data = view[:limit] chunk_write_buffer.append(data) if chunk_write_buffer._total_length >= chunk_max_size: break except IndexError: # the buffer is empty (so no memoryview inside) self._has_view = False break first_iteration = False return chunk_write_buffer._tobytes()
[ "def", "pop_chunk", "(", "self", ",", "chunk_max_size", ")", ":", "if", "self", ".", "_total_length", "<", "chunk_max_size", ":", "# fastpath (the whole queue fit in a single chunk)", "res", "=", "self", ".", "_tobytes", "(", ")", "self", ".", "clear", "(", ")",...
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.
[ "Pops", "a", "chunk", "of", "the", "given", "max", "size", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/write_buffer.py#L134-L190
train