codegen.py
23.9 KB
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
#! /usr/bin/env python
# ==========================================================================
# GammaLib code generator
#
# Copyright (C) 2017 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import os
import sys
import glob
import commands
import fileinput
from datetime import date
import gammalib
# ================= #
# Confirm something #
# ================= #
def confirm(text):
"""
Confirm something
Parameters
----------
text : str
Thing to confirm
Returns
-------
flag : bool
True if something is confirmed
"""
# Confirmation loop
waiting = True
while waiting:
confirmation = str(raw_input(text+' (y/n): '))
if confirmation == 'q':
sys.exit()
elif confirmation == 'y':
flag = True
waiting = False
elif confirmation == 'n':
flag = False
waiting = False
# Return confirmation flag
return flag
# ============ #
# Get response #
# ============ #
def response(text, confirm_response=False):
"""
Get response
Parameters
----------
text : str
Thing we want to get a response to
confirm_response : bool
True if response should be confirmed
Returns
-------
response : str
Reponse
"""
# Looping until response is accepted
looping = True
while looping:
# Get response from input
waiting = True
while waiting:
response = str(raw_input('%s: ' % text))
if response == 'q':
sys.exit()
else:
waiting = False
# If the version number change is confirmed then do the change
if confirm_response:
if confirm('Is "%s" ok?' % response):
looping = False
else:
looping = False
# Return response
return response
# ======== #
# Add file #
# ======== #
def add_file(infile, outfile, tokens):
"""
Add a class file, replacing all tokens
Parameters
----------
infile : str
Input filename
outfile : str
Output filename
tokens : list of dict
Token list
"""
# Create output file
file = open(outfile, "w")
# Initialise number of header lines
n_header = 0
# Loop over input file
for line in open(infile, 'r'):
# Signal if this is a header line
is_header = False
if len(line) > 75:
is_header = line[1] == '*' and line[75] == '*'
n_header += 1
# Replace tokens in line
for token in tokens:
line = line.replace(token['pattern'], token['string'])
# If we have a header line than format the line
if is_header:
text = line.strip(' *\n')
if n_header == 2:
line = ' *'+gammalib.centre(text,73)+'*\n'
elif n_header == 4:
line = ' *'+gammalib.left(' '+text,73)+'*\n'
# Write out line
file.write(line)
# Close file
file.close()
# Return
return
# ==================== #
# Determine base class #
# ==================== #
def get_base_class(filename):
"""
Determine base class of a file
Parameters
----------
filename : str
Filename
Returns
-------
baseclass : str
Base class name
"""
# Initialise empty baseclass
baseclass = ''
# Loop over file
for line in open(filename, 'r'):
# Search for base class name
if 'class' in line:
i = line.find('public')
if i != -1:
baseclass = line[i+7:].rstrip('{ \n')
break
# Return
return baseclass
# ===================== #
# Set instrument tokens #
# ===================== #
def set_class_tokens(classname, author, what, object):
"""
Set replacement tokens for a generic class
"""
# Get current year
year = str(date.today().year)
# Set tokens
tokens = [{'pattern': 'GTPLClass', 'string': classname},
{'pattern': 'GTPLCLASS', 'string': classname.upper()},
{'pattern': '[WHAT]', 'string': what},
{'pattern': '[what]', 'string': what.lower()},
{'pattern': '[AUTHOR]', 'string': author},
{'pattern': 'TPL_OBJECT', 'string': object.lower()},
{'pattern': '[YEAR]', 'string': year}]
# Return tokens
return tokens
# ===================== #
# Set instrument tokens #
# ===================== #
def set_inst_tokens(name, instrument, author):
"""
Set replacement tokens for an instrument
"""
# Get current year
year = str(date.today().year)
# Set tokens
tokens = [{'pattern': 'xxx', 'string': name.lower()},
{'pattern': 'XXX', 'string': name.upper()},
{'pattern': '[INSTRUMENT]', 'string': instrument},
{'pattern': '[AUTHOR]', 'string': author},
{'pattern': '[YEAR]', 'string': year}]
# Return tokens
return tokens
# ======================= #
# Add an instrument class #
# ======================= #
def add_instrument_class(name, tokens, classname, tmpname=None):
"""
Add an instrument class
Parameters
----------
name : str
Module name
tokens : str
Tokens for replacement
classname : str
Class name
tmpname : str, optional
Template name
"""
# Set template classname
if tmpname == None:
tmpname = classname.replace(name.upper(), 'XXX')
# Set destination file names
incfile = 'inst/%s/include/%s.hpp' % (name, classname)
srcfile = 'inst/%s/src/%s.cpp' % (name, classname)
pyfile = 'inst/%s/pyext/%s.i' % (name, classname)
# Add files
add_file('src/template/%s.hpp' % tmpname, incfile, tokens)
add_file('src/template/%s.cpp' % tmpname, srcfile, tokens)
add_file('src/template/%s.i' % tmpname, pyfile, tokens)
# Update module header
filename = 'inst/%s/include/G%sLib.hpp' % (name, name.upper())
afterline = '#include "G%sObservation.hpp"' % (name.upper())
insertline = '#include "%s.hpp"\n' % (classname)
for line in fileinput.FileInput(filename,inplace=1):
if afterline in line:
line = line.replace(line, line+insertline)
print line,
# Update module Makefile.am
filename = 'inst/%s/Makefile.am' % (name)
insertline1 = ' src/%s.cpp ' % (classname)
insertline2 = ' include/%s.hpp ' % (classname)
for line in fileinput.FileInput(filename,inplace=1):
if 'sources=' in line.replace(' ', ''):
last = line[-2]
line = line.replace(line, line+insertline1+last+'\n')
if 'pkginclude_HEADERS=' in line.replace(' ', ''):
last = line[-2]
line = line.replace(line, line+insertline2+last+'\n')
print line,
# Update Python module
filename = 'inst/%s/pyext/%s.i' % (name, name)
with open(filename, 'a') as f:
f.write('%%include "%s.i"\n' % classname)
# Return
return
# ============================================== #
# Adjust configuration for new instrument module #
# ============================================== #
def adjust_config(name):
"""
Parameters
----------
name : str
Module name
"""
# Adjust inst/Makefile.am
config = 'if WITH_INST_%s\nINST_%s = %s\nendif\n' % (name.upper(), name.upper(), name)
for line in fileinput.FileInput('inst/Makefile.am',inplace=1):
if 'Detect configuration' in line:
line = line.replace(line, line+config)
elif 'SUBDIRS=' in line.replace(' ', ''):
line = line.replace(line, line[:-1]+' $(INST_%s)\n' % name.upper())
print line,
# Adjust configure.ac
checks = '# Checks for %s interface\n' \
'AC_ARG_WITH([%s],\n' \
' [AS_HELP_STRING([--with-%s],\n' \
' [compile in %s specific interface [default=yes]])],\n' \
' [],\n' \
' [with_%s=yes])\n' \
'if test "x$with_%s" = "xyes"; then\n' \
' AC_CHECK_FILE([$srcdir/inst/%s/README.md],\n' \
' [with_%s=yes],\n' \
' [with_%s=no])\n' \
'fi\n' \
'AM_CONDITIONAL(WITH_INST_%s, test "x$with_%s" = "xyes")\n' % \
(name.upper(), name, name, name.upper(), name, name, name,
name, name, name.upper(), name)
wrap = ' if test "x$with_%s" = "xyes"; then\n' \
' AC_CHECK_FILES([$srcdir/pyext/gammalib/%s_wrap.cpp\n' \
' $srcdir/pyext/gammalib/%s.py],,\n' \
' [has_wrappers="no"])\n' \
' fi' % (name, name, name)
files = 'if test "x$with_%s" = "xyes"; then\n' \
' AC_CONFIG_FILES([inst/%s/Makefile])\n' \
' AC_CONFIG_FILES([inst/%s/test/Makefile])\n' \
'fi' % (name, name, name)
info = 'if test "x$with_%s" = "xyes"; then\n' \
' echo " * %s interface (yes)"\n' \
'else\n' \
' echo " - %s interface (no)"\n' \
'fi' % (name, name.upper(), name.upper())
for line in fileinput.FileInput('configure.ac',inplace=1):
if '# Insert new checks here' in line:
print(checks)
elif '# Insert new wrappers here' in line:
print(wrap)
elif '# Inset new Makefiles here' in line:
print(files)
elif '# Insert new interface informations here' in line:
print(info)
print line,
# Return
return
# ===================================================== #
# Adjust Python configuration for new instrument module #
# ===================================================== #
def adjust_python_config(name, instrument):
"""
Parameters
----------
name : str
Module name
instrument : str
Instrument
"""
# Adjust pyext/setup.py.in
module = 'if \'@WITH_INST_%s_TRUE@\' != \'#\':\n' \
' print(\'Include %s instrument interface in gammalib Python module.\')\n' \
' inst_modules.append(\'%s\')' % \
(name.upper(), instrument, name)
for line in fileinput.FileInput('pyext/setup.py.in',inplace=1):
if '# Insert new module here' in line:
print(module)
print line,
# Adjust pyext/Makefile.am
target = 'if WITH_INST_%s\n' \
' %s_SWIG_TARGETS = $(wrapperdir)/gammalib/%s_wrap.cpp \\\n' \
' $(wrapperdir)/gammalib/%s.py\n' \
' %s_TESTS = $(top_srcdir)/inst/%s/test/test_%s.py\n' \
'endif' % (name.upper(), name.upper(), name, name,
name.upper(), name, name.upper())
targets = ' $(%s_SWIG_TARGETS) ' % name.upper()
rule = '# Rule for %s module\n' \
'if WITH_INST_%s\n' \
'$(wrapperdir)/gammalib/%s.py: $(wrapperdir)/gammalib/%s_wrap.cpp\n' \
'$(wrapperdir)/gammalib/%s_wrap.cpp: $(top_srcdir)/inst/%s/pyext/%s.i\n' \
' if $(SWIGCOMPILE) -MMD -MF "gammalib/%s.Tpi" -I$(top_srcdir)/pyext -o gammalib/%s_wrap.cpp -outdir gammalib $<; \\\n' \
' then mv -f "gammalib/%s.Tpi" "gammalib/%s.Pi"; else rm -f "gammalib/%s.Tpi"; exit 1; fi\n' \
'endif\n' % (name.upper(), name.upper(), name, name, name,
name, name, name, name, name, name, name)
for line in fileinput.FileInput('pyext/Makefile.am',inplace=1):
if '# Insert new target here' in line:
print(target)
elif 'INST_SWIG_TARGETS=' in line.replace(' ', ''):
last = line[-2]
line = line.replace(line, line+targets+last+'\n')
elif '$(MWL_TESTS)' in line:
line = line.replace(line, line[:-1]+' $(%s_TESTS)\n' % name.upper())
if '# Insert new rule here' in line:
print(rule)
print line,
# Return
return
# =================================================== #
# Adjust test configuration for new instrument module #
# =================================================== #
def adjust_test_config(name, instrument):
"""
Parameters
----------
name : str
Module name
instrument : str
Instrument
"""
# Adjust test/Makefile.am
test = 'if WITH_INST_%s\n' \
' INST_%s = $(top_builddir)/inst/%s/test/test_%s\n' \
' TEST_%s = :$(top_srcdir)/inst/%s/test\n' \
' TEST_%s_ENV = TEST_%s_DATA=$(top_srcdir)/inst/%s/test/data\n' \
'endif' % (name.upper(), name.upper(), name, name.upper(),
name.upper(), name, name.upper(), name.upper(),
name)
testenv = ' $(TEST_%s_ENV) ' % name.upper()
tests = ' $(INST_%s) \\\n' % name.upper()
for line in fileinput.FileInput('test/Makefile.am',inplace=1):
if '# Insert new test here' in line:
print(test)
elif 'TEST_PYTHON_ENV=' in line.replace(' ', ''):
line = line.replace(line, line[:-1]+'$(TEST_%s)\n' % name.upper())
elif 'TEST_DATA=$(top_srcdir)/test/data' in line:
last = line[-2]
line = line.replace(line, line+testenv+last+'\n')
elif '$(TEST_PYTHON_SCRIPT)' in line:
line = line.replace(line, tests+line)
print line,
# Adjust test/test_python.py
test = '# Try importing %s tests\n' \
'try:\n' \
' import test_%s\n' \
' has_%s = True\n' \
'except:\n' \
' has_%s = False\n' % \
(instrument, name.upper(), name, name)
data = ' os.environ[\'TEST_%s_DATA\'] = \'%s/data\'' % \
(name.upper(), name)
suite = ' # Optionally handle %s suite\n' \
' if has_%s:\n' \
' suite_%s = test_%s.Test()\n' \
' suite_%s.set()\n' \
' suites.append(suite_%s)\n' % \
(instrument, name, name, name.upper(), name, name)
for line in fileinput.FileInput('test/test_python.py',inplace=1):
if '# Insert new test here' in line:
print(test)
if '# Insert new environment here' in line:
print(data)
if '# Insert new suite here' in line:
print(suite)
print line,
# Return
return
# ======================== #
# Manage instrument module #
# ======================== #
def module_menu():
"""
Manage instrument module
"""
# Annonce actions
print("")
print("Add instrument module")
print("---------------------")
# Stay in loop until there is a final confirmation
while True:
# Enter a module name
while True:
name = response('Please enter a 3 digit-name for the module').lower()
if len(name) == 3:
break
else:
print('*** Error: Module name "%s" has not 3 digits.' % name)
# If module exists already then ask if classes should be added, and
# quit if this is not the case
if os.path.isdir('inst/%s' % name):
if not confirm('Module "%s" exists already. Do you want to add '
'classes to this module?' % name):
return
# Enter other information
instrument = response('Please enter the instrument name (e.g. "Fermi/LAT")')
author = response('Please enter your name (e.g. "Joe Public")')
# Ask to confirm module summary
print('\nAll right. Have now:')
print('Module name .....: "%s"' % name)
print('Instrument name .: "%s"' % instrument)
print('Your name .......: "%s"' % author)
if confirm('Is this correct?'):
break
# Set tokens
tokens = set_inst_tokens(name, instrument, author)
# If the module exists already then determine all base classes that are
# not yet implemented and propose to add them one by one ...
if os.path.isdir('inst/%s' % name):
# Determine which of the baseclasses are not yet implemented
baseclasses = ['GObservation', 'GResponse',
'GEventList', 'GEventAtom', 'GEventCube', 'GEventBin',
'GInstDir', 'GRoi']
files = glob.glob('inst/%s/include/*.hpp' % name)
for file in files:
baseclass = get_base_class(file)
if baseclass in baseclasses:
baseclasses.remove(baseclass)
# If all baseclasses are already there then exist now
if len(baseclasses) == 0:
print('\nAll right. The module exists already and all base classes '
'are already implemented. Return now to main menu.')
return
else:
print('\nAll right. Now let\'s add some classes:')
# Loop over all missing baseclasses
for baseclass in baseclasses:
classname = 'G'+name.upper()+baseclass[1:]
if confirm('Add "%s" class?' % classname):
add_instrument_class(name, tokens, classname)
# ... otherwise add a new module
else:
# Setup base classes
baseclasses = ['GObservation', 'GResponse']
# Ask further questions
print('\nAll right. You want a new "%s" instrument module.' % name)
while True:
add_list = confirm('Do you want event list support?')
add_bin = confirm('Do you want binned event data support?')
if not add_list and not add_bin:
print('*** Warning: You need no support for event lists and '
'binned event data. This means that you have no data :o')
if confirm('Is this true? You want a module that cannot handle data?'):
break
else:
break
# Add base classes according to choice
if add_list or add_bin:
baseclasses.append('GInstDir')
if add_list:
baseclasses.extend(['GEventList', 'GEventAtom', 'GRoi'])
if add_bin:
baseclasses.extend(['GEventCube', 'GEventBin'])
# Create directory structure
os.mkdir('inst/%s' % name)
os.mkdir('inst/%s/caldb' % name)
os.mkdir('inst/%s/include' % name)
os.mkdir('inst/%s/pyext' % name)
os.mkdir('inst/%s/src' % name)
os.mkdir('inst/%s/test' % name)
os.mkdir('inst/%s/test/data' % name)
# Add some files
add_file('src/template/inst_Makefile.am',
'inst/%s/Makefile.am' % name, tokens)
add_file('src/template/inst_README.md',
'inst/%s/README.md' % name, tokens)
add_file('src/template/GXXXLib.hpp',
'inst/%s/include/G%sLib.hpp' % (name, name.upper()), tokens)
add_file('src/template/xxx.i',
'inst/%s/pyext/%s.i' % (name, name), tokens)
add_file('src/template/inst_test_Makefile.am',
'inst/%s/test/Makefile.am' % name, tokens)
add_file('src/template/inst_test_XXX.hpp',
'inst/%s/test/test_%s.hpp' % (name, name.upper()), tokens)
add_file('src/template/inst_test_XXX.cpp',
'inst/%s/test/test_%s.cpp' % (name, name.upper()), tokens)
add_file('src/template/inst_test_XXX.py',
'inst/%s/test/test_%s.py' % (name, name.upper()), tokens)
# Adjust configuration
adjust_config(name)
# Adjust Python configuration
adjust_python_config(name, instrument)
# Adjust test configuration
adjust_test_config(name, instrument)
# Loop over all baseclasses
for baseclass in baseclasses:
classname = 'G'+name.upper()+baseclass[1:]
add_instrument_class(name, tokens, classname)
# Return
return
# ==================== #
# Manage generic class #
# ==================== #
def generic_class_menu():
"""
Manage class
"""
# Annonce actions
print("")
print("Add generic class")
print("-----------------")
# Stay in loop until there is a final confirmation
while True:
# Get class directory
while True:
dir = response('Please enter directory where class should reside '
'(e.g. "inst/cta", "src/obs")').lower()
if os.path.isdir(dir):
break
else:
print('*** Error: Directory not found.')
# Enter other information
classname = response('Please enter a class name (e.g. "GEnergy")')
what = response('Please say what the class is for (e.g. "Energy")')
object = response('Please say how an instance of the class should be named (e.g. "energy")')
author = response('Please enter your name (e.g. "Joe Public")')
# Ask to confirm module summary
print('\nAll right. Have now:')
print('Class name ......: "%s"' % classname)
print('Class descriptor : "%s"' % what)
print('Class instance ..: "%s"' % object)
print('Your name .......: "%s"' % author)
if confirm('Is this correct?'):
break
# Set tokens
tokens = set_class_tokens(classname, author, what, object)
# If we have an instrument model then add a class to the instrument
if 'inst/' in dir:
name = dir[5:8]
add_instrument_class(name, tokens, classname, 'GTPLClass')
# Otherwise we have a core module
else:
print('Core modules not supported yet, sorry ;)')
# Return
return
# ================ #
# Manage main menu #
# ================ #
def main_menu():
"""
Manage main menu
"""
# Print main menu
print('[1] Add instrument module')
#print('[2] Add spectral model')
#print('[3] Add spatial model')
#print('[4] Add temporal model')
print('[4] Add generic class')
print('[q] Quit')
# Wait for the input
waiting = True
while waiting:
choice = str(raw_input('Enter your choice: '))
#if choice == '1' or choice == '2' or choice == '3' or choice == '4' or \
# choice == 'q':
if choice == '1' or choice == '4' or choice == 'q':
waiting = False
# Return choice
return choice
# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':
# Check if script has been started from GammaLib root directory
if not os.path.isfile('gammalib.pc.in'):
print('"codgen.py" script needs to be started from GammaLib source code '
'root directory, you are somewhere else. Quit now.')
sys.exit()
# Clear console
os.system('clear')
# Print header
print('GammaLib code generator')
print('=======================')
print('')
# Enter endless loop
while True:
# Show main menu
choice = main_menu()
# Dispatch according to choice
if choice == '1':
module_menu()
print('')
elif choice == '2':
#package_version_menu()
print('')
elif choice == '3':
#libtool_version_menu()
print('')
elif choice == '4':
generic_class_menu()
print('')
elif choice == 'q':
break