<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicolas Coca, PhD on Medium]]></title>
        <description><![CDATA[Stories by Nicolas Coca, PhD on Medium]]></description>
        <link>https://medium.com/@nicopez?source=rss-60149d1ba899------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*v7XGLi27QWFHm8WJRby09Q.jpeg</url>
            <title>Stories by Nicolas Coca, PhD on Medium</title>
            <link>https://medium.com/@nicopez?source=rss-60149d1ba899------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:46:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicopez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Removing Spikes from Raman Spectra with Python: A Step-by-Step Guide]]></title>
            <link>https://medium.com/data-science/removing-spikes-from-raman-spectra-a-step-by-step-guide-with-python-b6fd90e8ea77?source=rss-60149d1ba899------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fd90e8ea77</guid>
            <category><![CDATA[spike]]></category>
            <category><![CDATA[raman-spectroscopy]]></category>
            <category><![CDATA[hyperspectral-data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nicolas Coca, PhD]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 18:11:24 GMT</pubDate>
            <atom:updated>2024-11-06T18:11:24.935Z</atom:updated>
            <content:encoded><![CDATA[<h4>Find, remove and replace spikes with interpolated values</h4><p>This tutorial is part of a growing series on <a href="https://towardsdatascience.com/data-science-for-raman-spectroscopy-a-practical-example-e81c56cf25f">Data Science for Raman Spectroscopy with Python</a> published in <a href="https://towardsdatascience.com/">towards data science</a>. It is based on this <a href="https://doi.org/10.1016/j.aca.2024.342312">publication</a> in the journal Analytica Chimica Acta. By following along, you’ll add a valuable tool to your data analysis toolkit — an effective method for cleaning up Raman spectra that’s already used in published research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRGEmPt0mCvqlv3Jv9nSKA.jpeg" /><figcaption>Despiking Graphene’s Raman spectrum. Image by author.</figcaption></figure><h3><strong>Introduction</strong></h3><p>Spike removal is an essential part of Raman data preprocessing. Spikes, caused by cosmic rays impacting the detector, appear as intense, narrow peaks that can distort the analysis. These bursts of energy hit the charge-coupled device (CCD) camera, creating sharp, high-intensity peaks that, if left uncorrected, can interfere with further processing steps like normalization, spectral search, or multivariate data analysis. Cleaning these artifacts is therefore a priority. This tutorial will cover a practical algorithm for removing spikes from Raman spectra. Using Python, we’ll walk through a user-friendly, customizable approach for spike detection and correction to keep Raman data accurate and reliable.</p><p>Figure 1 shows an example of a graphene Raman spectrum where a spike is present. Graphene’s exceptional physical properties — such as its electrical and thermal conductivity — have made it a highly studied material. Its Raman spectrum contains peaks that reflect structural characteristics, revealing information about doping, strain, and grain boundaries. Therefore, Raman spectroscopy is a widely used technique to characterize graphene. However, to make the most of this tool, spikes must be previously removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APzQMIlrMgV37kDqtben3g.jpeg" /><figcaption>Figure 1. Raman spectrum from graphene with a spike. The code to generate this figure is shown below. Image by author.</figcaption></figure><pre>import numpy as np<br># Load data directly into a numpy array<br>data = np.loadtxt(spiked_spectrum.asc, delimiter=&#39;,&#39;, skiprows=1)<br><br># Extract Raman shift from the first column (index)<br>ramanshift = data[:, 0]<br><br># Extract intensity from the second column (index 1in Python)<br>intensity = data[:, 1]<br><br># Plot the data<br>import matplotlib.pyplot as plt<br>fig = plt.figure(figsize = (5,3))<br>plt.plot(ramanshift, intensity)<br>plt.xlabel(&#39;Raman shift (cm$^{-1}$)&#39;)<br>plt.ylabel(&#39;Intensity (a.u.)&#39;)<br>plt.show()</pre><h3>The spike removal algorithm</h3><p>The spike removal algorithm presented here consists of four main steps:</p><p><strong>1. Peak finding</strong><br> <strong>2. Spike detection</strong><br> <strong>3. Spike flagging</strong><br> <strong>4. Spectrum correction</strong></p><p>Let’s take a look at the different steps with Python code snippets:</p><p><strong>1. Peak finding:</strong> First, the algorithm identifies significant peaks by checking for local maxima with a minimum prominence threshold. Adding a prominence threshold helps to exclude small noise-generated peaks, as we don’t aim to correct all the noise. See the following figure for comparison.</p><pre>from scipy.signal import find_peaks<br># Find the peaks in the spectrum (with and without prominence threshold)<br>peaks_wo_p, _ = find_peaks(intensity) # Peaks found without a prominence threshold<br>peaks_w_p, _ = find_peaks(intensity, prominence = 20) # Peaks found without a prominence threshold<br><br>fig, ax = plt.subplots(1, 2, figsize = (10,3))<br>ax[0].plot(ramanshift, intensity, zorder=0, label=&#39;Raw spectrum&#39;)<br>ax[0].scatter(ramanshift[peaks_wo_p], intensity[peaks_wo_p], marker =&#39;.&#39;, color = &#39;red&#39;,label=&#39;Found peaks&#39;)<br>ax[1].plot(ramanshift, intensity, zorder=0, label=&#39;Raw spectrum&#39;)<br>ax[1].scatter(ramanshift[peaks_w_p], intensity[peaks_w_p], marker =&#39;.&#39;, color = &#39;red&#39;,label=&#39;Found peaks&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVMpwIUUWhBgrLDAWklZBQ.jpeg" /><figcaption>Step 1: Find the peaks in a spectrum. Image by author.</figcaption></figure><p><strong>2. Spike detection:</strong> Then, spikes are flagged based on their characteristic narrow widths. This point might help in the automation of large spectral datasets. If we know the width of the Raman bands present in our spectra, we can choose a threshold below such a value. For example, with our system resolution, we do not expect to have graphene Raman bands with widths below 10 cm-1.</p><pre>from scipy.signal import peak_widths<br>widths = peak_widths(intensity, peaks_w_p)[0]<br><br>fig, ax = plt.subplots(figsize = (5,3))<br>ax.plot(ramanshift, intensity, zorder=0, label=&#39;Raw spectrum&#39;)<br>ax2 = ax.twinx()<br>ax2.scatter(ramanshift[peaks_w_p], widths, marker =&#39;+&#39;, color = &#39;red&#39;,label=&#39;Peak widths&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjeLhAg_PyoZ6cQ4bmEg1w.jpeg" /><figcaption>Step 2: Finding the widths of the peaks. Image by author.</figcaption></figure><p><strong>3. Spike flagging</strong> Next, any data points affected by spikes are flagged using a range calculated from the peak’s prominence, effectively isolating corrupted pixels. In other words, we select the window that must be corrected</p><pre># Let&#39;s set the parameters:<br>width_param_rel = 0.8<br>width_threshold = 10 # Estimation of the width of the narrowest Raman band<br><br># Calculation of the range where the spectral points are asumed to be corrupted<br>widths_ext_a = peak_widths(intensity, peaks_w_p, rel_height=width_param_rel)[2]<br>widths_ext_b = peak_widths(intensity, peaks_w_p, rel_height=width_param_rel)[3]<br><br># Create a vector where spikes will be flag: no spike = 0, spike = 1.<br>spikes = np.zeros(len(intensity))<br>    <br># Flagging the area previously defined if the peak is considered a spike (width below width_threshold)<br>for a, width, ext_a, ext_b in zip(range(len(widths)), widths, widths_ext_a, widths_ext_b):<br>    if width &lt; width_threshold:<br>        spikes[int(ext_a) - 1: int(ext_b) + 2] = 1 <br><br>fig = plt.figure(figsize = (5,3))<br>plt.plot(ramanshift, intensity, zorder=0,label=&#39;Raw spectrum&#39;)<br>a=1<br>plt.scatter(ramanshift[int(widths_ext_a[a])-1 : int(widths_ext_b[a])+1], <br>            intensity[int(widths_ext_a[a])-1 : int(widths_ext_b[a])+1], <br>            color =&#39;red&#39;, label = &#39;corrupted points&#39;)<br>plt.axvline(x = ramanshift[int(widths_ext_a[a]) -1], linestyle = &#39;--&#39;, color = &#39;red&#39;)<br>plt.axvline(x = ramanshift[int(widths_ext_b[a]) + 1], linestyle = &#39;--&#39;, color = &#39;red&#39;)  <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I64b-LlWLDq1rXMat93lQg.jpeg" /><figcaption>Step 3: Flagging the corrupted bins. Image by author.</figcaption></figure><p><strong>4. Spectrum correction</strong> Finally, these points are corrected through interpolation of nearby values, preserving the spectrum’s integrity for subsequent analyses.</p><pre>from scipy import interpolate<br># Let&#39;s set the parameter:<br>moving_average_window = 10<br><br>intensity_out = intensity.copy()<br>    <br># Interpolation of corrupted points<br>for i, spike in enumerate(spikes):<br>    if spike != 0: # If we have an spike in position i<br>        window = np.arange(i - moving_average_window, i + moving_average_window + 1) # we select 2 ma + 1 points around our spike<br>        window_exclude_spikes = window[spikes[window] == 0] # From such interval, we choose the ones which are not spikes<br>        interpolator = interpolate.interp1d(window_exclude_spikes, intensity[window_exclude_spikes], kind=&#39;linear&#39;) # We use the not corrupted points around the spike to calculate the interpolation<br>        intensity_out[i] = interpolator(i) # The corrupted point is exchanged by the interpolated value.<br><br>fig = plt.figure(figsize = (5,3))<br>plt.plot(ramanshift, intensity, zorder=0, color =&#39;red&#39;,label=&#39;Raw spectrum&#39;)<br>plt.plot(ramanshift, intensity_out, zorder=0, label=&#39;Corrected spectrum&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-UgBJizzjS6FKU5IySuHQ.jpeg" /><figcaption>Step 4: Spectrum correction. Image by author.</figcaption></figure><h3>A full spike removal function in Python</h3><p>All these snippets can be summarized in a single function. This function is designed to be customizable based on your specific data needs, with parameters for adjusting prominence and width:</p><pre>import numpy as np<br>from scipy.signal import find_peaks, peak_widths, peak_prominences<br>from scipy import interpolate<br><br>def spike_removal(y, <br>                  width_threshold, <br>                  prominence_threshold=None, <br>                  moving_average_window=10, <br>                  width_param_rel=0.8, <br>                  interp_type=&#39;linear&#39;):<br>    &quot;&quot;&quot;<br>    Detects and replaces spikes in the input spectrum with interpolated values. Algorithm first <br>    published by N. Coca-Lopez in Analytica Chimica Acta. https://doi.org/10.1016/j.aca.2024.342312<br><br>    Parameters:<br>    y (numpy.ndarray): Input spectrum intensity.<br>    width_threshold (float): Threshold for peak width.<br>    prominence_threshold (float): Threshold for peak prominence.<br>    moving_average_window (int): Number of points in moving average window.<br>    width_param_rel (float): Relative height parameter for peak width.<br>    tipo: type of interpolation (linear, quadratic, cubic)<br>    <br>    Returns:<br>    numpy.ndarray: Signal with spikes replaced by interpolated values.<br>    &quot;&quot;&quot;<br><br>    # First, we find all peaks showing a prominence above prominence_threshold on the spectra<br>    peaks, _ = find_peaks(y, prominence=prominence_threshold)<br>    <br>    # Create a vector where spikes will be flag: no spike = 0, spike = 1.<br>    spikes = np.zeros(len(y))<br>    <br>    # Calculation of the widths of the found peaks<br>    widths = peak_widths(y, peaks)[0]<br>    <br>    # Calculation of the range where the spectral points are asumed to be corrupted<br>    widths_ext_a = peak_widths(y, peaks, rel_height=width_param_rel)[2]<br>    widths_ext_b = peak_widths(y, peaks, rel_height=width_param_rel)[3]<br>    <br>    # Flagging the area previously defined if the peak is considered a spike (width below width_threshold)<br>    for a, width, ext_a, ext_b in zip(range(len(widths)), widths, widths_ext_a, widths_ext_b):<br>        if width &lt; width_threshold:<br>            spikes[int(ext_a) - 1: int(ext_b) + 2] = 1 <br>            <br>    y_out = y.copy()<br>    <br>    # Interpolation of corrupted points<br>    for i, spike in enumerate(spikes):<br>        if spike != 0: # If we have an spike in position i<br>            window = np.arange(i - moving_average_window, i + moving_average_window + 1) # we select 2 ma + 1 points around our spike<br>            window_exclude_spikes = window[spikes[window] == 0] # From such interval, we choose the ones which are not spikes<br>            interpolator = interpolate.interp1d(window_exclude_spikes, y[window_exclude_spikes], kind=interp_type) # We use the not corrupted points around the spike to calculate the interpolation<br>            y_out[i] = interpolator(i) # The corrupted point is exchanged by the interpolated value.<br>            <br>    return y_out</pre><p>The function with the algorithm can then be applied to the spiked graphene spectrum as follows:</p><pre>intensity_despiked = spike_removal(intensity, <br>                                     width_threshold = 3, <br>                                     prominence_threshold = 20, <br>                                     moving_average_window=10, <br>                                     width_param_rel=0.8, <br>                                     interp_type=&#39;linear&#39;)<br><br>fig, ax = plt.subplots(1, 2, figsize = (2*5,3))<br>ax[0].plot(ramanshift, intensity, label = &#39;spike&#39;, color =&#39;red&#39;, linewidth = 0.9)<br>ax[0].plot(ramanshift, intensity_despiked)<br>ax[1].plot(ramanshift, intensity_despiked)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnkHtzGHl4ZRLMNBAxXLxg.jpeg" /><figcaption>Example of spike removal in a Raman spectrum. Image by author.</figcaption></figure><p>With this spike removal approach, you can ensure your Raman spectra are clean and reliable, minimizing artefacts without losing essential spectral details. The method is ideal for automation, especially if the expected minimum peak width is known, making it highly adaptable for large-scale spectral datasets and high-throughput analysis</p><p>I hope you enjoyed this tutorial. Feel free to drop any questions or share your own Raman data challenges in the comments — I’d love to hear how this algorithm helps in your projects!</p><p>Ready to try it out? Download the Jupyter Notebook <a href="https://github.com/nicocopez/pyspikes/blob/main/Tutorial%20to%20remove%20spikes%20from%20Raman%20spectra%20-%20A%20step%20by%20step%20guide.ipynb">here</a>. And if you found this useful, please, remember to cite the <a href="https://doi.org/10.1016/j.aca.2024.342312">original work</a>, that would help me a lot! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fd90e8ea77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/removing-spikes-from-raman-spectra-a-step-by-step-guide-with-python-b6fd90e8ea77">Removing Spikes from Raman Spectra with Python: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science for Raman spectroscopy]]></title>
            <link>https://medium.com/data-science/data-science-for-raman-spectroscopy-a-practical-example-e81c56cf25f?source=rss-60149d1ba899------2</link>
            <guid isPermaLink="false">https://medium.com/p/e81c56cf25f</guid>
            <category><![CDATA[spectroscopy]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[chemometrics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[raman-spectroscopy]]></category>
            <dc:creator><![CDATA[Nicolas Coca, PhD]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 06:56:18 GMT</pubDate>
            <atom:updated>2025-02-04T11:48:08.468Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science for Raman Spectroscopy: A Practical Example</h3><h4>A practical example on spectra pre-processing and modeling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*4fQ_B1fM8RCWub8fdJ-CsQ.gif" /><figcaption><strong>Data Science for Raman Spectra</strong>. From spectral pre-processing to modeling: Spike detection and removal, baseline subtraction, smoothing and application of classical least squares for components quantification. [Image by the author].</figcaption></figure><h3>Introduction</h3><p>Raman spectroscopy provides information about the vibrational modes of molecules in the form of Raman spectra. These spectra can work like a structural fingerprint by which molecules and materials can be identified and characterized. From them we can learn things like what is our material composed of, what is its temperature, where are the tension within the material, if there is any applied electromagnetic field, etc. However, in order to extract such information we first need to clean and process the data before applying a chemometric or machine learning model. In the present draft I will explain how the data science pipeline works on Raman spectral data and give an example chemometrics for quantitative spectral analysis.</p><p>This post is part of a series on Data Science for Raman spectroscopy with Python. The present one will help to wrap up the topics presented in the previous ones and use them for a full processing and modeling cycle. See the previous ones published in <a href="https://towardsdatascience.com/">Towards Data Science</a>:</p><ul><li><a href="https://medium.com/towards-data-science/removing-spikes-from-raman-spectra-8a9fdda0ac22?source=your_stories_page-------------------------------------">Removing Spikes from Raman Spectra with Anomaly Detection</a></li><li><a href="https://medium.com/towards-data-science/classical-least-squares-method-for-quantitative-spectral-analysis-with-python-1926473a802c?source=your_stories_page-------------------------------------">Classical Least Squares Method for Quantitative Spectral Analysis with Python</a></li></ul><p><strong>An example</strong></p><p>The aim of this post is to show the typical workflow of analysis and modelling of Raman spectral data. For that purpose, a synthetic Raman spectrum is generated based on three distinct components. Different kinds of noise are added for the shake of reality. The most usual steps of pre-processing are applied in order to recover a clean spectrum. Finally, a classical least squares method is used to estimate the concentration of the three distinct components.</p><p>This notebook is therefore divided into three parts: <br>1) Generation of a synthetic spectrum <br>2) Preprocessing of the spectrum <br>3) Application of classical least squares to calculate the amount of different components on the spectrum</p><p>Let’s start by loading the libraries that we are going to use.</p><pre># Loading the required packages:<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy import sparse<br>from scipy.sparse.linalg import spsolve<br>from scipy.signal import savgol_filter, general_gaussian<br>import sklearn.linear_model as linear_model</pre><h3>Generation of synthetic data</h3><p>For this practical example, we are going to simulate some Raman spectra, so we know what to expect.</p><p>1) We are going to generate three components, which we will mix with a given ratio.</p><p>2) In order to make it more real, we will add noise: Random noise, spikes and a baseline.</p><h3>Generation of a mixture spectrum made of three components</h3><p>Even this topic is much more complex, for this example, let’s assume that our signal is composed of Gaussian peaks. For this, we define a Gaussian function as</p><pre>def Gauss(x, mu, sigma, A = 1):<br>    # This def returns the Gaussian function of x<br>    # x is an array<br>    # mu is the expected value<br>    # sigma is the square root of the variance<br>    # A is a multiplication factor<br>    <br>    gaussian = A/(sigma * np.sqrt(2*np.pi)) * np.exp(-0.5*((x-mu)/sigma)**2)<br>    <br>    return gaussian</pre><p>We first generate the three components:</p><pre># X-axis (Wavelengths)<br>x_range =  np.linspace(650, 783, 1024)<br><br># Let&#39;s create three different components<br><br># Component A<br>mu_a1 = 663<br>sigma_a1 = 1<br>intensity_a1 = 1<br><br>mu_a2 = 735<br>sigma_a2 = 1<br>intensity_a2 = 0.2<br><br>mu_a3 = 771<br>sigma_a3 = 1<br>intensity_a3 = 0.3<br><br>gauss_a =  Gauss(x_range, mu_a1, sigma_a1, intensity_a1) + Gauss(x_range, mu_a2, sigma_a2, intensity_a2) + Gauss(x_range, mu_a3, sigma_a3, intensity_a3)<br><br># Component B<br>mu_b = 700<br>sigma_b = 1<br>intensity_b = 0.2<br><br>mu_b1 = 690<br>sigma_b1 = 2<br>intensity_b1 = 0.5<br><br>mu_b2 = 710<br>sigma_b2 = 1<br>intensity_b2 = 0.75<br><br>mu_b3 = 774<br>sigma_b3 = 1.5<br>intensity_b3 = 0.25<br><br>gauss_b = Gauss(x_range, mu_b, sigma_b, intensity_b) + Gauss(x_range, mu_b1, sigma_b1, intensity_b1) + Gauss(x_range, mu_b2, sigma_b2, intensity_b2) + Gauss(x_range, mu_b3, sigma_b3, intensity_b3)<br><br># Component C<br>mu_c1 = 660<br>sigma_c1 = 1<br>intensity_c1 = 0.05<br><br>mu_c2 = 712<br>sigma_c2 = 4<br>intensity_c2 = 0.7<br><br>gauss_c = Gauss(x_range, mu_c1, sigma_c1, intensity_c1) + Gauss(x_range, mu_c2, sigma_c2, intensity_c2)<br><br># Component normalization<br>component_a = gauss_a/np.max(gauss_a)<br>component_b = gauss_b/np.max(gauss_b)<br>component_c = gauss_c/np.max(gauss_c)<br><br># How do they look?<br>plt.plot(x_range, component_a, label = &#39;Component 1&#39;)<br>plt.plot(x_range, component_b, label = &#39;Component 2&#39;)<br>plt.plot(x_range, component_c, label = &#39;Component 3&#39;)<br>plt.title(&#39;Known components in our mixture&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Normalized intensity&#39;, fontsize = 15)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*6mXN1L08At8YzFwvlj52Bg.png" /><figcaption>Three (known) synthetic components’ spectra. [Image by the author].</figcaption></figure><p>We can then generate a mixture spectrum base on these three different components:</p><pre># What concentrations we want these components to have in our mixture:<br>c_a = 0.5<br>c_b = 0.3<br>c_c = 0.2<br><br>comps = np.array([c_a, c_b, c_c])<br><br># Let&#39;s build the spectrum to be studied: The mixture spectrum<br>mix_spectrum = c_a * component_a + c_b * component_b + c_c *component_c<br><br># How does it look?<br>plt.plot(x_range, mix_spectrum, color = &#39;black&#39;, label = &#39;Mixture spectrum with noise&#39;)<br>plt.title(&#39;Mixture spectrum&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Intensity&#39;,  fontsize = 15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*Td5p_lOWcsNkk0L22wuNWQ.png" /><figcaption>Synthetic spectrum. [Image by the author].</figcaption></figure><p>In order to have our mixture more real, let’s add now some noise:</p><pre># Let&#39;s add some noise for a bit of realism:<br><br># Random noise:<br>mix_spectrum = mix_spectrum +  np.random.normal(0, 0.02, len(x_range))<br><br># Spikes: <br>mix_spectrum[800] = mix_spectrum[800] + 1<br>mix_spectrum[300] = mix_spectrum[300] + 0.3<br><br># Baseline as a polynomial background:<br>poly = 0.2 * np.ones(len(x_range)) + 0.0001 * x_range + 0.000051 * (x_range - 680)**2 <br>mix_spectrum = mix_spectrum + poly<br><br># How does it look now?<br>plt.plot(x_range, mix_spectrum, color = &#39;black&#39;, label = &#39;Mixture spectrum with noise&#39;)<br>plt.title(&#39;Mixture spectrum&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Intensity&#39;,  fontsize = 15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*cXohZExW-IeVdhrlh8Ls8Q.png" /><figcaption>Synthetic spectrum with added noise. [Image by the author].</figcaption></figure><p>We have now a synthetic measured spectrum.</p><h3>Pre-processing of the spectrum</h3><p>Before we could do any modelling, we need to pre-process our spectrum. These are some of the things that we would do with a real measured spectra: Clean the spikes, smooth the noise and subtract the baseline. To do so, we will use some simple algorithms as described below.</p><p>For a more complete list of Raman spectra processing steps, the reader is encouraged to go to B. Barton et al (Applied Spectroscopy 76 (9), 1021–1041) or to O. Ryabchykov et al (<a href="https://doi.org/10.1515/psr-2017-0043">https://doi.org/10.1515/psr-2017-0043</a>).</p><h3>i) Despiking the spectrum</h3><p>The first step is to locate and correct the spikes. For this we use a modified z-score based algorithm. The modified z-scores are calculated as</p><p>z(i) = 0.6745 (x(i)-M) / MAD</p><p>where the MAD = median(|x-M|), |…| represents the absolute value, and x are the values of the differentiated spectrum.</p><p>For more information see my previous <a href="https://towardsdatascience.com/removing-spikes-from-raman-spectra-8a9fdda0ac22">post</a> or <a href="https://github.com/nicocopez/Outlier_detection_for_Spikes_Removal_from_Raman_Spectra/blob/master/Despiking_Raman_spectra_1.ipynb">this jupyter notebook</a> my github account. (Note: I currently recommend the use of <a href="https://doi.org/10.1016/j.aca.2024.342312">this algorithm</a>. You can read a tutorial on how to use it <a href="https://medium.com/towards-data-science/removing-spikes-from-raman-spectra-a-step-by-step-guide-with-python-b6fd90e8ea77">here</a>. Edited on 4th of Feb 2025)</p><pre># The next function calculates the modified z-scores of a diferentiated spectrum<br><br>def modified_z_score(ys):<br>    ysb = np.diff(ys) # Differentiated intensity values<br>    median_y = np.median(ysb) # Median of the intensity values<br>    median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in ysb]) # median_absolute_deviation of the differentiated intensity values<br>    modified_z_scores = [0.6745 * (y - median_y) / median_absolute_deviation_y for y in ysb] # median_absolute_deviationmodified z scores<br>    return modified_z_scores<br>    <br># The next function calculates the average values around the point to be replaced.<br>def fixer(y,ma):<br>    threshold = 7 # binarization threshold<br>    spikes = abs(np.array(modified_z_score(y))) &gt; threshold<br>    y_out = y.copy()<br>    for i in np.arange(len(spikes)):<br>        if spikes[i] != 0:<br>            w = np.arange(i-ma,i+1+ma)<br>            we = w[spikes[w] == 0]<br>            y_out[i] = np.mean(y[we])<br>    return y_out</pre><p>We next apply the despiking algorithm:</p><pre>despiked_spectrum = fixer(mix_spectrum,ma=10)</pre><p>and compare with the original mix spectrum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*8FT_YX_YPh7bbVoa3ZWf-g.png" /><figcaption>Spike detection. [Image by the author].</figcaption></figure><h3>ii) Baseline separation</h3><p>In order to calculate the baseline, we use a baseline estimation algorithm based on asymetric least squares, as presented in this paper by Eilers and Boelens in 2005.</p><pre># Baseline stimation with asymmetric least squares<br># According to paper: &quot;Baseline Correction with Asymmetric Least Squares Smoothing&quot; <br># by Paul H. C. Eilers and Hans F.M. Boelens. October 21, 2005<br><br># We need the following packages here:<br>from scipy import sparse<br>from scipy.sparse.linalg import spsolve<br><br># Baseline stimation function:<br>def baseline_als(y, lam, p, niter=100):<br>    L = len(y)<br>    D = sparse.diags([1,-2,1],[0,-1,-2], shape=(L,L-2))<br>    w = np.ones(L)<br>    for i in range(niter):<br>        W = sparse.spdiags(w, 0, L, L)<br>        Z = W + lam * D.dot(D.transpose())<br>        z = spsolve(Z, w*y)<br>        w = p * (y &gt; z) + (1-p) * (y &lt; z)<br>    return z<br><br># For more info see the paper and https://stackoverflow.com/questions/29156532/python-baseline-correction-library</pre><p>Baseline Subtraction parameters:<br>As they say in their paper, “there are two parameters: <strong>p for asymmetry</strong> and <strong>l for smoothness</strong>. Both have to be tuned to the data at hand. We found that generally 0.001 &lt; p &lt; 0.1 is a good choice (for a signal with positive peaks) and 10² &lt; l &lt; 10⁹.” See Eiler and Boelens, 2005.</p><pre># Parameters for this case:<br>l = 10000000 # smoothness<br>p = 0.05 # asymmetry</pre><p>With the help of this algorithm we can estimate the baseline and subtract it from the measured spectrum.</p><pre># Estimation of the baseline:<br>estimated_baselined = baseline_als(despiked_spectrum, l, p)<br><br># Baseline subtraction:<br>baselined_spectrum = despiked_spectrum - estimated_baselined<br><br># How does it look like?<br>fig, (ax1, ax2) = plt.subplots(1,2, figsize=(16,4))<br><br># We compared the original mix spectrum and the estimated baseline:<br>ax1.plot(x_range, despiked_spectrum, color = &#39;black&#39;, label = &#39;Mix spectrum with noise&#39; )<br>ax1.plot(x_range, estimated_baselined, color = &#39;red&#39;, label = &#39;Estimated baseline&#39;)<br>ax1.set_title(&#39;Baseline estimation&#39;, fontsize = 15)<br>ax1.set_xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>ax1.set_ylabel(&#39;Intensity&#39;,  fontsize = 15)<br>ax1.legend()<br><br># We plot the mix spectrum after baseline subtraction<br>ax2.plot(x_range, baselined_spectrum, color = &#39;black&#39;, label = &#39;Baselined spectrum with noise&#39; )<br>ax2.set_title(&#39;Baselined spectrum&#39;, fontsize = 15)<br>ax2.set_xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>ax2.set_ylabel(&#39;Intensity&#39;,  fontsize = 15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bH6mDgQfTJ4HC8NTUqEF4A.png" /><figcaption>Baseline subtraction. [Image by the author].</figcaption></figure><h3>iii) Smoothing</h3><p>In order to smooth the spectra, we use a Savitzky Golay filter as implemented in the library SciPy. The parameters window (number of points) w and polynomial order p can be optimized for every set of spectra.</p><pre>from scipy.signal import savgol_filter, general_gaussian<br><br># Parameters:<br>w = 9 # window (number of points)<br>p = 2 # polynomial order<br><br>smoothed_spectrum = savgol_filter(baselined_spectrum, w, polyorder = p, deriv=0)<br><br># Some more information on the implementation of this method can be found here:<br># https://nirpyresearch.com/savitzky-golay-smoothing-method/<br><br><br># We plot the mix spectrum after baseline subtraction<br>plt.plot(x_range, baselined_spectrum, color = &#39;black&#39;, label = &#39;Baselined spectrum with noise&#39; )<br>plt.plot(x_range, smoothed_spectrum, color = &#39;red&#39;, label = &#39;Smoothed spectrum&#39; )<br>plt.title(&#39;Smoothed spectrum&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Intensity&#39;,  fontsize = 15)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*jTnJRaxgPvwwJLZazSjQ0g.png" /><figcaption>Noise smoothing. [Image by the author].</figcaption></figure><p>We finally have a processed spectrum to which we can apply a model.</p><h3>Classical Least Squares (CLS) Method for Quantitative Spectral Analysis</h3><p>Now we have preprocessed our mix spectrum, we can apply CLS to quantify its composition. For more information on CLS you can see my previous post in <a href="https://medium.com/towards-data-science/classical-least-squares-method-for-quantitative-spectral-analysis-with-python-1926473a802c">here</a>.</p><pre>query_spectrum = smoothed_spectrum # Let&#39;s just rename it</pre><p>We first generate the matrix of the components K</p><pre># Generate the components matrix or K matrix<br>components = np.array([component_a, component_b, component_c])  </pre><p>We can make use of Scikit-learn to implement CLS, so we import the library</p><pre>import sklearn.linear_model as linear_model</pre><p>and apply CLS to calculate the concentrations</p><pre>cs = linear_model.LinearRegression().fit(components.T, query_spectrum).coef_<br>#We print the result:<br>print(&#39;The expected concentrations for components A, B and C are: &#39; + str(cs))  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUGsBj3s4q62CPpj08O-Ag.png" /></figure><p>Let’s look at it graphically:</p><pre># Does the result match the original data?<br><br># Plot the original data:<br>plt.plot(x_range, query_spectrum, color = &#39;black&#39;, label = &#39;Mix spectrum&#39; )<br><br># Plot the separate components times its calculated concentration:<br>for i in np.arange(len(cs)):<br>    plt.plot(x_range, cs[i]*components[i], label = &#39;c&#39; + str(i)+ &#39; = &#39; + str(np.round(cs[i], 3)))<br><br># Plot the result: the sum of separate components times its calculated concentration:<br>plt.plot(x_range, np.dot(cs,components), color = &#39;red&#39;, linewidth = 2, label = &#39;Calculation&#39;)<br>    <br>plt.title(&#39;Mixture spectrum and calculated components&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Intensity&#39;, fontsize = 15)<br>plt.legend()<br>plt.ylim(ymin = -0.1)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*E8xeKCsUGQYlJ2EvAiO57g.png" /><figcaption>Spectrum fitting. [Image by the author].</figcaption></figure><p>The fit concentrations, shown in the legend of the figure, perfectly agree with the set values for the synthetic spectrum.</p><p>So, in summary, we have seen how to preprocess a spectrum and we have applied a simple least squares model to recover the different components and their concentration. This simple, yet powerful tools might help you to get most of your spectral data. Importantly, different steps of this approach can be applied to not only Raman spectra, but to any kind of spectral data, as for example Infrared spectra, X-ray diffraction spectra, etc.</p><p>Now it is your turn, synthesize different spectra and play with the parameters of the different algorithms or apply them to your own measured spectra.</p><p>… and if you have any <strong>question, comment or suggestion</strong>, please do not hesitate to <strong>contact me</strong> via message or at my linkedin account: <a href="https://www.linkedin.com/in/nicolascocalopez/">nicolascocalopez</a>.</p><h3><strong>Jupyter notebook:</strong></h3><p>See the complete jupyter notebook <a href="https://github.com/nicocopez/Data-Science-for-Raman-spectroscopy-a-practical-example/blob/main/Workshop%20ML%20with%20Python%20-%20DS%20for%20Raman%20spectroscopy%20-%20An%20example%20by%20NCL.ipynb">here</a>.</p><h3><strong>References</strong>:</h3><p>You can read more about despiking spectra in my previous post <a href="https://medium.com/towards-data-science/removing-spikes-from-raman-spectra-8a9fdda0ac22">here</a> and about classical least squares in <a href="https://medium.com/towards-data-science/classical-least-squares-method-for-quantitative-spectral-analysis-with-python-1926473a802c">here</a> or at my github or medium accounts:</p><ul><li><a href="https://medium.com/@nicopez">https://medium.com/@nicopez</a></li><li><a href="https://github.com/nicocopez/">https://github.com/nicocopez/</a></li></ul><p>Original papers:</p><ul><li><a href="https://chemrxiv.org/engage/api-gateway/chemrxiv/assets/orp/resource/item/60c73e33469df41c2af4281c/original/a-simple-algorithm-for-despiking-raman-spectra.pdf">Despiking algorithm with modified z-scores</a>. <br> Whitaker et al. Chemometrics and Intelligent Laboratory Systems Vol 179, 15 August 2018.</li><li>Baseline subtration with asymetric least squares. <br> “Baseline Correction with Asymmetric Least Squares Smoothing” by Paul H. C. Eilers and Hans F.M. Boelens. October 21, 2005</li></ul><p>For a complete guide on how to process and apply chemometrics to Raman spectra see:</p><ul><li>Barton, B., Thomson, J., Diz, E. L., &amp; Portela, R. (2022). Chemometrics for Raman Spectroscopy Harmonization. Applied Spectroscopy, 76(9), 1021–1041.</li><li>Ryabchykov, O., Guo, S., &amp; Bocklitz, T. (2019). Analyzing Raman spectroscopic data. Physical Sciences Reviews, 4(2).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e81c56cf25f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-science-for-raman-spectroscopy-a-practical-example-e81c56cf25f">Data Science for Raman spectroscopy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classical Least Squares Method for Quantitative Spectral Analysis with Python]]></title>
            <link>https://medium.com/data-science/classical-least-squares-method-for-quantitative-spectral-analysis-with-python-1926473a802c?source=rss-60149d1ba899------2</link>
            <guid isPermaLink="false">https://medium.com/p/1926473a802c</guid>
            <category><![CDATA[chemometrics]]></category>
            <category><![CDATA[spectroscopy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[least-squares]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Nicolas Coca, PhD]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 12:16:07 GMT</pubDate>
            <atom:updated>2020-04-13T15:09:25.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Classical Least Squares Method for Quantitative Spectral Analysis with Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*6pF9hUhqO5JQcidQTeYWQg.gif" /><figcaption>Finding spectrum components with Classical Least Squares</figcaption></figure><p><strong>Abstract</strong>. In this short tutorial, the Classical Least Squares method to calculate the similarity between spectra will be explained. This method, also known as Beer’s method, can be used to estimate the concentration of different components in an unknown spectrum. First, the physical context and Lambert-Beer’s law will be introduced, followed by the Classical Least Squares theoretical approach and derivation of the Normal equations. To wrap up, a Python implementation will be used to present an application example on how to calculate the concentration of different components on a sample spectrum.</p><h3>Introduction</h3><p>Spectroscopy is the study of emitted, reflected or scattered light by a solid, liquid or gas, as a function of wavelength [1]. Most spectroscopy methods are therefore classified as absorption, emission or scattering spectroscopy. Some examples are Absorption, X-Ray, Infrared and Raman spectroscopy among others.</p><p>Sometimes, the substance under spectroscopic study is unknown. If knowing the composition of such substance is required, its measured spectrum (query spectrum) can be compared against a spectral library of known substances (components) in order to be identified. To do so, the unknown spectrum is searched using a search algorithm which computes a score based on a similarity metric, providing a list of nearest matches or concentrations. A similarity metric is a function that quantifies the similarity between two objects. In some sense, such measures are the inverse of distance metrics: they return a large value for similar objects and either zero or negative value for dissimilar objects. When normalized, similarities range between 1 (complete similarity, meaning that the objects are equal) and 0 (no similarity at all). Similarity metrics are also the very basic building block for other activities such as Recommendation systems, clustering, classification or anomaly detection.<br>Regarding spectroscopy, there are several standard spectral search algorithms [2] based on different similarity metrics [3]. In the following, the Classical Least Squares method will be used to identify the spectrum of an unknown substance and to obtain the concentrations of known substances in a mixture. This approach is also known as Direct Least Squares, K-matrix calibration algorithm, or Beer’s method, since it is based on Beer-Lambert’s law.</p><h3>Physical context and Classical Least Squares - Beer’s Method</h3><p>The Beer-Lambert law relates the attenuation of light to the properties of the material through which the light is traveling. It is commonly applied to physical and chemical analysis measurements and used in understanding light attenuation in physical optics. The Beer-Lambert law says that at any given wavelength i, the light absorbance (<em>A</em>) is proportional to the absorbance coefficient of the pure substance (k) at the chosen wavelength i and the concentration of the pure substance (c):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*qSrMpgfQVAU0SYgws9jbeg.png" /></figure><p>where the absorbance coefficient (kᵢ = aᵢL) is the product of the the path length of the light through the material (L) and the molar attenuation coefficient or absorptivity (a) of the pure substance at the chosen wavelength i, which is a molecular property constituting the ‘spectrum’ of such molecule.</p><p>The equation Aᵢ = kᵢc applies to a single pure substance or component in a sample. When there are multiple absorbing components, the total absorbance at any wavelength is the sum of the absorbances, at that wavelength, of all the components in the mixture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*evkDLLWh_xbU3sgt-iyLiQ.png" /></figure><p>If what we have recorded is not a single value A for a given wavelength i, but a whole absorbance spectrum with w points, this is better represented with matrix notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*dquiYT4oTEEoGistxJQvgQ.png" /></figure><p>or in a more compact manner as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/1*mYZWBqkCoIBzomylKcMy2Q.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*3MaMF69HqN73WGymHhY8SQ.png" /></figure><p>so A is our recorded absorbance spectrum (also called query spectrum, or unknown spectrum, since we do not know yet what does it contain), K is the matrix of the pure component spectra (where the spectra values of such components are arranged in columns), and c is a vector with the concentration of the n pure substances.</p><p>Therefore, having the values of our measured unknown spectra, Aᵢ, and knowing the ones of the pure components spectra making up the mixture, Kᵢⱼ, we can find the concentrations cⱼ that best determine the mixture absorbance <em>A. However, </em>because the measured spectrum and the pure substances spectra contain noise, there will be, in general, no exact solution for the equation A = Kc. But we can still find c such that the product Kc is as close as possible to A, as measured by the euclidean norm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/1*1hbO5OCX8mOto8YdKBk7dw.png" /></figure><p>In other words, we want to find c such that the sum of the squares of the errors A-Kc is minimized. The errors are defined as the difference between the measured spectra A and the spectra calculated by multiplying K and c. c will be then the best least squares solution for equation A = Kc.</p><p>Using the fact that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*zLhig48LbzKFtUwMYj2qsg.png" /></figure><p>The Euclidean norm of our error is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*KYtAb4ENjqpOnOOzPtH3-Q.png" /></figure><p>In order to find the minimum of such function, we just need to derive it, set the resulting expression equal to zero and solve for c. To do so, we will make use of the property</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*18M5bK7mt_IhOlt_imLs5w.png" /></figure><p>where x is a vector and M is a symmetric matrix [4].</p><p>So,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*Y7zJfLRmelt52LrIgqglow.png" /></figure><p>Setting this expression to 0 we obtain the Normal Equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*m_4KbNgFPxjcEb6JY_lltg.png" /></figure><p>which can be solved to finally obtain the similarity scores between the measured spectrum and the known spectra in the library, or what its the same, the concentrations of pure substances in the unknown mixture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*nVMcV0iOEyQkRUpnTnRfoA.png" /></figure><p>Note that the second derivative of the squared sum of A-Kc is a positive semidefinite matrix, implying that the solution c is the global minimum (and not a maximum or a saddle point).</p><p>More detailed information on this method can be found in the book Chemometric techniques for quantitative analysis [5] or the spectroscopyonline webpage column about CLS [6].</p><h3><strong>Code and example implemented with Python</strong></h3><p>First, the Python packages that will be needed are loaded:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from numpy.linalg import inv</pre><p>The least squares formula to obtain the concentration of pure substances in the unknown mixture is defined as:</p><pre>def least_sq(sample_spectrum, components):</pre><pre>   # sample_spectrum (unknown spectrum): array of w values.<br>   # components (known spectra): array of n (number of components) columns with w values.<br>   # This def returns an array of n values. Each value is the similarity score for the sample_spectrum and a component spectrum.</pre><pre>   similarity = np.dot(inv(np.dot(components, components.T)) , np.dot(components, sample_spectrum))<br></pre><pre>    return similarity</pre><p>Next, some spectra to play with are fabricated. These spectra will be composed of Gaussian peaks. Therefore Gaussian function is defined:</p><pre>def Gauss(x, mu, sigma, intensity = 1):</pre><pre># x is an array<br># mu is the expected value<br># sigma is the square root of the variance<br># intensity is a multiplication factor<br># This def returns the Gaussian function of x</pre><pre>    return intensity/(sigma * np.sqrt(2*np.pi)) * np.exp(-0.5*((x-mu)/sigma)**2</pre><p>and use it to create three different components:</p><pre># X-axis (Wavelengths)<br>x_range =  np.linspace(100, 200, 1000)</pre><pre># Let&#39;s create three different components</pre><pre># Component A<br>mu_a1 = 120<br>sigma_a1 = 2<br>intensity_a1 = 1</pre><pre>mu_a2 = 185<br>sigma_a2 = 2<br>intensity_a2 = 0.2</pre><pre>gauss_a =  Gauss(x_range, mu_a1, sigma_a1, intensity_a1) + Gauss(x_range, mu_a2, sigma_a2, intensity_a2)</pre><pre># Component B<br>mu_b = 150<br>sigma_b = 15<br>intensity_b = 1<br>gauss_b = Gauss(x_range, mu_b, sigma_b, intensity_b)</pre><pre># Component C<br>mu_c1 = 110<br>sigma_c1 = 2<br>intensity_c1 = 0.05</pre><pre>mu_c2 = 160<br>sigma_c2 = 10<br>intensity_c2 = 1</pre><pre>gauss_c = Gauss(x_range, mu_c1, sigma_c1, intensity_c1) + Gauss(x_range, mu_c2, sigma_c2, intensity_c2)</pre><pre># Spectra normalization:<br>component_a = gauss_a/np.max(gauss_a)<br>component_b = gauss_b/np.max(gauss_b)<br>component_c = gauss_c/np.max(gauss_c)</pre><pre># How do they look?<br>plt.plot(x_range, component_a, label = &#39;Component 1&#39;)<br>plt.plot(x_range, component_b, label = &#39;Component 2&#39;)<br>plt.plot(x_range, component_c, label = &#39;Component 3&#39;)<br>plt.title(&#39;Known components in our mixture&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Normalized intensity&#39;, fontsize = 15)<br>plt.legend()<br>plt.show()</pre><p>This result in the next three different components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*tXCIPECsnWtTz4stAQ3yCA.png" /></figure><p>These three spectra will make our component matrix or K-matrix, where the spectra are arranged in rows.</p><p>In order to generate a query spectrum, the three components will be multiplied by a concentration and summed up together. To make it a bit more real, some noise will be added.</p><pre># What concentrations we want them to have in our mixture:<br>c_a = 0.5<br>c_b = 0.3<br>c_c = 0.2</pre><pre># Let&#39;s build the spectrum to be studied: The mixture spectrum<br>query_spectra = c_a * component_a + c_b * component_b + c_c *component_c<br># Let&#39;s add it some noise for a bit of realism:<br>query_spectra = query_spectra +  np.random.normal(0, 0.02, len(x_range))</pre><pre>plt.plot(x_range, query_spectra, color = &#39;black&#39;, label = &#39;Mixture spectrum with noise&#39;)<br>plt.title(&#39;Mixture spectrum&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Intensity&#39;,  fontsize = 15)<br>plt.show()</pre><p>The resulting mixture spectrum looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*HwqeEWGZrogVTDWCIOFIXg.png" /></figure><p>Our query spectrum is composed of three known components (n=3). Therefore, for this example the system of equations in matrix form looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*30m5FIShgfguwBA6Kip8fg.png" /></figure><p>where w = 1000 for this case (the wavelength axis has 1000 values). So A is a vector composed of 1000 values, c is a vector composed of 3 values (the three component concentrations) and K is a 3x1000 matrix.</p><p>Knowing A and K it is possible now to recalculate the 3 components concentration in the ‘unknown’ mixture:</p><pre># Generate the components matrix or K matrix<br>components = np.array([component_a, component_b, component_c])</pre><pre># Apply Least squares<br>cs = least_sq(query_spectra, components)</pre><pre># And plot the result:</pre><pre>plt.plot(x_range, query_spectra, color = &#39;black&#39;, label = &#39;Mix spectrum&#39; ) # Plot the unknown spectrum</pre><pre>plt.plot(x_range, np.dot(cs,components), color = &#39;red&#39;, linewidth = 2, label = &#39;Calculation&#39;) # Plot the calculated spectrum</pre><pre>for i in np.arange(len(cs)):<br>    plt.plot(x_range, cs[i]*components[i], label = &#39;c&#39; + str(i)+ &#39; =               &#39; + str(np.round(cs[i], 3)))</pre><pre>plt.title(&#39;Mixture spectrum and calculated components&#39;, fontsize = 15)<br>plt.xlabel(&#39;Wavelength&#39;, fontsize = 15)<br>plt.ylabel(&#39;Intensity&#39;, fontsize = 15)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*buRjuDP-o28cOgqeyjxPfQ.png" /><figcaption>Figure: Mixture spectrum (black), calculated spectrum (red) and calculated component spectra (blue, orange and green)</figcaption></figure><p>The calculated concentrations, shown in the legend of the figure, perfectly agree with the set values. <br>Note that the mixture spectra were not normalized. In case that the mixture spectra was normalized, the inverse of such normalization constant should be applied to the obtained concentrations in order to have the right values.</p><p>The next figure show three more examples, where the calculated concentration agree with the previously set values (see the figure’s caption).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0MVAQe96BvmMW1WqFbUBQ.png" /><figcaption>Three more examples. The query spectra were generated using concentrations = (0, 0.5, 0.5) for the first spectrum, c = (0.1, 0.5, 0.4) for the second, and c = (0.2, 0.2, 0.6) for the third. The curves calculated with Least squares are shown in blue, orange and green colors, whose calculated concentrations are written in the legend box.</figcaption></figure><p><strong>Least squares with Python libraries: SciPy and Skit-learn</strong></p><p>Alternatively, the Least squares problem can also be solved using some Python’s libraries.</p><p>As for example with SciPy:</p><pre>import scipy.optimize as optimization</pre><pre>x0 = np.array([1,1,1])</pre><pre>def func(params, xdata, ydata):<br>    return (ydata - np.dot(xdata.T, params))**2</pre><pre>optimization.leastsq(func, x0, args=(components, query_spectra))[0]</pre><p>or with Scikit-learn:</p><pre>import sklearn.linear_model as linear_model</pre><pre>linear_model.LinearRegression().fit(components.T, query_spectra).coef_</pre><p>resulting both of them in the concentrations 0.48, 0.30, 0.20 for components A, B and C, respectively.</p><h3>Summary and further considerations</h3><p>In this short tutorial, a Classical Least Squares approach was used to calculate the similarity between spectra and show how this is useful to estimate the concentration of different components in a absorbance spectrum (Beer’s method). Three different ways to implement this in Python were presented (based on the Normal equations and using the packages SciPy and Scikit-learn).<br>Importantly, this approach can be applied to not only Absorption spectra, but to any kind of spectral data, as for example Raman spectra, Infrared spectra, etc. However, because the presence of certain artifacts and side effects, several spectral pre-processing steps are required to clean the spectra before applying any similarity metric [2,7]. These steps include cropping and interpolation of the spectra, spikes removal (see my previous post), baseline subtraction, smoothing, and spectra normalization, which are specially important when dealing with weak signal (e.g. Raman spectra). But this will be the topic of a different post.</p><p>The original Jupyter Notebook can be found on <a href="https://github.com/nicocopez">GitHub</a>.</p><p><strong>Acknowledgements.</strong> I would like to thank <a href="https://medium.com/u/9fd2702e9b85">Jorge Luis Hita, Ph.D.</a>, <a href="https://medium.com/u/931dc03d0fba">Avinash Mishra</a> and <a href="https://medium.com/u/eb06b41f4c3e">Ana Solaguren-Beascoa, PhD</a> for taking the time to proofread this notes.</p><h3>References:</h3><p>[1] Spectroscopy. Wikipedia. <a href="https://en.wikipedia.org/wiki/Spectroscopy">https://en.wikipedia.org/wiki/Spectroscopy</a></p><p>[2] Khan, S. S., &amp; Madden, M. G. (2012). New similarity metrics for Raman spectroscopy. <em>Chemometrics and Intelligent Laboratory Systems</em>, <em>114</em>, 99–108.</p><p>[3] Implementing the five most popular similarity measures in Python. <a href="https://dataaspirant.com/2015/04/11/five-most-popular-similarity-measures-implementation-in-python/">https://dataaspirant.com/2015/04/11/five-most-popular-similarity-measures-implementation-in-python/</a></p><p>[4] Zico Kolter, Chuong Do (September 30, 2015). Linear Algebra Review and Reference notes. <a href="http://cs229.stanford.edu/section/cs229-linalg.pdf">http://cs229.stanford.edu/section/cs229-linalg.pdf</a></p><p>[5] Kramer, R. (1998). Chemometric techniques for quantitative analysis. CRC Press.</p><p>[6] Workman, J. and Mark, H. (2010). Chemometrics in Spectroscopy: Classical Least Squares, Part I: Mathematical Theory<br><a href="http://www.spectroscopyonline.com/classical-least-squares-part-i-mathematical-theory?id=&amp;pageID=1&amp;sk=&amp;date=">http://www.spectroscopyonline.com/classical-least-squares-part-i-mathematical-theory?id=&amp;pageID=1&amp;sk=&amp;date=</a></p><p>[7] Bocklitz, T. W., Guo, S., Ryabchykov, O., Vogler, N., &amp; Popp, J. (2016). Raman based molecular imaging and analytics: a magic bullet for biomedical applications!?. <em>Analytical chemistry</em>, <em>88</em>(1), 133–151.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1926473a802c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/classical-least-squares-method-for-quantitative-spectral-analysis-with-python-1926473a802c">Classical Least Squares Method for Quantitative Spectral Analysis with Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Removing Spikes from Raman Spectra with Anomaly Detection]]></title>
            <link>https://medium.com/data-science/removing-spikes-from-raman-spectra-8a9fdda0ac22?source=rss-60149d1ba899------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9fdda0ac22</guid>
            <category><![CDATA[raman-spectroscopy]]></category>
            <category><![CDATA[chemometrics]]></category>
            <category><![CDATA[spectroscopy]]></category>
            <category><![CDATA[cosmic-rays]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Nicolas Coca, PhD]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 20:06:40 GMT</pubDate>
            <atom:updated>2020-04-13T11:32:42.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Removing Spikes from Raman Spectra with Anomaly Detection: Whitaker-Hayes algorithm in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*TgD0KPshDXQz0NhgrqB8dw.gif" /><figcaption>Detecting and removing spikes from Raman spectra</figcaption></figure><p><strong>Abstract</strong>. In this article, I would like to comment on a new approach to remove spikes from Raman spectra, presented in the Chemometrics and Intelligent Laboratory Systems journal by D. Whitaker and K. Hayes¹. In their publication, the authors use a modified Z-scores outlier detection based algorithm to locate such spikes, when present, followed by a simple moving average to remove them. Instead of calculating the Z-scores of the spectrum intensity, they calculate the Z-scores of the once-differenced spectrum. They also provided the code for the algorithm implementation in R. Here, I present the implementation of the algorithm in Python and show how I applied it to a different data set.</p><p>Raman spectroscopy is a widely used analytical technique which provides structural and electronic information from molecules and solids. It is applicable at both laboratory and mass-production scales, and has applications in many different fields such as physics, chemistry, biology, medicine or industry.</p><p>A typical issue known in Raman spectroscopy is that Raman spectra are sometimes ‘contaminated’ by spikes. Spikes are positive, narrow bandwidth peaks present at random position on the spectrum. They originate when a high-energy cosmic ray impacts in the charge-couple device detector used to measure Raman spectra. These spikes are problematic as they might hinder subsequent analysis, particularly if multivariate data analysis is required. Therefore, one of the first steps in the treatment of Raman spectral data is the cleaning of spikes.</p><p>First, the Python packages that will be needed are loaded:</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><p>Figure 1 shows the Raman spectrum of graphene. In the previous years, graphene has become a very popular material due to its remarkable physical properties, including superior electronic, thermal, optical and mechanical properties. Its characteristic Raman spectrum consists of several peaks as shown in the figure. From their shape and related intensity, a large amount of information such as doping, strain or grain boundaries can be learned. This spectrum is a clear example of a spectrum contaminated with a spike.</p><pre># load the data as data frame<br>df = pd.read_csv(‘folder_name.../spectrum.txt’, delimiter = ‘\t’)</pre><pre># Transform the data to a numpy array<br>wavelength = np.array(df.Wavelength)<br>intensity = np.array(df.Intensity)</pre><pre># Plot the spectrum:<br>plt.plot(wavelength, intensity)<br>plt.title(‘Spectrum’, fontsize = 20)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel(‘Wavelength (nm)’, fontsize = 20)<br>plt.ylabel(‘Intensity (a.u.)’, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*QsAj9LaOXXAfWW_qrs9RBg.jpeg" /><figcaption><strong>Figure 1.</strong> A spike was recorded while measuring the typical Raman spectrum of graphene (characterized by the G and 2D bands).</figcaption></figure><p><strong>Z-score based approach for spike detection in Raman spectra</strong></p><p>Spikes intensities are normally above the intensities of other Raman peaks in the spectrum, therefore using a z-scores based method could be a good starting point. The z-scores tell how far a value is from the average in units of standard deviation. So, if the population mean and population standard deviation are known, the standard score of a raw score x(i) is calculated as:</p><p>z(i) = (x(i)-μ) / σ</p><p>where <em>μ</em> is the mean <em>and σ</em> is the standard deviation of the population x (x(i) represent the values of a single Raman spectrum). More in detail information on how to detect outliers using Z-score approaches can be found in reference [3].</p><p>Let’s calculate the z-scores for the points in our spectrum:</p><pre>def z_score(intensity):<br> mean_int = np.mean(intensity)<br> std_int = np.std(intensity)<br> z_scores = (intensity — mean_int) / std_int<br> return z_scores</pre><pre>intensity_z_score = np.array(z_score(intensity))<br>plt.plot(wavelength, intensity_z_score)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel( ‘Wavelength’ ,fontsize = 20)<br>plt.ylabel( ‘Z-Score’ ,fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*7u2PCweQYQbWy6vyVOd4wg.png" /><figcaption><strong>Figure 2.</strong> Z-scores of the spectrum plotted in figure 1.</figcaption></figure><p>A threshold is then needed in order to tell whether a value is an outlier or not. A typical value for this threshold is 3.5, as proposed as guideline by the American Society of Quality control as the basis of an outlier-labeling rule², while the authors of the publication used 6. In order to apply a threshold to exclude spikes, the absolute value of the Z-score must be taken:</p><p>|z(i)| = |(x(i)-μ) / σ|</p><p>calculated as</p><pre>def z_score(intensity):<br> mean_int = np.mean(intensity)<br> std_int = np.std(intensity)<br> z_scores = (intensity — mean_int) / std_int<br> return z_scores</pre><pre>threshold = 3.5</pre><pre>intensity_z_score = np.array(abs(z_score(intensity)))<br>plt.plot(wavelength, intensity_z_score)<br>plt.plot(wavelength, threshold*np.ones(len(wavelength)), label = ‘threshold’)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel( ‘Wavelength’ ,fontsize = 20)<br>plt.ylabel( ‘|Z-Score|’ ,fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*BAVlCFSgx-mwPQGtr0kYVA.png" /><figcaption><strong>Figure 2b.</strong> Z-scores of the spectrum plotted in figure 1. The threshold still cuts the 2D Raman peak.</figcaption></figure><p>However, the z-score pretty much resembles the original spectrum and the threshold still cut off the main Raman peak. Let’s plot what was detected as spikes using a 3.5 threshold:</p><pre>threshold = 3.5</pre><pre># 1 is assigned to spikes, 0 to non-spikes:<br>spikes = abs(np.array(z_score(intensity))) &gt; threshold</pre><pre>plt.plot(wavelength, spikes, color = ‘red’)<br>plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)<br>plt.grid()<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel( ‘Wavelength’ ,fontsize = 20)<br>plt.ylabel( &#39;Z-scores &gt; &#39; + str(threshold) ,fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*C5A8bLvW4i04ZpYc42v-2g.png" /><figcaption><strong>Figure 3.</strong>Using modified Z-Scores, 18 spectral point are above the threshold.</figcaption></figure><p><strong>Modified Z-score based approach for spike detection in Raman spectra</strong></p><p>A second option would be making use of robust statistics and calculate the modified z-scores of the spectrum. This modified Z-score method uses the median (M) and median absolute deviation (MAD) rather than the mean and standard deviation:</p><p>z(i) = 0.6745 (x(i)-M) / MAD</p><p>where the MAD = median(|x-M|) and |…| represents the absolute value. Both the median and the MAD are robust measures of the central tendency and dispersion, respectively. The multiplier 0.6745 is the 0.75th quartile of the standard normal distribution, to which the MAD converges to⁴.</p><pre>def modified_z_score(intensity):<br> median_int = np.median(intensity)<br> mad_int = np.median([np.abs(intensity — median_int)])<br> modified_z_scores = 0.6745 * (intensity — median_int) / mad_int<br> return modified_z_scores</pre><pre>threshold = 3.5</pre><pre>intensity_modified_z_score = np.array(abs(modified_z_score(intensity)))<br>plt.plot(wavelength, intensity_modified_z_score)<br>plt.plot(wavelength, threshold*np.ones(len(wavelength)), label = &#39;threshold&#39;)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel(&#39;Wavelength (nm)&#39; ,fontsize = 20)<br>plt.ylabel(&#39;|Modified Z-Score|&#39; ,fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*tyIkOZ9TnkVt5NS0XN5xqQ.png" /><figcaption><strong>Figure 4. </strong>Modified Z-scores of the spectrum plotted in figure 1. The threshold still cuts the 2D Raman peak.</figcaption></figure><p>The same issue can still be observed:</p><pre># 1 is assigned to spikes, 0 to non-spikes:<br>spikes = abs(np.array(modified_z_score(intensity))) &gt; threshold</pre><pre>plt.plot(wavelength, spikes, color = ‘red’)<br>plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)<br>plt.grid()<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel( ‘Wavelength’ ,fontsize = 20)<br>plt.ylabel( &#39;Modified Z-scores &gt; &#39; + str(threshold) ,fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*XeUgNepxKrBEo3I-f1Yr5w.png" /><figcaption><strong>Figure 5. </strong>Using modified Z-Scores, 24 spectral points are above the threshold.</figcaption></figure><p>The 2D Raman peak is still detected as spike, so a more sensitive approach is required.</p><p><strong>Whitaker and Hayes’</strong> <strong>modified Z-score based approach for spike detection in Raman spectra</strong></p><p>Whitaker and Hayes propose to make advantage of the high intensity and small width of spikes and therefore use the difference between consecutive spectrum points ∇x(i) = x(i)-x(i-1) to calculate the z-scores, where x(1), …, x(n) are the values of a single Raman spectrum recorded at equally spaced wavenumbers and i = 2, …, n. This step annihilates linear and slow moving curve linear trends, while sharp thin spikes will be preserved. Now,</p><p>z(i) = 0.6745 (∇x(i)-M) / MAD</p><p>So there is only an extra step included in which the difference between consecutive values are included.</p><pre># First we calculated ∇x(i):<br>dist = 0<br>delta_intensity = [] <br>for i in np.arange(len(intensity)-1):<br> dist = intensity[i+1] — intensity[i]<br> delta_intensity.append(dist)</pre><pre>delta_int = np.array(delta_intensity)<br># Alternatively to the for loop one can use: <br># delta_int = np.diff(intensity)</pre><pre><br>intensity_modified_z_score = np.array(modified_z_score(delta_int))<br>plt.plot(wavelength[1:], intensity_modified_z_score)<br>plt.title(&#39;Modified Z-Score using ∇x(i)&#39;)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel(&#39;Wavelength (nm)&#39;, fontsize = 20)<br>plt.ylabel(&#39;Score&#39;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*d6yetjmD3Gn7bqnvoVeCsQ.png" /><figcaption><strong>Figure 6. </strong>Modified Z-scores using ∇x(i) of the spectrum plotted in figure 1.</figcaption></figure><p>Again, in order to apply a threshold to exclude spikes, the absolute value of the modified Z-score must be taken:</p><p>|z(i)| =|0.6745 (∇x(i)-M) / MAD|</p><p>Resulting in</p><pre>threshold = 3.5</pre><pre>intensity_modified_z_score = np.array(np.abs(modified_z_score(delta_int)))<br>plt.plot(wavelength[1:], intensity_modified_z_score)<br>plt.plot(wavelength[1:], threshold*np.ones(len(wavelength[1:])), label = &#39;threshold&#39;)<br>plt.title(&#39;Modified Z-Score of ∇x(i)&#39;, fontsize = 20)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel(&#39;Wavelength (nm)&#39;, fontsize = 20)<br>plt.ylabel(&#39;Score&#39;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*3tbMDde93x1IwDjK-EMv-A.png" /><figcaption><strong>Figure 7. </strong>Abosolute value of the modified Z-scores of ∇x(i) of the spectrum plotted in figure 1.</figcaption></figure><p>And once more, the number of detected spikes can be calculated as</p><pre># 1 is assigned to spikes, 0 to non-spikes:<br>spikes = abs(np.array(modified_z_score(intensity))) &gt; threshold</pre><pre>plt.plot(wavelength, spikes, color = ‘red’)<br>plt.title(‘Spikes: ‘ + str(np.sum(spikes)), fontsize = 20)<br>plt.grid()<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel( ‘Wavelength’ ,fontsize = 20)<br>#plt.ylabel( ‘Spike(1) or not(0)?’ ,fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*lcxq5eftbDz_Loph7hw_gA.png" /><figcaption><strong>Figure 8. </strong>Using modified Z-Scores with ∇x(i), 17 spectral points are above the threshold = 3.5.</figcaption></figure><p>For the 3.5 recommended threshold many false spikes are assigned. However, the value scored by this approach is much higher in comparison with the Raman peaks than before.</p><pre>plt.plot(wavelength[1:],<br>np.array(abs(modified_z_score(delta_int))), color=&#39;black&#39;, label = &#39;|Modified Z-Score using ∇x(i)|&#39;)<br>plt.plot(wavelength, np.array(abs(modified_z_score(intensity))), label = &#39;|Modified Z-Score|&#39;, color = &#39;red&#39;)<br>plt.plot(wavelength, np.array(abs(z_score(intensity))), label = &#39;|Z-Score|&#39;, color = &#39;blue&#39;)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel( &#39;Wavelength&#39; ,fontsize = 20)<br>plt.ylabel( &#39;Score&#39; ,fontsize = 20)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*JF42-i12nt75m8ae11QnpA.png" /><figcaption><strong>Figure 9. </strong>Comparison between the three different approaches.</figcaption></figure><p>In general, the right threshold must be chosen depending on the data set. For this case, a threshold = 7 is already enough to obtain a clear selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*SE1F9OYtU9bMm8ZSX7o3kQ.png" /><figcaption><strong>Figure 10. </strong>Absolute values of the modified Z-scores with ∇x(i) of the spectrum plotted in figure 1.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*92lrc5EKkT6RtwJ9B3CNIg.png" /><figcaption><strong>Figure 11. </strong>Using modified Z-Scores with ∇x(i), 3 spectral points are above the threshold = 7.</figcaption></figure><p><strong>Fixing the Raman spectrum</strong></p><p>Once the spikes are detected, the next step is to remove them and fix the spectra. For this, interpolated values are obtained at each candidate wavenumber by calculating the mean of its immediate neighbors (within a 2m+1 values window).</p><pre>def fixer(y,m):<br> threshold = 7 # binarization threshold. <br> spikes = abs(np.array(modified_z_score(np.diff(y)))) &gt; threshold<br> y_out = y.copy() # So we don’t overwrite y</pre><pre> for i in np.arange(len(spikes)):<br>  if spikes[i] != 0: # If we have an spike in position i<br>   w = np.arange(i-m,i+1+m) # we select 2 m + 1 points around our spike<br>   w2 = w[spikes[w] == 0] # From such interval, we choose the ones which are not spikes<br>   y_out[i] = np.mean(y[w2]) # and we average their values<br> <br>return y_out</pre><pre># Does it work?<br>plt.plot(wavelength, intensity, label = &#39;original data&#39;)<br>plt.plot(wavelength, fixer(intensity,m=3), label = &#39;fixed spectrum&#39;)<br>plt.title(&#39;Despiked spectrum&#39;,fontsize = 20)<br>plt.xticks(fontsize = 15)<br>plt.yticks(fontsize = 15)<br>plt.xlabel(&#39;Wavelength (nm)&#39; ,fontsize = 20)<br>plt.ylabel(&#39;Intensity (a.u.)&#39; ,fontsize = 20)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*fIFCd43DQcmoof3VQAIUCA.png" /><figcaption><strong>Figure 12. </strong>Original and despiked Raman spectrum using modified Z-Scores with ∇x(i) with the threshold = 7.</figcaption></figure><p>So after calculation of the modified Z scores of ∇x, and thresholding by setting an appropiate threshold value, the spike is removed and smoothed by applying a moving average filter.</p><p><strong>Other examples</strong></p><p>To wrap up, two examples of spikes with different intensity signal are presented, showing the strenght of this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pGmRJ9ds17VmXLvBdLghQ.png" /><figcaption><strong>Figure 13.</strong> Examples of two more spectra in the first row of graphs, their Z-scores (blue lines) , modified Z-scores (red lines) and modified Z-scores using ∇x(i) (black lines) in the second row of graphs and thei despiked spectra in the third row, are presented.</figcaption></figure><p><strong>Aknowledgements.</strong> I would like to thank <a href="https://medium.com/@jluishita">Jorge Luis Hita</a> and <a href="https://medium.com/@ana.solagurenbeascoa">Ana Solaguren-Beascoa</a> for taking the time to proofread this notes.</p><p>[1] Whitaker, Darren A., and Kevin Hayes. “A simple algorithm for despiking Raman spectra.” <em>Chemometrics and Intelligent Laboratory Systems</em> 179 (2018): 82–84.</p><p>[2] Iglewicz, B., and D. Hoaglin. “The ASQC basic references in quality control: statistical techniques.” <em>How to detect and handle outliers</em> 16 (1993): 1–87.</p><p>[3] <a href="http://colingorrie.github.io/outlier-detection.html">Colin Gorrie’s Data Story: Three ways to detect outliers. http://colingorrie.github.io/outlier-detection.html</a></p><p>[4] Joao Rodrigues. “Outliers make us go MAD: Univariate Outlier Detection”. Medium. <a href="https://medium.com/james-blogs/outliers-make-us-go-mad-univariate-outlier-detection-b3a72f1ea8c7">https://medium.com/james-blogs/outliers-make-us-go-mad-univariate-outlier-detection-b3a72f1ea8c7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9fdda0ac22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/removing-spikes-from-raman-spectra-8a9fdda0ac22">Removing Spikes from Raman Spectra with Anomaly Detection</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>