-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter.py
54 lines (35 loc) · 1.54 KB
/
converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from collections import namedtuple
import numpy as np
from scipy import fft
from spring_array import SpringArray
from spring import Spring
class Converter:
spring: Spring
spring_array: SpringArray
DURATION = 5
SAMPLE_RATE = 100
def __init__(self, spring_array):
self.spring_array = spring_array
def set_spring_from_binary(self, byte):
springs = []
spring_expression = '['
for index, bit in enumerate(byte):
if bit == '1':
stiffness = 2 ** (8 - 1 - index)
springs.append(Spring(k=stiffness))
spring_expression += '{}'
spring_expression += ']'
self.spring = self.spring_array.equivalent_spring(spring_expression, springs)
def get_oscillations(self):
return self.spring.move(self.DURATION, 1 / self.SAMPLE_RATE, 2)
def get_frequency_amplitudes(self, oscillations):
frequency_powers = fft.rfft(oscillations)
total_number_of_samples = self.SAMPLE_RATE * self.DURATION
frequency_values = fft.rfftfreq(total_number_of_samples, 1 / self.SAMPLE_RATE)
frequency_amplitudes = np.abs(frequency_powers)
FFTResult = namedtuple('FFTResult', 'frequency_values frequency_amplitudes')
return FFTResult(frequency_values=frequency_values, frequency_amplitudes=frequency_amplitudes)
def get_decimal(self, fft_result):
max_index = np.argmax(fft_result.frequency_amplitudes)
max_freq = fft_result.frequency_values[max_index]
return int(max_freq * max_freq)