def test_parseXML():  # Improve this test!
    from MJOLNIR.Geometry import Wedge, Analyser, Detector, Instrument
    import os
    tempFileName = '__temp__'

    Instr = Instrument.Instrument()
    Instr.settings['Author'] = 'Jakob Lass'

    wedge = Wedge.Wedge(position=(0.5, 0, 0))

    Det = Detector.TubeDetector1D(position=(1.0, 1, 0), direction=(1, 0, 0))
    Ana = Analyser.FlatAnalyser(position=(0.5, 0, 0), direction=(1, 0, 1))

    wedge.append([Det, Ana])
    Instr.append([wedge, wedge])
    Instr.append(wedge)

    f = open(tempFileName, 'w')

    f.write(createXMLString(Instr))
    f.close()

    InstrLoaded = parseXML(tempFileName)
    os.remove(tempFileName)

    assert (Instr == InstrLoaded)
Beispiel #2
0
def test_CalcualteA4Ef():

    Instr = Instrument.Instrument()
    Det = Detector.TubeDetector1D(position=(1, 0, 1),
                                  direction=(1, 0, 0),
                                  pixels=10,
                                  split=[2, 5, 8],
                                  length=1.0)
    Det2 = Detector.TubeDetector1D(position=(1, 0.1, 1),
                                   direction=(1, 0, 0),
                                   pixels=10,
                                   split=[2, 5, 8],
                                   length=1.0)
    Ana = Analyser.FlatAnalyser(position=(0.5, 0, 0), direction=(1, 0, 1))
    Ana2 = Analyser.FlatAnalyser(position=(1, 0, 0), direction=(1, 0, 1))

    wedge = Wedge.Wedge(position=(0, 0, 0),
                        detectors=[Det, Det2],
                        analysers=[Ana, Ana2])

    Instr.append(wedge)

    Instr.initialize()
    print(Instr.A4)
    print(Instr.Ef)
def test_Build_a_simple_instrument(saveFig=False):
    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits.mplot3d import Axes3D

    Instr = Instrument.Instrument()

    Det = Detector.TubeDetector1D(position=(1, 0, 1), direction=(1, 0, 0))
    Ana = Analyser.FlatAnalyser(position=(1, 0, 0), direction=(1, 0, 1))

    wedge = Wedge.Wedge(position=(0, 0, 0), detectors=Det, analysers=Ana)

    Instr.append(wedge)

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    Instr.plot(ax)

    ax.set_xlim(-0.1, 1.1)
    ax.set_ylim(-0.1, 1.1)
    ax.set_zlim(-0.1, 1.1)

    if saveFig:
        plt.savefig('../docs/_templates/Build_a_simple_instrument.png',
                    format='png',
                    dpi=300)
        plt.show()
def Tester():
    from MJOLNIR.Geometry import Instrument,Detector,Analyser,Wedge
    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits.mplot3d import Axes3D

    Instr = Instrument.Instrument()

    Det = Detector.TubeDetector1D(position=(1,0,1),direction=(1,0,0))
    Ana = Analyser.FlatAnalyser(position=(1,0,0),direction=(1,0,1))

    wedge = Wedge.Wedge(position=(0,0,0),detectors=Det,analysers=Ana)

    Instr.append(wedge)

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    Instr.plot(ax)

    ax.set_xlim(-0.1,1.1)
    ax.set_ylim(-0.1,1.1)
    ax.set_zlim(-0.1,1.1)

    fig.savefig('/home/lass/Dropbox/PhD/Software/MJOLNIR/docs/Tutorials/Instrument/SimpleInstrument.png',format='png')
Beispiel #5
0
def Tester():
    from MJOLNIR.Geometry import Instrument, Detector, Analyser, Wedge
    # Create instrument
    Instr = Instrument.Instrument()

    # Create two detectors and their corresponding analysers
    Det = Detector.TubeDetector1D(position=(1, 0, 1),
                                  direction=(1, 0, 0),
                                  pixels=10,
                                  split=[2, 5, 8],
                                  length=1.0)
    Det2 = Detector.TubeDetector1D(position=(1, 0.1, 1),
                                   direction=(1, 0, 0),
                                   pixels=10,
                                   split=[2, 5, 8],
                                   length=1.0)
    Ana = Analyser.FlatAnalyser(position=(0.5, 0, 0), direction=(1, 0, 1))
    Ana2 = Analyser.FlatAnalyser(position=(1, 0, 0), direction=(1, 0, 1))

    # Collect everything in the wedge object
    wedge = Wedge.Wedge(position=(0, 0, 0),
                        detectors=[Det, Det2],
                        analysers=[Ana, Ana2])

    Instr.append(wedge)

    Instr.initialize()
    print(Instr.A4)
    print(Instr.Ef)
def test_Load_XML(save=False):
    import matplotlib.pyplot as plt
    import numpy as np
    Instr = Instrument.Instrument(
        fileName='Tutorials/SimpleInstrument.xml')  # Load XML file

    fig = plt.figure()  # Create 3D figure
    ax = fig.gca(projection='3d')

    Instr.plot(ax)  # Plot instrument

    ax.set_ylim(0.0, 1.5)
    ax.set_xlim(-0.2, 0.2)
    ax.set_zlim(0.0, 1.1)
    ax.set_xlabel('x [m]')
    ax.set_ylabel('y [m]')
    ax.set_zlabel('z [m]')
    plt.tight_layout()
    if save:
        plt.savefig('SimpleInstrument.png', format='png', dpi=300)

    Instr.initialize()  # Initialize instrument

    plt.figure()
    for det in range(len(Instr.wedges[0].detectors)):
        start, stop = Instr.wedges[0].detectors[det]._split[[0, -1]]
        plt.scatter(
            np.arange(start,
                      stop),  #range(Instr.wedges[0].detectors[det].pixels),
            Instr.A4[0][det] * 180.0 / np.pi,
            zorder=10,
            s=3)

    plt.grid(True)
    plt.xlabel('Pixel')
    plt.ylabel('A4 [deg]')
    if save:
        plt.savefig('SimpleInstrument_A4.png', format='png', dpi=300)
    plt.figure()
    for det in range(len(Instr.wedges[0].detectors)):
        start, stop = Instr.wedges[0].detectors[det]._split[[0, -1]]
        plt.scatter(
            np.arange(start, stop),  #Instr.wedges[0].detectors[det].pixels),
            Instr.Ef[0][det],
            zorder=10,
            s=3)

    plt.grid(True)
    plt.xlabel('Pixel')
    plt.ylabel('Ef [meV]')
    plt.tight_layout()
    if save:
        plt.savefig('SimpleInstrument_Ef.png', format='png', dpi=300)
        plt.show()
def Generate_normalization(plot=False):
    Instr = Instrument.Instrument(
        fileName='/home/lass/Dropbox/PhD/Software/MJOLNIR/Data/CAMEA_Updated.xml'
    )  #'TestData/1024/CAMEA_Full.xml')
    Instr.initialize()

    VanNormFile = '/home/lass/Dropbox/PhD/CAMEAData/camea2018n000119.hdf'  #'/home/lass/Dropbox/PhD/CAMEAData/camea2018n000084.hdf'#'/TestData/1024/camea2018n000038.hdf'#'TestData/1024/EScanRunDoubleFocusHS.h5'
    Instr.generateCalibration(
        Vanadiumdatafile=VanNormFile,
        savelocation='/home/lass/Dropbox/PhD/CAMEAData/NormalizationUpdated/',
        plot=plot,
        tables=[1, 3, 8])
Beispiel #8
0
def Tester():
    from MJOLNIR.Geometry import Instrument
    import matplotlib.pyplot as plt
    import numpy as np
    Instr = Instrument.Instrument(fileName='/home/lass/Dropbox/PhD/Software/MJOLNIR/Tutorials/SimpleInstrument.xml') # Load XML file


    fig = plt.figure() # Create 3D figure
    ax = fig.gca(projection='3d')

    Instr.plot(ax) # Plot instrument

    ax.set_ylim(0.0,1.5)
    ax.set_xlim(-0.2,0.2)
    ax.set_zlim(0.0,1.1)
    ax.set_xlabel('x [m]')
    ax.set_ylabel('y [m]')
    ax.set_zlabel('z [m]')
    plt.tight_layout()
    
    plt.savefig('/home/lass/Dropbox/PhD/Software/MJOLNIR/docs/Tutorials/Instrument/SimpleInstrument2.png',format='png',dpi=300)

    Instr.initialize() # Initialize instrument

    plt.figure()
    for det in range(len(Instr.wedges[0].detectors)):
        start,stop = Instr.wedges[0].detectors[det]._split[[0,-1]]
        plt.scatter(np.arange(start,stop),#range(Instr.wedges[0].detectors[det].pixels),
                    Instr.A4[0][det]*180.0/np.pi,zorder=10,s=3)

    plt.grid(True)
    plt.xlabel('Pixel')
    plt.ylabel('A4 [deg]')
    plt.savefig('/home/lass/Dropbox/PhD/Software/MJOLNIR/docs/Tutorials/Instrument/SimpleInstrument2_A4.png',format='png',dpi=300)

    plt.figure()
    for det in range(len(Instr.wedges[0].detectors)):
        start,stop = Instr.wedges[0].detectors[det]._split[[0,-1]]
        plt.scatter(np.arange(start,stop),
                    Instr.Ef[0][det],zorder=10,s=3)

    plt.grid(True)
    plt.xlabel('Pixel')
    plt.ylabel('Ef [meV]')
    plt.tight_layout()

    plt.savefig('/home/lass/Dropbox/PhD/Software/MJOLNIR/docs/Tutorials/Instrument/SimpleInstrument2_Ef.png',format='png',dpi=300)
def parseXML(filename):

    from MJOLNIR.Geometry import Detector, Analyser, Wedge, Instrument
    import xml.etree.ElementTree as ET
    import numpy as np

    tree = ET.parse(filename)
    instr_root = tree.getroot()

    instrSettings = {}

    for attrib in instr_root.keys():
        instrSettings[attrib] = instr_root.attrib[attrib]

    Instr = Instrument.Instrument(**instrSettings)

    for wedge in list(instr_root):  #.getchildren():

        if wedge.tag in dir(Wedge):
            Wedgeclass_ = getattr(Wedge, wedge.tag)
        else:
            raise ValueError(
                "Element is supposed to be a Wedge, but got '{}'.".format(
                    wedge.tag))
        wedgeSettings = {}

        for attrib in wedge.keys():
            if attrib == 'concept':
                wedgeSettings[attrib] = np.array(
                    wedge.attrib[attrib].strip().split(','), dtype=str)
            else:
                wedgeSettings[attrib] = np.array(
                    wedge.attrib[attrib].strip().split(','), dtype=float)

        temp_wedge = Wedgeclass_(**wedgeSettings)
        #print(temp_wedge)

        for item in list(wedge):  #.getchildren():
            if item.tag in dir(Detector):
                class_ = getattr(Detector, item.tag)
            elif item.tag in dir(Analyser):
                class_ = getattr(Analyser, item.tag)
            else:
                raise ValueError(
                    "Item '{}' not recognized as MJOLNIR detector or analyser."
                    .format(item.tag))

            itemSettings = {}
            for attrib in item.keys():
                attribVal = item.get(attrib).strip().split(',')
                if len(attribVal) == 1:
                    itemSettings[attrib] = float(attribVal[0])
                else:
                    if (attrib == 'split'):
                        #print(type(attribVal))
                        itemSettings[attrib] = attribVal
                    else:
                        itemSettings[attrib] = np.array(attribVal, dtype=float)
            try:
                temp_item = class_(**itemSettings)
            except TypeError as e:
                print(e.args[0])
                raise ValueError('Item {} misses argument(s):{}'.format(
                    class_, e.args[0].split(':')[1]))
            except ValueError:
                raise ValueError(
                    'Item {} not initialized due to error.'.format(class_))
            #print(temp_item)
            temp_wedge.append(temp_item)
            #print()

        #print(str(temp_wedge))
        Instr.append(temp_wedge)
    return Instr
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 26 16:49:34 2018

@author: lass
"""
from MJOLNIR.Geometry import Detector, Analyser, Wedge, Instrument
from MJOLNIR.Data import DataSet
import numpy as np
import h5py as hdf
import matplotlib.pylab as plt

Instr = Instrument.Instrument(
    filename='/home/lass/Dropbox/PhD/Software/CAMEA_Full.xml')
Instr.initialize()

NF = '/home/lass/Dropbox/PhD/Software/CAMEA_Test_Files/cameasim2018n000004.h5'  #'/home/lass/Documents/PhD/McStas/HDFFullEi/RITA_FULL_AUTO_20171023_103342.hdf'

dataset = DataSet.DataSet(instrument=Instr, normalizationfiles=NF)

dataset.EnergyCalibration(
    NF,
    'Normalization/',
    plot=True,
    tables=['Single', 'PrismaticLowDefinition', 'PrismaticHighDefinition'])