-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathscda.py
executable file
·5114 lines (4495 loc) · 276 KB
/
scda.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
"""
Core definitions of python tools for the STScI
Segmented Coronagraph Design & Analysis investigation
02/14/2016 -- created by NTZ
"""
import os
import shutil
import sys
import logging
import datetime
import textwrap
import csv
import numpy as np
import scipy.ndimage.interpolation
import scipy.special
import pdb
import getpass
import socket
import itertools
import pprint
import pickle
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import pyfits
import matplotlib
matplotlib.use('Agg') # non-interactive
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.patches
matplotlib.rcParams['image.origin'] = 'lower'
matplotlib.rcParams['image.interpolation'] = 'nearest'
matplotlib.rcParams['image.cmap'] = 'gray'
matplotlib.rcParams['axes.linewidth'] = 1.
matplotlib.rcParams['lines.linewidth'] = 2.5
matplotlib.rcParams['font.size'] = 12
def configure_log(log_fname=None):
# logger = logging.getLogger("scda.logger")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if not len(logger.handlers):
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout) # console dump
ch.setLevel(logging.INFO)
logger.addHandler(ch)
if sys.version_info[0] >= 3:
ch.setFormatter(WrappedFixedIndentingLog(indent=8, width=120))
if log_fname is not None: # optional file log in addition to the console dump
fh = logging.FileHandler(log_fname, mode="w")
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
class WrappedFixedIndentingLog(logging.Formatter):
def __init__(self, fmt=None, datefmt=None, style='%', width=70, indent=4):
super(WrappedFixedIndentingLog, self).__init__(fmt=fmt, datefmt=datefmt)
self.wrapper = textwrap.TextWrapper(width=width)
#self.wrapper = textwrap.TextWrapper(width=width, subsequent_indent=' '*indent)
def format(self, record):
return self.wrapper.fill(super().format(record))
def make_ampl_bundle(coron_list, bundled_dir, queue_spec='auto', email=None, arch=None):
bundled_coron_list = []
if not os.path.exists(bundled_dir):
os.makedirs(bundled_dir)
cwd = os.getcwd()
os.chdir(bundled_dir)
serial_bash_fname = "run_" + os.path.basename(os.path.normpath(bundled_dir)) + "_serial.sh"
serial_bash_fobj = open(serial_bash_fname, "w")
serial_bash_fobj.write("#! /bin/bash -x\n")
sbatch_bash_fname = "run_" + os.path.basename(os.path.normpath(bundled_dir)) + "_sbatch.sh"
sbatch_bash_fobj = open(sbatch_bash_fname, "w")
sbatch_bash_fobj.write("#! /bin/bash -x\n")
for coron in coron_list:
bundled_fileorg = {'work dir': ".", 'ampl src fname': os.path.basename(coron.fileorg['ampl src fname']),
'TelAp fname': os.path.basename(coron.fileorg['TelAp fname']),
'FPM fname': os.path.basename(coron.fileorg['FPM fname']),
'LS fname': os.path.basename(coron.fileorg['LS fname'])}
if not os.path.exists(os.path.basename(coron.fileorg['TelAp fname'])):
shutil.copy2(coron.fileorg['TelAp fname'], ".")
if not os.path.exists(os.path.basename(coron.fileorg['FPM fname'])):
shutil.copy2(coron.fileorg['FPM fname'], ".")
if not os.path.exists(os.path.basename(coron.fileorg['LS fname'])):
shutil.copy2(coron.fileorg['LS fname'], ".")
if 'LDZ fname' in coron.fileorg and coron.fileorg['LDZ fname'] is not None:
if not os.path.exists(os.path.basename(coron.fileorg['LDZ fname'])):
shutil.copy2(coron.fileorg['LDZ fname'], ".")
bundled_fileorg['LDZ fname'] = os.path.basename(coron.fileorg['LDZ fname'])
design_params = coron.design.copy()
if 'M' in design_params['FPM'] and isinstance(coron, SPLC): # M is only defined implicitly in the SPLC class
design_params['FPM'].pop('M',None)
design_params['LS'].pop('s',None)
design_params['Image'].pop('Nimg',None)
design_params['Image'].pop('bw+',None)
bundled_coron = coron.__class__(design=coron.design, fileorg=bundled_fileorg,
solver=coron.solver)
bundled_coron_list.append(bundled_coron)
if bundled_coron.check_ampl_input_files() is True:
bundled_coron.write_ampl(overwrite=True)
bundled_coron.write_slurm_script(queue_spec=queue_spec, email=email, arch=arch,
overwrite=True, verbose=False)
else:
logging.warning("Input file configuration check failed; AMPL source file not written")
logging.warning("Bundled file organization: {0}".format(bundled_coron.fileorg))
serial_bash_fobj.write("ampl {0:s}\n".format(bundled_coron.fileorg['ampl src fname']))
sbatch_bash_fobj.write("sbatch {0:s}\n".format(bundled_coron.fileorg['slurm fname']))
serial_bash_fobj.close()
sbatch_bash_fobj.close()
os.chmod(serial_bash_fname, 0775)
os.chmod(sbatch_bash_fname, 0775)
os.chdir(cwd)
return bundled_coron_list
def load_design_param_survey(pkl_fname):
fobj = open(pkl_fname, 'rb')
survey_obj = pickle.load(fobj)
fobj.close()
return survey_obj
def merge_design_param_surveys(survey_list, merged_survey_fname=None):
assert len(survey_list) >= 1, "The input list must contain at least one survey."
for survey in survey_list:
assert isinstance(survey, DesignParamSurvey), "Each element in the input list must be a DesignParamSurvey."
assert survey.coron_class == survey_list[0].coron_class, "The coronagraph classes of the input surveys must match."
# Until we take the time to write out a more intelligent merge routine,
# require the fixed and varied parameter categories to match
# This means, if there are parameters that are constant within an individual survey
# but change across the surveys, they must be defined as single-element lists so that they
# are classified as 'varied' in the input survey objects.
assert survey.fixed_param_index == survey_list[0].fixed_param_index, "Fixed parameter categories of each survey must be the same."
assert survey.fixed_param_vals == survey_list[0].fixed_param_vals, "Fixed parameter values of each survey must be the same."
assert survey.varied_param_index == survey_list[0].varied_param_index, "Varied parameter categories of each survey must be the same."
merged_survey = DesignParamSurvey(coron_class=survey_list[0].coron_class, survey_config=survey_list[0].survey_config,
fileorg=survey_list[0].fileorg, solver=survey_list[0].solver)
varied_param_combos_list_merged = list(merged_survey.varied_param_combos)
for survey in survey_list[1:]:
varied_param_combos_list_B = list(survey.varied_param_combos)
for ii, combo in enumerate(varied_param_combos_list_B):
if combo not in varied_param_combos_list_merged:
varied_param_combos_list_merged.append(combo)
merged_survey.coron_list.append(survey.coron_list[ii])
merged_survey.varied_param_combos = tuple(varied_param_combos_list_merged)
merged_survey.N_combos = len(merged_survey.varied_param_combos)
if merged_survey_fname is not None: # unless specified, use the same name as the first input survey
merged_survey.fileorg['survey fname'] = merged_survey_fname
merged_survey_name = os.path.basename(merged_survey.fileorg['survey fname'][:-4])
num_ID_digits = int(np.floor(np.log10(merged_survey.N_combos))) + 1
ID_fmt_str = "{{:s}}-{{:0{:d}d}}".format(num_ID_digits)
for idx, coron in enumerate(merged_survey.coron_list): # overwrite design IDs in coron_list
coron.fileorg['design ID'] = ID_fmt_str.format(merged_survey_name, idx)
return merged_survey
class DesignParamSurvey(object):
def __init__(self, coron_class, survey_config, **kwargs):
#self.logger = logging.getLogger('scda.logger')
setattr(self, 'coron_class', coron_class)
self._param_menu = coron_class._design_fields.copy()
self._file_fields = coron_class._file_fields.copy()
self._solver_menu = coron_class._solver_menu.copy()
self._file_fields['fileorg'].append('survey fname')
setattr(self, 'survey_config', {})
for keycat, param_dict in survey_config.items():
self.survey_config[keycat] = {}
if keycat in self._param_menu:
for param, values in param_dict.items():
if param in self._param_menu[keycat]:
if values is not None:
if hasattr(values, '__iter__'): #check the type of all items
if all(isinstance(value, self._param_menu[keycat][param][0]) for value in values):
self.survey_config[keycat][param] = values
#self.survey_config[keycat][param] = tuple(values)
else:
warnstr = ("Warning: Invalid type found in survey set {0} for parameter {1} under category \"{2}\" " + \
"design initialization argument, expecting {3}").format(values, param, keycat, self._param_menu[keycat][param][0])
logging.warning(warnstr)
else:
if isinstance(values, self._param_menu[keycat][param][0]):
self.survey_config[keycat][param] = values
else:
warnstr = ("Warning: Invalid {0} for parameter \"{1}\" under category \"{2}\" " + \
"design initialization argument, expecting a {3}").format(type(values), param, keycat, self._param_menu[keycat][param][0])
logging.warning(warnstr)
else:
logging.warning("Warning: Unrecognized parameter \"{0}\" under category \"{1}\" in design initialization argument".format(param, keycat))
else:
logging.warning("Warning: Unrecognized key category \"{0}\" in design initialization argument".format(keycat))
self.survey_config[keycat] = None
varied_param_flat = []
varied_param_index = []
fixed_param_flat = []
fixed_param_index = []
for keycat in self._param_menu: # Fill in default values where appropriate
if keycat not in self.survey_config:
self.survey_config[keycat] = {}
for param in self._param_menu[keycat]:
if param not in self.survey_config[keycat] or (self.survey_config[keycat][param] is None and \
self._param_menu[keycat][param][1] is not None):
self.survey_config[keycat][param] = self._param_menu[keycat][param][1] # default value
elif param in self.survey_config[keycat] and self.survey_config[keycat][param] is not None and \
not hasattr(self.survey_config[keycat][param], '__iter__'):
fixed_param_flat.append(self.survey_config[keycat][param])
fixed_param_index.append((keycat, param))
elif hasattr(self.survey_config[keycat][param], '__iter__'):
varied_param_flat.append(self.survey_config[keycat][param])
varied_param_index.append((keycat, param))
varied_param_combos = []
for combo in itertools.product(*varied_param_flat):
varied_param_combos.append(combo)
self.varied_param_combos = tuple(varied_param_combos)
self.varied_param_index = tuple(varied_param_index)
self.fixed_param_vals = tuple(fixed_param_flat)
self.fixed_param_index = tuple(fixed_param_index)
self.N_combos = len(varied_param_combos)
#////////////////////////////////////////////////////////////////////////////////////////////////////
# The fileorg attribute holds the locations of telescope apertures,
# intermediate masks, co-eval AMPL programs, solutilons, logs, etc.
#////////////////////////////////////////////////////////////////////////////////////////////////////
setattr(self, 'fileorg', {})
if 'fileorg' in kwargs:
for namekey, location in kwargs['fileorg'].items():
if namekey in self._file_fields['fileorg']:
if location is not None:
if namekey.endswith('dir'):
self.fileorg[namekey] = os.path.expanduser(location)
if not os.path.exists(self.fileorg[namekey]):
logging.warning("Warning: The specified location of '{0}', \"{1}\" does not exist".format(namekey, self.fileorg[namekey]))
else:
self.fileorg[namekey] = location
else:
self.fileorg[namekey] = None
else:
logging.warning("Warning: Unrecognized field {0} in fileorg argument".format(namekey))
# Handle missing directory values, and create the directories if they don't exist
if 'work dir' not in self.fileorg or self.fileorg['work dir'] is None:
self.fileorg['work dir'] = os.getcwd()
for namekey in self._file_fields['fileorg']: # Set other missing directory locations to 'work dir'
if namekey.endswith('dir'):
if namekey not in self.fileorg or self.fileorg[namekey] is None:
self.fileorg[namekey] = self.fileorg['work dir']
if not os.path.exists(self.fileorg[namekey]):
os.mkdir(self.fileorg[namekey])
#////////////////////////////////////////////////////////////////////////////////////////////////////
# In most cases we don't expect to directly specify file names for apertures, FPM, or LS files
# for the SCDA parameter survey. However, it easy enough to make this option available.
# If the location of the optimizer input file is not known,
# look for it in the directory corresponding to its specific category
#////////////////////////////////////////////////////////////////////////////////////////////////////
if 'TelAp fname' in self.fileorg and self.fileorg['TelAp fname'] is not None and \
not os.path.exists(self.fileorg['TelAp fname']) and os.path.exists(self.fileorg['TelAp dir']) and \
os.path.dirname(self.fileorg['TelAp fname']) == '':
try_fname = os.path.join(self.fileorg['TelAp dir'], self.fileorg['TelAp fname'])
if os.path.exists(try_fname):
self.fileorg['TelAp fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified telescope aperture file \"{0}\" in {1}".format(self.fileorg['TelAp fname'],
self.fileorg['TelAp dir']))
if 'FPM fname' in self.fileorg and self.fileorg['FPM fname'] is not None and \
not os.path.exists(self.fileorg['FPM fname']) and os.path.exists(self.fileorg['FPM dir']) and \
os.path.dirname(self.fileorg['FPM fname']) == '':
try_fname = os.path.join(self.fileorg['FPM dir'], self.fileorg['FPM fname'])
if os.path.exists(try_fname):
self.fileorg['FPM fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified FPM file \"{0}\" in {1}".format(self.fileorg['FPM fname'],
self.fileorg['FPM dir']))
if 'LS fname' in self.fileorg and self.fileorg['LS fname'] is not None and \
not os.path.exists(self.fileorg['LS fname']) and os.path.exists(self.fileorg['LS dir']) and \
os.path.dirname(self.fileorg['LS fname']) == '':
try_fname = os.path.join(self.fileorg['LS dir'], self.fileorg['LS fname'])
if os.path.exists(try_fname):
self.fileorg['LS fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified LS file \"{0}\" in {1}".format(self.fileorg['LS fname'],
self.fileorg['LS dir']))
#////////////////////////////////////////////////////////////////////////////////////////////////////
# The solver attribute holds the options handed from AMPL to Gurobi,
# and determines how the field constraints are mathematically expressed.
#////////////////////////////////////////////////////////////////////////////////////////////////////
setattr(self, 'solver', {})
if 'solver' in kwargs:
for field, value in kwargs['solver'].items():
if field in self._file_fields['solver']:
if value in self._solver_menu[field]:
self.solver[field] = value
else:
logging.warning("Warning: Unrecognized solver option \"{0}\" in field \"{1}\", reverting to default".format(value, field))
else:
logging.warning("Warning: Unrecognized field {0} in solver argument".format(field))
# Handle missing values
if 'planeofconstr' not in self.solver or self.solver['planeofconstr'] is None: self.solver['planeofconstr'] = 'FP2'
if 'constr' not in self.solver or self.solver['constr'] is None: self.solver['constr'] = 'lin'
if 'solver' not in self.solver or self.solver['solver'] is None: self.solver['solver'] = 'gurobi'
if 'method' not in self.solver or self.solver['method'] is None: self.solver['method'] = 'bar'
if 'convtol' not in self.solver: self.solver['convtol'] = None
if 'threads' not in self.solver: self.solver['threads'] = None
if 'presolve' not in self.solver or self.solver['presolve'] is None: self.solver['presolve'] = True
if 'crossover' not in self.solver: self.solver['crossover'] = None
setattr(self, 'coron_list', [])
design = {}
for keycat in self._param_menu:
design[keycat] = {}
for (fixed_keycat, fixed_parname), fixed_val in zip(self.fixed_param_index, self.fixed_param_vals):
design[fixed_keycat][fixed_parname] = fixed_val
self.coron_list = []
for idx, param_combo in enumerate(self.varied_param_combos): # TODO: Switch the coronagraph type depending on the symmetry of the telescope aperture and support struts
for (varied_keycat, varied_parname), current_val in zip(self.varied_param_index, param_combo):
design[varied_keycat][varied_parname] = current_val
coron_fileorg = self.fileorg.copy()
if 'survey fname' in coron_fileorg:
survey_name = os.path.basename(coron_fileorg['survey fname'][:-4])
coron_fileorg.pop('survey fname')
else:
survey_name = os.path.basename(os.path.abspath(self.fileorg['work dir']))
num_ID_digits = int(np.floor(np.log10(self.N_combos))) + 1
ID_fmt_str = "{{:s}}-{{:0{:d}d}}".format(num_ID_digits)
coron_fileorg['design ID'] = ID_fmt_str.format(survey_name, idx)
self.coron_list.append( coron_class(design=design, fileorg=coron_fileorg, solver=self.solver) )
setattr(self, 'ampl_infile_status', False)
self.check_ampl_input_files()
setattr(self, 'ampl_src_status', False)
setattr(self, 'ampl_submission_status', False)
setattr(self, 'solution_status', False)
setattr(self, 'eval_status', False)
def write_serial_bash(self, serial_bash_fname=None, overwrite=False, override_infile_status=False):
# Write a bash script to sequentially run each program in a design survey
if serial_bash_fname is None:
coron_fileorg = self.fileorg.copy()
if 'survey fname' in coron_fileorg:
survey_name = os.path.basename(coron_fileorg['survey fname'][:-4])
else:
survey_name = os.path.basename(os.path.abspath(coron_fileorg['work dir']))
serial_bash_fname = os.path.join(coron_fileorg['work dir'], "run_" + survey_name + "_serial.sh")
else:
basename = os.path.basename(serial_bash_fname)
serial_bash_fname = os.path.join(coron_fileorg['work dir'], basename)
if self.ampl_infile_status is False and not override_infile_status:
logging.warning("Error: the most recent input file check for this survey configuration failed.")
logging.warning("The override_infile_status switch is off, so write_serial_bash() will now abort.")
return 2
if not os.path.exists(serial_bash_fname) or overwrite:
serial_bash_fobj = open(serial_bash_fname, "w")
serial_bash_fobj.write("#! /bin/bash -x\n")
for coron in self.coron_list:
serial_bash_fobj.write("ampl {0:s} > {1:s}\n".format(coron.fileorg['ampl src fname'],
coron.fileorg['log fname']))
serial_bash_fobj.close()
os.chmod(serial_bash_fname, 0775)
logging.info("Wrote serial bash survey script to {:s}".format(serial_bash_fname))
return serial_bash_fname
else:
logging.warning("Denied overwrite of serial bash survey script {:s}".format(serial_bash_fname))
return 1
def write_ampl_batch(self, overwrite=False, override_infile_status=False):
write_count = 0
overwrite_deny_count = 0
infile_deny_count = 0
for coron in self.coron_list:
status = coron.write_ampl(overwrite, override_infile_status, verbose=False)
if status == 2:
infile_deny_count += 1
elif status == 1:
overwrite_deny_count += 1
else:
write_count += 1
if write_count == self.N_combos:
logging.info("Wrote all {0:d} of {1:d} design survey AMPL programs into {2:s}".format(write_count, self.N_combos, self.fileorg['ampl src dir']))
else:
logging.warning("Wrote {0:d} of {1:d} design survey AMPL programs into {2:s}. {3:d} already existed and were denied overwriting. {4:d} were denied writing because of a failed input file configuration status.".format(write_count, self.N_combos, self.fileorg['ampl src dir'], overwrite_deny_count, infile_deny_count))
def write_slurm_batch(self, queue_spec='auto', account='s1649', email=None, arch=None,
overwrite=False, override_infile_status=False):
write_count = 0
overwrite_deny_count = 0
for coron in self.coron_list:
status = coron.write_slurm_script(queue_spec=queue_spec, account=account, email=email, arch=arch,
overwrite=overwrite, verbose=False)
if status == 1:
overwrite_deny_count += 1
else:
write_count += 1
if write_count == self.N_combos:
logging.info("Wrote all {0:d} of {1:d} design survey slurm scripts into {2:s}".format(write_count, self.N_combos, self.fileorg['slurm dir']))
else:
logging.warning("Wrote {0:d} of {1:d} design survey AMPL programs into {2:s}. {3:d} already existed and were denied overwriting.".format(write_count, self.N_combos, self.fileorg['slurm dir'], overwrite_deny_count))
def describe(self):
print("This survey has {0:d} design parameter combinations.".format(self.N_combos))
print("{0:d} parameters are varied: {1}".format(len(self.varied_param_index), self.varied_param_index))
print("")
print("File organization:")
pprint.pprint(self.fileorg)
print("")
print("All input files exist? {}".format(self.check_ampl_input_files()))
print("")
print("Last coronagraph in survey list:")
if self.coron_class != AxisymAPLC:
print("Telescope aperture file {:s}".format(self.coron_list[-1].fileorg['TelAp fname']))
print("Focal plane mask file {:s}".format(self.coron_list[-1].fileorg['FPM fname']))
print("Lyot stop file {:s}".format(self.coron_list[-1].fileorg['LS fname']))
print("Job label {:s}".format(self.coron_list[-1].fileorg['job name']))
print("Varied parameter combo tuple:")
pprint.pprint(self.varied_param_combos[-1])
def check_ampl_input_files(self):
survey_status = True
for coron in self.coron_list: # Update all individual statuses
coron_status = coron.check_ampl_input_files()
if coron_status is False: # If one is missing input files, set the survey-wide input file status to False
survey_status = False
self.ampl_infile_status = survey_status
return survey_status
def check_ampl_src_files(self):
status = True
for coron in self.coron_list:
if not os.path.exists(coron.fileorg['ampl src fname']):
status = False
break
self.ampl_src_status = status
return status
def check_solution_files(self):
status = True
for coron in self.coron_list:
if not os.path.exists(coron.fileorg['sol fname']):
status = False
break
self.solution_status = status
return status
def check_eval_status(self):
status = True
for coron in self.coron_list: # Update all individual statuses
if coron.eval_metrics['fwhm area'] is None or coron.eval_metrics['apod nb res ratio'] is None:
status = False
break
self.eval_status = status
return status
def get_metrics(self, fp2res=16, verbose=False):
telap_warning = False
for coron in self.coron_list:
if os.path.exists(coron.fileorg['sol fname']) and \
(coron.eval_metrics['fwhm area'] is None \
or coron.eval_metrics['apod nb res ratio'] is None):
telap_flag = coron.get_metrics(verbose=verbose)
coron.eval_status = True
if telap_flag > 0:
telap_warning = True
if os.path.exists(coron.fileorg['sol fname']) and os.path.exists(coron.fileorg['log fname']) and \
(not hasattr(coron, 'ampl_completion_time') or coron.ampl_completion_time is None):
setattr(coron, 'ampl_completion_time', None)
log = open(coron.fileorg['log fname'])
lines = log.readlines()
for line in lines:
if 'iterations' in line and 'seconds' in line:
split_line = line.split()
coron.ampl_completion_time = float(split_line[split_line.index('seconds')-1])/3600
break
if telap_warning:
logging.warning("No unpadded version of telescope aperture was found, so the optimization version was used to derive throughput metrics.")
def write(self, fname=None):
if fname is not None:
if os.path.dirname(fname) is '': # if no path specified, assume work dir
self.fileorg['survey fname'] = os.path.join(self.fileorg['work dir'], fname)
else:
self.fileorg['survey fname'] = fname
else:
if 'survey fname' not in self.fileorg or \
('survey fname' in self.fileorg and self.fileorg['survey fname'] is None): # set the filename based on the coronagraph type, user, and date
fname_tail = "{0:s}_{1:s}_{2:s}.pkl".format(os.path.basename(os.path.abspath(self.fileorg['work dir'])), getpass.getuser(), datetime.datetime.now().strftime("%Y-%m-%d"))
self.fileorg['survey fname'] = os.path.join(self.fileorg['work dir'], fname_tail)
fobj = open(self.fileorg['survey fname'], 'wb')
pickle.dump(self, fobj)
fobj.close()
os.chmod(self.fileorg['survey fname'], 0644)
logging.info("Wrote the design parameter survey object to {:s}".format(self.fileorg['survey fname']))
def write_spreadsheet(self, overwrite=False, csv_fname=None):
if csv_fname is not None:
if os.path.dirname(csv_fname) is '': # if no path specified, assume work dir
csv_fname = os.path.join(self.fileorg['work dir'], csv_fname)
else:
csv_fname = csv_fname
else:
if 'survey fname' not in self.fileorg or ('survey fname' in self.fileorg and self.fileorg['survey fname'] is None):
#csv_fname_tail = "scda_{:s}_survey_{:s}_{:s}.csv".format(self.coron_class.__name__, getpass.getuser(), datetime.datetime.now().strftime("%Y-%m-%d"))
csv_fname_tail = "{0:s}_{1:s}_{2:s}.csv".format(os.path.basename(os.path.abspath(self.fileorg['work dir'])), getpass.getuser(), datetime.datetime.now().strftime("%Y-%m-%d"))
csv_fname = os.path.join(self.fileorg['work dir'], csv_fname_tail)
else:
csv_fname = self.fileorg['survey fname'][:-4] + ".csv"
with open(csv_fname, 'wb') as survey_spreadsheet:
self.check_ampl_src_files()
self.check_ampl_input_files()
self.check_solution_files()
self.check_eval_status()
surveywriter = csv.writer(survey_spreadsheet)
#/////////////////////////////////////////////////
# Write a header for the spreadsheet
#/////////////////////////////////////////////////
surveywriter.writerow(["Created by {:s} on {:s} at {:s}".format(getpass.getuser(), socket.gethostname(), datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))])
surveywriter.writerow(["FILE ORGANIZATION AND STATUS"])
surveywriter.writerow(["Work dir", self.fileorg['work dir']])
surveywriter.writerow(["AMPL source location", self.fileorg['ampl src dir']])
surveywriter.writerow(["Solution location", self.fileorg['sol dir']])
surveywriter.writerow(["Telescope aperture location", self.fileorg['TelAp dir']])
surveywriter.writerow(["Focal plane mask location", self.fileorg['FPM dir']])
surveywriter.writerow(["Lyot stop location", self.fileorg['LS dir']])
if self.ampl_src_status is True:
surveywriter.writerow(["All AMPL source files exist?", 'Y'])
else:
surveywriter.writerow(["All AMPL source files exist?", 'N'])
if self.ampl_infile_status is True:
surveywriter.writerow(["All input files exist?", 'Y'])
else:
surveywriter.writerow(["All input files exist?", 'N'])
if self.ampl_submission_status is True:
surveywriter.writerow(["All AMPL jobs submitted?", 'Y'])
else:
surveywriter.writerow(["All AMPL jobs submitted?", 'N'])
if self.solution_status is True:
surveywriter.writerow(["All solution files exist?", 'Y'])
else:
surveywriter.writerow(["All solution files exist?", 'N'])
if self.eval_status is True:
surveywriter.writerow(["All evaluation metrics extracted?", 'Y'])
else:
surveywriter.writerow(["All evaluation metrics extracted?", 'N'])
#/////////////////////////////////////////////////
# Write out the fixed design parameters
#/////////////////////////////////////////////////
surveywriter.writerow([""])
surveywriter.writerow(["FIXED design parameters"])
fixed_param_category_row = []
fixed_param_subheading_row = []
for cat in self._param_menu:
fixed_param_category_row.extend([cat,''])
fixed_param_subheading_row.extend(['param name', 'value'])
surveywriter.writerow(fixed_param_category_row)
surveywriter.writerow(fixed_param_subheading_row)
self.fixed_param_table = []
max_N_params = 0
for cat in self._param_menu:
param_col = []
val_col = []
for (param_cat, param) in self.fixed_param_index:
if param_cat is cat:
param_col.append(param)
val_col.append(self.survey_config[cat][param])
N_params = len(param_col)
if N_params > max_N_params:
max_N_params = N_params
self.fixed_param_table.append(param_col)
self.fixed_param_table.append(val_col)
N_cols = len(self.fixed_param_table)
for ci in range(N_cols):
N_rows = len(self.fixed_param_table[ci])
if N_rows < max_N_params:
self.fixed_param_table[ci].extend(['']*(max_N_params - N_rows))
for ri in range(max_N_params):
fixed_table_row = []
for ci in range(N_cols):
fixed_table_row.append(self.fixed_param_table[ci][ri])
surveywriter.writerow(fixed_table_row)
#/////////////////////////////////////////////////
# Write out the varied design parameters
#/////////////////////////////////////////////////
surveywriter.writerow([""])
surveywriter.writerow(["VARIED design parameters ({:d} total combinations)".format(self.N_combos)])
varied_param_category_row = []
varied_param_subheading_row = []
for cat in self._param_menu:
varied_param_category_row.extend([cat,'',''])
varied_param_subheading_row.extend(['param name', 'value list', 'num'])
surveywriter.writerow(varied_param_category_row)
surveywriter.writerow(varied_param_subheading_row)
self.varied_param_table = []
max_N_params = 0
for cat in self._param_menu:
param_col = []
vals_col = []
num_col = []
for (param_cat, param) in self.varied_param_index:
if param_cat is cat:
param_col.append(param)
vals_col.append(self.survey_config[cat][param])
num_col.append(len(self.survey_config[cat][param]))
N_params = len(param_col)
if N_params > max_N_params:
max_N_params = N_params
self.varied_param_table.append(param_col)
self.varied_param_table.append(vals_col)
self.varied_param_table.append(num_col)
N_cols = len(self.varied_param_table)
for ci in range(N_cols):
N_rows = len(self.varied_param_table[ci])
if N_rows < max_N_params:
self.varied_param_table[ci].extend(['']*(max_N_params - N_rows))
for ri in range(max_N_params):
varied_table_row = []
for ci in range(N_cols):
varied_table_row.append(self.varied_param_table[ci][ri])
surveywriter.writerow(varied_table_row)
#/////////////////////////////////////////////////////////
# Write out the survey design parameter combinations
#/////////////////////////////////////////////////////////
surveywriter.writerow([""])
surveywriter.writerow(["SURVEY TABLE"])
catrow = []
paramrow = []
if len(self.varied_param_index) > 0:
for (cat, name) in self.varied_param_index:
catrow.append(cat)
paramrow.append(name)
catrow.extend(['Design ID', 'AMPL program', '', '', '', 'Solution', '', 'Evaluation metrics', '', ''])
paramrow.extend(['survey-index', 'src filename', 'src exists?', 'input files?', 'submitted?', 'sol filename', 'sol exists?', 'comp time (h)',
'inc. energy', 'apodizer non-binarity', 'Tot thrupt', 'half-max thrupt', 'half-max circ thrupt', 'rel. half-max thrupt', 'r=0.7 thrupt', 'r=0.7 circ thrupt', 'rel. r=0.7 thrupt', 'PSF area'])
surveywriter.writerow(catrow)
surveywriter.writerow(paramrow)
for ii, param_combo in enumerate(self.varied_param_combos):
param_combo_row = list(param_combo)
param_combo_row.append(self.coron_list[ii].fileorg['design ID'])
param_combo_row.append(os.path.basename(self.coron_list[ii].fileorg['ampl src fname']))
if os.path.exists(self.coron_list[ii].fileorg['ampl src fname']):
param_combo_row.append('Y')
else:
param_combo_row.append('N')
if self.coron_list[ii].ampl_infile_status is True:
param_combo_row.append('Y')
else:
param_combo_row.append('N')
if self.coron_list[ii].ampl_submission_status is True:
param_combo_row.append('Y')
else:
param_combo_row.append('N')
param_combo_row.append(os.path.basename(self.coron_list[ii].fileorg['sol fname']))
if os.path.exists(self.coron_list[ii].fileorg['sol fname']):
param_combo_row.append('Y')
else:
param_combo_row.append('N')
if hasattr(self.coron_list[ii], 'ampl_completion_time') and self.coron_list[ii].ampl_completion_time is not None:
param_combo_row.append(self.coron_list[ii].ampl_completion_time)
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['inc energy'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['inc energy'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['apod nb res ratio'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['apod nb res ratio'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['tot thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['tot thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['fwhm thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['fwhm thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['fwhm circ thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['fwhm circ thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['rel fwhm thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['rel fwhm thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['p7ap thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['p7ap thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['p7ap circ thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['p7ap circ thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['rel p7ap thrupt'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['rel p7ap thrupt'])
else:
param_combo_row.append('')
if self.coron_list[ii].eval_metrics['fwhm area'] is not None:
param_combo_row.append(self.coron_list[ii].eval_metrics['fwhm area'])
else:
param_combo_row.append('')
surveywriter.writerow(param_combo_row)
survey_spreadsheet.close()
os.chmod(csv_fname, 0644)
logging.info("Wrote design survey spreadsheet to {:s}".format(csv_fname))
class LyotCoronagraph(object): # Lyot coronagraph base class
_file_fields = { 'fileorg': ['work dir', 'ampl src dir', 'TelAp dir', 'FPM dir', 'LS dir',
'sol dir', 'log dir', 'eval dir', 'eval subdir', 'slurm dir',
'ampl src fname', 'slurm fname', 'log fname', 'job name', 'design ID',
'TelAp fname', 'FPM fname', 'LS fname', 'LDZ fname', 'sol fname'],
'solver': ['planeofconstr', 'constr', 'method', 'presolve', 'threads', 'solver', 'crossover', 'convtol'] }
_solver_menu = { 'planeofconstr': ['FP1', 'Lyot', 'FP2'],
'constr': ['lin', 'quad'], 'solver': ['LOQO', 'gurobi', 'gurobix'],
'method': ['bar', 'barhom', 'dualsimp'],
'convtol': [None]+range(5,20),
'presolve': [True, False], 'threads': [None]+range(1,33), 'crossover': [None]+[True, False] }
_aperture_menu = { 'prim': ['hex1', 'hex2', 'hex3', 'hex4', 'key24', 'pie12', 'pie08', 'circ',
'ochex1', 'ochex2', 'ochex3', 'ochex4', 'irisao', 'atlast',
'luvoir15m', 'luvoir15mwStruts'],
'secobs': ['Y60d','Yoff60d','X','Cross','T','Y90d', 'Y00d'],
'thick': ['025','100','125'],
'centobs': [True, False],
'edge': ['gray', 'round', 'floor'] }
def __init__(self, verbose=False, **kwargs):
# Only set fileorg and solver attributes in this constructor,
# since design and eval parameter checking is design-specific.
#////////////////////////////////////////////////////////////////////////////////////////////////////
# The fileorg attribute holds the locations of telescope apertures,
# intermediate masks, co-eval AMPL programs, solutilons, logs, etc.
#////////////////////////////////////////////////////////////////////////////////////////////////////
setattr(self, 'fileorg', {})
if 'fileorg' in kwargs:
for namekey, location in kwargs['fileorg'].items():
if namekey in self._file_fields['fileorg']:
if location is not None:
if namekey.endswith('dir'):
self.fileorg[namekey] = os.path.expanduser(location)
if not os.path.exists(self.fileorg[namekey]):
logging.warning("Warning: The specified location of '{0}', \"{1}\" does not exist".format(namekey, self.fileorg[namekey]))
else:
self.fileorg[namekey] = location
else:
self.fileorg[namekey] = None
else:
logging.warning("Warning: Unrecognized field {0} in fileorg argument".format(namekey))
# Handle missing directory values
if 'work dir' not in self.fileorg or self.fileorg['work dir'] is None:
self.fileorg['work dir'] = os.getcwd()
for namekey in self._file_fields['fileorg']: # Set other missing directory locations to 'work dir'
if namekey.endswith(' dir') and ( namekey not in self.fileorg or self.fileorg[namekey] is None ):
self.fileorg[namekey] = self.fileorg['work dir']
# Make directories for optimization solutions and logs if they don't exist
if not os.path.exists(self.fileorg['sol dir']):
os.mkdir(self.fileorg['sol dir'])
if not os.path.exists(self.fileorg['log dir']):
os.mkdir(self.fileorg['log dir'])
# If the location of the optimizer input file is not known,
# look for it in the directory corresponding to its specific category
if 'TelAp fname' in self.fileorg and self.fileorg['TelAp fname'] is not None and \
not os.path.exists(self.fileorg['TelAp fname']) and os.path.exists(self.fileorg['TelAp dir']) and \
os.path.dirname(self.fileorg['TelAp fname']) == '':
try_fname = os.path.join(self.fileorg['TelAp dir'], self.fileorg['TelAp fname'])
if os.path.exists(try_fname):
self.fileorg['TelAp fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified telescope aperture file \"{0}\" in {1}".format(self.fileorg['TelAp fname'], \
self.fileorg['TelAp dir']))
if 'FPM fname' in self.fileorg and self.fileorg['FPM fname'] is not None and \
not os.path.exists(self.fileorg['FPM fname']) and os.path.exists(self.fileorg['FPM dir']) and \
os.path.dirname(self.fileorg['FPM fname']) == '':
try_fname = os.path.join(self.fileorg['FPM dir'], self.fileorg['FPM fname'])
if os.path.exists(try_fname):
self.fileorg['FPM fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified FPM file \"{0}\" in {1}".format(self.fileorg['FPM fname'], \
self.fileorg['FPM dir']))
if 'LS fname' in self.fileorg and self.fileorg['LS fname'] is not None and \
not os.path.exists(self.fileorg['LS fname']) and os.path.exists(self.fileorg['LS dir']) and \
os.path.dirname(self.fileorg['LS fname']) == '':
try_fname = os.path.join(self.fileorg['LS dir'], self.fileorg['LS fname'])
if os.path.exists(try_fname):
self.fileorg['LS fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified LS file \"{0}\" in {1}".format(self.fileorg['LS fname'], \
self.fileorg['LS dir']))
if 'LDZ fname' in self.fileorg and self.fileorg['LDZ fname'] is not None and \
not os.path.exists(self.fileorg['LDZ fname']) and os.path.exists(self.fileorg['LS dir']) and \
os.path.dirname(self.fileorg['LDZ fname']) == '':
try_fname = os.path.join(self.fileorg['LS dir'], self.fileorg['LDZ fname'])
if os.path.exists(try_fname):
self.fileorg['LDZ fname'] = try_fname
else:
logging.warning("Warning: Could not find the specified LDZ file \"{0}\" in {1}".format(self.fileorg['LDZ fname'], \
self.fileorg['LS dir']))
# If the specified ampl source filename is a simple name with no directory, append it to the ampl source directory.
if 'ampl src fname' in self.fileorg and self.fileorg['ampl src fname'] is not None and \
not os.path.exists(self.fileorg['ampl src fname']) and os.path.dirname(self.fileorg['ampl src fname']) == '':
self.fileorg['ampl src fname'] = os.path.join(self.fileorg['ampl src dir'], self.fileorg['ampl src fname'])
#////////////////////////////////////////////////////////////////////////////////////////////////////
# The solver attribute holds the options handed from AMPL to Gurobi,
# and determines how the field constraints are mathematically expressed.
#////////////////////////////////////////////////////////////////////////////////////////////////////
setattr(self, 'solver', {})
if 'solver' in kwargs:
for field, value in kwargs['solver'].items():
if field in self._file_fields['solver']:
if value in self._solver_menu[field]:
self.solver[field] = value
else:
logging.warning("Warning: Unrecognized solver option \"{0}\" in field \"{1}\", reverting to default".format(value, field))
elif field is 'convtol':
if 8 <= value < 10:
self.solver['convtol'] = value
else:
self.solver['convtol'] = None
else:
logging.warning("Warning: Unrecognized field {0} in solver argument".format(field))
# Handle missing values
if 'planeofconstr' not in self.solver or self.solver['planeofconstr'] is None: self.solver['planeofconstr'] = 'FP2'
if 'constr' not in self.solver or self.solver['constr'] is None: self.solver['constr'] = 'lin'
if 'solver' not in self.solver or self.solver['solver'] is None: self.solver['solver'] = 'gurobi'
if 'method' not in self.solver or self.solver['method'] is None: self.solver['method'] = 'bar'
if 'convtol' not in self.solver: self.solver['convtol'] = None
if 'threads' not in self.solver: self.solver['threads'] = None
if 'presolve' not in self.solver or self.solver['presolve'] is None: self.solver['presolve'] = True
if 'crossover' not in self.solver: self.solver['crossover'] = None
setattr(self, 'ampl_infile_status', None)
if not issubclass(self.__class__, LyotCoronagraph):
self.check_ampl_input_files()
setattr(self, 'ampl_submission_status', None) # Only changed by the queue filler program
setattr(self, 'solution_status', False) # Only changed by the queue filler program
setattr(self, 'ampl_completion_time', None)
setattr(self, 'eval_metrics', {})
self.eval_metrics['inc energy'] = None
self.eval_metrics['tot thrupt'] = None
self.eval_metrics['fwhm thrupt'] = None
self.eval_metrics['fwhm circ thrupt'] = None
self.eval_metrics['p7ap thrupt'] = None
self.eval_metrics['p7ap circ thrupt'] = None
self.eval_metrics['rel fwhm thrupt'] = None
self.eval_metrics['rel p7ap thrupt'] = None
self.eval_metrics['fwhm area'] = None
self.eval_metrics['apod nb res ratio'] = None
def check_ampl_input_files(self):
status = True
if self.design['LS']['aligntol'] is not None:
checklist = ['TelAp fname', 'FPM fname', 'LS fname', 'LDZ fname']
else:
checklist = ['TelAp fname', 'FPM fname', 'LS fname']
for fname in checklist:
if not os.path.exists(self.fileorg[fname]):
status = False
logging.warning("Missing {:s}".format(self.fileorg[fname]))
break
self.ampl_infile_status = status
return status
def get_design_portrait(self, intens_maps, intens_curves, xis, seps, star_diams,
second_curve_diam=None, use_gray_gap_zero=False, get_big_telap=False):
if get_big_telap:
TelAp_big, TelAp, Apod, FPM, LS = self.get_coron_masks(use_gray_gap_zero=use_gray_gap_zero, get_big_telap=True)
else:
TelAp, Apod, FPM, LS = self.get_coron_masks(use_gray_gap_zero=use_gray_gap_zero, get_big_telap=False)
N = self.design['Pupil']['N']
matplotlib.rcParams['font.size'] = 12
portrait_fig = plt.figure(figsize=(10,7))
gs1 = gridspec.GridSpec(2, 3)
gs1.update(left=0.01, right=0.99, bottom=0.02, top=0.99, wspace=0.01)
if get_big_telap:
ax1 = plt.subplot(gs1[0,0])
if N <= 128:
s = 4
else:
s = 2
scaled_TelAp = scipy.ndimage.interpolation.zoom(TelAp, s, order=0)
plt.imshow(scaled_TelAp[s*(N+N/2):, s*N:s*(N+N/2)] + \
TelAp_big[s*(N+N/2):, s*N:s*(N+N/2)])
_ = plt.axis('off')
ax2 = plt.subplot(gs1[0,1])
plt.imshow(TelAp - LS)
_ = plt.axis('off')
ax3 = plt.subplot(gs1[0,2])
plt.imshow(Apod)
_ =plt.axis('off')
else:
ax1 = plt.subplot(gs1[0,0])
plt.imshow(TelAp)
_ = plt.axis('off')
ax2 = plt.subplot(gs1[0,1])
plt.imshow(TelAp - LS)
_ = plt.axis('off')
ax3 = plt.subplot(gs1[0,2])
plt.imshow(Apod)
_ =plt.axis('off')
gs2 = gridspec.GridSpec(2, 3)
gs2.update(left=0.03, right=1.36, bottom=0.04, top=1.10, wspace=0.01)
ax4 = plt.subplot(gs2[1,0])
pixscale_lamoD = xis[1] - xis[0]
tick_labels = np.arange(np.round(xis[0]), np.round(xis[-1]+pixscale_lamoD), 2.)
xc_pix = intens_maps.shape[-1]/2 - 0.5
if isinstance(self, NdiayeAPLC):
fpm_rad = self.design['FPM']['rad']
else:
fpm_rad = self.design['FPM']['R0']
fpm_rad_pix = fpm_rad/pixscale_lamoD
tick_locs = tick_labels/pixscale_lamoD + xc_pix
plt.imshow(np.log10(intens_maps[0,:,:]),
vmin=-(self.design['Image']['c']+1),
vmax=-(self.design['Image']['c']-2), cmap='CMRmap')
fpm_circle = matplotlib.patches.Circle((xc_pix, xc_pix), fpm_rad_pix, facecolor='none',
edgecolor='w', linewidth=2., alpha=1.,
clip_on=False, linestyle='--')
ax4.add_patch(fpm_circle)
plt.xticks(tick_locs, tick_labels)
plt.yticks(tick_locs, tick_labels)
plt.tick_params(labelsize=9)
plt.colorbar(orientation='vertical', shrink=0.75, pad=0.03)
gs3 = gridspec.GridSpec(2, 3)
gs3.update(left=0.36, right=0.98, bottom=0.08, top=1.05, wspace=0.01)
ax5 = plt.subplot(gs3[1,1:])
diam_1 = star_diams[0]
#diam_1_curve, = plt.semilogy(seps, intens_curves[0,:], 'b', zorder=3)
diam_1_curve, = plt.semilogy(seps, intens_curves[0,:], color=plt.cm.tab10(0), zorder=3)
if second_curve_diam is not None:
ind_diam_2 = np.argmin(np.abs(np.array(star_diams) - second_curve_diam))
diam_2 = star_diams[ind_diam_2]
#diam_2_curve, = plt.semilogy(seps, intens_curves[ind_diam_2,:], 'r', zorder=2)
diam_2_curve, = plt.semilogy(seps, intens_curves[ind_diam_2,:], color=plt.cm.tab10(3), zorder=2)
fpm_line = plt.vlines(fpm_rad, 10**-16, 1, linestyle='--', color='gray', zorder=1)
plt.xlim([seps[0], seps[-1]])
plt.ylim([10**-(self.design['Image']['c']+1), 5*10**-(self.design['Image']['c'])])
plt.ylabel(r'$I/I_\star$',fontsize=16)
plt.xlabel(r'Separation ($\lambda/D$)',fontsize=12)
plt.grid('on')
if second_curve_diam is not None:
plt.legend([diam_1_curve, diam_2_curve, fpm_line],
[r'$\theta_\star=${:.2f} $\lambda/D$'.format(diam_1),
r'$\theta_\star=${:.2f} $\lambda/D$'.format(diam_2),
'FPM radius'], fontsize=12, loc='upper center')
else:
plt.legend([diam_1_curve, fpm_line],
[r'$\theta_\star=${:.2f} $\lambda/D$'.format(diam_1),
'FPM radius'], fontsize=12, loc='upper center')
return portrait_fig
def write_design_package(self, eval_path=None, pixscale_lamoD=0.25, Nlam=None, dpi=300):
"""
Write a coronagraph design package including mask files (Telescope pupil,
Apodizer, FPM, Lyot stop) in FITS format and a simple portrait viewgraph.
TBA: example PSF evaluation scripts.
"""
if eval_path is None:
if 'design ID' in self.fileorg:
design_label = "{:s}_{:s}".format(self.fileorg['design ID'],
self.fileorg['job name'])
else:
design_label = self.fileorg['job name']
self.fileorg['eval subdir'] = os.path.join(self.fileorg['eval dir'], design_label)
else:
self.fileorg['eval subdir'] = os.path.normpath(eval_path)
design_label = os.path.basename(eval_path)
eval_path = self.fileorg['eval subdir']
if not os.path.exists(eval_path):
os.mkdir(eval_path)
if Nlam is None:
Nlam = 2*self.design['Image']['Nlam'] + 1
TelAp, Apod, FPM, LS = self.get_coron_masks(use_gray_gap_zero=False)
telap_hdu = pyfits.PrimaryHDU(TelAp)
telap_fits_fname = os.path.join(eval_path, 'TelAp.fits')
telap_hdu.writeto(telap_fits_fname, clobber=True)
apod_hdu = pyfits.PrimaryHDU(Apod)
apod_fits_fname = os.path.join(eval_path, 'Apod.fits')
apod_hdu.writeto(apod_fits_fname, clobber=True)
fpm_hdu = pyfits.PrimaryHDU(FPM)
fpm_fits_fname = os.path.join(eval_path, 'FPM.fits')
fpm_hdu.writeto(fpm_fits_fname, clobber=True)
LS_hdu = pyfits.PrimaryHDU(LS)
LS_fits_fname = os.path.join(eval_path, 'LS.fits')
LS_hdu.writeto(LS_fits_fname, clobber=True)
if isinstance(self, NdiayeAPLC):