#!/usr/bin/env python


import sys
import re
import numpy as np
from matplotlib import pyplot

num_entries = int(sys.argv[1])
max_val =32*3
    
# generate entries
seg120 = 2*np.pi/3
a = np.empty(num_entries)
b = np.empty(num_entries)
c = np.empty(num_entries)
phase = np.linspace(0, 2*np.pi, num=num_entries, endpoint=False);

# segment 0
x = 0*num_entries/3
y = 1*num_entries/3
a[x:y] =        np.sin(phase[x:y]           )
b[x:y] =       -np.sin(phase[x:y] - 1*seg120)
c[x:y] = np.zeros_like(phase[x:y]           )

# segment 1
x = 1*num_entries/3
y = 2*num_entries/3
a[x:y] =       -np.sin(phase[x:y] - 2*seg120)
b[x:y] = np.zeros_like(phase[x:y]           )
c[x:y] =        np.sin(phase[x:y] - 1*seg120)

# segment 2
x = 2*num_entries/3
y = 3*num_entries/3
a[x:y] = np.zeros_like(phase[x:y]           )
b[x:y] =        np.sin(phase[x:y] - 2*seg120)
c[x:y] =       -np.sin(phase[x:y]           )

# scale to requirements
a *= max_val
b *= max_val
c *= max_val

# convert to integer
a = a.astype(int)
b = b.astype(int)
c = c.astype(int)

# write to lut_data.c
with open('lut_data.c', 'w') as f:
    f.write('/////////////////////////////////////////\n')
    f.write('//// - autogenerated by {} - ////\n'.format(sys.argv[0]))
    f.write('/////////////////////////////////////////\n')
    f.write('\n')
    f.write('#include "lut.h"\n')
    f.write('\n')
    f.write('uint8_t lut[][3] = {\n')
    for [aa, bb, cc] in zip(a, b, c):
        f.write('\t{{ 0x{:02X}, 0x{:02X}, 0x{:02X} }},\n'.format(aa, bb, cc))
    f.write('};\n')
    
# apply throttle and clipping
pwm_period = 1024
pwm_isr_len = 40
throttle = int(0.9*pwm_period/max_val)
a *= throttle
b *= throttle
c *= throttle
a[a<pwm_isr_len] = 0
b[b<pwm_isr_len] = 0
c[c<pwm_isr_len] = 0
a[a>pwm_period-pwm_isr_len] = pwm_period-pwm_isr_len
b[b>pwm_period-pwm_isr_len] = pwm_period-pwm_isr_len
c[c>pwm_period-pwm_isr_len] = pwm_period-pwm_isr_len

# write lut data to plot
pyplot.figure()
pyplot.plot(phase, a, phase, b, phase, c, linestyle='steps')
pyplot.savefig('lut_data.png', bbox_inches='tight')
    
# calculate Delta configuration coil voltages
#
#   b
#  / \
# a---c
#
u = a-b
v = b-c
w = c-a

pyplot.figure()
pyplot.plot(phase, u, phase, v, phase, w, linestyle='steps')
pyplot.savefig('lut_interphase_voltage.png', bbox_inches='tight')

# calculate steady state dipole vectors
x = u*np.cos(0*seg120) + v*np.cos(1*seg120) + w*np.cos(2*seg120)
y = u*np.sin(0*seg120) + v*np.sin(1*seg120) + w*np.sin(2*seg120)

pyplot.figure()
pyplot.scatter(x, y, marker='.')
pyplot.savefig('lut_vectors.png', bbox_inches='tight')


