RTModel 2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
RTModel/lib/bumper.cpp ADDED
@@ -0,0 +1,168 @@
1
+ // bumper.cpp
2
+ // Implementation of all methods in bumper.h
3
+
4
+ #define _CRT_SECURE_NO_WARNINGS
5
+ #define _USE_MATH_DEFINES
6
+ #include "bumper.h"
7
+ #include <math.h>
8
+ #include <malloc.h>
9
+
10
+ const double epsilon = 1.e-99;
11
+
12
+ bumper::bumper(double *pr,int ns){
13
+ nps=ns;
14
+ p0=(double *)malloc(sizeof(double)*nps);
15
+ dp=(double *)malloc(sizeof(double)*nps);
16
+ for(int i=0;i<nps;i++){
17
+ p0[i]=pr[i];
18
+ }
19
+ curv=cov=0;
20
+
21
+ next=0;
22
+ }
23
+
24
+ bumper::~bumper(){
25
+ free(p0);
26
+ free(dp);
27
+ if(curv) free(curv);
28
+ if (cov) free(cov);
29
+ }
30
+
31
+ void bumper::SetCurvature(double *sr,double nrm){
32
+ curv=(double *)malloc(sizeof(double)*nps*nps);
33
+ for(int i=0;i<nps*nps;i++){
34
+ curv[i]=sr[i]*nrm;
35
+ }
36
+ }
37
+
38
+ void bumper::SetCovariance(double* sr, double nrm) {
39
+ cov = (double*)malloc(sizeof(double) * nps * nps);
40
+ for (int i = 0; i < nps * nps; i++) {
41
+ cov[i] = sr[i] / nrm;
42
+ }
43
+ //curv = (double*)malloc(sizeof(double) * nps * nps);
44
+ //Inverse(sr, curv, nps);
45
+ }
46
+
47
+ void bumper::UpdateCurvature(double bumperpower){
48
+ for(int i=0;i<nps*nps;i++){
49
+ curv[i]/=(bumperpower*bumperpower);
50
+ }
51
+ }
52
+
53
+ double bumper::distance(double *pr){
54
+ double dist;
55
+ for(int i=0;i<nps;i++){
56
+ dp[i]=pr[i]-p0[i]+epsilon;
57
+ }
58
+ dist=0;
59
+ for(int i=0;i<nps;i++){
60
+ dist+=dp[i]*curv[i*nps+i]*dp[i];
61
+ for(int j=0;j<i;j++){
62
+ dist+=2*dp[i]*curv[i*nps+j]*dp[j];
63
+ }
64
+ }
65
+ return dist;
66
+ }
67
+
68
+ void bumper::signCovariance(int j) {
69
+ for (int i = 0; i < nps; i++) {
70
+ cov[j * nps + i] = -cov[j * nps + i];
71
+ cov[i * nps + j] = -cov[i * nps + j];
72
+ }
73
+ }
74
+
75
+ void bumper::flipCovariance(int i,int j) {
76
+ double sc;
77
+ for (int k = 0; k < nps; k++) {
78
+ sc = cov[k * nps + i];
79
+ cov[k * nps + i] = cov[k * nps + j];
80
+ cov[k * nps + j] = sc;
81
+ }
82
+ for (int k = 0; k < nps; k++) {
83
+ sc = cov[i * nps + k];
84
+ cov[i * nps + k] = cov[j * nps + k];
85
+ cov[j * nps + k] = sc;
86
+ }
87
+ }
88
+
89
+ double Determinant(double *A,int n){
90
+ double *U,L,M;
91
+ double det=1.;
92
+ int iM;
93
+
94
+ U=(double *)malloc(sizeof(double)*n*n);
95
+
96
+ for(int i=0;i<n;i++){
97
+ for(int j=0;j<n;j++){
98
+ U[i*n+j]=A[i*n+j];
99
+ }
100
+ }
101
+
102
+ for(int j=0;j<n-1;j++){
103
+ for(int i=j+1;i<n;i++){
104
+ // find row with largest pivot
105
+ M=0.;
106
+ iM=j;
107
+ for(int i1=j;i1<n;i1++){
108
+ if (M < fabs(U[i1 * n + j])) {
109
+ M = fabs(U[i1 * n + j]);
110
+ iM = i1;
111
+ }
112
+ }
113
+ if(M==0.){
114
+ free(U);
115
+ return 0.;
116
+ }
117
+ // select row with largest pivot as the next to be processed
118
+ for(int j1=j;j1<n;j1++){
119
+ L=U[j*n+j1];
120
+ U[j*n+j1]=U[iM*n+j1];
121
+ U[iM*n+j1]=-L;
122
+ }
123
+
124
+ L = (fabs(U[j * n + j])>1.e-100) ? U[i * n + j] / U[j * n + j] : 1.0;
125
+ for(int k=j;k<n;k++){
126
+ U[i*n+k]-=L*U[j*n+k];
127
+ }
128
+ }
129
+ }
130
+
131
+ for(int i=0;i<n;i++){
132
+ det*=U[i*n+i];
133
+ }
134
+
135
+ free(U);
136
+ return det;
137
+ }
138
+
139
+
140
+ void Inverse(double* source, double* dest, int n) {
141
+ double p1;
142
+ int j1, k1;
143
+ double* minor;
144
+ minor = (double*)malloc(sizeof(double) * (n - 1) * (n - 1));
145
+ p1 = Determinant(source, n)+1.e-100;
146
+ for (int i = 0; i < n; i++) {
147
+ for (int i2 = 0; i2 < n; i2++) {
148
+ for (int j = 0; j < n - 1; j++) {
149
+ for (int k = 0; k < n - 1; k++) {
150
+ j1 = (j < i2) ? j : j + 1;
151
+ k1 = (k < i) ? k : k + 1;
152
+ minor[j * (n - 1) + k] = source[j1 * n + k1];
153
+ }
154
+ }
155
+ dest[i * n + i2] = Determinant(minor, n - 1) / p1 * (((i + i2) % 2) ? 1 : -1);
156
+ }
157
+ }
158
+ free(minor);
159
+ }
160
+
161
+ void CombineCovariances(bumper* scanbumper, bumper* scanbumper2,double *Cov, double *Curv, int nps) {
162
+ for (int i = 0; i < nps; i++) {
163
+ for (int j = 0; j < nps; j++) {
164
+ Cov[i * nps + j] = scanbumper->cov[i * nps + j] + scanbumper2->cov[i * nps + j];
165
+ }
166
+ }
167
+ Inverse(Cov, Curv, nps);
168
+ }
@@ -0,0 +1,5 @@
1
+ __version__ = "2.0.0"
2
+ __author__ = 'Valerio Bozza'
3
+ __credits__ = 'University of Salerno, Italy'
4
+
5
+ from .plotmodel import plotmodel
@@ -0,0 +1,452 @@
1
+ import VBBinaryLensing
2
+ import math
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
5
+ import matplotlib.animation as animation
6
+ from matplotlib.patches import Circle
7
+ import os
8
+ import numpy as np
9
+ import shutil
10
+ from PIL import Image
11
+ from tqdm import tqdm
12
+ import sys
13
+ import inspect
14
+ import glob
15
+
16
+
17
+ class plotmodel:
18
+ def __init__(self, eventname,model = '', tmin = '', tmax = '', referencephot = 0, timesteps = 300, \
19
+ modelfile = None, parameters = [], line = 0,printpars = True, animate = False,interval = 1000, satellitedir = '.'):
20
+ self.satellitedir = satellitedir
21
+ self.parameters = parameters
22
+ filin=inspect.getfile(VBBinaryLensing)
23
+ self.filout= os.path.dirname(filin) + '/data/ESPL.tbl'
24
+ self.eventname = eventname
25
+ self.model = model
26
+ self.tmin = tmin
27
+ self.tmax = tmax
28
+ self.timesteps = timesteps
29
+ self.referencephot = referencephot
30
+ self.modelfile = modelfile
31
+ self.line = line
32
+ self.printpars = printpars
33
+ self.animate = animate
34
+ if(self.model == ''):
35
+ if(modelfile == None):
36
+ print('Please specify a model or a modelfile')
37
+ return
38
+ self.model = os.path.basename(self.modelfile)
39
+ if(modelfile == None and parameters == []):
40
+ print('Please specify model parameters')
41
+ return
42
+ self.vbbl = VBBinaryLensing.VBBinaryLensing()
43
+ # General information on models
44
+ self.modelcodes= ['PS','PX','BS','BO','LS','LX','LO']
45
+ self.npars=[4,6,7,10,7,9,12]
46
+ self.logposs=[[0,1,3],
47
+ [1,3],
48
+ [0,1,6],
49
+ [2,3,9],
50
+ [0,1,4,5],
51
+ [0,1,4,5],
52
+ [0,1,4,5]]
53
+ self.parnames = [['u0','tE','t0','rho'],
54
+ ['u0','tE','t0','rho','piN','piE'],
55
+ ['tE','FR','u01','u02','t0','t02','rho'],
56
+ ['u0','t0','tE','rho','xi1','xi2','om','inc','phi','qs'],
57
+ ['s','q','u0','alpha','rho','tE','t0'],
58
+ ['s','q','u0','alpha','rho','tE','t0','piN','piE'],
59
+ ['s','q','u0','alpha','rho','tE','t0','piN','piE','gamma1','gamma2','gammaz']]
60
+ self.colors = ['blue','red','green','darkorange','magenta','cyan','gray','teal','maroon','gold','lime','darkviolet']
61
+ self.sourcecolor = 'pink'
62
+ self.causticcolor = (0.5,0.5,0.5)
63
+ self.satellitecolors = ['k-','r-','g-','b-','y-']
64
+ self.legendlocation = 'best'
65
+ if(animate):
66
+ self.animateplots(interval = interval)
67
+ else:
68
+ self.readdata()
69
+ self.readparameters()
70
+ self.calculate()
71
+ self.showall()
72
+
73
+ # Reading data from LCToFit.txt
74
+ def readdata(self):
75
+ if(self.eventname== None):
76
+ self.lightcurves = []
77
+ self.telescopes = []
78
+ self.nfil = 0
79
+ self.npoints = 0
80
+ else:
81
+ os.chdir(self.eventname)
82
+ with open('LCToFit.txt') as f:
83
+ self.npoints=int(f.readline())
84
+ ofil=0
85
+ data=[[]]
86
+ while True:
87
+ line=f.readline()
88
+ if(line == ''):
89
+ break
90
+ chunks=line.split(' ')
91
+ self.nfil=int(chunks[0])
92
+ if(self.nfil != ofil):
93
+ data.append([])
94
+ ofil=self.nfil
95
+ data[self.nfil].append([float(chunks[1]),float(chunks[2]),float(chunks[3]),int(chunks[4])])
96
+ self.nfil +=1
97
+ self.lightcurves = [ [np.array([dl[0] for dl in d]),np.array([dl[1] for dl in d]),np.array([dl[2] for dl in d]),d[0][3]] for d in data]
98
+ with open('FilterToData.txt') as f:
99
+ self.telescopes = f.readlines()
100
+ for i in range(0,self.nfil):
101
+ self.telescopes[i] = self.telescopes[i][0:self.telescopes[i].index('.')]
102
+ while(len(self.colors)<self.nfil):
103
+ self.colors.extend(self.colors)
104
+
105
+ # Reading model parameters
106
+ def readparameters(self):
107
+ self.modnumber = self.modelcodes.index(self.model[0:2])
108
+ if(self.eventname != None):
109
+ os.chdir(self.eventname)
110
+ if(self.parameters == []):
111
+ with open(self.modelfile) as f:
112
+ lines = f.readlines()
113
+ self.maxlines = len(lines)
114
+ if(self.line>=self.maxlines):
115
+ return False
116
+ else:
117
+ line = lines[self.line]
118
+ chunks = line.split(' ')
119
+ values = [float(v) for v in chunks]
120
+ self.pars = values[0:self.npars[self.modnumber]]
121
+ self.parsprint=self.pars[:]
122
+ for i in self.logposs[self.modnumber]:
123
+ self.pars[i] = math.log(self.pars[i])
124
+ self.blends = np.array([values[self.npars[self.modnumber]+i*2] for i in range(0,self.nfil)])
125
+ self.sources = np.array([values[self.npars[self.modnumber]+i*2+1] for i in range(0,self.nfil)])
126
+ self.chi2=values[-1]
127
+ #Errors
128
+ if(not self.animate):
129
+ line = lines[self.line +1 ]
130
+ chunks = line.split(' ')
131
+ values = [float(v) for v in chunks]
132
+ self.parerrs = values[0:self.npars[self.modnumber]]
133
+ self.blenderrs = np.array([values[self.npars[self.modnumber]+i*2] for i in range(0,self.nfil)])
134
+ self.sourceerrs = np.array([values[self.npars[self.modnumber]+i*2+1] for i in range(0,self.nfil)])
135
+ return True
136
+ else:
137
+ self.pars = self.parameters[0:self.npars[self.modnumber]]
138
+ self.parsprint=self.pars[:]
139
+ for i in self.logposs[self.modnumber]:
140
+ self.pars[i] = math.log(self.pars[i])
141
+ self.blends = []
142
+ self.sources = []
143
+ self.chi2 = 0
144
+ for i in range(0,self.nfil):
145
+ lc0 = self.lightcurves[i]
146
+ lcarr = np.array(lc0[0:3])
147
+ lctran=np.transpose(lcarr)
148
+ lc = np.transpose(lctran)
149
+ self.t = lc[0]
150
+ self.vbbl.satellite = lc0[3]
151
+ self.lightcurve()
152
+ f = np.array(self.results[0])
153
+ sumf = (f/(lc[2]*lc[2])).sum()
154
+ sumf2 = (f*f/(lc[2]*lc[2])).sum()
155
+ sumsigma =(1/(lc[2]*lc[2])).sum()
156
+ sumy = (lc[1]/(lc[2]*lc[2])).sum()
157
+ sumfy = (f*lc[1]/(lc[2]*lc[2])).sum()
158
+ sumy2 = (lc[1]*lc[1]/(lc[2]*lc[2])).sum()
159
+ p1=sumf*sumf-sumf2*sumsigma + 1.0e-50;
160
+ self.blends.append((sumf*sumfy-sumf2*sumy)/p1)
161
+ self.sources.append((sumf*sumy-sumsigma*sumfy)/p1)
162
+ self.chi2 += sumy2+(sumfy*sumfy*sumsigma+sumf2*sumy*sumy-2*sumf*sumy*sumfy)/p1
163
+
164
+ def lightcurve(self):
165
+ if(self.modnumber < 4):
166
+ self.vbbl.LoadESPLTable(self.filout)
167
+ if(self.modnumber == 1 or self.modnumber > 4):
168
+ self.vbbl.SetObjectCoordinates(glob.glob('Data/*.coordinates')[0],self.satellitedir)
169
+ self.vbbl.parallaxsystem = 1
170
+ if(self.modnumber == 0):
171
+ self.results = self.vbbl.ESPLLightCurve(self.pars,self.t)
172
+ elif(self.modnumber == 1):
173
+ self.results = self.vbbl.ESPLLightCurveParallax(self.pars,self.t)
174
+ elif(self.modnumber == 2):
175
+ self.results = self.vbbl.BinSourceExtLightCurve(self.pars,self.t)
176
+ elif(self.modnumber == 3):
177
+ self.results = self.vbbl.BinSourceSingleLensXallarap(self.pars,self.t)
178
+ elif(self.modnumber == 4):
179
+ self.results = self.vbbl.BinaryLightCurve(self.pars,self.t)
180
+ elif(self.modnumber == 5):
181
+ self.results = self.vbbl.BinaryLightCurveParallax(self.pars,self.t)
182
+ elif(self.modnumber == 6):
183
+ self.results = self.vbbl.BinaryLightCurveOrbital(self.pars,self.t)
184
+
185
+
186
+ def calculate(self):
187
+ # Light curve calculation
188
+ t0i = self.parnames[self.modnumber].index('t0')
189
+ tEi = self.parnames[self.modnumber].index('tE')
190
+ rhoi = self.parnames[self.modnumber].index('rho')
191
+ self.rho = self.parsprint[rhoi]
192
+ if(self.tmin == ''):
193
+ self.tmin = self.pars[t0i]-2*self.parsprint[tEi]
194
+ if(self.tmax == ''):
195
+ self.tmax = self.pars[t0i]+2*self.parsprint[tEi]
196
+
197
+ self.lctimes=[]
198
+ self.lcmags=[]
199
+ self.lcerrs=[]
200
+ self.satellites = []
201
+ for i in range(0,self.nfil):
202
+ lc0 = self.lightcurves[i]
203
+ lcarr = np.array(lc0[0:3])
204
+ lctran=np.transpose(lcarr)
205
+ lcsel = [x for x in lctran if(x[0]<self.tmax and x[0]>self.tmin and (x[1]-self.blends[i])/self.sources[i]*self.sources[self.referencephot] +self.blends[self.referencephot]>0)]
206
+ lc = np.transpose(lcsel)
207
+ if(len(lc)>0):
208
+ self.lctimes.append(lc[0])
209
+ self.lcmags.append(np.array([-2.5*math.log10((y-self.blends[i])/self.sources[i]*self.sources[self.referencephot]+self.blends[self.referencephot]) for y in lc[1]]))
210
+ self.lcerrs.append(lc[2]/lc[1]*2.5/math.log(10.0))
211
+ else:
212
+ self.lctimes.append(np.array([]))
213
+ self.lcmags.append(np.array([]))
214
+ self.lcerrs.append(np.array([]))
215
+ self.satellites.append(lc0[3])
216
+
217
+
218
+ self.t0 = np.linspace(self.tmin,self.tmax,self.timesteps)
219
+ self.usedsatellites = list(set(self.satellites))
220
+ while(len(self.satellitecolors)<len(self.usedsatellites)):
221
+ self.satellitecolors.extend(self.satellitecolors)
222
+ self.minmag = 1000
223
+ self.maxmag = -1000
224
+ self.maxy1 = -1000
225
+ self.maxy2 = -1000
226
+ self.miny1 = 1000
227
+ self.miny2 = 1000
228
+ self.magnifications = []
229
+ self.trajectories = []
230
+ for satellite in self.usedsatellites:
231
+ self.t =self.t0[:]
232
+ for i in range(self.nfil):
233
+ if(self.satellites[i] == satellite):
234
+ self.t = np.concatenate((self.t,self.lctimes[i]))
235
+ self.t = np.sort(self.t)
236
+ self.vbbl.satellite = satellite
237
+ self.lightcurve()
238
+ self.mags = [-2.5*math.log10(self.sources[self.referencephot]*yi+self.blends[self.referencephot]) for yi in self.results[0]]
239
+ self.y1 = self.results[1]
240
+ self.y2 = self.results[2]
241
+ self.magnifications.append([self.t,self.mags])
242
+ self.trajectories.append([self.y1,self.y2])
243
+ minmag = min(self.mags)
244
+ maxmag = max(self.mags)
245
+ self.minmag = min(self.minmag, minmag)
246
+ self.maxmag = max(self.maxmag, maxmag)
247
+ miny = min(self.y1)
248
+ maxy = max(self.y1)
249
+ self.miny1 = min(self.miny1, miny)
250
+ self.maxy1 = max(self.maxy1, maxy)
251
+ miny = min(self.y2)
252
+ maxy = max(self.y2)
253
+ self.miny2 = min(self.miny2, miny)
254
+ self.maxy2 = max(self.maxy2, maxy)
255
+ margin = (self.maxmag-self.minmag)*0.1
256
+ self.minmag -= margin
257
+ self.maxmag += margin
258
+
259
+ self.lcress = []
260
+ for i in range(self.nfil):
261
+ ress = []
262
+ isat = np.where(np.array(self.usedsatellites) == self.satellites[i])[0][0]
263
+ for j in range(0,len(self.lctimes[i])):
264
+ ip = np.where(self.magnifications[isat][0] == self.lctimes[i][j])[0][0]
265
+ ress.append(self.magnifications[isat][1][ip]-self.lcmags[i][j])
266
+ self.lcress.append(ress)
267
+
268
+ # Caustic plot preparation
269
+ self.rancau = max([self.maxy1-self.miny1,self.maxy2 - self.miny2])
270
+ if(self.modnumber>3):
271
+ self.caus = self.vbbl.Caustics(self.parsprint[0],self.parsprint[1])
272
+ else:
273
+ self.caus = np.array([[[0,1,0,-1,0],[1,0,-1,0,1]]])*self.rancau*0.001
274
+ # tE=parsprint[parnames[modnumber].index('tE')]
275
+
276
+ def printparameters(self):
277
+ print('Parameters')
278
+ for i in range(self.npars[self.modnumber]):
279
+ if((not self.animate) and len(self.parameters)==0):
280
+ print(self.parnames[self.modnumber][i],' = ', self.parsprint[i], ' +- ', self.parerrs[i])
281
+ else:
282
+ print(self.parnames[self.modnumber][i],' = ', self.parsprint[i])
283
+ print()
284
+ print('blending = ', np.array(self.blends)/np.array(self.sources))
285
+ print('baseline = ', -2.5*np.log10(np.array(self.blends)+np.array(self.sources)))
286
+ print('chi2 =', self.chi2)
287
+
288
+ def axeslightcurve(self,ax):
289
+ for i in range(0,self.nfil):
290
+ ax.errorbar(self.lctimes[i],self.lcmags[i],yerr=self.lcerrs[i],color=self.colors[i],fmt='.',label=self.telescopes[i])
291
+ for i in range(len(self.usedsatellites)):
292
+ ax.plot(self.magnifications[i][0],self.magnifications[i][1],self.satellitecolors[i],linewidth=0.5)
293
+ ax.set_ylabel('mag')
294
+ ax.set_ylim([self.maxmag,self.minmag])
295
+ ax.set_xlim([self.tmin,self.tmax])
296
+ ax.xaxis.set_minor_locator(AutoMinorLocator())
297
+ ax.yaxis.set_minor_locator(AutoMinorLocator())
298
+ ax.legend(loc=self.legendlocation)
299
+
300
+ def axesresiduals(self,ax):
301
+ ax.plot((self.tmin,self.tmax),(0,0),'k-',linewidth=0.5)
302
+ for i in range(0,self.nfil):
303
+ ax.errorbar(self.lctimes[i],self.lcress[i],yerr=self.lcerrs[i],color=self.colors[i],fmt='.')
304
+ ax.set_xlabel('t')
305
+ ax.set_ylabel('Res')
306
+ ax.set_ylim([-0.1,0.1])
307
+ ax.set_xlim([self.tmin,self.tmax])
308
+ ax.xaxis.set_minor_locator(AutoMinorLocator())
309
+ ax.yaxis.set_minor_locator(AutoMinorLocator())
310
+
311
+ def showlightcurve(self):
312
+ plt.figure()
313
+ fig, axs =plt.subplots(2,1,figsize=(12,6), gridspec_kw={'height_ratios': [5, 1]},sharex='col')
314
+ self.axeslightcurve(axs[0])
315
+ self.axesresiduals(axs[1])
316
+ plt.subplots_adjust(hspace=0.1)
317
+
318
+
319
+ def showcaustics(self):
320
+ plt.figure()
321
+ fig, ax =plt.subplots(figsize=[5,5])
322
+ self.axescaustics(ax)
323
+
324
+ def axescaustics(self,ax):
325
+ for cau in self.caus:
326
+ ax.plot(cau[0],cau[1],color = self.causticcolor)
327
+ ax.set_xlabel('y1')
328
+ ax.set_ylabel('y2')
329
+ ax.set_xlim([(self.miny1+self.maxy1-self.rancau)/2,(self.miny1+self.maxy1+self.rancau)/2])
330
+ ax.set_ylim([(self.miny2+self.maxy2-self.rancau)/2,(self.miny2+self.maxy2+self.rancau)/2])
331
+ for i in range(len(self.usedsatellites)):
332
+ ax.plot(self.trajectories[i][0],self.trajectories[i][1],self.satellitecolors[i])
333
+ n = len(self.trajectories[i][0])
334
+ arrlength = self.rancau*0.01
335
+ i0 = n-10
336
+ dir = np.array([self.trajectories[i][0][i0+1]-self.trajectories[i][0][i0],self.trajectories[i][1][i0+1]-self.trajectories[i][1][i0]])
337
+ dir = dir/(math.sqrt(dir.dot(dir)))
338
+ dirort = np.array([-dir[1], dir[0]])
339
+ p0 = np.array([self.trajectories[i][0][i0],self.trajectories[i][1][i0]])
340
+ p1 = (-dir +dirort)*arrlength + p0
341
+ p2 = (-dir -dirort)*arrlength + p0
342
+ ax.plot((p0[0],p1[0]),(p0[1],p1[1]),self.satellitecolors[i])
343
+ ax.plot((p0[0],p2[0]),(p0[1],p2[1]),self.satellitecolors[i])
344
+ i0 = 20
345
+ dir = np.array([self.trajectories[i][0][i0+1]-self.trajectories[i][0][i0],self.trajectories[i][1][i0+1]-self.trajectories[i][1][i0]])
346
+ dir = dir/(math.sqrt(dir.dot(dir)))
347
+ dirort = np.array([-dir[1], dir[0]])
348
+ p0 = np.array([self.trajectories[i][0][i0],self.trajectories[i][1][i0]])
349
+ p1 = (-dir +dirort)*arrlength + p0
350
+ p2 = (-dir -dirort)*arrlength + p0
351
+ ax.plot((p0[0],p1[0]),(p0[1],p1[1]),self.satellitecolors[i])
352
+ ax.plot((p0[0],p2[0]),(p0[1],p2[1]),self.satellitecolors[i])
353
+ i0 = int(n*0.5)
354
+ p0 = np.array([self.trajectories[i][0][i0],self.trajectories[i][1][i0]])
355
+ ax.add_patch(Circle(p0,self.rho,color = self.sourcecolor))
356
+ ax.xaxis.set_minor_locator(AutoMinorLocator())
357
+ ax.yaxis.set_minor_locator(AutoMinorLocator())
358
+
359
+ def showall(self):
360
+ fig, axes = plt.subplot_mosaic([['tl','right'],['bl','right']],figsize=(12,5.5), gridspec_kw={'height_ratios': [5, 1]})
361
+ fig.suptitle(self.model);
362
+ self.axeslightcurve(axes['tl'])
363
+ axes['tl'].xaxis.set_ticklabels([])
364
+ self.axesresiduals(axes['bl'])
365
+ self.axescaustics(axes['right'])
366
+ plt.subplots_adjust(hspace=0.1)
367
+ plt.show()
368
+ if(self.printpars):
369
+ self.printparameters()
370
+
371
+ def update(self, frame):
372
+ self.im.set_array(self.images_array[frame])
373
+ return self.im,
374
+
375
+ def animateplots(self, interval = 1000):
376
+ if(os.path.exists('tmpsteps')):
377
+ shutil.rmtree('tmpsteps')
378
+ os.mkdir('tmpsteps')
379
+ os.chdir('tmpsteps')
380
+ dirocco = os.getcwd()
381
+ self.line = 0
382
+ self.readdata()
383
+ with open(self.modelfile) as f:
384
+ lines = f.readlines()
385
+ self.maxlines = len(lines)
386
+ pbar = tqdm(total = self.maxlines,desc = 'Frames',file=sys.stdout, colour='GREEN', smoothing = 0)
387
+ for frame in range(self.maxlines):
388
+ self.line = frame
389
+ self.readparameters()
390
+ self.fig, self.axes = plt.subplot_mosaic([['tl','right'],['bl','right']],figsize=(12,6), gridspec_kw={'height_ratios': [5, 1]})
391
+ self.fig.suptitle(self.model + ' - frame: ' + str(self.line));
392
+ self.calculate()
393
+ self.axeslightcurve(self.axes['tl'])
394
+ self.axes['tl'].xaxis.set_ticklabels([])
395
+ self.axesresiduals(self.axes['bl'])
396
+ self.axescaustics(self.axes['right'])
397
+ _ = plt.subplots_adjust(hspace=0.1)
398
+ os.chdir(dirocco)
399
+ plt.savefig(str(self.line) + '.png', bbox_inches = 'tight', dpi = 300)
400
+ plt.close(self.fig)
401
+ pbar.update(1)
402
+ pbar.close()
403
+ self.images_array = []
404
+ for i in range(self.maxlines):
405
+ image = Image.open(str(i) + '.png')
406
+ self.images_array.append(image)
407
+ plt.close(self.fig)
408
+ self.fig, ax = plt.subplots()
409
+ ax.spines['top'].set_visible(False)
410
+ ax.spines['right'].set_visible(False)
411
+ ax.spines['bottom'].set_visible(False)
412
+ ax.spines['left'].set_visible(False)
413
+ ax.get_xaxis().set_ticks([])
414
+ ax.get_yaxis().set_ticks([])
415
+ self.fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
416
+ self.im = ax.imshow(self.images_array[0], animated=True)
417
+ self.animation_fig = animation.FuncAnimation(self.fig, self.update, frames=len(self.images_array), interval=interval, blit=True,repeat = False)
418
+ os.chdir(dirocco)
419
+ os.chdir('..')
420
+ self.animation_fig.save('ani.gif',dpi = 150)
421
+ plt.close(self.fig)
422
+
423
+ def plotchain(eventname, model, par1, par2):
424
+ chains = []
425
+ filenames = glob.glob(eventname+ '/PreModels/' + model + '/*step*')
426
+ for fil in filenames:
427
+ with open(fil) as f:
428
+ chainstrings = f.readlines()
429
+ chainlist = []
430
+ for st in chainstrings:
431
+ chunks = st.split(' ')
432
+ chainlist.append([float(v) for v in chunks])
433
+ chain = np.array(chainlist)
434
+ chains.append(chain)
435
+ colors = ['blue','red','green','darkorange','magenta','cyan','gray','teal','maroon','gold','lime','darkviolet']
436
+ while(len(colors)<len(chains)):
437
+ colors.extend(colors)
438
+ fig, ax = plt.subplots()
439
+ # ax.set_xlabel('s')
440
+ # ax.set_ylabel('q')
441
+ for i in range(len(filenames)):
442
+ chain = chains[i]
443
+ x = chain.transpose()[par1]
444
+ y = chain.transpose()[par2]
445
+ ax.plot(x,y,color = colors[i])
446
+ ax.scatter(x[-1], y[-1],s=20,color = colors[i])
447
+
448
+
449
+
450
+
451
+
452
+