################################################################################
#
#	FourierCoefficients, compute the fourier coefficients of a
#	piecewise-linear function given by a set of points.
#
#	The function y(x) is given by a set of pairs x[i], y[i].
#	It is assumed that the period is x[0]..x[N]
#
#	The function returns the list of a coefficients (length k+1) and
#	the list of b coefficients (length k).
#
#	Gaston H. Gonnet (Tue Jul 17 01:35:47 CEST 2018, Vorhaldenstrasse)
#
################################################################################

FourierCoefficients := proc( y:list(numeric), x0:list(numeric), k:{0,posint} )
x := x0;
N := length(x);
assert( N = length(y) and N > 1 and sort(x) = x and x[N] > x[1] );

#
#	a[n] = 1/Pi * int( y(x) * cos(n*x), x=0..2*Pi )
#	b[n] = 1/Pi * int( y(x) * sin(n*x), x=0..2*Pi )

#
#	maple code
#
#	f := ((x-x0)*(y1-y0)/(x1-x0) + y0);
#	Fs := int( f*sin(n*x), x=x0..x1 );
#	Fc := int( f*cos(n*x), x=x0..x1 );
#
#	factor( coeff( expand(Fs), sin(n*x0) )) * sin(n*x0);
#	factor( coeff( expand(Fs), cos(n*x0) )) * cos(n*x0);
#	factor( coeff( expand(Fs), sin(n*x1) )) * sin(n*x1);
#	factor( coeff( expand(Fs), cos(n*x1) )) * cos(n*x1);
#
#	factor( coeff( expand(Fc), sin(n*x0) )) * sin(n*x0);
#	factor( coeff( expand(Fc), cos(n*x0) )) * cos(n*x0);
#	factor( coeff( expand(Fc), sin(n*x1) )) * sin(n*x1);
#	factor( coeff( expand(Fc), cos(n*x1) )) * cos(n*x1);
#
#	spat := sin(n*x0) = sinnx[i], cos(n*x0) = cosnx[i],
#		sin(n*x1) = sinnx[i+1], cos(n*x1) = cosnx[i+1],
#		y0 = y[i], y1 = y[i+1], x0 = x[i], x1 = x[i+1];
#	lprint( subs(spat,%) );

#	normalize x to be in 0 .. 2*Pi
f := 2*Pi/(x[N]-x[1]);
x := [ seq( f*(w-x[1]), w=x )];
a := [ sum( (y[i]+y[i-1]) * (x[i]-x[i-1]), i=2..N ) / (2*Pi) ];
b := [];

for n to k do
    sinnx := [ seq( sin(n*v), v=x )];
    cosnx := [ seq( cos(n*v), v=x )];
    sa := y[N]/n*sinnx[N] - y[1]/n*sinnx[1];
    sb := y[1]/n*cosnx[1] - y[N]/n*cosnx[N];
    for i to N-1 do
	if x[i+1] <= x[i] then
	     v := (y[i+1]-y[i]) / n;
	     sa := sa - v * sinnx[i];
	     sb := sb + v * cosnx[i];
	else v := (y[i+1]-y[i]) / n^2 / (x[i]-x[i+1]);
	     sa := sa + v * (cosnx[i]-cosnx[i+1]);
	     sb := sb + v * (sinnx[i]-sinnx[i+1]);
	fi
    od;
    a := append(a,sa/Pi);
    b := append(b,sb/Pi);
od:

[a,b]
end:


#
# compute a Fourier approximation based on the coefficients 0 <= x <= 2*Pi
#
FourierApprox := proc( ab:list(list(numeric)), x:numeric )
assert( x >= 0 and x <= 2*Pi*(1+1e-12) );
a := ab[1];  b := ab[2];
assert( length(a) = length(b)+1 );
a[1]/2 + sum( a[n+1]*cos(n*x) + b[n]*sin(n*x), n=1..length(b) )
end:
