1 """
2 Template
3 """
4
5 import li
6 import numpy as np
7 import copy as pythoncopy
8 from scipy.optimize import leastsq
9
11 """Groups lines from which we create a template gaussian flux"""
12 - def __init__(self, linelist = None, plotcolour="black", dashes=(5,5)):
13 if linelist == None:
14 linelist = []
15 self.linelist = linelist
16
17 self.plotcolour = plotcolour
18 self.dashes = dashes
19
21 """Returns a copy of the object"""
22 return pythoncopy.deepcopy(self)
23
25 """gives the flux at wavelength l, corresponding to the sum of all the lines"""
26 retflux = 0.0
27 for line in self.linelist:
28 retflux += line.flux_gauss(l)
29 return retflux
30
32 """sets the same redshift for all the lines in the template"""
33 for line in self.linelist:
34 line.setz(z)
35
36 """
37 #the two next functions can be used if you want to fit not only the height of the template, but also its width ; the optimize function should works functions
38 def getparam(self):
39 param = np.array([])
40 for line in self.linelist:
41 param = np.append(param, [line.height, line.width])
42 return param
43
44 def setparam(self, param):
45 for i in range(len(param)/2):
46 self.linelist[i].height = param[2 * i]
47 self.linelist[i].width = param[2 * i + 1]
48 """
49
51 """returns a list containing the height of each line in the template"""
52 param = np.array([])
53 for line in self.linelist:
54 param = np.append(param, line.height)
55 return param
56
58 """it takes a list of heights which are set in the lines"""
59 for i in range(len(param)):
60 self.linelist[i].height = param[i]
61
62
63 - def optimize(self, sp, fluxchoice, withmask = True):
64 """optimize the template to fit with the spectra (the parameters are the heights of the lines)"""
65 a = []
66 for line in self.linelist:
67 a.append(line.angst)
68 minangst = min(a)
69 maxangst = max(a)
70
71 index1 = sp.angsttopix(minangst-100)
72 index2 = sp.angsttopix(maxangst+100)
73 size = len(sp.allfluxes[fluxchoice])
74 if index1 < 0:
75 index1 = 0
76
77 if index2 > size:
78 index2 = size
79
80 x = sp.angst[index1:index2]
81 a = sp.allfluxes[fluxchoice].copy()
82 if withmask:
83 a[sp.mask] = 0
84 y = a[index1:index2]
85
86 if len(x) > 10:
87 p0 = self.getparam()
88
89 def f(x, p):
90 self.setparam(p)
91 return self.flux_gauss(x)
92 def residus(p,y,x):
93 return y-f(x,p)
94
95 result = leastsq(residus, p0, args=(y, x), maxfev=20000)
96 self.setparam(result[0])
97
99 """factory function for template : from a list of tuples (with 4 items), it returns a template"""
100
101 newlines = template()
102
103 for item in tuplelist:
104 newline = li.line(item[0], item[1], item[2], item[3])
105 newlines.linelist.append(newline)
106
107 return newlines
108