コード例 #1
0
ファイル: andor_sdk.py プロジェクト: ivanalam/nplab
 def save_params_to_file(self, filepath=None):
     if filepath is None:
         data_file = df.create_file(set_current=False, mode='a')
     else:
         data_file = df.DataFile(filepath)
     data_file.create_dataset(name='AndorSettings', data=[], attrs=self.get_andor_parameters())
     data_file.close()
コード例 #2
0
ファイル: spectrum_aligner_ir.py プロジェクト: ivanalam/nplab
def main(filepath, debug=0):
    f = df.DataFile(filepath, "r")
    g = f["calibration"]
    keys = list(g.keys())

    center_wavelengths = []
    for k in keys:
        center_wavelengths = center_wavelengths + [
            g[k].attrs["center_wavelength"]
        ]

    center_wavelengths = sorted(np.unique(center_wavelengths))
    print("main:max center wavelength:", np.max(center_wavelengths))

    dataset = []
    for cw in center_wavelengths:

        entry = (cw, [], [])
        for k in keys:
            if g[k].attrs["center_wavelength"] == cw:
                entry[2].append(g[k].attrs["laser_wavelength"])
                entry[1].append(np.array(g[k]))
        dataset.append(entry)

    # print "-="*10
    # for d in dataset:
    # 	print d
    # print "-="*10
    mapper = scan_fit(dataset, debug=debug)

    return mapper
コード例 #3
0
def initialize_datafile(path):
    """
	This function defines the format of the group structure

	Parameters are path on filesystem 
	
	"""
    f = df.DataFile(path, 'a')

    return f
コード例 #4
0
ファイル: andor_sdk.py プロジェクト: ivanalam/nplab
 def load_params_from_file(self, filepath=None):
     if filepath is None:
         data_file = df.open_file(set_current=False, mode='r')
     else:
         data_file = df.DataFile(filepath)
     if 'AndorSettings' in list(data_file.keys()):
         self.set_andor_parameters(dict(data_file['AndorSettings'].attrs))
     else:
         self._logger.error('Load settings failed as "AndorSettings" does not exist')
     data_file.close()
コード例 #5
0
def initialize_measurement():
    f = df.DataFile("ir_calibration.hdf5", "a")
    g = f.require_group("calibration")
    print("Starting..")

    print("Pixis...")
    p = Pixis(debug=1)

    p.StartUp()
    print("Acton...")
    act = Acton("COM7", debug=1)
    print("Done...")
    pacton = Pacton(pixis=p, acton=act)
    print("Measuring...")
    fig, ax = plt.subplots(1)
    p.SetExposureTime(500)
    pacton.get_pixel_response_calibration_spectrum()
    return pacton, g
コード例 #6
0
def main(debug=0):
    #Measurements and Calibration files
    measurement_file = df.DataFile("measured_spectrum.hdf5", "r")
    reference_file = df.DataFile(
        "maxwell_room_light_spectrum_calibration.hdf5", "r")

    #Load reference within given range
    ref_xs, ref_ys = load_reference_data(reference_file,
                                         lower_wavelength=430,
                                         upper_wavelength=714)

    #Load measured data from file
    data = load_measured_data(measurement_file)

    center_wavelengths = [d[0] for d in data]
    #Load the raw counts from the measured data

    #Merge individual spectra (using median) and normalise to set minimum value to zero
    signal_spectrum, mapper_1 = median_spectrum(data, debug=1)
    signal_spectrum = zero_min(signal_spectrum)
    #handcrafted truncation to "valid range" where we can see peaks & that matches the reference spectrum
    signal_spectrum = signal_spectrum[1550:10570]
    #Apply smoothing to the measured signal - want to eliminate most false peaks
    signal_spectrum = SUREShrink(signal_spectrum)
    signal_spectrum, _, _ = convex_smooth(signal_spectrum, 1.0)

    #rescale the reference and fit a line to the wavelength range [nm]
    ref_xs, ref_ys, gradient, offset = rescale_reference(
        xs=ref_xs,
        ys=ref_ys,
        max_size=np.nanmax(signal_spectrum),
        N=len(signal_spectrum),
        debug=1)

    #Get peaks from the signal, with thresholding to eliminate low order maxima/minima
    signal_peaks = get_peaks(signal_spectrum, threshold=1.0)
    ref_peaks = get_peaks(ref_ys, threshold=2.0)

    #Link peaks, handcrated to ignore false peaks
    interpolator_function, interpolator_bounds, lines = link_peaks(
        signal_peaks=signal_peaks,
        reference_peaks=ref_peaks,
        ignored_signal_indices=[3, 8, 11, 13, 19, 22, 23],
        ignored_reference_indices=[11, 14, 18],
        debug=debug)

    if debug > 0:
        fig, ax = plt.subplots(1, figsize=(12, 10))
        ax.set_title("fname: main, debug 0")
        ax.plot(ref_ys, "-", label="Reference")
        ax.plot(signal_spectrum, label="Signal")

        ax.plot(ref_peaks[0, :], ref_peaks[1, :], "o", label="Reference peaks")
        t1s = annotate_points(ref_peaks[0, :], ref_peaks[1, :], ax)
        ax.plot(signal_peaks[0, :],
                signal_peaks[1, :],
                "o",
                label="Signal peaks")
        t2s = annotate_points(signal_peaks[0, :], signal_peaks[1, :], ax)

        for (xs, ys) in lines:
            ax.plot(xs, ys, "-", color="red")

        ax.set_xlabel("Array index")
        ax.set_ylabel("Counts [arb. units]")

        ax.legend()

    def make_mapper2(interpolator_function, gradient, offset):
        def index_to_wavelength(index, with_correction=True):

            if with_correction:
                alignment_correction = int(
                    np.round(interpolator_function(index)))
                index = index - alignment_correction
            #this out linear model
            wavelength = index * gradient + offset
            return wavelength

        return index_to_wavelength

    index_to_wavelength = mapper_2 = make_mapper2(interpolator_function,
                                                  gradient, offset)
    if debug > 0:
        fig, ax = plt.subplots(1)
        ax.set_title("fname: main, debug plot 1")
        xs = list(
            range(np.min(interpolator_bounds), np.max(interpolator_bounds)))
        ys = [index_to_wavelength(x) for x in xs]
        plt.plot(xs, ys)

        fig, ax = plt.subplots(1)
        ax.set_title("fname: main, debug plot 2")
        wavelengths_reference = [
            index_to_wavelength(x, with_correction=False)
            for x in range(len(ref_ys))
        ]
        ax.plot(wavelengths_reference,
                ref_ys,
                label="Reference spectrum (rescaled)")
        xs = list(range(interpolator_bounds[0], interpolator_bounds[1]))

        ax.plot([index_to_wavelength(x, with_correction=True) for x in xs],
                [signal_spectrum[x] for x in xs],
                label="Stitched signal (corrected)")
        ax.plot([index_to_wavelength(x, with_correction=False) for x in xs],
                [signal_spectrum[x] for x in xs],
                alpha=0.4,
                label="Stitched signal (uncorrected)")
        ax.set_ylim(0)

        ax.set_xlabel("Wavelength [nm]")
        ax.set_ylabel("Intensity (arb. units)")
        ax.set_title(
            "Alignment to reference spectrum\n Reference: Ocean Optics Spectrometer\n Signal: Acton+Pixis"
        )
        ax.legend()

    # mapper_1 : maps from (center_wavelength, pixel_index) to index in spectrum array
    # mapper_2 : maps from index in spectrum array to wavelenegth
    def mapper(center_wavelength, pixel_index):
        try:
            array_index = mapper_1(center_wavelength, pixel_index)
            wavelength = mapper_2(array_index)
            return wavelength
        except:
            return np.nan

    if debug > 0:

        plt.show()

    #This tests the data
    plot_layers(center_wavelengths, data, mapper, show_plot=True)
    return mapper
コード例 #7
0
from skimage import feature, filters
import cv2
import math
from skimage.filters import gaussian
from skimage.segmentation import active_contour
from scipy.signal import convolve2d, correlate2d
import scipy.misc
from PIL import Image
import re
import sys
import scipy.ndimage as ndimage
import skimage

FILEPATH = "/home/ilya/Desktop/2018-02-17.h5"
FOLDERPATH = "ParticleScannerScan_2"
datafile = datafile.DataFile(FILEPATH, mode="r")
TAG = "Raman_White_Light_0Order.*"

TAGS = [
    "Infinity3_Bias_Image", "Infinity3_FirstBkgndWhiteLight_Image",
    "Infinity3_FirstWhiteLight_Image", "Infinity3_SecondWhiteLight_Image",
    "Infinity3_SecondWhiteLight_atBkgndLoc_Image", "Raman_Bias_0Order_int",
    "Raman_Bias_Spectrum_int", "Raman_Bias_Spectrum_wl",
    "Raman_Laser_0Order_atBkgndLoc_int", "Raman_Laser_0Order_int",
    "Raman_Laser_Spectrum_atBkgndLoc_int",
    "Raman_Laser_Spectrum_atBkgndLoc_wl", "Raman_Laser_Spectrum_int",
    "Raman_Laser_Spectrum_wl", "Raman_White_Light_0Order_int",
    "Raman_White_Light_Bkgnd_0Order_int",
    "Raman_White_Light_Bkgnd_Spectrum_int",
    "Raman_White_Light_Bkgnd_Spectrum_wl", "Raman_White_Light_Spectrum_int",
    "Raman_White_Light_Spectrum_wl"
コード例 #8
0
    return pacton, g


def plot_measurement(pacton, center_wavelength):
    fig, ax = plt.subplots(1)
    spectrum, _ = pacton.get_spectrum(center_wavelength,
                                      subtract_background=True,
                                      roi=[0, 1024, 600, 800],
                                      debug=1)
    ax.plot(spectrum)
    plt.show()


if __name__ == "__main__":

    f = df.DataFile("ir_calibration_1200gmm.hdf5", "a")
    g = f.require_group("calibration")
    print("Starting..")

    print("Pixis...")
    p = Pixis(debug=0)

    p.StartUp()
    print("Acton...")
    act = Acton("COM5", debug=0)
    print("Done...")
    pacton = Pacton(pixis=p, acton=act)

    print("Setting grating...")
    pacton.acton.set_grating(1)  # 1 : 1200g/mm, 2: 300g/mm
    # print pacton.acton.read_grating()
コード例 #9
0
ファイル: Pacton.py プロジェクト: ivanalam/nplab
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal

from nplab import datafile as df
from nplab.analysis.smoothing import convex_smooth
from nplab.instrument import Instrument

f = df.DataFile("maxwell_room_light_spectrum_calibration.hdf5", "r")
spectrum = np.array(f["calibration"]["spectrum_1"])

CALIBRATION_WAVELENGTHS = spectrum[0, :]
CALIBRATION_COUNTS = spectrum[1, :]


def spectrum_pixel_offset(spectrum_1, spectrum_2):
    sp1 = spectrum_1
    sp2 = spectrum_2

    sp1 = sp1 - np.mean(sp1)
    sp2 = sp2 - np.mean(sp2)

    #compute cross correlation to match
    xcs = np.correlate(sp1, sp2, mode="same")
    #perform fftshift to center zero offset on 0th position
    xcs = np.fft.fftshift(xcs)
コード例 #10
0
ファイル: test.py プロジェクト: ivanalam/nplab
    return pacton, g


def plot_measurement(pacton, center_wavelength):
    fig, ax = plt.subplots(1)
    spectrum, _ = pacton.get_spectrum(center_wavelength,
                                      subtract_background=True,
                                      roi=[0, 1024, 600, 800],
                                      debug=1)
    ax.plot(spectrum)
    plt.show()


if __name__ == "__main__":

    f = df.DataFile("ir_calibration.hdf5", "a")
    g = f.require_group("calibration")
    print("Starting..")

    print("Pixis...")
    p = Pixis(debug=1)

    p.StartUp()
    print("Acton...")
    act = Acton("COM7", debug=1)
    print("Done...")
    pacton = Pacton(pixis=p, acton=act)
    print("Measuring...")
    fig, ax = plt.subplots(1)
    p.SetExposureTime(500)
    pacton.get_pixel_response_calibration_spectrum()
コード例 #11
0
from nplab.instrument.camera.Picam.pixis import Pixis
from .Pacton import Pacton

print("Starting..")
print("Pixis...")
p = Pixis(debug=0)
p.StartUp()
print("Acton...")
act = Acton("COM6", debug=0)
print("Done...")

pacton = Pacton(pixis=p, acton=act, debug=0)

print("Measuring...")
from nplab import datafile as df
output_file = df.DataFile("measured_spectrum.hdf5", "w")
dg = output_file.require_group("spectra")
fig, axarr = plt.subplots(3)
p.SetExposureTime(500)
pacton.get_pixel_response_calibration_spectrum()
measured_ys = []
measured_xs = []
from nplab.analysis.signal_alignment import correlation_align

for wl in range(400, 800, 4):

    print(p.GetExposureTime())
    spectrum, wavelengths = pacton.get_spectrum(wl,
                                                subtract_background=True,
                                                roi=[0, 1024, 600, 800],
                                                debug=1)
コード例 #12
0
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 05 17:41:32 2016

@author: Will

A Python file that allows you to run the databrowser from cmd line on a h5 file
"""

import qtpy
import sys
import nplab.datafile as df
import h5py

file_path = sys.argv[1]  #Take the file location from sys.argv list

data_file = h5py.File(file_path, mode='r')  #Open the file using h5py
data_file = df.DataFile(data_file)  #convert the file to nplab.datafile type
data_file.show_gui()  #Show data browser