Advertisement
DeaD_EyE

MinMaxScaler

Sep 29th, 2022
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. from contextlib import suppress
  2.  
  3.  
  4. class MinMaxScaler:
  5.     """
  6.    This class scales raw values automatically.
  7.    The min/max values are set by the `scale` method when called.
  8.    At least two different values must be given for the scaling to work.
  9.  
  10.    The purpose of this class is to be used for a VR glove
  11.    where all potentiometers are set differently.
  12.  
  13.    By gripping and opening the hand,
  14.    the min/max values are automatically set
  15.    and then scaled to the full range.
  16.  
  17.    This has the advantage that the full range of the raw value is covered
  18.    and does not need to be adjusted in VR runtime.
  19.    """
  20.  
  21.     def __init__(self, raw_min, raw_max):
  22.         self.min = None
  23.         self.max = None
  24.         self.raw_min = raw_min
  25.         self.raw_max = raw_max
  26.  
  27.     def scale(self, value):
  28.         if self.min is None:
  29.             self.min = value
  30.         else:
  31.             self.min = min(self.min, value)
  32.  
  33.         if self.max is None:
  34.             self.max = value
  35.         else:
  36.             self.max = max(self.max, value)
  37.  
  38.         with suppress(ZeroDivisionError):
  39.             slope = self.max - self.min
  40.             return int((value - self.min) / slope * self.raw_max + self.raw_min)
  41.  
  42.         return 0
  43.  
  44.  
  45. mm = MinMaxScaler(raw_min=0, raw_max=2**12 - 1)
  46. # raw_max is in this example a 12 bit value from an ADC: 4095
  47. mm.scale(512)  # first min == max, result not useable.
  48. mm.scale(1023)  # second value, this time max is set
  49.  
  50. mm.scale(767)  # now the value is half between 512 and 1023
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement