Fitting Diffraction Grating Data

Introduction

Here's an example program on how to use Mathematica to fit your diffraction grating data.  A few things you need to do first.  1) using logger pro export your data to a text file 2) the data file has some header lines at the top, erase those and save the file.

Finally, don't be afraid to use the help browser.  It's very HELPFUL.  Just search anything you don't understand and it'll tell you what it is, how to use it, and give some examples.

Opening and Reading a file

First you need to open the text file, so use the OpenRead command and it takes as input the file name surrounded by quatation marks.  Set this equal to dataFile.  Change the location to match that of your data file.

dataFile = 
      OpenRead["C:\Documents and \
Settings\powl3-3109b\Desktop\Jordan\sampleData.txt"]

Then read the list of data from the text file and save it as a list called dataList.  To do this use the ReadList command as follows.  The {Number, Number} part reads things in as pairs so, for each time you have an associated voltage.

dataList = ReadList[dataFile, {Number, Number}];

Here's an exmple of a plot.

lp = 
        ListPlot[dataList, PlotRange -> {{5, 17}, {0, 7}}];

Massaging the Data

First I'm gonna cut down the data and focus on the region in the middle that looks the most like an airy disk.  To do this I run a For loop and only take the data that fits between time 8.7 and 13.6.  And I'm gonna save it in a list called cutDataList.

cutDataList = {};
For[i = 1, 
      i ≤ 
        Length[dataList], i++, 
If[dataList[[i]][[1]] == 8.7, 
        start = i]; 
If[dataList[[i]][[1]] == 13.6,  finish = i];
]
cutDataList = Take[dataList, {start, finish}];

Here's a Picture of the new data

ListPlot[cutDataList];

Fitting

Next I load the statistics software needed to do the fit program.

<< Statistics`NonlinearFit`

Finall I run the command fit command that is called Nonlinear Regress.  It is executed as follows:

NonlinearRegress[data,model,variables,{parameter,start value}]

Now this takes some time to get correct.  It helps not to let all your parameters vary at first.  Fix a few you know from looking at the data like the amplitude or the off set.

Clear[a, b, c, d];
fp = 
      NonlinearRegress[cutDataList,  
        a*(Sin[b*x - c]/(b*x - c))^2 + d , 
        x, {{a, 6}, {c, 15}, {b, 1.39}, {d,  .3}}, 
        RegressionReport -> {BestFit, ParameterTable}]

Here's a Plot of the fit against the data:

Plot[
        0.30619370225230047` + (5.791853778294638` Sin[29.617577616200993` - 2.660111157746425` x]^2)/(((-29.617577616200993` + 2.660111157746425` x))^2), {x, 8.7, 
          13.6}, PlotRange -> {0, 7}, 
        Epilog -> Point /@ cutDataList];

Looks pretty good.