maps.py 18.1 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
17
18
19
from pykat.optics.romhom import makeReducedBasis, makeEmpiricalInterpolant, makeWeights, makeWeightsNew
from scipy.interpolate import interp2d, interp1d
from pykat.maths.zernike import *        

Daniel Brown's avatar
Daniel Brown committed
20
import numpy as np
21
import math
22
import pickle
Daniel Brown's avatar
Daniel Brown committed
23
		   
Daniel Brown's avatar
Daniel Brown committed
24
class surfacemap(object):
25
26
27
28
29
30
31
    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
32
33
        self.__interp = None
        
34
        if data is None:
Daniel Brown's avatar
Daniel Brown committed
35
36
37
38
            self.data = np.zeros(size)
        else:
            self.data = data

39
        self._rom_weights = None
40
41
42
43
44
45
46
        
    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))
47
            mapfile.write("% Size: {0} {1}\n".format(self.data.shape[0], self.data.shape[1]))
48
49
50
51
52
53
54
55
56
57
            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")
    
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
92
93
    @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
94
95
    @property
    def x(self):
Daniel Brown's avatar
Daniel Brown committed
96
        return self.step_size[0] * (np.array(range(1, self.data.shape[0]+1)) - self.center[0])
Daniel Brown's avatar
Daniel Brown committed
97
98
99
        
    @property
    def y(self):
Daniel Brown's avatar
Daniel Brown committed
100
        return self.step_size[1] * (np.array(range(1, self.data.shape[1]+1))- self.center[1])
101
102
103
104
105

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

148
    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
149
150
151
152
153
154
        
        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
155
156
157
            if interpolate_N is None:
                interpolate_N = (self.size[0], self.size[1])
                
Daniel Brown's avatar
Daniel Brown committed
158
159
            # only want even number of data points spread equally
            # about the axes
Daniel Brown's avatar
Daniel Brown committed
160
161
            if interpolate_N[0] % 2 == 0:
                Nx = interpolate_N[0]
Daniel Brown's avatar
Daniel Brown committed
162
            else:
Daniel Brown's avatar
Daniel Brown committed
163
                Nx = interpolate_N[0]-1
Daniel Brown's avatar
Daniel Brown committed
164

Daniel Brown's avatar
Daniel Brown committed
165
166
            if interpolate_N[1] % 2 == 0:
                Ny = interpolate_N[1]
Daniel Brown's avatar
Daniel Brown committed
167
            else:
Daniel Brown's avatar
Daniel Brown committed
168
                Ny = interpolate_N[1]-1
Daniel Brown's avatar
Daniel Brown committed
169
            
Daniel Brown's avatar
Daniel Brown committed
170
171
            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
172
173
174
            
            data = D(nx-self.offset[0], ny-self.offset[0])
            
175
            self.name += "[ROMHOM_Interpolated]"
Daniel Brown's avatar
Daniel Brown committed
176
177
178
179
            
            self.center = (np.array(data.shape)+1)/2.0
            
            self.data = data
180
181
182
183
184
185
186
    
        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
187
188
189
        
        if min(xm) == min(ym) and max(xm) == max(ym) and len(xm) == len(ym):
            symm = True
190
191
192
        else:
            symm = False
            
Daniel Brown's avatar
Daniel Brown committed
193
194
        EI = {}
        
195
        EI["x"] = makeEmpiricalInterpolant(makeReducedBasis(xm, isModeMatched=isModeMatched, tolerance = tolerance, sigma = sigma, greedyfile=greedyfile), sort=sort)
Daniel Brown's avatar
Daniel Brown committed
196
197
        
        if symm:
198
            EI["y"] = EI["x"]
Daniel Brown's avatar
Daniel Brown committed
199
        else:
200
            EI["y"] = makeEmpiricalInterpolant(makeReducedBasis(ym, isModeMatched=isModeMatched, tolerance = tolerance, sigma = sigma, greedyfile=greedyfile), sort=sort)
Daniel Brown's avatar
Daniel Brown committed
201
        
202
        EI["limits"] = EI["x"].limits
Daniel Brown's avatar
Daniel Brown committed
203
        
204
        self._rom_weights = makeWeights(self, EI, verbose=verbose, useSymmetry=useSymmetry)
205
        
206
        return self.ROMWeights, EI
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    
    
    def generateROMWeightsNew(self, EIxFilename, EIyFilename=None, verbose=False, interpolate=False):
        if interpolate == True:
            # Use EI nodes to interpolate if we
            with open(EIxFilename, 'rb') as f:
                EIx = pickle.load(f)

            if EIyFilename is None:
                EIy = EIx
            else:
                with open(EIyFilename, 'rb') as f:
                    EIy = pickle.load(f)

            x = EIx.x
            x.sort()
            nx = np.unique(np.hstack((x, -x[::-1])))
        
            y = EIy.x
            y.sort()
            ny = np.unique(np.hstack((y, -y[::-1])))
            
            self.interpolate(nx, ny)
        
        self._rom_weights = makeWeightsNew(self, EIxFilename, EIyFilename, verbose=verbose)
        return self.ROMWeights

    def interpolate(self, nx, ny, **kwargs):
        """
        Interpolates the map for some new x and y values.
237
        
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
        Uses scipy.interpolate.interp2d and any keywords arguments are
        passed on to it, thus settings like interpolation type and
        fill values can be set.
        
        The range of nx and ny must contain the value zero so that the
        center point of the map can be set.
        """

        D = interp2d(self.x, self.y, self.data, **kwargs)
        
        data = D(nx-self.offset[0], ny-self.offset[0])
        
        Dx = interp1d(nx, np.arange(1,len(nx)+1))
        Dy = interp1d(ny, np.arange(1,len(ny)+1))
        
        self.center = (Dx(0), Dy(0))
        self.step_size = (nx[1]-nx[0], ny[1]-ny[0])
        self.data = data

257
    def plot(self, show=True, clabel=None, xlim=None, ylim=None):
258
259
260
        
        import pylab
        
261
        if xlim is not None:
262
263
264
265
266
267
268
269
            _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]
    
270
        if ylim is not None:
271
272
273
274
275
276
277
278
279
280
281
            _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()

282
        # 100 factor for scaling to cm
Daniel Brown's avatar
Daniel Brown committed
283
284
        xrange = 100*self.x
        yrange = 100*self.y
285

286
        fig = pylab.figure()
287
        axes = pylab.pcolormesh(xrange, yrange, self.data, vmin=zmin, vmax=zmax)
288
289
        pylab.xlabel('x [cm]')
        pylab.ylabel('y [cm]')
290

291
292
        if xlim is not None: pylab.xlim(xlim)
        if ylim is not None: pylab.ylim(ylim)
293

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

296
        cbar = fig.colorbar(axes)
297
        cbar.set_clim(zmin, zmax)
298
        
299
        if clabel is not None:
300
            cbar.set_label(clabel)
301
    
302
303
        if show:
            pylab.show()
304
        
305
        return fig
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

class mergedmap:
    """
    A merged map combines multiple surfaces map to form one. Such a map can be used
    for computations of coupling coefficients but it cannot be written to a file to 
    be used with Finesse. For this you must output each map separately.
    
    """
    
    def __init__(self, name, size, center, step_size, scaling):
        
        self.name = name
        self.center = center
        self.step_size = step_size
        self.scaling = scaling
        self.__interp = None
        self._rom_weights = None
        self.__maps = []
324
325
        self.weighting = None
        
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    def addMap(self, m):
        self.__maps.append(m)
    
    @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
    
    @property
    def x(self):
        return self.step_size[0] * (np.array(range(1, self.size[0]+1)) - self.center[0])
        
    @property
    def y(self):
        return self.step_size[1] * (np.array(range(1, self.size[1]+1))- self.center[1])

    @property
    def size(self):
        return self.__maps[0].data.shape
            
    @property
    def offset(self):
        return np.array(self.step_size)*(np.array(self.center) - 1/2. - np.array(self.size)/2.0)
    
    @property
    def ROMWeights(self):
        return self._rom_weights
    
    def z_xy(self, wavelength=1064e-9, direction="reflection", nr1=1.0, nr2=1.0):
        
        z_xy = np.ones(self.size, dtype=np.complex128)
        
        for m in self.__maps:
            z_xy *= m.z_xy(wavelength=wavelength, direction=direction, nr1=nr1, nr2=nr2)
            
383
384
385
386
        if self.weighting is None:
            return z_xy
        else:
            return z_xy * self.weighting
387
        
388
    def generateROMWeights(self, EIxFilename, EIyFilename=None, verbose=False, interpolate=False, newtonCotesOrder=8):
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
        if interpolate == True:
            # Use EI nodes to interpolate if we
            with open(EIxFilename, 'rb') as f:
                EIx = pickle.load(f)

            if EIyFilename is None:
                EIy = EIx
            else:
                with open(EIyFilename, 'rb') as f:
                    EIy = pickle.load(f)

            x = EIx.x
            x.sort()
            nx = np.unique(np.hstack((x, -x[::-1])))
        
            y = EIy.x
            y.sort()
            ny = np.unique(np.hstack((y, -y[::-1])))
            
            self.interpolate(nx, ny)
        
410
        self._rom_weights = makeWeightsNew(self, EIxFilename, EIyFilename, verbose=verbose, newtonCotesOrderMapWeight=newtonCotesOrder)
411
        
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
        return self.ROMWeights

    def interpolate(self, nx, ny, **kwargs):
        """
        Interpolates all the maps that are used to fc
        
        Uses scipy.interpolate.interp2d and any keywords arguments are
        passed on to it, thus settings like interpolation type and
        fill values can be set.
        
        The range of nx and ny must contain the value zero so that the
        center point of the map can be set.
        """

        for m in self.__maps:
            m.interpolate(nx, ny)

    def plot(self, mode="absorption", show=True, clabel=None, xlim=None, ylim=None, wavelength=1064e-9):
        
        import pylab
        
        if xlim is not None:
            _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]
    
        if ylim is not None:
            _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]

        if mode == "absorption":
            # plots how much of field is absorbed
            data = 1-np.abs(self.z_xy())
        elif mode == "meter":
            # plot the phase in terms of meters of displacement
            k = 2*np.pi/wavelength
            data = np.angle(self.z_xy()) / (2*k)
            
        zmin = data[xmin:xmax,ymin:ymax].min()
        zmax = data[xmin:xmax,ymin:ymax].max()

        # 100 factor for scaling to cm
        xrange = 100*self.x
        yrange = 100*self.y

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

        if xlim is not None: pylab.xlim(xlim)
        if ylim is not None: pylab.ylim(ylim)

        pylab.title('Merged map {0}, mode {1}'.format(self.name, mode))

        cbar = fig.colorbar(axes)
        cbar.set_clim(zmin, zmax)
478
        
479
480
481
482
483
484
485
486
        if clabel is not None:
            cbar.set_label(clabel)
    
        if show:
            pylab.show()
        
        return fig

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
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
527
528
529
530

class tiltmap(surfacemap):
    
    def __init__(self, name, size, step_size, tilt):
Daniel Brown's avatar
Daniel Brown committed
531
        surfacemap.__init__(self, name, "phase reflection", size, (np.array(size)+1)/2.0, step_size, 1e-9)
Daniel Brown's avatar
Daniel Brown committed
532
533
534
535
536
537
538
539
540
541
542
543
        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)
        
544
        self.data = (yy * self.tilt[1] + xx * self.tilt[0])/self.scaling
Daniel Brown's avatar
Daniel Brown committed
545
        
Daniel Brown's avatar
Daniel Brown committed
546
547
548

class zernikemap(surfacemap):
	def __init__(self, name, size, step_size, radius, scaling=1e-9):
Daniel Brown's avatar
Daniel Brown committed
549
		surfacemap.__init__(self, name, "phase reflection", size, (np.array(size)+1)/2.0, step_size, scaling)
Daniel Brown's avatar
Daniel Brown committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
		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
	
			
	
579
580
581
582
583
584
def read_map(filename):
    with open(filename, 'r') as f:
        
        f.readline()
        name = f.readline().split(':')[1].strip()
        maptype = f.readline().split(':')[1].strip()
Daniel Brown's avatar
Daniel Brown committed
585
        size = tuple(map(lambda x: float(x), f.readline().split(':')[1].strip().split()))
586
587
588
589
590
591
        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
592
    data = np.loadtxt(filename, dtype=np.float64,ndmin=2,comments='%')    
593
594
595
596
597
        
    return surfacemap(name,maptype,size,center,step,scaling,data)
    
    
        
598