Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Example

In this lesson, we will illustrate the capabilities of Python by running and editing pre-existing code.

This program:

  1. Opens a .csv file containing UV-Vis absorption data

  2. Converts its wavelength units to energy units

  3. Finds all peaks in the data above a threshold

  4. Plots the spectrum and peaks to a scientific standard

  5. Saves the figure as a .pdf

Preparing your folder

The easiest way to allow Python programs to interact with files is to store the source code in the same folder as the file. In this case, we need our .py file and .csv files in the same place.

Syntax

What now follows is a program which reads all the lines of this file which start with a number (allowing us to skip the header). The data is stored by the program and the last x and y data points are printed out as a health check.

"""
UV spectrum analyser

Input a spectrum in nm units and csv format.

"""

import matplotlib.pyplot as plt

# parse csv data
file_name = "benzene_uv-vis_nm.csv"

wavelengths = []
absorbances = []

with open(file_name) as spec_file:
    for line in spec_file:
        # only conserve lines that start with a number
        # to skip header
        if line[0].isdigit():
            split_line = line.split(",")
            wavelengths.append(float(split_line[0]))
            absorbances.append(float(split_line[1]))

print(wavelengths[-1],absorbances[-1])

Let’s look at a few features of how Python is written, using this as an example.

Debugging code

Let’s complete our code.

You should see a plot on the top right of the window. The spectrum looks fine but our peak detection seems to have failed. Our strategy was to look at each absorbance value and check that it is strictly higher than the value before and after.

Solution
Due to the limited significant figures, the absorbance values at smooth peaks are repeated in pairs, which means that neither value is strictly higher than its neighbours.

Our solution below will compare candidate peaks with next nearest neighbours instead.

Let’s fix our code with a better peak detection strategy.

Now that our code works as intended, let’s take control of it.

Solution

The line to change reads:


threshold = 3.0

Raise the value to something like:


threshold = 3.7

Extra functionality

We’ve demonstrated how to use Python in basic data processing. You can already take this code and modify it to suit the uses of your own data.

Let’s demonstrate some last tricks that are possible in Python.

Finally, let’s use a more complicated piece of code.

Summary

The next lessons will return to basics and teach you the fundamentals of Python. By the end, you should be able to understand everything shown in this lesson’s example.

References
  1. Romand, J., & Vodar, B. (1951). Spectres d’absorption du benzène à l’état vapeur et à l’état condensé dans l’ultraviolet lointain. Comptes Rendus, 233, 930–932.