Tuesday, 1 January 2013

Fourier series, conditions and recursive functions

This script uses recursive functions to plot a square pulse function and its Fourier series expansion, truncated to some maximum Nmax.  The terms of the series itself must be found analytically, but once found this script allows one to visualize the convergence of the series.  The resulting plot is shown on the right.

The result of the Fourier series is found by summing over the terms of the series, each of which have a simple analytic dependence on the summation variable.  To do this, the gnuplot script makes use of the Ternary operator ?, which can be used for conditional assignment.  The syntax for this can be described as:
y(x) = (cond) ? [true] : [false]
The function y(x) takes the value [true] if condition (cond) is true, and [false] if condition (cond) is false.  The Ternary operator itself is ? and a colon : is used to separate the possible results [true] and [false].  Both [true] and [false] may be further conditional statements, meaning the statements can be nested, e.g.,
y(x) = (cond1) ? (cond2) ? [true2] : [false2] : [false1]
If (cond1) is true, then the second condition (cond2) is tested.  If both are true, y(x) takes the value [true2].  If (cond1) is true but (cond2) is false, y(x) has the value [false2].  Finally if (cond1) is false y(x) takes the value [false1].

The step function for the present example is defined as:
f(x) = -2 (-π≤x<0)
     =  1 (0≤x<+π)
and is periodic with period 2π.  The terms of the Fourier series can be evaluated analytically.  The gnuplot code to produce the plot is:
set terminal png enhanced size 800,600 font "sans, 18"
set output "fourier.png"

set tics nomirror
set border 2
set xzeroaxis lt -1 lw 2
set xtics axis

pi = 3.14159265359

# f(x) is the step function that is being expanded
f(x) = (x<-pi) ? f(x+2*pi) : (x>pi) ? f(x-2*pi) : (x<0) ? -2 : 1

# g(n,x) is the nth term in the Fourier series
g(n,x) = (n==0) ? -0.5 : (1-(-1)**n)*3*sin(n*x)/(n*pi)

# s(n,x) is the Fourier series up to the nth term
s(n,x) = (n>=0) ? g(n,x) + s(n-1,x) : 0

set yrange[-3.5:2.5]
set xlabel "x"
set ylabel "f(x)"

set samples 400

# set the maximum term in the series
nmax1=3
nmax2=10

plot f(x) title "Step pulse",\
     s(nmax1,x) title "Fourier Series, N_{max}=".nmax1,\
     s(nmax2,x) title "Fourier Series, N_{max}=".nmax2
The first two lines set the png terminal options and the output file name.  f(x) is the step function itself.  The first two conditions (x<-pi) and (x>pi) move the value of x into the range -π to +π, and the last condition (x<0) gives the function the value -2 or 1. g(n,x) is the nth term in the Fourier series, determined analytically, and s(n,x) gives the full Fourier series up to a maximum value of n, nmax. The condition in s(n,x) makes sure the recursion stops when n=0.  The script will plot the exact step function and the Fourier series truncated to maximum order nmax1 and nmax2.  By varying nmax, the convergence of the series can be seen.

There are a couple other neat tricks in there too.  The second group of set commands remove the normal borders and place the x-axis at y=0, and in the last line the string concatenation operator "." is used to append the gnuplot variable nmax onto the title for the Fourier series.

Wednesday, 5 December 2012

Hello, fitting and piecewise functions

Welcome to the Surrey Physics Plotters blog. It exists in the spirit of other blogs dedicated to the use of the gnuplot plotting program. While I don't consider myself as much of an expert at gnuplot as the writers of gnuplotting or gnuplot tricks, I think it would still be helpful to have another repository for useful examples that I, at least, will otherwise forget.

So - the first example comes in the form of a plot which includes a set of data defined at equally spaced points in the abscissa, whose ordinates show a sudden kink in the gradient (the data are the radii of a series of isotopes of lead nuclei - if you're interested, the paper is here).

I wanted to include on the plot a fit to the data, assuming one straight line up to atomic number 208, and  a different straight line from 208 up.  I'll show the code here, and explain how it works below.
set term postscript enhanced col size 10cm,8cm font 'Helvetica,12'
set out 'lead-exp.eps'

f1(x) = m1*(x-208)
f2(x) = m2*(x-208)

fit [202:208] f1(x) 'expdat.gnu' using 1:($2-5.5010):3 via m1
fit [208:214] f2(x) 'expdat.gnu' using 1:($2-5.5010):3 via m2

f(x) = abs(x-205)<3 ? f1(x) : abs(x-211)<3 ? f2(x) : 1/0

set xrange [201:215]
set yrange [-0.05:0.08]
set ylabel '{/Symbol d}<r_{ch}^2>^{1/2} [fm]'
set xlabel 'A'
plot 'expdat.gnu' u 1:($2-5.5010):3 w yerr ls 1 notit, f(x) lt 2 notit
quit

# Data from I. Angeli, At. Data Nucl. Data Tables, 87, 185 (2004)
202 5.4690 .0055 .0007
204 5.4794 .0008 .0005
206 5.4897 .0007 .0003
208 5.5010 .0009
210 5.5230 .0035 .0005
212 5.5450 .0075 .0010
214 5.5650 .0105 .0014
The first two lines set up the output file as a postscript file (since this is what I wanted for the publication).  Specifying the size here adds in the BoundingBox for encapsulated postscript, though it probably makes sense to use the eps option instead.

The two separate fitting functions are defined as f1(x) and f2(x).  They have undetermined parameters m1 and m2 and are designed to be zero at x=208.

I then fit the two separate lines in specified ranges, using the data that comes at the end of the plot file - I have assumed that the above file is saved as expdat.gnu.

The line defining f(x) makes a piecewise function, which is f1(x) if x is in the range 202<x<208, is f2(x) if it is in the range 208<x<214 and undefined otherwise - the "1/0" serves to make the function undefined.

Everything else is a bit more straightforward, I think.  The range in x and y are set, as are the labels, though the enhanced option in the set term line means that the _ and ^ symbols are treated as subscript and superscript indicators as in LaTeX in the label text.  The results (turned into a png file) is shown at the top.