The second week of the Gaussian Beams lab is intended to introduce you to LabVIEW and guide you though interfacing LabVIEW with the instrumentation and data acquisition systems that we use in this course.
This week’s lab is divided into two parts. In part 1, you are guided through the LabVIEW Environment and will get to see many useful features that can be realized throughout this course. In part 2, you begin to see the power of using LabVIEW to interface with your lab experiment by acquiring data through a standard National Instrument data acquisition device, NI USB-6009. This multifunction USB powered device has 4 (differential) analog inputs (14-bit, 48 kS/s), 2 analog outputs (12-bit, 150 S/s), 12 digital I/O channels, and a 32-bit counter.
LabVIEW is a graphical programing language designed for scientists and engineers for experimental control and data acquisition. Many table-top research labs use LabVIEW to communicate with their commercial equipment (e.g., frequency synthesizers, oscilloscopes) and for acquiring data. It has advantages over basic languages such as C++. The graphical environment is intuitive and easy to learn. Also, since it is so widely used, almost all commercial test and measurement equipment comes with LabVIEW drivers and example programs.
You can choose to use LabVIEW on the lab laptops. You can also install LabVIEW on your own laptop. The student edition of LabVIEW can be obtained through CU Boulder’s OIT. In addition, you will also eventually need to download the NI-DAQmx data acquisition drivers (if installing on your own laptop) .
After completing the first part of this week’s lab, you will be:
After completing the second part of this week’s lab you will be:
This week’s prelab will be a continuation of the measurement uncertainty and error analysis exploration that was covered in last week’s lab. This is a “user’s guide” to least-squares fitting and to determining the goodness of your fits. It doesn’t derive many results. There are good textbooks listed in the references. At the end of the prelab you will be able to:
Question: Why do we call it “least-squares” fitting?
Answer: Because the best fit is determined by minimizing the weighted sum of squares of the deviation between the data and the fit. Properly speaking this “sum of squares” is called “chi-squared” and is given by
\[\chi^2 = {\displaystyle \sum_{i=1}^{N}}\frac{1}{\sigma_i^2}(y_i-y(x_i,a,b,c, \ ... \ ))^2\text{,}\](1)
where there are where \(N\) data points, \((x_i,y_i )\), and the fit function is given by \(y(x_i,a,b,c, \ … \ )\) where \(a, b,\) etc. are the fit parameters.
Question: What assumptions are made for the method to be valid?
Answer: The two assumptions are:
Question: Why does minimizing the sum of squares give us the best fit?
Answer: Given the two above assumptions, the fit that minimizes the sum of squares is the most likely function to produce the observed data. This can be proven using a little calculus and probability. A more detailed explanation is found in Taylor’s Introduction to Error Analysis Sec. 5.5 “Justification of the Mean as Best Estimate” or Bevington and Robinson’s Data Reduction Sec. 4.1 “Method of Least-Squares”.
You will rarely minimize \(\chi^2\) graphically in a lab. However, this exercise will help you better understand what the fitting routines in Mathematica actually do to find the best fit. This video can be reviewed if you need a reminder on how to fit data in Mathematica.
Import and plot this data set. It was generated by inserting a razor blade into path of a laser beam and measuring the photodetector voltage of the laser light. The \(x\) column is the micrometer (razor) position in meters and the \(y\) column is the photodetector voltage in volts.
Import
["profile_data_without_errors",”CSV”]
Define the same fit function as:
\[y(x,a,b,c,w) = a \ Erf\left(\frac{\sqrt{2}}{w}(x-b)\right)+c\]
Reduce the fit to two free parameters. This step is only necessary because it is hard to visualize more than 3 dimensions. Assume \(a_{fit}=(V_{max}-V_{min})/2 = 1.4375\) and \(c_{fit} =(V_{max}+V_{min})/2 = 1.45195\). These were determined by averaging the first 6 data points to get \(V_{min}\) and the last 5 to get \(V_{max}\).
Use Equation 1 to write an expression for \(\chi^2\) in terms of your \(w\) and \(c\) parameters, and the \(x\) (position) data and \(y\) (voltage) data. Since you don’t have any estimate for the uncertainties \(\sigma_i\), do what Mathematica does and assume they are all unity so \(\sigma_i=1\).
Make a contour plot of \(\chi^2(w,b)\) and tweak the plot range until you see the minimum. Just like with NonlinearModelFit
, it will help to have a good initial guess for your fit parameters. You can iteratively improve the plot range of your plot to zoom in on the parameter values that minimize \(\chi^2\). You should get a plot kind of like Figure 1.
NonlinearModelFit
(allow all 4 parameters to vary). Do the fits agree for those three digits of precision?Question: Where does the uncertainty in the fit parameters come from?
Answer: The optimal fit parameters depend on the data points \((x_i,y_i)\). The uncertainty, \(\sigma_i\), in the \(y_i\) means there is a propagated uncertainty in the calculation of the fit parameters. The error propagation calculation is explained in detail in the references, especially Bevington and Robinson.
Question: How does Mathematica calculate the uncertainty in the fit parameters when no error estimate for the \(\sigma_i\) is provided?
Answer: Mathematica (and other programs) estimate the uncertainty in the data \(\sigma_y^2\) using the “residuals” of the best fit:
\[\sigma_y^2 = \frac{1}{N-n}{\displaystyle \sum_{i=1}^{N}}(y_i-y(x_i,a_0,b_0,c_0, \ ... \ ))^2\text{,}\quad\quad\](2)
where there are \(N\) data points \(y_i\) and the best fit value at each point is given by \(y\), which depends on \(x_i\) and the \(n\) best fit parameters \(a_0,b_0,c_0, \ ... \ \). It is very similar to how you would estimate the standard deviation of a repeated measurement, which for comparison’s sake is given by:
\[\sigma_y^2 = \frac{1}{N-n}{\displaystyle \sum_{i=1}^{N}}(y_i-\overline{y})^2\text{.}\](3)
NonlinearModelFit
, which can also output this estimate of the random error. If nlm
is the NonlinearModelFit
output, the estimate of \(\sigma_y^2\) is given by nlm[“EstimatedVariance”]
.This section covers two ways to analyze if a fit is good.
The first step is to look at the residuals. The residuals, \(r_i\), are defined as the difference between the data and the fit.
\[r_i=y_i-y(x_i,a,b,c, \ ... \ )\]
ListPlot
of the residuals. If nlm
is the NonlinearModelFi
t output, the list of residuals is given by nlm[“FitResiduals”]
.Question: If I have a good fit, should every data point lie within an error bar?
Answer: No. Most should, but we wouldn’t expect every data point to lie within an error bar. If the uncertainty is Gaussian distributed with a standard deviation \(\sigma_i\) for each data point, \(y_i\), then we expect roughly 68% of the data points to lie within their error bar. This is because 68% of the probability in a Gaussian distribution lies within one standard deviation of the mean.
This section answers the question “What should \(\chi^2\) be for a good fit?”
Suppose the only uncertainty in the data is statistical (i.e., random) error, with a known standard deviation \(\sigma_i\), then on average each term in the sum is
\[\frac{1}{\sigma_i^2}(y_i-y(x_i,a,b,c, \ ... \ ))^2 \approx 1\text{,}\](4)
and the full \(\chi^2\) sum of squares is approximately
\[\chi^2 = {\displaystyle \sum_{i=1}^{N}}\frac{1}{\sigma_i^2}(y_i-y(x_i,a,b,c, \ ... \ ))^2\approx N-n\text{.}\quad\quad\](5)
So a good fit has
\[\chi_{red}^2 \equiv \frac{\chi^2}{N-n}\approx 1\text{.}\](6)
Considering your answers from Section 2.6.1 (especially 2.6.1.5), which method would give you the best estimate of the uncertainty for each data point, and why?
Eyeballing the fluctuations in each data point.
Taking \(N\) measurements at each razor position and then going to the next position.
Taking the entire data set \(N\) times.
When you have estimated the uncertainty \(\sigma_i\) of each data point \(y_i\) you would like to use this information when fitting to correctly evaluate the \(\chi^2\) expression in Equation 1. The points with high uncertainty contribute less information when choosing the best fit parameters. If you have a list of uncertainties
sigmalist = { sigma1, sigma2, sigma3, ...}
,
then the weights for the fit are:
weightslist = 1/ sigmalist^2 = {1/ sigma1^2, 1/ sigma2^2, ...}
.
Add the Weights->weightslist
option to the LinearModelFit
or NonlinearModelFit
. For example:
NonlinearModelFit[data,fit[x,a,b,c],{a,b,c},x, Weights->weightslist]
Import this data set for a beam width measurement with uncertainties. The first column is razor position in meters, the second column is photodetector output voltage, and the third column is the uncertainty on the photodetector output voltage.
Import
["profile_data_with_errors.csv",,”CSV”]
Do a weighted fit using the same fit function as in Section 2.3. Use the uncertainty estimates in the third column to calculate the weights.
Calculate \(\chi^2\). You can obtain \(\chi^2\) from the fit returned by Mathematica. Supposing the fit was called nlmError
, use nlmError[“ANOVATable”]
. For the curious, ANOVA stands for ANalysis Of VAriance.
Overestimating the uncertainties makes the fit seem good (according to a \(\chi^2\) test), even when it might be obviously a bad fit. It is best to do the \(\chi^2\) test using an honest estimate of your uncertainties. If the \(\chi^2\) is larger than expected \((\chi^2>𝑁−𝑛)\), then you should consider both the possibility of systematic error sources and the quality of your estimates of the uncertainties. On the other hand, if the \(\chi^2\) test is good \((\chi^2\approx 𝑁−𝑛)\), then it shows you have a good handle on the model of your system, and your sources of uncertainty. Finally, if \(\chi^2\ll (𝑁−𝑛)\), this likely indicates overestimated uncertainties.
Check out the NI Apps YouTube channel playlist, Getting Started with LabVIEW, for more helpful videos
Learn how to navigate LabVIEW and use the block diagram, front panel, and Functions and Controls palettes. Watch the LabVIEW Environment video: Writing Your First LabVIEW Program.
For additional information, you may want to review the NI LabVIEW Environment: Detailed Explanation.
Examine the basics of graphical programming and how to determine data flow and order of execution in the LabVIEW environment. Watch the Graphical Programming video: Data Flow Programming Basics.
For additional information, you may want to review the Graphical of Programming: Detailed Explanation.
Discover how to use important tools in LabVIEW that can save you time. Watch the Programming Tools video: Using the Tools Palette.
Display Format
.Tools Palette
and switch between “automatic tool selection” and “manual tool selection.”
For additional information, you may want to review the Programming Tools: Detailed Explanation.
Learn how to use key debugging and troubleshooting tools that optimize code. Watch the Debugging and Handling Errors video: Using Debugging Tools in NI LabVIEW.
Error List
.For additional information, you may want to review the Debugging and Handling Errors: Detailed Explanation.
Explore the different data types (e.g., integer, Boolean, string) and methods to organize and group data, controls, and indicators in LabVIEW. Watch the Data Types and Structures video: LabVIEW Data Types.
Controls Palette
.Modern Controls Palette
to the desktop.Function Palette
.Programming->String->String/Numeric Conversion Palette
.Number to Exponential String
.Number to Exponential String
function to the string array.For additional information, you may want to review the Data Types and Structures: Detailed Explanation.
See how to loop code and conditionally execute code in LabVIEW using For Loops, While Loops, and Case structures. Watch the Using Loops in LabVIEW and Using LabView Case Structures videos.
Goal: Include a while loop around the code, so that the user can enter a new wavelength and not have to press run to get the updated result.
While Loop
around your entire program in the block diagram.Goal: Change your VI to calculate the energy in units of either Joules or eV using a case structure. Use the same Wavelength Control and Energy Indicator, but the numerical calculation to either Joules or eV will reside in a case structure. The case structure has two cases. In one case, place the code to convert to Joules and the other to convert to eV. A control (switch) on the front panel will determine which case is executed.
Here are a few questions to help you get started.
Should your case structure be inside or outside the While Loop
?
Should the control and indicator be inside or outside the case structure?
Where do you connect the Boolean switch to control which case runs?
For additional information, you may want to review the Execution Structures: Detailed Explanation.
In part 2 of this week’s lab, you will learn how to connect a USB DAQ (data acquisition) device to your computer and test to see if it is working properly using the NI-DAQmx driver and NI-MAX. This screencast might be of help.
My System-> Software
.Test Panel
for the device to test the analog input.AI0+
and ground to the AI0-
. You must connect both wires, since the device measures a potential difference between the two terminals.AI0
is working.For additional information, you may want to review the Connecting Hardware: Detailed Explanation.
This section covers how to take an analog voltage measurement by creating a LabVIEW VI with DAQ Assistant sub-VI and measuring the output of a function generator. Watch the Taking a Measurement with your Computer video.
Functions Palette->Input
.AI0
. You will need to set the Samples to Read
and Sample Rate
in the DAQ assistant. The following explains how these parameters are determined.
Samples to Read
:
Samples to Read
and Sample Rate
and enter them. Use N Samples
for the Acquisition Mode.Samples to Read
and Sample Rate
.Continuous Sampling
. When saving, accept the option to create a loop. Check if this works.For additional information, you may want to review the Taking a Measurement: Step by Step Procedure.
This section covers how to create a VI to output a DC voltage from your USB DAQ device. Watch the Generating a Signal with Your Computer video.
Note: The DAQ-6009 does not have the ability to create a waveform as depicted in the video. It can produce a waveform with an update rate 150 samples/sec using the example program you can find here.
AI0
is reading from AO0
rather than from the function generator.You can create sub Vis. Here is a video on Creating Sub VIs in NI LabVIEW. Also, you may want to review this page: Create and Configure a LabVIEW SubVI.
For additional information, you may want to review the Generating a Signal: Step by Step Procedure.
This section covers how to create a VI to filter and analyze the signal acquired by your USB DAQ device. Watch the Real-time Signal Processing and Analysis on Measurement Data video.
Goal: Demonstrate the effect of a low-pass filter. Acquire a sine wave voltage signal using the DAQ device and put those data through a low pass filter. The Spectral Measurements VI can then be used to create a power spectrum of the filtered data. Display both the filtered data and power spectrum as graphs. Vary the frequency of the signal from below to above the cutoff frequency.
Describe the qualitative behavior of the filtered signal and the power spectrum as the frequency is varied.
Here are a few questions to help you get started.
For additional information, you may want to review the Signal Processing: Step-by-Step Procedure.
This section covers how create, save, and read a file containing data acquired from your USB DAQ device. Watch the Logging Data with a USB Data Acquisition Device video.
Use the Write to Measurement File VI
to save the filtered signal data. Make sure to use Append to File
to avoid writing over your previously saved data. The Text file format is the easiest to read into Mathematica or other data processing program.
For additional information, you may want to review the Adding Data Logging: Step-by-Step Procedure.
This section covers how to create and use various graphs and charts. This page is very useful. Or you can watch the Using Charts and Graphs in NI LabVIEW video.
For additional information, you may want to review the Using Graphs and Charts: Step by Step Procedure.
This section covers how to implement formulas using formula and mathscript nodes, as well as incorporate MATLAB scripts into LabVIEW. Watch the Integrating MATLAB code video on text-based Programming.
Goal: Instead of using individual functions such as multiply, use a formula node to calculate the energy of the photon in both Joules and eV.
For additional information, you may want to review the Text-Based Integration: Step by Step Procedure.
Check out the NI Apps Youtube channel playlist, Getting Started with LabVIEW, for more helpful videos. LabVIEW has built-in help resources that can assist in better understand concepts and coding techniques.
Context Help
by clicking the yellow question mark in the upper right hand corner of the block diagram.Array Subset
. It is located in Functions palette-> Programming->Array
.For additional information you may want to review the Help Within LabVIEW: Detailed Explanation.