utils.utils — Utility Functions

The utils.utils module includes a collection of utility functions

New in version 0.1.0.

autocnet.utils.utils.array_to_poly(array)[source]

Generate a geojson geom :param array: 2-D array of size (n, 2) of x, y coordinates :type array: array-like

Returns

geom – geojson containing the necessary data to construct a poly gon

Return type

GeoJson

autocnet.utils.utils.bytescale(data, cmin=None, cmax=None, high=255, low=0)[source]

This is pulled directly from scipy.misc as they are deprecating bytescale.

Byte scales an array (image). Byte scaling means converting the input image to uint8 dtype and scaling the range to (low, high) (default 0-255). If the input image already has dtype uint8, no scaling is done. This function is only available if Python Imaging Library (PIL) is installed. :param data: PIL image data array. :type data: ndarray :param cmin: Bias scaling of small values. Default is data.min(). :type cmin: scalar, optional :param cmax: Bias scaling of large values. Default is data.max(). :type cmax: scalar, optional :param high: Scale max value to high. Default is 255. :type high: scalar, optional :param low: Scale min value to low. Default is 0. :type low: scalar, optional

Returns

img_array – The byte-scaled array.

Return type

uint8 ndarray

Examples

>>> from scipy.misc import bytescale
>>> img = np.array([[ 91.06794177,   3.39058326,  84.4221549 ],
...                 [ 73.88003259,  80.91433048,   4.88878881],
...                 [ 51.53875334,  34.45808177,  27.5873488 ]])
>>> bytescale(img)
array([[255,   0, 236],
       [205, 225,   4],
       [140,  90,  70]], dtype=uint8)
>>> bytescale(img, high=200, low=100)
array([[200, 100, 192],
       [180, 188, 102],
       [155, 135, 128]], dtype=uint8)
>>> bytescale(img, cmin=0, cmax=255)
array([[91,  3, 84],
       [74, 81,  5],
       [52, 34, 28]], dtype=uint8)
autocnet.utils.utils.calculate_slope(x1, x2)[source]

Calculates the 2-dimensional slope between the points in two dataframes each containing two columns [‘x’, ‘y’] The slope is calculated from x1 to x2.

Parameters
  • x1 (dataframe) – Each row is a point with columns [‘x’, ‘y’]

  • x2 (dataframe) – Each row is a point with columns [‘x’, ‘y’]

Returns

A dataframe with the slope between the points in x1 and x2 for each row.

Return type

dataframe

autocnet.utils.utils.cartesian(arrays, out=None)[source]

Generate a cartesian product of input arrays. :param arrays: 1-D arrays to form the cartesian product of. :type arrays: list of array-like :param out: Array to place the cartesian product in. :type out: ndarray

Returns

  • out (ndarray) – 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays.

  • from scikit-learn

  • https (//github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/extmath.py)

autocnet.utils.utils.checkbandnumbers(bands, checkbands)[source]

Given a list of input bands, check that the passed tuple contains those bands.

In case of THEMIS, we check for band 9 as band 9 is the temperature band required to derive thermal temperature. We also check for band 10 which is required for TES atmosphere calculations.

Parameters
  • bands (tuple) – of bands in the input image

  • checkbands (list) – of bands to check against

Returns

True if the bands are present, else False

Return type

bool

autocnet.utils.utils.checkdeplaid(incidence)[source]

Given an incidence angle, select the appropriate deplaid method.

Parameters

incidence (float) – incidence angle extracted from the campt results.

autocnet.utils.utils.checkmonotonic(iterable, piecewise=False)[source]

Check if a given iterable is monotonically increasing.

Parameters
  • iterable (iterable) – Any Python iterable object

  • piecewise (boolean) – If false, return a boolean for the entire iterable, else return a list with elementwise monotinicy checks

Returns

monotonic – A boolean list of all True if monotonic, or including an inflection point

Return type

bool/list

autocnet.utils.utils.compare_dicts(d, o)[source]

Given two dictionaries, compare them with support for np.ndarray and pd.DataFrame objects

Parameters
  • d (dict) – first dict to compare

  • o (dict) – second dict to compare

Examples

>>> d = {'a':0}
>>> o = {'a':0}
>>> compare_dicts(d, o)
True
>>> d['a'] = 1
>>> compare_dicts(d,o)
False
>>> d['a'] = np.arange(3)
>>> o['a'] = np.arange(3)
>>> compare_dicts(d,o)
True
autocnet.utils.utils.compute_depression(input_dem, scale_factor=1, curvature_percentile=75)[source]

Compute depressions and return a new image with larges depressions filled in.

Parameters
  • input_dem (np.array, rd.rdarray) – 2d array of elevation DNs, a DEM

  • scale_factor (float) – Value to scale the erotion of planform curvatures by

  • curvature_percentile (float) – what percentile of the curvature to keep, lower values results in bigger blobs

Returns

  • dem (rd.rdarray) – Dem with filled depressions

  • mask (np.array) – Change mask, true on pixels that have been changed

autocnet.utils.utils.create_decorator(dec, **namespace)[source]

Create a decorator function using arbirary params. The objects passed in can be used in the body. Originally designed with the idea of automatically updating one object after the decorated object was modified.

autocnet.utils.utils.crossform(a)[source]

Return the cross form, e.g. a in the cross product of a b. :param a: (3,) vector :type a: ndarray

Returns

a – (3,3)

Return type

ndarray

autocnet.utils.utils.decorate_class(cls, decorator, exclude=[], *args, **kwargs)[source]

Decorates a class with a give docorator. Returns a subclass with dectorations applied

Parameters
  • cls (Class) – A class to be decorated

  • decorator (callable) – callable to wrap cls’s methods with

  • exclude (list) – list of method names to exclude from being decorated

  • args (list, dict) – Parameters to pass into decorator

  • kwargs (list, dict) – Parameters to pass into decorator

autocnet.utils.utils.find_in_dict(obj, key)[source]

Recursively find an entry in a dictionary

Parameters
  • obj (dict) – The dictionary to search

  • key (str) – The key to find in the dictionary

Returns

item – The value from the dictionary

Return type

obj

autocnet.utils.utils.find_nested_in_dict(data, key_list)[source]

Traverse a list of keys into a dict.

Parameters
  • data (dict) – The dictionary to be traversed

  • key_list (list) – The list of keys to be travered. Keys are traversed in the order they are entered in the list

Returns

value – The value in the dict

Return type

object

autocnet.utils.utils.generate_dem(alpha=1.0, size=800, scales=[160, 80, 32, 16, 8, 4, 2, 1], scale_factor=5)[source]

Produces a random DEM

Parameters
  • alpha (float) – Controls height variation. Lower number makes a shallower and noisier DEM, higher values create smoother DEM with large peaks and valleys. Reccommended range = (0, 1.5]

  • size (int) – size of DEM, output DEM is in the shape of (size, size)

  • scale_factor (float) – Scalar to multiply the slope degradation by, higher values = more erosion. Recommended to increase proportionately with alpha (higher alphas mean you might want higher scale_factor)

Returns

dem – DEM array in the shape (size, size)

Return type

np.array

autocnet.utils.utils.getnearest(iterable, value)[source]

Given an iterable, get the index nearest to the input value

Parameters
  • iterable (iterable) – An iterable to search

  • value (int, float) – The value to search for

Returns

The index into the list

Return type

int

autocnet.utils.utils.hillshade(img, azi=255, min_slope=20, max_slope=100, min_bright=0, grayscale=False)[source]

hillshade a DEM, based on IDL code by Colin Dundas

Parameters
  • img (np.array) – DEM to hillshade

  • azi (float) – Sun azimuth

  • min_slope (float) – minimum slope value

  • max_slope (float) – maximum slope value

  • min_bright (float) – minimum brightness

  • grayscale (bool) – whether or not to produce grayscale image

Returns

dem – hillshaded DEM

Return type

np.array

autocnet.utils.utils.import_func(func)[source]

Imports a function from the autocnet package.

Parameters

func (str) – import path. For example, to import the place_points_in_overlap function, this func can be called with: ‘spatial.overlap.place_points_in_overlap’

Returns

func – The function object for use.

Return type

obj

autocnet.utils.utils.make_homogeneous(points)[source]
Convert a set of points (n x dim array) to

homogeneous coordinates.

Parameters

points (arraylike) – n x m array of points, where n is the number of points.

Returns

n x m + 1 array of homogeneous points

Return type

arraylike

autocnet.utils.utils.methodispatch(func)[source]

New dispatch decorator that looks at the second argument to avoid self

Parameters
  • func (Object) – Function object to be dispatched

  • Returns

  • wrapper (Object) – Wrapped function call chosen by the dispatcher

  • ----------

autocnet.utils.utils.normalize_vector(line)[source]

Normalize a standard form line

Parameters

line (ndarray) – Standard form of a line (Ax + By + C = 0)

Returns

line – The normalized line

Return type

ndarray

Examples

>>> x = np.array([3, 1, 2])
>>> nv = normalize_vector(x)
>>> print(np.round(nv, 6))  # For doc test float percision
[0.801784 0.267261 0.534522]
autocnet.utils.utils.rasterize_polygon(shape, vertices, dtype=<class 'bool'>)[source]

Simple tool to convert poly into a boolean numpy array.

source: https://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array

Parameters
  • shape (tuple) – size of the array in (y,x) format

  • vertices (np.array, list) – array of vertices in [[x0, y0], [x1, y1]…] format

  • dtype (type) – datatype of output mask

Returns

mask – mask with filled polygon set to true

Return type

np.array

autocnet.utils.utils.remove_field_name(a, name)[source]

Given a numpy structured array, remove a column and return a copy of the remainder of the array

Parameters
  • a (ndarray) – Numpy structured array

  • name (str) – of the index (column) to be removed

Returns

b – Numpy structured array with the ‘name’ column removed

Return type

ndarray