-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface.py
executable file
·3057 lines (2502 loc) · 118 KB
/
interface.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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
478
479
480
481
482
483
484
485
486
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import copy
import os
import sys
import nlopt
import numpy as np
import shutil
import subprocess
from astropy import units
from matplotlib import pyplot as plt
from multiprocessing import cpu_count
from multiprocessing import Queue
from multiprocessing import Process
from scipy import ndimage
from scipy.interpolate import interpn
from scipy.interpolate import RectBivariateSpline
from scipy.io import FortranFile
from .auxilliary import DFT2d
from .auxilliary import get_offset
from .auxilliary import get_mulfac
from .auxilliary import interpolate1d
from .auxilliary import interpolate1d_hermite
from .auxilliary import quad_phase
from .auxilliary import write_file
from .auxilliary import append_file
from .auxilliary import rotateX
from .auxilliary import rotateZ
from .definitions import fitter_definitions
from .definitions import filters, eff_wave, eff_band, calibration_flux
from .definitions import shsp_template as default_template
from .definitions import shsp_executable as default_executable
from .definitions import shsp_params as default_params
from .definitions import shsp_abundance as default_abundance
from .model import Model
from .objects import CentralObject
from .objects import Companion
from .objects import Disk
from .objects import Nebula
from .objects import Distance
from .objects import Envelope
from .objects import Orbit
from .objects import Spot
from .objects import Ufo
from .objects import Flow
from .objects import Jet
from .observations import Data
from .plotting import plot_light_curve
from .plotting import plot_squared_visibility
from .plotting import plot_triple_product
from . import limcof
class Interface(object):
"""
This class should serve as an interface to the
Pyshellspec
"""
def __init__(self, data=None, model=None, image_size=None, shellspec_abundance=None,
shellspec_executable=None, shellspec_params=None,
shellspec_template=None, debug=False, ncpu=1,
if_phase_precision=3, df_phase_precision=3, lc_phase_precision=2, sed_phase_precision=2, spe_phase_precision=2,
if_ew_precision=9, df_ew_precision=10, lc_ew_precision=9, sed_ew_precision=10, spe_ew_precision=10,
exclude_cp=False, exclude_t3amp=False, exclude_vis2=False, exclude_visamp=False, exclude_visphi=False,
use_offset=True, use_differential=False, dry_run=False, overwrite=True):
"""
Constructs the class.
:param data: All data files wrapped in pyshellspec.Data type.
:param model: All pyshellspec models wrapped in pyshellspec.Model type.
:param image_size: Size of the zero-padded image. This parameter is important only for FFT.
:param shellspec_abundance: Path to shellspec 'abundances' file, if None, built-in is used
:param shellspec_executable: Path to shellspec executable file, if None, built-in is used
:param shellspec_params: Path to shellspec parameter (param.inc) file, if None, built-in is used
:param shellspec_template: Path to shellspec control (shellspec.in) file, if None, built-in is used
:param if_phase_precision: The phase rounding order for interferometry,
phase = np.around(phase, if_phase_precision)
:param df_phase_precision: The same for differential interferometry.
:param lc_phase_precision: The same for photometric data.
:param sed_phase_precision: The same for SED data.
:param spe_phase_precision: The same for spectral data.
:param if_ew_precision: The effective wavelength rounding order for interferometry,
ew = np.around(ew, if_ew_precision)
:param df_ew_precision: The same for differential interferometry.
:param lc_ew_precision: The same for photometric data.
:param sed_ew_precision: The same for SED data.
:param spe_ew_precision: The same for spectral data.
:param debug: If true, more information is printed / plotted.
:param ncpu: number of cpus that will be employd in computation
:param exclude_cp: excludes closure phase from chi^2 fitting
:param exclude_t3amp: excludes triple product amplitude from chi^2 fitting
:param exclude_vis2: excludes squared visibility from chi^2 fitting
:param exclude_visamp: excludes visibility amplitude from chi^2 fitting
:param exclude_visphi: excludes visibility phase from chi^2 fitting
:param use_offset: offset synthetic lightcurves to better match the observed ones
:param use_differential: assume differential visibilities and shift |V|
:param dry_run: do NOT call shellspec, read previous output files; very useful for debugging
:param overwrite: do NOT overwrite files; very useful for restarts of hi-res simulations
:return:
"""
# stores data
self.__data = data
# stores model
self.__model = model
# stores the size of images from which FTis computed
self.__image_size = image_size
# sets which interferometric observables should not be fitted
self.__exclude_cp = exclude_cp
self.__exclude_t3amp = exclude_t3amp
self.__exclude_vis2 = exclude_vis2
self.__exclude_visamp = exclude_visamp
self.__exclude_visphi = exclude_visphi
self.__use_offset = use_offset
self.__use_differential = use_differential
# sets address of all shellspec files
# abundance
if shellspec_abundance is None:
self.__shellspec_abundance_file = default_abundance
else:
self.__shellspec_abundance_file = shellspec_abundance
# executable
if shellspec_executable is None:
self.__shellspec_executable_file = default_executable
else:
self.__shellspec_executable_file = shellspec_executable
# grid parameters
if shellspec_params is None:
self.__shellspec_params_file = default_params
else:
self.__shellspec_params_file = shellspec_params
# template
if shellspec_template is None:
self.__shellspec_template_file = default_template
else:
self.__shellspec_template_file = shellspec_template
# stores precision in phase and effective wavelength for
# photometric and interferometric data in 10 ** prec
self.__if_phase_precision = if_phase_precision
self.__df_phase_precision = df_phase_precision
self.__lc_phase_precision = lc_phase_precision
self.__sed_phase_precision = sed_phase_precision
self.__spe_phase_precision = spe_phase_precision
self.__if_ew_precision = if_ew_precision
self.__df_ew_precision = df_ew_precision
self.__lc_ew_precision = lc_ew_precision
self.__sed_ew_precision = sed_ew_precision
self.__spe_ew_precision = spe_ew_precision
# read the template file
self.__read_template()
# update the model from the template file -- if some was passed
# and model was passed
if shellspec_template is not None and model is not None:
self.__update_model_from_initial_template()
# update the model from the template file -- if some was passed
# but no model was passed
elif shellspec_template is not None and model is None:
# creates the model from the shellspec
# template
objects = []
if int(self.__read_parameter_from_template('istar')) > 0:
objects.append(CentralObject())
if int(self.__read_parameter_from_template('icomp')) > 0:
objects.append(Companion())
if int(self.__read_parameter_from_template('idisc')) > 0:
objects.append(Disk())
if int(self.__read_parameter_from_template('inebl')) > 0:
objects.append(Nebula())
if int(self.__read_parameter_from_template('ienv')) > 0:
objects.append(Envelope())
if int(self.__read_parameter_from_template('ispot')) > 0:
objects.append(Spot())
if int(self.__read_parameter_from_template('iufo')) > 0:
objects.append(Ufo())
if int(self.__read_parameter_from_template('iflow')) > 0:
objects.append(Flow())
if int(self.__read_parameter_from_template('ijet')) > 0:
objects.append(Jet())
# always append orbit -- this is necessary now
# because pyshellspec needs that always
objects.append(Orbit())
# construct the model
model = Model(objects=objects)
# assign the model to the object
self.__model = model
# update the model from template
self.__update_model_from_initial_template()
# extract dependent and independent variables from data
# and create arrays for consequent comparison
if self.__data is not None:
self.__cp_comparison = self.__ready_comparison('cp')
self.__lc_comparison, self.__lcsyn = self.__ready_comparison('lc')
self.__vis2_comparison = self.__ready_comparison('vis2')
self.__vis_comparison = self.__ready_comparison('vis')
self.__sed_comparison, self.__sedsyn = self.__ready_comparison('sed')
self.__spe_comparison, self.__spesyn = self.__ready_comparison('spe')
# attributes for effective wavelength and phases
# at which the model will be evaluated
self.__has_phase = False
# number of employed cpu
# correct for situation where we exceed the number of
# cpus in the computer
ncpu = min([cpu_count(), ncpu])
self.__ncpu = ncpu
print("ncpu = ", ncpu)
# set debug mode
self.debug = debug
self.dry_run = dry_run
self.overwrite = overwrite
# empty array for iteration
self.__iterations = []
self.limcofst = None
self.limcofcp = None
def compute_chi2(self, pars=[], fitparams=None, verbose=False):
"""
Comutes chi^2
:param pars:
:param fitparams:
:param verbose:
:return:
"""
# just in case the function is called withou
# parameters
if fitparams is None:
fitparams = self.get_fitted_parameters()
# update parameters if the passed array
# is the same length as that of fitted parameters
# and then update parameters based on the orbital
# model
if len(pars) == len(fitparams):
self.__update_fitted_parameters(pars, fitparams)
self.__update_from_orbit() # modified by MB, Nov 27th 2017
# propagate them into the shellspec control file
self.set_model_to_shellspec()
# prepare limb-darkening coef. for both (central) star and companion
self.limcofst= limcof.Limcof(Teff=self.__model['central_object']['tstar'].to('Kelvin').value, R=self.__model['central_object']['rstar'].to('solRad').value, M=self.__model['central_object']['emstar'].to('solMass').value)
self.limcofcp= limcof.Limcof(Teff=self.__model['companion']['tempcp'].to('Kelvin').value, R=self.__model['companion']['rcp'].to('solRad').value, M=self.__model['companion']['qq'].value*self.__model['central_object']['emstar'].to('solMass').value)
# compute light curves
self.compute_lc()
# compute interferometric observables
self.compute_if_DFT(dtype='if')
self.compute_if_DFT(dtype='df')
# compute SED
self.compute_sed()
# compute spectra
self.compute_spe()
# compute partial chi-squares
# light curves
self.__lc_comparison['chi2'] = ((self.__lc_comparison['magnitude'] - self.__lc_comparison['magnitudesyn']) / self.__lc_comparison['error']) ** 2
chi2_lc = np.sum(self.__lc_comparison['chi2'])
n_lc = self.__lc_comparison['magnitude'].size
# squared visibilities
chi2_vis2 = 0.0
n_vis2 = 0
if not self.__exclude_vis2:
for i in range(len(self.__vis2_comparison['vis2data'])):
if self.__vis2_comparison['vis2data'][i] == None:
self.__vis2_comparison['chi2'].append(None)
else:
weight = self.__vis2_comparison['weight'][i]
self.__vis2_comparison['chi2'][i] = weight * ((self.__vis2_comparison['vis2data'][i] - self.__vis2_comparison['vis2syn'][i]) / self.__vis2_comparison['vis2err'][i]) ** 2
chi2_vis2 += self.__vis2_comparison['chi2'][i]
n_vis2 += weight
# closure phases
chi2_cp = 0.0
n_cp = 0
if not self.__exclude_cp:
for i in range(len(self.__cp_comparison['t3phi'])):
if self.__cp_comparison['t3phi'][i] == None:
self.__cp_comparison['chi2phi'].append(None)
else:
self.__cp_comparison['chi2phi'][i] = ((self.__cp_comparison['t3phi'][i] - self.__cp_comparison['t3phisyn'][i]) / self.__cp_comparison['t3phierr'][i]) ** 2
chi2_cp += self.__cp_comparison['chi2phi'][i]
n_cp += 1
# triple product amplitudes
chi2_t3amp = 0.0
n_t3amp = 0
if not self.__exclude_t3amp:
for i in range(len(self.__cp_comparison['t3amp'])):
if self.__cp_comparison['t3amp'][i] == None:
self.__cp_comparison['chi2amp'][i] = None
else:
weight = self.__cp_comparison['weight'][i]
self.__cp_comparison['chi2amp'][i] = weight * ((self.__cp_comparison['t3amp'][i] - self.__cp_comparison['t3ampsyn'][i]) / self.__cp_comparison['t3amperr'][i]) ** 2
chi2_t3amp += self.__cp_comparison['chi2amp'][i]
n_t3amp += weight
# visibility amplitudes
chi2_visamp = 0.0
n_visamp = 0
if not self.__exclude_visamp:
for i in range(len(self.__vis_comparison['visamp'])):
if self.__vis_comparison['visamp'][i] == None:
self.__vis_comparison['chi2amp'].append(None)
else:
weight = self.__vis_comparison['weight'][i]
self.__vis_comparison['chi2amp'][i] = weight * ((self.__vis_comparison['visamp'][i] - self.__vis_comparison['visampsyn'][i]) / self.__vis_comparison['visamperr'][i]) ** 2
chi2_visamp += self.__vis_comparison['chi2amp'][i]
n_visamp += weight
# visibility phases
chi2_visphi = 0.0
n_visphi = 0
if not self.__exclude_visphi:
for i in range(len(self.__vis_comparison['visphi'])):
if self.__vis_comparison['visphi'][i] == None:
self.__vis_comparison['chi2phi'].append(None)
else:
weight = self.__vis_comparison['weight'][i]
self.__vis_comparison['chi2phi'][i] = weight * ((self.__vis_comparison['visphi'][i] - self.__vis_comparison['visphisyn'][i]) / self.__vis_comparison['visphierr'][i]) ** 2
chi2_visphi += self.__vis_comparison['chi2phi'][i]
n_visphi += weight
# spectral-energy distribution
self.__sed_comparison['chi2'] = ((self.__sed_comparison['flux'] - self.__sed_comparison['fluxsyn']) / self.__sed_comparison['error']) ** 2
chi2_sed = np.sum(self.__sed_comparison['chi2'])
n_sed = self.__sed_comparison['flux'].size
# spectra
self.__spe_comparison['chi2'] = ((self.__spe_comparison['flux'] - self.__spe_comparison['fluxsyn']) / self.__spe_comparison['error']) ** 2
chi2_spe = np.sum(self.__spe_comparison['chi2'])
n_spe = self.__spe_comparison['flux'].size
# compute total chi-square
n = n_lc + n_vis2 + n_cp + n_t3amp + n_visamp + n_visphi + n_sed + n_spe
chi2 = chi2_lc + chi2_vis2 + chi2_cp + chi2_t3amp + chi2_visamp + chi2_visphi + chi2_sed + chi2_spe
ns = [n_lc, n_vis2, n_cp, n_t3amp, n_visamp, n_visphi, n_sed, n_spe, n]
chi2s = [chi2_lc, chi2_vis2, chi2_cp, chi2_t3amp, chi2_visamp, chi2_visphi, chi2_sed, chi2_spe, chi2]
r_chi2s = [chi2 / (n+1.0e-8) for chi2, n in zip(chi2s, ns)]
# append info on each iteration
if len(pars) == 0:
one_iter = [rec['value'] for rec in fitparams]
else:
one_iter = [par for par in pars]
for rec in ns:
one_iter.append(rec)
for rec in chi2s:
one_iter.append(rec)
for rec in r_chi2s:
one_iter.append(rec)
self.__iterations.append(one_iter)
self.write_iterations()
if len(self.__iterations) % 10 == 0:
self.write_iterations('fit.intermediate.log')
self.write_model() # dbg
# return the output
if verbose:
return chi2s.extend(r_chi2s)
else:
return chi2
def compute_if_DFT(self,dtype='if'):
"""
Computes synthetic visibilities.
"""
if dtype == 'df':
phase_precision = self.__df_phase_precision
ew_precision = self.__df_ew_precision
else:
phase_precision = self.__if_phase_precision
ew_precision = self.__if_ew_precision
# first copy the model to shellspec
self.set_model_to_shellspec()
# get phases and ews at which we shall compute
ifsyn = self.get_ew_and_phase(dtype)
# get the position of the barycentre, inclination
# ascending node longitude
if self.__model.has_object('orbit'):
bar_pos = self.__model['orbit'].get_barycentre()
omega = self.__model['orbit']['omega_an']
incl = self.__model['orbit']['dinc']
else:
raise TypeError('The tool is currently working with binaries only '
'i.e. for models, where orbit has been defined.')
# get the physical resolution along the
# x-axis and size of the grid in pixels
if self.__model.has_object('grid'):
npx, npy, npz = self.__model['grid'].get_pixel_size()
else:
raise KeyError('Object grid was not found among defined objects.'
'It should be alway defined')
# get the size of the final image - it is padded to get a
# square format, which is convenient for rotation of the
# image. Nonetheless padding of the image is not
# necessary for DFT.
newsize = self.__image_size
if newsize is None:
if npx > npy:
newsize = npx
else:
newsize = npy
# extract the resolution along x-axis
phys_res = self.__model['grid']['stepx']
# compute spatial frequencies
# get parallax and stepsize
plx = self.__model['distance']['dd'].to('m')
step_physical = phys_res.to('m')
# compute angular step
step_angular = step_physical.value / plx.value
# axis of the image
if newsize % 2 > 1:
xscale = np.arange(-newsize // 2 + 1, newsize // 2 + 1, 1) * step_angular
else:
xscale = np.arange(-newsize // 2, newsize // 2, 1) * step_angular
yscale = xscale.copy()
if self.__ncpu > 1:
# get number of cpu
ncpu = self.__ncpu
# get the number of wavelengths
newave = len(ifsyn['eff_wave'])
print("newave = " + str(newave))
# creates output files (different directory for each wavelength)
directories = []
for i in range(newave):
# get directory
directory = os.path.join(os.getcwd(), 'temp' + dtype + str(i).zfill(2))
if not os.path.isdir(directory):
os.mkdir(directory)
directories.append(directory)
# go over each wavelength
for i in range(0, newave, ncpu):
# empty list for threads
threads = []
queues = []
results = []
# spawn processes
nprocess = min([ncpu, len(ifsyn['eff_wave']) - i])
for j in range(nprocess):
# get phase and wavelength
ew = ifsyn['eff_wave'][i + j] * units.m
phase = ifsyn['phase'][i + j]
# spawn queue
queues.append(Queue())
# define process args
args = (directories[i+j], ew, phase, npx, npy, phys_res, bar_pos, incl, omega, newsize, queues[j], True)
# spawn processes
threads.append(Process(target=self.__pp_get_images_one_wavelength, args=args))
# run processes
for j in range(len(threads)):
threads[j].start()
# readout processes and join threads
for j in range(len(threads)):
results.append(queues[j].get())
queues[j].close()
threads[j].join()
if threads[j].exitcode != 0:
print("compute_if_DFT: Error running shellspec! exitcode = " + str(threads[j].exitcode))
sys.exit(1)
# compute DFT over the data
for res in results:
ew, phases, images = res
for phase, img in zip(phases, images):
self.__get_if_observables_DFT(img, ew.value, phase, xscale, yscale, ew_precision, phase_precision)
else: # 1 cpu
# get the number of wavelengths
newave = len(ifsyn['eff_wave'])
print("newave = " + str(newave))
# creates output files (different directory for each wavelength)
directories = []
for i in range(newave):
# get directory
directory = os.path.join(os.getcwd(), 'temp' + dtype + str(i).zfill(2))
if not os.path.isdir(directory):
os.mkdir(directory)
directories.append(directory)
# go over each wavelength
for i in range(newave):
print("directory = ", directories[i])
# set directory and phase
ew = ifsyn['eff_wave'][i] * units.m
phase = ifsyn['phase'][i]
# process one wavelength
self.__process_wavelength_DFT(directories[i], ew, phase, npx, npy, phys_res, bar_pos,
incl, omega, newsize, xscale, yscale, image_only=True)
if dtype == 'df':
self.zero_slips()
self.adjust_differential()
self.adjust_slips()
self.adjust_differential()
self.adjust_slips()
def zero_slips(self):
"""
Set mulfac to one, offset and slips to zero.
"""
n = len(self.__vis_comparison['mulfac'])
self.__vis_comparison['mulfac'][:] = np.ones(n)
self.__vis_comparison['offset'][:] = np.zeros(n)
self.__vis_comparison['slips'][:] = np.zeros(n)
self.__vis_comparison['visamp'][:] = self.__vis_comparison['visamp_']
self.__vis_comparison['visphi'][:] = self.__vis_comparison['visphi_']
def adjust_differential(self):
"""
Multiply synthetic (differential) visibility amplitude |V|,
and shift phase arg V to match the observed values.
"""
filenames = self.__vis_comparison['filename']
for filename in np.unique(filenames):
find = np.where(filenames == filename)[0]
visamp = self.__vis_comparison['visamp'][find]
visampsyn = self.__vis_comparison['visampsyn'][find]
if self.__use_differential:
mulfac = get_mulfac(visamp, visampsyn)
mulfac = mulfac.x
else:
mulfac = 1.0
self.__vis_comparison['visampsyn'][find] = visampsyn * mulfac
self.__vis_comparison['mulfac'][find] *= np.ones(len(visampsyn)) * mulfac
visphi = self.__vis_comparison['visphi'][find]
visphisyn = self.__vis_comparison['visphisyn'][find]
if self.__use_differential:
offset = get_offset(visphi, visphisyn)
offset = offset.x
else:
offset = 0.0
self.__vis_comparison['visphisyn'][find] = visphisyn + offset
self.__vis_comparison['offset'][find] += np.ones(len(visphisyn)) * offset
def adjust_slips(self):
"""
Adjust slips of the differential phase by +-360 deg.
"""
visphi = self.__vis_comparison['visphi']
visphisyn = self.__vis_comparison['visphisyn']
find = np.where(visphisyn-visphi > 180.0)
slips = -360.0
self.__vis_comparison['visphisyn'][find] = visphisyn[find] + slips
self.__vis_comparison['slips'][find] = np.ones(len(find))*slips
find = np.where(visphisyn-visphi < -180.0)
slips = 360.0
self.__vis_comparison['visphisyn'][find] = visphisyn[find] + slips
self.__vis_comparison['slips'][find] = np.ones(len(find))*slips
def compute_if_FFT(self):
"""
Computes synthetic visibilities.
"""
# first copy the model to shellspec
self.set_model_to_shellspec()
# get phases and ews at which we shall compute
ifsyn = self.get_ew_and_phase('if')
# get the position of the barycentre, inclination
# ascending node longitude
if self.__model.has_object('orbit'):
bar_pos = self.__model['orbit'].get_barycentre()
omega = self.__model['orbit']['omega_an']
incl = self.__model['orbit']['dinc']
else:
raise TypeError('The tool is currently working with binaries only '
'i.e. for models, where orbit has been defined.')
# get the physical resolution along the
# x-axis and size of the grid in pixels
if self.__model.has_object('grid'):
npx, npy, npz = self.__model['grid'].get_pixel_size()
else:
raise KeyError('Object grid was not found among defined objects.'
'It should be alway defined')
# get the size of the padded image
newsize = self.__image_size
# extract the resolution along x-axis
phys_res = self.__model['grid']['stepx']
# compute spatial frequencies
# get parallax and stepsize
plx = self.__model['distance']['dd'].to('m')
step_physical = phys_res.to('m')
# compute angular step
step_angular = step_physical.value / plx.value
# compute the frequency
fu_img = np.fft.fftshift(np.fft.fftfreq(newsize, d=step_angular))
fv_img = fu_img.copy()
# set directory
directory = os.path.join(os.getcwd(), 'tempfft')
if not os.path.isdir(directory):
os.mkdir(directory)
for i in range(len(ifsyn['eff_wave'])):
# readout one effective wavelength and corresponding phases
ew = ifsyn['eff_wave'][i] * units.m
phase = ifsyn['phase'][i]
# set the effective wavelength to template
self.set_wavelength(w0=ew, wn=ew + 1.0 * units.nm, step=1.0 * units.nm)
# write template and phases
phase_file = os.path.join(directory, 'phases')
control_file = os.path.join(directory, 'shellspec.in')
self.write_phase(phase, filename=phase_file)
self.write_template(filename=control_file)
# run shellspec
cwd = os.getcwd()
os.chdir(directory)
self.__run_shellspec()
os.chdir(cwd)
# read the images - one for each phase
for j in range(0, len(phase)):
# set the filename
filename = os.path.join(directory, '2Dimage_%03d' % (j + 1))
# read the image
img = self.__read_image(filename)
# compute its Fourier transform
fftimg = self.__FT_one_image(img, npx, npy, phys_res, bar_pos, phase[j], incl, omega, newsize)
# in case of debug mode, save both - the image and its Fourier transform
if self.debug:
# the image
tmp = '%.2f' % (ew.to('Angstrom').value)
figname = '.'.join(['fftimg', tmp, str(phase[j]), 'png'])
plt.imshow(self.debug_image, cmap='plasma')
plt.xlabel('x [pxl]')
plt.ylabel('y [pxl]')
plt.colorbar()
plt.tight_layout()
plt.savefig(figname)
plt.close()
# and its Fourier transform
figname = '.'.join(['fftabs', tmp, str(phase[j]), 'png'])
plt.imshow(np.abs(fftimg), cmap='plasma')
plt.xlabel('u [pxl]')
plt.ylabel('v [pxl]')
plt.colorbar()
plt.tight_layout()
plt.savefig(figname)
plt.close()
figname = '.'.join(['fftang', tmp, str(phase[j]), 'png'])
plt.imshow(np.angle(fftimg, deg=True), cmap='plasma')
plt.xlabel('u [pxl]')
plt.ylabel('v [pxl]')
plt.colorbar()
plt.tight_layout()
plt.savefig(figname)
plt.close()
# transpose AFTER debugging and BEFORE observables! otherwise, it's misleading...
fftimg = fftimg.T
# compute observables
self.__get_if_observables_FFT(fftimg, ew.value, phase[j], fu_img, fv_img, self.__if_ew_precision, self.__if_phase_precision)
return ifsyn
def compute_lc(self):
"""
Computes synthetic light curve.
"""
# first copy the model to shellspec
self.set_model_to_shellspec()
# free synthetic light curves from previous
# computation
self.__lcsyn['magnitude'] = []
# get ews and phases at which we shall compute
lcsyn = self.get_ew_and_phase('lc')
# get number of cpu
ncpu = self.__ncpu
# get the number of wavelengths
newave = len(lcsyn['eff_wave'])
print("newave = " + str(newave))
# creates output files
directories = []
for i in range(newave):
# get directory
directory = os.path.join(os.getcwd(), 'templc' + str(i).zfill(2))
if not os.path.isdir(directory):
os.mkdir(directory)
directories.append(directory)
# go over each wavelength
for i in range(0, newave, ncpu):
# empty list for threads
threads = []
queues = []
results = []
# spawn processes
nprocess = min([ncpu, newave - i])
print("nprocess = " + str(nprocess))
# effective wavelength and phase for one passband
for j in range(nprocess):
ew = lcsyn['eff_wave'][i + j]
phase = lcsyn['phase'][i + j]
# print "ew = " + str(ew) # dbg
# print "phase = " + str(phase) # dbg
# spawn queue
queues.append(Queue())
# define process args
args = (directories[i+j], ew, phase, queues[j])
# spawn processes
threads.append(Process(target=self.__pp_get_lc_one_wavelength, args=args))
# run processes
for j in range(nprocess):
threads[j].start()
# readout processes and join threads
for j in range(nprocess):
results.append(queues[j].get())
queues[j].close()
threads[j].join()
if threads[j].exitcode != 0:
print("compute_lc: Error running shellspec! exitcode = " + str(threads[j].exitcode))
sys.exit(1)
# append to the output structure
for j in range(nprocess):
mags = results[j]
lcsyn['magnitude'].append(mags)
# compute observables
self.__get_lc_observables(lcsyn)
# overwrite lcsyn
self.__lcsyn = copy.deepcopy(lcsyn)
def get_ew_and_phase(self, dtype):
"""
Determines at which phase and effective wavelength will the model be evaluated
:param dtype:
:return:
"""
# compute phases
if not self.__has_phase:
self.__set_phase()
# photometric data
if dtype == 'lc':
# copy the object with effective wavelengths and passbands
lc_phase_precision = self.__lc_phase_precision
lc_ew_precision = self.__lc_ew_precision
ew_ph = copy.deepcopy(self.__lcsyn)
# add list for phases
ew_ph['phase'] = []
# determine phases for each passband
for i, pband in enumerate(ew_ph['passband']):
# extract all phases with the coresponding passband
# ind = np.where(self.__lc_comparison['passband'] == pband)[0]
# print self.__lc_comparison['phase']
# phase = self.__lc_comparison['phase'][ind]
# get extrema
step = 10 ** -lc_phase_precision
# pmin = max([np.around(phase.min() - 2 * step, lc_phase_precision), 0.0])
# pmax = min([np.around(phase.max() + 2 * step, lc_phase_precision), 1.0 - 10 ** -lc_phase_precision])
pmin = 0.0
pmax = 1.0 - step
# create array of phases
compute_phase = np.arange(pmin, pmax + step / 2., step)
# apend it to the structure
ew_ph['phase'].append(compute_phase)
return ew_ph
# visibilities and closure phases
elif dtype == 'if':
# first join visibility and closure phase data
if_phase_precision = self.__if_phase_precision
if_ew_precision = self.__if_ew_precision
ew = self.__vis2_comparison['eff_wave'].copy()
ew = np.append(ew, self.__cp_comparison['eff_wave'])
# ew = np.append(ew, self.__vis_comparison['eff_wave'])
phase = self.__vis2_comparison['phase'].copy()
phase = np.append(phase, self.__cp_comparison['phase'])
# phase = np.append(phase, self.__vis_comparison['phase'])
# around phases
phase = np.around(phase, if_phase_precision)
# create a dictionary of ews and phases
ew_ph = dict(eff_wave=np.unique(np.around(ew, if_ew_precision)).tolist(), phase=[])
# attach the corresponding phases
for eff_wave in ew_ph['eff_wave']:
diff = np.absolute(ew - eff_wave)
ind = np.where(diff < 10 ** -if_ew_precision)[0]
ew_ph['phase'].append(phase[ind].tolist())
# make all phases unique
for i in range(0, len(ew_ph['eff_wave'])):
ew_ph['phase'][i] = np.unique(ew_ph['phase'][i]).tolist()
return ew_ph
# differential visibilities (separate)
elif dtype == 'df':
phase_precision = self.__df_phase_precision
ew_precision = self.__df_ew_precision
ew = self.__vis_comparison['eff_wave'].copy()
phase = self.__vis_comparison['phase'].copy()
phase = np.around(phase, phase_precision)
ew_ph = dict(eff_wave=np.unique(np.around(ew, ew_precision)).tolist(), phase=[])
for eff_wave in ew_ph['eff_wave']:
diff = np.absolute(ew - eff_wave)
ind = np.where(diff < 10 ** -ew_precision)[0]
ew_ph['phase'].append(phase[ind].tolist())
for i in range(0, len(ew_ph['eff_wave'])):
ew_ph['phase'][i] = np.unique(ew_ph['phase'][i]).tolist()
return ew_ph
elif dtype == 'sed' or dtype == 'spe':
if dtype == 'sed':
phase_precision = self.__sed_phase_precision
ew_precision = self.__sed_ew_precision
ew = self.__sed_comparison['eff_wave'].copy()
ph = self.__sed_comparison['phase'].copy()
ew_ph = copy.deepcopy(self.__sedsyn)
elif dtype == 'spe':
phase_precision = self.__spe_phase_precision
ew_precision = self.__spe_ew_precision
ew = self.__spe_comparison['eff_wave'].copy()
ph = self.__spe_comparison['phase'].copy()
ew_ph = copy.deepcopy(self.__spesyn)
ph_ = np.unique(np.around(ph, phase_precision)).tolist()
ew = np.floor(ew/10**(-ew_precision))*10**(-ew_precision) # np.around() w. float
ew_ph['phase'] = ph_
# attach the corresponding wavelengths
for phase in ph_:
diff = np.absolute(ph - phase)
idx = np.where(diff < 10**(-phase_precision))[0]
ew_ph['eff_wave'].append(ew[idx].tolist())
for i in range(0,len(ph_)):
ew_ph['eff_wave'][i] = np.unique(ew_ph['eff_wave'][i]).tolist()
return ew_ph
def get_fitted_parameters(self, attr=None):
"""
Returns a list of all fitted parameters.
:param attr:
:return:
"""
# empty array to store output
fitparams = []
# go over each object and parameter
for objname in list(self.__model.keys()):
for parname in list(self.__model[objname].keys()):
if self.__model[objname].get_parameter(parname, 'fitted'):
# append the whole parameter
if attr is None:
value = self.__model[objname].get_parameter(parname, 'value')
vmin = self.__model[objname].get_parameter(parname, 'vmin')
vmax = self.__model[objname].get_parameter(parname, 'vmax')
fitparams.append(dict(object=objname,
parameter=parname,
value=value.value,
vmin=vmin.value,
vmax=vmax.value))
# append attribute of a parameter
else:
fitparams.append(self.__model[objname].get_parameter(parname, attr))
return fitparams
def get_image(self, phase, eff_wave, figname=None, img_only=False, **img_kwargs):
"""
Creates an image of the system.
:param phase:
:param eff_wave: effective wavelength in m
:param figname:
:param img_only:
:param img_kwargs:
:return:
"""
# convert to units
ew = eff_wave * units.m
# set the name
if figname is None:
figname = '.'.join(['image', str(eff_wave), str(phase), 'png'])
# first copy the model to shellspec
self.set_model_to_shellspec()
# get the position of the barycentre, inclination
# ascending node longitude
if self.__model.has_object('orbit'):
bar_pos = self.__model['orbit'].get_barycentre()
omega = self.__model['orbit']['omega_an']