|
| 1 | +#!/usr/bin/env python |
| 2 | +""" |
| 3 | +The tools.maths module contains some useful tools for maths operations which aren't |
| 4 | +easily available else where. |
| 5 | +
|
| 6 | +""" |
| 7 | +from typing import Union, List |
| 8 | + |
| 9 | +import numpy |
| 10 | + |
| 11 | +import rsgislib |
| 12 | + |
| 13 | + |
| 14 | +def round_to_nearest_val( |
| 15 | + input_val: Union[numpy.array, int, float, List[int], List[float]], |
| 16 | + round_val: int = 1, |
| 17 | + round_direction: int = rsgislib.ROUND_NEAREST, |
| 18 | +): |
| 19 | + """ |
| 20 | + Rounds elements of a NumPy array to the nearest multiple of the value specified, |
| 21 | + with options for rounding up, down or to the nearest value. For example, if a |
| 22 | + round_val of 5 is provided then the numbers will be rounded to intervals of 5. |
| 23 | +
|
| 24 | + :param input_val: A NumPy array of numbers. |
| 25 | + :param round_val: The value by which the input is to be rounded to. |
| 26 | + :param round_direction: Specify the round direction (rsgislib.ROUND_NEAREST, |
| 27 | + rsgislib.ROUND_UP, or rsgislib.ROUND_DOWN). The |
| 28 | + default is rsgislib.ROUND_NEAREST. |
| 29 | + :return: a single value or a numpy array of the rounded values. |
| 30 | +
|
| 31 | + """ |
| 32 | + if isinstance(input_val, list): |
| 33 | + input_val = numpy.array(input_val, dtype=float) |
| 34 | + |
| 35 | + round_val_flt = float(round_val) |
| 36 | + round_val_int = int(round_val) |
| 37 | + if round_direction == rsgislib.ROUND_NEAREST: |
| 38 | + return numpy.round(input_val / round_val_flt) * round_val_int |
| 39 | + elif round_direction == rsgislib.ROUND_UP: |
| 40 | + return numpy.ceil(input_val / round_val_flt) * round_val_int |
| 41 | + elif round_direction == rsgislib.ROUND_DOWN: |
| 42 | + return numpy.floor(input_val / round_val_flt) * round_val_int |
| 43 | + else: |
| 44 | + raise rsgislib.RSGISPyException( |
| 45 | + f"Invalid round_direction: '{round_direction}'. Please use " |
| 46 | + f"rsgislib.ROUND_NEAREST, rsgislib.ROUND_UP, or rsgislib.ROUND_DOWN." |
| 47 | + ) |
0 commit comments