Software defined PFC

For the power supply of my medical project PFC (power factor correction) was a requirement. As I have a P2 on board anyway I decided to use it to control the PWM of the PFC power stage instead of using an extra (analogue) IC.
I soon regretted that decision because it turned out much harder than I expected. During each cycle of the AC voltage the ratio of input to output voltage sweeps almost the full range from 0 to 100% and so does the duty cycle. Additionally, the current can also go from zero to maximum current and depending on the load the inductor current can change from continous (CCM) to discontinous conduction mode (DCM) and vice versa. It is almost impossible to cover all possible operating states with a single set of PID coefficients. This is one of the best I could get after hours of tuning attempts.
Green = AC input voltage, red = current, blue = PWM duty cycle
Ideally, the red line should be a sine half-wave. It takes a long time for the I part of the PID to ramp up. Then, at the transition from DCM to CCM the effective gain changes an oscillations occur. If I decrease the gain the (low frequency) harmonic distortions of the red curve get worse. If I increase it the (high frequency) oscillations get worse. Filtering is not really possible because phase delay also makes things worse.
Comments
The solution was to pre-calculate the duty cycle with with a behavioural model of the inductor, the switches and the input and output voltage. This way the correct PWM duty cycle required to drive the commanded current through the inductor can be aproximated in advance and the PID loop only has to make small corrections.

Cyan = pre-calculated PWM duty cycle, blue = actual duty cycle with PID corrections
The formulas for the calculations are rather complex and require many multiplications, divisions and even a square root. But thanks to the CORDIC unit in the P2 this is no problem at all even at 100kHz update rate. Interestingly, by making use of the pipelined execution it is faster to do both calculations for CCM and DCM and decide at the end which one is used and which is discarded.