dicdata.py

Also download ascii file bellow to run script - Buehler Rolf, 07/22/2014 04:11 PM

Download (2.16 KB)

 
1
#! /usr/bin/env python 
2
# ================================================================
3
# This class stores/plots/prints/manipulates data given as a python
4
# dictionary of form:
5
#
6
# dict = {"parameter1":{"value":[..],"eu_value":[..],"ed_value":[..],
7
# "unit":[..]}, "parameter2",...}
8
#
9
# Author: Rolf Buehler (rolf.buehler@desy.de)
10
# Date: 22.7.2014
11
# ================================================================
12

    
13
import astropy.table as apytab
14
import json
15
import matplotlib.pyplot as plt
16
from astropy.io import ascii
17

    
18
class dicdata:
19
    "Class to store spectra"
20
    def __init__(self):
21
        self.data=apytab.Table()
22
    def adddic(self,dic):
23
        "Adds dictionary to data"
24
        for key in dic:
25
            self.data[key]       = apytab.Column(dic[key]["value"], unit=dic[key]["unit"])
26
            if len(dic[key]["eu_value"])==len(dic[key]["value"]):
27
                self.data["eu_"+key] = apytab.Column(dic[key]["eu_value"], unit=dic[key]["unit"])
28
            if len(dic[key]["ed_value"])==len(dic[key]["value"]):
29
                self.data["ed_"+key] = apytab.Column(dic[key]["ed_value"], unit=dic[key]["unit"])
30
    def addjson(self,filename):
31
        "Adds json file to data"
32
        json_data=open(filename)
33
        self.adddic(json.load(json_data))
34
    def printout(self):
35
        "Prints table out"
36
        print self.data
37
    def draw(self,xvar,yvar,log=True,fmt="o"):
38
        "Draws spectrum data"
39
        if log:
40
            plt.xscale('log')
41
            plt.yscale('log')
42
        plt.xlabel(xvar+" ["+str(self.data[xvar].unit)+"]")
43
        plt.ylabel(yvar+" ["+str(self.data[yvar].unit)+"]")
44
        
45
        plt.errorbar(self.data[xvar],self.data[yvar], xerr=[self.data["ed_"+xvar],self.data["eu_"+xvar]],
46
                     yerr=[self.data["ed_"+yvar],self.data["eu_"+yvar]],fmt=fmt)
47
        plt.show()
48
    def writetoascii(self,filename,asciiformat='ipac'):
49
        "Writes data to ascii"
50
        ascii.write(self.data, filename,format=asciiformat)
51

    
52
if __name__ == '__main__':
53
    print "Testing dicdata class.."
54
    specdata = dicdata()
55
    specdata.addjson("spectrum.json")
56
    specdata.printout()
57
    specdata.draw("energy","flux")
58
    specdata.writetoascii("spectrum.ipac")
59