data_to_01.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import numpy as np
  2. class LinearNormalizer(object):
  3. def __init__(self, vmin, vmax):
  4. super().__init__()
  5. self.vmin = vmin
  6. self.vmax = vmax
  7. def scale_with_revised_limits_to01(self, data_clipped, vmin2use, vmax2use):
  8. data_scaled = (data_clipped - vmin2use) / (vmax2use - vmin2use)
  9. return data_scaled
  10. def normalize(self, data):
  11. data_clipped = np.clip(data, self.vmin, self.vmax)
  12. return self.scale_with_revised_limits_to01(data_clipped, self.vmin, self.vmax)
  13. def get_data_limits(self):
  14. """
  15. Return the lower and upper limits of data as a tuple
  16. :return: tuple
  17. """
  18. return self.vmin, self.vmax
  19. class LinearNormalizerAcross0(LinearNormalizer):
  20. def __init__(self, vmin, vmax):
  21. assert (vmin < 0) & (vmax > 0), "LinearScaleAcross0 only works when vmin < 0 and vmax > 0"
  22. super().__init__(vmin, vmax)
  23. class BilinearNormalizerCentering0(LinearNormalizerAcross0):
  24. def __init__(self, vmin, vmax):
  25. super().__init__(vmin=vmin, vmax=vmax)
  26. def scale_with_revised_limits_to01(self, data_clipped, vmin2use, vmax2use):
  27. data_negative_masked_out = np.ma.MaskedArray(data=data_clipped, mask=data_clipped < 0, fill_value=0)
  28. data_positive_masked_out = np.ma.MaskedArray(data=data_clipped, mask=data_clipped >= 0, fill_value=0)
  29. data_negative_masked_out_scaled \
  30. = 0.5 + 0.5 * super().scale_with_revised_limits_to01(data_negative_masked_out, 0, vmax2use)
  31. data_positive_masked_out_scaled \
  32. = 0.5 * super().scale_with_revised_limits_to01(data_positive_masked_out, vmin2use, 0)
  33. return data_negative_masked_out_scaled.filled() + data_positive_masked_out_scaled.filled()
  34. class LinearNormalizerCentering0Symmetric(LinearNormalizerAcross0):
  35. def __init__(self, vmin=None, vmax=None):
  36. super().__init__(vmin=vmin, vmax=vmax)
  37. max_one_sided = max(np.abs(self.vmin), np.abs(self.vmax))
  38. self.vmin, self.vmax = -max_one_sided, max_one_sided
  39. def get_normalizer(mv_individualScale, vmin, vmax):
  40. scale_modifier = int(mv_individualScale / 10)
  41. if scale_modifier == 0 or not (vmin < 0 < vmax):
  42. scaler_class = LinearNormalizer
  43. elif scale_modifier == 1:
  44. scaler_class = BilinearNormalizerCentering0
  45. elif scale_modifier == 2:
  46. scaler_class = LinearNormalizerCentering0Symmetric
  47. else:
  48. raise NotImplementedError
  49. return scaler_class(vmin=vmin, vmax=vmax)