Utility class for data-type agnostic processing. Args: template_array (np.ndarray or torch.Tensor or list or tuple or int or float, optional): Template array. Defaults to None.
| 202 | |
| 203 | |
| 204 | class ArrayConverter: |
| 205 | """Utility class for data-type agnostic processing. |
| 206 | |
| 207 | Args: |
| 208 | template_array (np.ndarray or torch.Tensor or list or tuple or int or |
| 209 | float, optional): Template array. Defaults to None. |
| 210 | """ |
| 211 | SUPPORTED_NON_ARRAY_TYPES = (int, float, np.int8, np.int16, np.int32, |
| 212 | np.int64, np.uint8, np.uint16, np.uint32, |
| 213 | np.uint64, np.float16, np.float32, np.float64) |
| 214 | |
| 215 | def __init__(self, |
| 216 | template_array: Optional[TemplateArrayType] = None) -> None: |
| 217 | if template_array is not None: |
| 218 | self.set_template(template_array) |
| 219 | |
| 220 | def set_template(self, array: TemplateArrayType) -> None: |
| 221 | """Set template array. |
| 222 | |
| 223 | Args: |
| 224 | array (np.ndarray or torch.Tensor or list or tuple or int or |
| 225 | float): Template array. |
| 226 | |
| 227 | Raises: |
| 228 | ValueError: If input is list or tuple and cannot be converted to a |
| 229 | NumPy array, a ValueError is raised. |
| 230 | TypeError: If input type does not belong to the above range, or the |
| 231 | contents of a list or tuple do not share the same data type, a |
| 232 | TypeError is raised. |
| 233 | """ |
| 234 | self.array_type = type(array) |
| 235 | self.is_num = False |
| 236 | self.device = 'cpu' |
| 237 | |
| 238 | if isinstance(array, np.ndarray): |
| 239 | self.dtype = array.dtype |
| 240 | elif isinstance(array, torch.Tensor): |
| 241 | self.dtype = array.dtype |
| 242 | self.device = array.device |
| 243 | elif isinstance(array, (list, tuple)): |
| 244 | try: |
| 245 | array = np.array(array) |
| 246 | if array.dtype not in self.SUPPORTED_NON_ARRAY_TYPES: |
| 247 | raise TypeError |
| 248 | self.dtype = array.dtype |
| 249 | except (ValueError, TypeError): |
| 250 | print('The following list cannot be converted to a numpy ' |
| 251 | f'array of supported dtype:\n{array}') |
| 252 | raise |
| 253 | elif isinstance(array, (int, float)): |
| 254 | self.array_type = np.ndarray |
| 255 | self.is_num = True |
| 256 | self.dtype = np.dtype(type(array)) |
| 257 | else: |
| 258 | raise TypeError( |
| 259 | f'Template type {self.array_type} is not supported.') |
| 260 | |
| 261 | def convert( |