In [395]:
import matplotlib.pyplot as plt
%matplotlib inline
from pylab import rcParams
rcParams['figure.figsize'] = 10, 5

In [ ]:
%run /Users/schriste/Developer/repositories/foxsipy/foxsipy/foxsi2_export_effarea_excel.py

In [38]:
plt.errorbar(data_array[1, 0, :], data_array[3, 0, :], yerr=data_array[3 + offset])
plt.ylabel("Effective area cm^2")
plt.xlabel("Energy [kev]")
plt.xlim(0, 30)


Out[38]:
(0, 30)

In [68]:
plt.figure(figsize=(20, 10))
plt.imshow(data_array[2:13, 0, :], aspect=10, interpolation='none')


Out[68]:
<matplotlib.image.AxesImage at 0x10cd14510>

In [67]:
plt.contourf(energies, offaxis_angle, data_array[2:13, 0, :])
plt.colorbar()
plt.xlim(0, 20)


Out[67]:
(0, 20)

Smoothed Data


In [191]:
import os

In [716]:
__author__ = 'schriste'

import xlrd
import glob
from astropy.units import Quantity

class effarea_file(object):
    def __init__(self, filename):

        dirs = ['10-shell/', '7-shell/']
        rootdir = '/Users/schriste/Desktop/FOXSI-2 Optics Calibration/Effective Area/'
        self.files = []
        for d in dirs:
            result = glob.glob(rootdir + d + filename)
            for f in result:
                self.files.append(f)

        if self.files[0].count('7-shell') != 0:
            self.number_of_shells = 7
        if self.files[0].count('10-shell') != 0:
            self.number_of_shells = 10
            
        if len(files) > 2:
            raise ValueError("Too many files found")

        sheet_names = ('-9 arc min', '-7 arc min', '-5 arc min ', '-3 arc min', '-1 arc min', 'on-axis', '+1 arc min',
               '+3 arc min', '+5 arc min', '+7 arc min ', '+9 arc min ')
        col_dict = dict(energy=0, effective_area=2, error=3)
        nenergies = 13
        self.data = np.zeros((2, len(sheet_names), nenergies))
        self.edata = np.zeros((2, len(sheet_names), nenergies))
        self.energies = Quantity(np.zeros(nenergies), 'keV')
        self.angles = Quantity(np.array([-9, -7, -5, -3, -1, 0, 1, 3, 5, 7, 9]), 'arcmin')
        self.names = [os.path.basename(s) + ' ' + str(self.number_of_shells) + ' shells' for s in self.files]
        self._typeindex = np.array(['pan', 'tilt'])
        self.number = int(self.names[0][9:10])
        for f in self.files:
            xls = xlrd.open_workbook(f)
            if f.count('pan'):
                index = 0
            else:
                index = 1
            for k, sheet_name in enumerate(sheet_names):
                sheet = xls.sheet_by_name(sheet_name)
                for row in range(nenergies):
                    if k == 0:
                        cell = sheet.cell(row + 17, col_dict["energy"])
                        self.energies[row] = Quantity(cell.value, 'keV')

                    cell = sheet.cell(row + 17, col_dict["effective_area"])
                    if cell.ctype == 2:
                        self.data[index, k, row] = cell.value 
                    cell = sheet.cell(row + 17, col_dict["error"])
                    if cell.ctype == 2:
                        self.edata[index, k, row] = cell.value 
    def effective_area(self, angle, kind='pan'):
        type_index = np.where(self._typeindex == kind)[0][0]
        angle_index = np.where(self.angles.value == angle)[0][0]
        return self.data[type_index, angle_index, :]
    def effective_area_error(self, angle, kind='pan'):
        type_index = np.where(self._typeindex == kind)[0][0]
        angle_index = np.where(self.angles.value == angle)[0][0]
        return self.edata[type_index, angle_index, :]
    def plot_effective_area( self, angle, kind='pan', axes=None):
        type_index = np.where(self._typeindex == kind)[0][0]
        if not axes:
            axes = plt.gca()
        plot_label = 'X' + str(self.number) + ' ' + str(angle) + ' arcmin'
        axes.errorbar(self.energies.value, self.effective_area(angle, kind=kind), 
                yerr=self.effective_area_error(angle, kind=kind), fmt='o-', label=plot_label)
        axes.set_title(self.names[type_index])
        return axes
    def fov(self, energy, kind='pan'):
        type_index = np.where(self._typeindex == kind)[0][0]
        energy_index = np.where(self.energies.value == energy)[0][0]
        return self.data[type_index, :, energy_index]
    def fov_error(self, energy, kind='pan'):
        type_index = np.where(self._typeindex == kind)[0][0]
        energy_index = np.where(self.energies.value == energy)[0][0]
        return self.edata[type_index, :, energy_index]
    def plot_fov(self, energy_index, kind='pan', axes=None):
        type_index = np.where(self._typeindex == kind)[0][0]
        plot_label = 'X' + str(self.number) + ' ' + str(self.energies[energy_index])
        if not axes:
            axes = plt.gca()
        axes.errorbar(self.angles.value, self.fov(self.energies[energy_index].value, kind=kind), 
                      yerr=self.fov_error(self.energies[energy_index].value, kind=kind), fmt='o-',
                      label=plot_label)
        axes.set_xlabel(str(self.angles.unit))
        axes.set_title(self.names[type_index])
    def contourf(self, kind='pan', axes=None):
        if not axes:
            axes = plt.gca()
        type_index = np.where(self._typeindex == kind)[0][0]
        cs = axes.contourf(self.energies, self.angles, self.data[type_index, :, :], levels=np.arange(0, np.max(self.data) * 1.2, 1))
        axes.set_xlabel(self.energies.unit)
        axes.set_ylabel(self.angles.unit)
        axes.set_title(self.names[type_index])
        plt.colorbar(cs, ax=axes)
    def export(self):
        for i, kind in enumerate(['pan', 'tilt']):
            header = "Module X" + str(self.number) + ' ' + kind + '\n'
            header += "row 0 are off axis angle in arcmin\n"
            header += "row 1+ are effective area in cm2"
            filename = os.path.basename(self.files[i]).replace(' ', '_').replace('xlsx', 'txt').replace('(', '').replace(')', '')
            array = np.vstack([self.energies.value, self.data[0, :, :]])
            array = np.vstack([self.angles.value, array.transpose()])
            np.savetxt(filename, array, header=header, delimiter=',')

In [717]:
module_filenames = ['Module X-' + str(num) + '*.xlsx' for num in [0, 1, 2, 3, 4, 5, 6]]

In [718]:
modules = []
for i, f in enumerate(module_filenames):
    modules.append(effarea_file(f))

In [719]:
for module in modules:
    module.export()


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-719-c16c42fbde8c> in <module>()
      1 for module in modules:
----> 2     module.export()

<ipython-input-716-69d24020ac84> in export(self)
    105             filename = os.path.basename(self.files[i]).replace(' ', '_').replace('xlsx', 'txt').replace('(', '').replace(')', '')
    106             array = np.vstack([self.energies.value, self.data[0, :, :]])
--> 107             array = np.hstack([self.angles.value, array.transpose()])
    108             np.savetxt(filename, array, header=header, delimiter=',')

/Users/schriste/anaconda/lib/python2.7/site-packages/numpy/core/shape_base.pyc in hstack(tup)
    273     # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    274     if arrs[0].ndim == 1:
--> 275         return _nx.concatenate(arrs, 0)
    276     else:
    277         return _nx.concatenate(arrs, 1)

ValueError: all the input arrays must have same number of dimensions

In [704]:
modules[0].energies.value.shape


Out[704]:
(13,)

In [706]:
modules[0].data[0,:,:].transpose().shape


Out[706]:
(13, 11)

In [732]:
arr = np.vstack([modules[0].energies.value, modules[0].data[0, :, :]])
#np.vstack([modules[0].angles.value, arr])
a = np.concatenate(np.array(0), modules[0].angles.value)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-732-894573e56a9c> in <module>()
      1 arr = np.vstack([modules[0].energies.value, modules[0].data[0, :, :]])
      2 #np.vstack([modules[0].angles.value, arr])
----> 3 a = np.concatenate(np.array(0), modules[0].angles.value)

TypeError: only length-1 arrays can be converted to Python scalars

In [729]:
a


Out[729]:
[0, array([-9., -7., -5., -3., -1.,  0.,  1.,  3.,  5.,  7.,  9.])]

In [623]:
fig, axs = plt.subplots(1,2)
fig.set_size_inches(20, 5)
modules[0].contourf(kind='pan', axes=axs[0])
modules[0].contourf(kind='tilt', axes=axs[1])



In [624]:
fig, axs = plt.subplots(1,2)
fig.set_size_inches(20, 5)
for i, kind in enumerate(['pan', 'tilt']):
    for angle in modules[0].angles.value:
        modules[0].plot_effective_area(angle, axes=axs[i], kind=kind)
        axs[i].legend()



In [625]:
fig, axs = plt.subplots(1,2)
fig.set_size_inches(20, 5)
for i, kind in enumerate(['pan', 'tilt']):
    for j in np.arange(0, len(modules[0].energies), 3):
        modules[0].plot_fov(j, kind=kind, axes=axs[i])
        axs[i].legend()



In [631]:
fig, axs = plt.subplots(len(module_filenames), 2)
fig.set_size_inches((20, 6 * len(module_filenames)))
for j, kind in enumerate(['pan', 'tilt']):
    for i, module in enumerate(modules):
        module.contourf(axes=axs[i, j], kind=kind)



In [638]:
fig, axs = plt.subplots(len(modules[0].angles), 2)
fig.set_size_inches(20, 5 * len(modules[0].angles))
for i, angle in enumerate(modules[0].angles.value):
    for j, kind in enumerate(['pan', 'tilt']):
        for module in modules:
            axes = module.plot_effective_area(angle, axes=axs[i, j], kind=kind)
            axs[i, j].legend()



In [ ]: