Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from contextlib import suppress
- class MinMaxScaler:
- """
- This class scales raw values automatically.
- The min/max values are set by the `scale` method when called.
- At least two different values must be given for the scaling to work.
- The purpose of this class is to be used for a VR glove
- where all potentiometers are set differently.
- By gripping and opening the hand,
- the min/max values are automatically set
- and then scaled to the full range.
- This has the advantage that the full range of the raw value is covered
- and does not need to be adjusted in VR runtime.
- """
- def __init__(self, raw_min, raw_max):
- self.min = None
- self.max = None
- self.raw_min = raw_min
- self.raw_max = raw_max
- def scale(self, value):
- if self.min is None:
- self.min = value
- else:
- self.min = min(self.min, value)
- if self.max is None:
- self.max = value
- else:
- self.max = max(self.max, value)
- with suppress(ZeroDivisionError):
- slope = self.max - self.min
- return int((value - self.min) / slope * self.raw_max + self.raw_min)
- return 0
- mm = MinMaxScaler(raw_min=0, raw_max=2**12 - 1)
- # raw_max is in this example a 12 bit value from an ADC: 4095
- mm.scale(512) # first min == max, result not useable.
- mm.scale(1023) # second value, this time max is set
- mm.scale(767) # now the value is half between 512 and 1023
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement