maps.py 11.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
------------------------------------------------------
Utility functions for handling mirror surface
maps. Some functions based on earlier version
in Matlab (http://www.gwoptics.org/simtools/)
Work in progress, currently these functions are
untested!

http://www.gwoptics.org/pykat/
------------------------------------------------------
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

16
from pykat.optics.romhom import makeReducedBasis, makeEmpiricalInterpolant, makeWeights
17
from scipy.interpolate import interp2d
Daniel Brown's avatar
Daniel Brown committed
18
import numpy as np
19
import math
20
from pykat.math.zernike import *        
Daniel Brown's avatar
Daniel Brown committed
21
		   
Daniel Brown's avatar
Daniel Brown committed
22
class surfacemap(object):
23
24
25
26
27
28
29
    def __init__(self, name, maptype, size, center, step_size, scaling, data=None):
        
        self.name = name
        self.type = maptype
        self.center = center
        self.step_size = step_size
        self.scaling = scaling
30
31
        self.__interp = None
        
32
        if data is None:
Daniel Brown's avatar
Daniel Brown committed
33
34
35
36
            self.data = np.zeros(size)
        else:
            self.data = data

37
        self._rom_weights = None
38
39
40
41
42
43
44
        
    def write_map(self, filename):
        with open(filename,'w') as mapfile:
            
            mapfile.write("% Surface map\n")
            mapfile.write("% Name: {0}\n".format(self.name))
            mapfile.write("% Type: {0}\n".format(self.type))
45
            mapfile.write("% Size: {0} {1}\n".format(self.data.shape[0], self.data.shape[1]))
46
47
48
49
50
51
52
53
54
55
            mapfile.write("% Optical center (x,y): {0} {1}\n".format(self.center[0], self.center[1]))
            mapfile.write("% Step size (x,y): {0} {1}\n".format(self.step_size[0], self.step_size[1]))
            mapfile.write("% Scaling: {0}\n".format(float(self.scaling)))
            mapfile.write("\n\n")
            
            for i in range(0, self.data.shape[0]):
                for j in range(0, self.data.shape[1]):
                    mapfile.write("%.15g " % self.data[i,j])
                mapfile.write("\n")
    
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    @property
    def data(self):
        return self.__data
    
    @data.setter
    def data(self, value):
        self.__data = value
        self.__interp = None
    
    @property
    def center(self):
        return self.__center
    
    @center.setter
    def center(self, value):
        self.__center = value
        self.__interp = None
    
    @property
    def step_size(self):
        return self.__step_size
    
    @step_size.setter
    def step_size(self, value):
        self.__step_size = value
        self.__interp = None

    @property
    def scaling(self):
        return self.__scaling
    
    @scaling.setter
    def scaling(self, value):
        self.__scaling = value
        self.__interp = None

Daniel Brown's avatar
Daniel Brown committed
92
93
    @property
    def x(self):
Daniel Brown's avatar
Daniel Brown committed
94
        return self.step_size[0] * (np.array(range(1, self.data.shape[0]+1)) - self.center[0])
Daniel Brown's avatar
Daniel Brown committed
95
96
97
        
    @property
    def y(self):
Daniel Brown's avatar
Daniel Brown committed
98
        return self.step_size[1] * (np.array(range(1, self.data.shape[1]+1))- self.center[1])
99
100
101
102
103

    @property
    def size(self):
        return self.data.shape
            
104
105
    @property
    def offset(self):
Daniel Brown's avatar
Daniel Brown committed
106
        return np.array(self.step_size)*(np.array(self.center) - 1/2. - np.array(self.size)/2.0)
107
108
109
110
    
    @property
    def ROMWeights(self):
        return self._rom_weights
111
    
112
    def z_xy(self, x=None, y=None, wavelength=1064e-9, direction="reflection", nr1=1.0, nr2=1.0):
113
        
114
        if x is None and y is None:
115
116
            data = self.scaling * self.data
        else:
117
            if self.__interp is None:
118
119
120
121
                self.__interp = interp2d(self.x, self.y, self.data * self.scaling)
                
            data = self.__interp(x, y)
            
122
123
124
        if direction == "reflection":
            if "phase" in self.type:
                k = math.pi * 2 / wavelength
125
126
                return np.exp(2j * k * data)
                
127
            elif "absorption" in self.type:
128
129
                return np.sqrt(1.0 - data)
                
130
131
132
133
134
            else:
                raise BasePyKatException("Map type needs handling")
        elif direction == "transmission":
            if "phase" in self.type:
                k = math.pi * 2 / wavelength
135
136
                return np.exp((nr1-nr2)*k * data)
                
137
            elif "absorption" in self.type:
138
139
                return np.sqrt(1.0 - data)
                
140
141
            else:
                raise BasePyKatException("Map type needs handling")
142
143
144
        else:
            raise BasePyKatException("Map type needs handling")
        
Daniel Brown's avatar
Daniel Brown committed
145

146
    def generateROMWeights(self, isModeMatched=True, verbose=False, interpolate=False, interpolate_N=None, tolerance = 1e-12, sigma = 1, sort=False, greedyfile=None, useSymmetry=True):
Daniel Brown's avatar
Daniel Brown committed
147
148
149
150
151
152
        
        if interpolate:
            from scipy.interpolate import interp2d
            import numpy as np

            D = interp2d(self.x, self.y, self.data, fill_value=0)
Daniel Brown's avatar
Daniel Brown committed
153
154
155
            if interpolate_N is None:
                interpolate_N = (self.size[0], self.size[1])
                
Daniel Brown's avatar
Daniel Brown committed
156
157
            # only want even number of data points spread equally
            # about the axes
Daniel Brown's avatar
Daniel Brown committed
158
159
            if interpolate_N[0] % 2 == 0:
                Nx = interpolate_N[0]
Daniel Brown's avatar
Daniel Brown committed
160
            else:
Daniel Brown's avatar
Daniel Brown committed
161
                Nx = interpolate_N[0]-1
Daniel Brown's avatar
Daniel Brown committed
162

Daniel Brown's avatar
Daniel Brown committed
163
164
            if interpolate_N[1] % 2 == 0:
                Ny = interpolate_N[1]
Daniel Brown's avatar
Daniel Brown committed
165
            else:
Daniel Brown's avatar
Daniel Brown committed
166
                Ny = interpolate_N[1]-1
Daniel Brown's avatar
Daniel Brown committed
167
            
Daniel Brown's avatar
Daniel Brown committed
168
169
            nx = np.linspace(min(self.x), max(self.x), interpolate_N[0]) 
            ny = np.linspace(min(self.y), max(self.y), interpolate_N[1])
Daniel Brown's avatar
Daniel Brown committed
170
171
172
173
174
175
176
177
            
            data = D(nx-self.offset[0], ny-self.offset[0])
            
            self.name += " [ROMHOM interpolated]"
            
            self.center = (np.array(data.shape)+1)/2.0
            
            self.data = data
178
179
180
181
182
183
184
    
        if useSymmetry:
            xm = self.x[self.x<0]
            ym = self.y[self.y<0]
        else:
            xm = self.x
            ym = self.y
Daniel Brown's avatar
Daniel Brown committed
185
186
187
        
        if min(xm) == min(ym) and max(xm) == max(ym) and len(xm) == len(ym):
            symm = True
188
189
190
        else:
            symm = False
            
Daniel Brown's avatar
Daniel Brown committed
191
192
        EI = {}
        
193
        EI["x"] = makeEmpiricalInterpolant(makeReducedBasis(xm, isModeMatched=isModeMatched, tolerance = tolerance, sigma = sigma, greedyfile=greedyfile), sort=sort)
Daniel Brown's avatar
Daniel Brown committed
194
195
        
        if symm:
196
            EI["y"] = EI["x"]
Daniel Brown's avatar
Daniel Brown committed
197
        else:
198
            EI["y"] = makeEmpiricalInterpolant(makeReducedBasis(ym, isModeMatched=isModeMatched, tolerance = tolerance, sigma = sigma, greedyfile=greedyfile), sort=sort)
Daniel Brown's avatar
Daniel Brown committed
199
        
200
        EI["limits"] = EI["x"].limits
Daniel Brown's avatar
Daniel Brown committed
201
        
202
        self._rom_weights = makeWeights(self, EI, verbose=verbose, useSymmetry=useSymmetry)
203
        
204
        return self.ROMWeights, EI
205
        
206
    def plot(self, show=True, clabel=None, xlim=None, ylim=None):
207
208
209
        
        import pylab
        
210
        if xlim is not None:
211
212
213
214
215
216
217
218
            _x = np.logical_and(self.x<=max(xlim)/100.0, self.x>=min(xlim)/100.0)
            xmin = np.min(np.where(_x == True))
            xmax = np.max(np.where(_x == True))
        else:
            xmin = 0
            xmax = len(self.x)-1
            xlim = [self.x.min()*100, self.x.max()*100]
    
219
        if ylim is not None:
220
221
222
223
224
225
226
227
228
229
230
            _y = np.logical_and(self.y<=max(ylim)/100.0, self.y>=min(ylim)/100.0)
            ymin = np.min(np.where(_y == True))
            ymax = np.max(np.where(_y == True))
        else:
            ymin = 0
            ymax = len(self.y)-1
            ylim = [self.y.min()*100, self.y.max()*100]
        
        zmin = self.data[xmin:xmax,ymin:ymax].min()
        zmax = self.data[xmin:xmax,ymin:ymax].max()

231
        # 100 factor for scaling to cm
Daniel Brown's avatar
Daniel Brown committed
232
233
        xrange = 100*self.x
        yrange = 100*self.y
234

235
        fig = pylab.figure()
236
        axes = pylab.pcolormesh(xrange, yrange, self.data, vmin=zmin, vmax=zmax)
237
238
        pylab.xlabel('x [cm]')
        pylab.ylabel('y [cm]')
239

240
241
        if xlim is not None: pylab.xlim(xlim)
        if ylim is not None: pylab.ylim(ylim)
242

243
        pylab.title('Surface map {0}, type {1}'.format(self.name, self.type))
244

245
        cbar = fig.colorbar(axes)
246
        cbar.set_clim(zmin, zmax)
247
        
248
        if clabel is not None:
249
            cbar.set_label(clabel)
250
    
251
252
        if show:
            pylab.show()
253
        
254
        return fig
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        
class aperturemap(surfacemap):
    
    def __init__(self, name, size, step_size, R):
        surfacemap.__init__(self, name, "absorption both", size, (np.array(size)+1)/2.0, step_size, 1)
        self.R = R
        
    @property
    def R(self):
        return self.__R
    
    @R.setter
    def R(self, value):
        self.__R = value
    
        xx, yy = np.meshgrid(self.x, self.y)
        
        radius = np.sqrt(xx**2 + yy**2)
        
        self.data = np.zeros(self.size)
        self.data[radius > self.R] = 1.0
        
        
class curvedmap(surfacemap):
    
    def __init__(self, name, size, step_size, Rc):
        surfacemap.__init__(self, name, "phase reflection", size, (np.array(size)+1)/2.0, step_size, 1e-6)
        self.Rc = Rc
        
    @property
    def Rc(self):
        return self.__Rc
    
    @Rc.setter
    def Rc(self, value):
        self.__Rc = value
    
        xx, yy = np.meshgrid(self.x, self.y)
        
        Rsq = xx**2 + yy**2
        self.data = (self.Rc - math.copysign(1.0, self.Rc) * np.sqrt(self.Rc**2 - Rsq))/ self.scaling
Daniel Brown's avatar
Daniel Brown committed
296
297
298
299

class tiltmap(surfacemap):
    
    def __init__(self, name, size, step_size, tilt):
Daniel Brown's avatar
Daniel Brown committed
300
        surfacemap.__init__(self, name, "phase reflection", size, (np.array(size)+1)/2.0, step_size, 1e-9)
Daniel Brown's avatar
Daniel Brown committed
301
302
303
304
305
306
307
308
309
310
311
312
        self.tilt = tilt
        
    @property
    def tilt(self):
        return self.__tilt
    
    @tilt.setter
    def tilt(self, value):
        self.__tilt = value
        
        xx, yy = np.meshgrid(self.x, self.y)
        
313
        self.data = (yy * self.tilt[1] + xx * self.tilt[0])/self.scaling
Daniel Brown's avatar
Daniel Brown committed
314
        
Daniel Brown's avatar
Daniel Brown committed
315
316
317

class zernikemap(surfacemap):
	def __init__(self, name, size, step_size, radius, scaling=1e-9):
Daniel Brown's avatar
Daniel Brown committed
318
		surfacemap.__init__(self, name, "phase reflection", size, (np.array(size)+1)/2.0, step_size, scaling)
Daniel Brown's avatar
Daniel Brown committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
		self.__zernikes = {}
		self.radius = radius
		
	@property
	def radius(self): return self.__radius

	@radius.setter
	def radius(self, value, update=True):
		self.__radius = float(value)
		if update: self.update_data()

	def setZernike(self, m, n, amplitude, update=True):
		self.__zernikes["%i%i" % (m, n)] = (m,n,amplitude)
		if update: self.update_data()

	def update_data(self):
		X,Y = np.meshgrid(self.x, self.y)
		R = np.sqrt(X**2 + Y**2)
		PHI = np.arctan2(Y, X)

		data = np.zeros(np.shape(R))

		for i in self.__zernikes.items():
			data += i[1][2] * zernike(i[1][0], i[1][1], R/self.radius, PHI)

		self.data = data
	
			
	
348
349
350
351
352
353
354
355
356
357
358
359
360
def read_map(filename):
    with open(filename, 'r') as f:
        
        f.readline()
        name = f.readline().split(':')[1].strip()
        maptype = f.readline().split(':')[1].strip()
        size = tuple(map(lambda x: int(x), f.readline().split(':')[1].strip().split()))
        center = tuple(map(lambda x: float(x), f.readline().split(':')[1].strip().split()))
        step = tuple(map(lambda x: float(x), f.readline().split(':')[1].strip().split()))
        scaling = float(f.readline().split(':')[1].strip())
        
        
        
Daniel Brown's avatar
Daniel Brown committed
361
    data = np.loadtxt(filename, dtype=np.float64,ndmin=2,comments='%')    
362
363
364
365
366
        
    return surfacemap(name,maptype,size,center,step,scaling,data)
    
    
        
367