#!/usr/bin/env python
# coding: utf-8

# In[1]:


import numpy as np


# In[2]:


# Select cavites to use for Chirp (cc_sel), FB+ (fp_sel) and FB- (fm_sel)
#    Three CMs are assumed here, but any number can be used
#    Avoid using common cavities for FB+ and FB-
#    For L0 and L3, set cc_sel = fp_sel OR fm_sel even though the cavities   
#    would not be used to change the section chirp

cc_sel = np.array([1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0])
fp_sel = np.array([0,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,1])
fm_sel = np.array([0,0,0,0,0,0,0,0, 1,1,1,1,0,0,0,0])


# In[3]:


# Load cavity ADES and PDES values (PDES should = 0 if cavity not powered)
vg = 10*np.ones(16) + (np.random.random(16) - 0.5)*0.01                 # Cavity energy gains (MeV)
ps = (np.pi/180)*((-20*cc_sel - 12*fp_sel - 28*fm_sel) * (np.random.random(16) - 0.5)*0.01) # Initial cavity phases in radians 


# In[4]:


Cc = np.sum(cc_sel * vg * np.exp(1j*ps)); # Chirp complex energy
Fp = np.sum(fp_sel * vg * np.exp(1j*ps)); # FB+ complex energy
Fm = np.sum(fm_sel * vg * np.exp(1j*ps)); # FB- complex energy

print(f'{Cc=}, {Fp=}, {Fm=}')


# In[5]:


# Derivatives wrt to phase 
dCc_dpCc = 1j*Cc;
dFp_dpFp = 1j*Fp;
dFm_dpFm = 1j*Fm;


# In[6]:


# Relation between complex energy changes and phase changes,
#   and constraint equation so FB+ + FB- does not change Chirp
# dE = real(dCc_dpCc) * dpCc + real(dFp_dpFp) * dpFp + real(dFm_dpFm) * dpFm
# dC = imag(dCc_dpCc) * dpCc + imag(dFp_dpFp) * dpFp + imag(dFm_dpFm) * dpFm
#  0 =                         imag(dFp_dpFp) * dpFp + imag(dFm_dpFm) * dpFm


# In[7]:


# Matrix formulaiton of these equations 
M = np.array([[np.real(dCc_dpCc), np.real(dFp_dpFp), np.real(dFm_dpFm)],
     [np.imag(dCc_dpCc), np.imag(dFp_dpFp), np.imag(dFm_dpFm)],
     [0,    np.imag(dFp_dpFp), np.imag(dFm_dpFm)  ]])


# In[8]:


MI = np.linalg.inv(M); # Inverse of M


# In[9]:


assert np.allclose(np.dot(M, MI), np.eye(3)) # chk:  M * M^-1 = I


# In[10]:


# FB operation 
# Example of complex energy corrections sent to FB algorithm
#   For L0 and L3, dC should be zero


# In[11]:


dE = -0.25; dC = -0.25;  # Requested energy and chirp changes in MeV
print(f'{dE=}, {dC=}')
deltas = np.atleast_2d([dE, dC, 0])

dFC = np.dot(MI, deltas.T)  # Computed phase changes to implement corrections


# In[12]:


print(f'{dFC=}')


# In[13]:


# Check that complex energy changed as expected (not needed in actual FB loop) 
#  The quanity below should equal ~ dE + i*dC (i.e. to a first order approximation)
x = np.sum(vg * np.exp(1j * (ps + (dFC[0] * cc_sel) + (dFC[1] * fp_sel) + (dFC[2] * fm_sel)))) - \
        np.sum(vg * np.exp(1j * ps))

print(f'{x=}')
# In[14]:


# Updated cavity phases (in radians) - set PDES to these values
ps = ps + dFC[0] * cc_sel + dFC[1] * fp_sel + dFC[2]*fm_sel; 
print(f'ps = {np.rad2deg(ps)}')
