#!/usr/bin/env python """ Quick and dirty script to convert PR config files to ACL Translation table up to date with ACL v0r10 (12 Jul 2016) B. Swinkels, D. Bersanetti, L. Rolland, 2016 """ import os, sys, shlex from itertools import chain # utility functions def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in xrange(0, len(l), n): yield l[i:i+n] def add_quotes(s): if not s or ' ' in s: s = '"%s"' % s return s class Struct(object): '''simple container''' pass # translation table """ Define translation table as a multi-line string with alternating lines of old and new syntax. Empty lines are skipped. Old syntax should be a keyword followed by list of arguments surrounded by {}. For arguments that are no longer used use any name you like. New keyword can be any valid input to str.format() format, see https://docs.python.org/2/library/string.html#formatstrings It is required that all {args} used in the new syntax are present in the old syntax. As a special case {*} can be used for matching keywords with a variable number of arguments at the end. Defaults for missing parameters (only at the end) can be defines as: OLD_KEYWORD {par1} {par2} {par3} {par4=defaultval} Arguments that are missing in the old syntax can be hard-coded in the new syntax to something that can be easily replaced by hand later, e.g """ table = ''' PR_ADC_CH {name} {input} {offset} {slope} {unit} # nameOut - unit - rampTime - samplingFreq - nameIn - offset - gain - filterName ACL_ADC_CH {name} {unit} 1 {input} {offset} {slope} # PR2ACL WARNING: set manually FSAMPLE and FILTERNAME PR_CLIP {name} {input} {min} {max} # nameOut - nameIn - min - max ACL_CLIP_CH {name} {input} {min} {max} PR_CONST_CH {name} {value} {fsample} {unit} {ramptime=1} # nameOut - unit - rampTime - samplingFreq - value ACL_CONST_CH {name} {unit} {ramptime} {fsample} {value} PR_DAC_CH {name} {chanID} {type} {input} {offset} {gain} {fsample} {filtname} # nameOut - rampTime - samplingFreq - nameIn - offset - gain - filterName - dacType ACL_DAC_CH {name} 1 {fsample} {input} {offset} {gain} {filtname} {type} PR_DECL_CH {name} {fsample} {unit} # nameOut - unit - samplingFreq ACL_DECL_CH {name} {unit} {fsample} PR_DEBUG {level} # ACL_DEBUG {level} PR_DEMOD_1I {name} {input} {demod_line} {fsample} {filtname} {phase} {ramptime} {comp} # nameOut - rampTime - samplingFreq - nameIn - line - filterName - phase - additional phase ACL_DEMOD {name} {ramptime} {fsample} {input} {filtname} {phase} 0.0 # PR2ACL WARNING: manually convert the computation method "{comp}" and the demodulation line "{demod_line}" into a ACL_SINELINE_CH object PR_DEMOD_1I_CH {name} {input} {unused_parameter} {function} # OBSOLETE #ACL_DEMOD_1I_CH {name} {input} {function} # PR2ACL WARNING: obsolete key, use one of the available outputs of the corresponding ACL_DEMOD channel PR_DEMOD_1I_LINE {name} {property} {fsample} {comp} {unit} # OBSOLETE #ACL_DEMOD_1I_LINE {name} {property} {fsample} {comp} {unit} # PR2ACL WARNING: OBSOLETE, manually convert this to a ACL_SINELINE_CH object, to be used in the definition of the corresponding ACL_DEMOD channel PR_DEMOD_2I {name} {fmod} {inputA} {inputB} {n_cycle} {n_avg} {phase} {threshold} # OBSOLETE? #ACL_DEMOD_2I {name} {fmod} {inputA} {inputB} {n_cycle} {n_avg} {phase} {threshold} # PR2ACL WARNING: KEYWORD NOT (YET?) DEFINED IN ACL PR_DEMOD_2I_CH {name} {input} {unit} {function} # OBSOLETE #ACL_DEMOD_2I_CH {name} {input} {unit} {function} # PR2ACL WARNING: KEYWORD NO MORE DEFINED IN ACL PR_FILTER_BUTTERWORTH {name} {type} {order} {atten} {freq} {param} # fltName - FltType - order - attenuation_dB - @Freq - notch or bandwidth info ACL_FILTER_BUTTERWORTH {name} {type} {order} {atten} {freq} {param} PR_FILTER_2ND_S {name} {*} # fltName - b0,b1,b2, a0,a1,a2 - ... ACL_FILTER_2ND_S {name} {*} PR_FILTER_GC_POLES {name} {*} # fltName - f,Q - ... ACL_FILTER_POLES {name} {*} PR_FILTER_GC_ZEROS {name} {*} # fltName - f,Q - ... ACL_FILTER_ZEROS {name} {*} PR_FILTER_1ST_POLES {name} {*} # fltName - f,Q - ... ACL_FILTER_1ST_POLES {name} {*} PR_FILTER_1ST_ZEROS {name} {*} # fltName - f,Q - ... ACL_FILTER_1ST_ZEROS {name} {*} PR_FILTER_2ND_POLES {name} {*} # fltName - f,Q - ... ACL_FILTER_2ND_POLES {name} {*} PR_FILTER_2ND_ZEROS {name} {*} # fltName - f,Q - ... ACL_FILTER_2ND_ZEROS {name} {*} PR_FILTER_SET {name} {gain} {freq} {max_biquad} # fltName - filter ramp time - filterGain - @Freq - max filter order ACL_FILTER_SET {name} 1.0 {gain} {freq} {max_biquad} #PR2ACL WARNING: last number must be multiplied by two PR_FILTER_CH {name} {input} {gain} {filtname} {fsample} {unit} {ramptime=1} {unused_parameter} # nameOut - unit - rampTime - samplingFreq - nameIn - gain - filterName ACL_FILTER_CH {name} {unit} {ramptime} {fsample} {input} {gain} {filtname} # PR2ACL WARNING: FLAG = {unused_parameter} has to be defined in a ACL_FILTER_SET channel PR_FILTER_CH_LATCH_CND {name} {channel} # nameFilterOut - nameRelay ACL_FILTER_CH_LATCH_CND {name} {channel} PR_FILTER_CH_RESET_CND {name} {channel} # nameFilterOut - nameRelay ACL_FILTER_CH_RESET_CND {name} {channel} PR_INFO {*} # List of channels for user messages ACL_INFO {*} PR_NOISE_CH {name} {density} {seed} {unit} {fsample} {ramptime=1} # nameOut - unit - rampTime - samplingFreq - density - seed ACL_NOISE_CH {name} {unit} {ramptime} {fsample} {density} {seed} PR_NTP {name} {mode} {offset} {leaps} {flag} # ACL_NTP {name} {mode} {offset} {leaps} {flag} PR_NTP_CH {name} {input} {function} # ACL_NTP_CH {name} {input} {function} PR_NTP_DAC {name} {input} {unit} {start} # ACL_NTP_DAC {name} {unit} {input} {start} PR_OP {name} {*} # nameOut - unit - ... #ACL_OP_CH {name} {*} # PR2ACL WARNING: move the last parameter (UNIT) as second, right after the name; CHECK CORRECT ORDERING PR_OP_CH {name} {input} {operand} {fsample} {pos} # nameOut - samplingFreq - nameIn - operationType - samplingDelay(deci) ACL_LF_CH {name} {fsample} {input} {operand} {pos} # PR2ACL WARNING: check the sampling position parameter (the last one in Pr) if "deci" is used PR_PERF {number} # ACL_PERF {number} PR_RAMP_CH {name} {ampl} {freq} {t0} {t01} {t1} {t10} {offset} {unit} {fsample=} {ramptime=1} # nameOut - unit - rampTime - samplingFreq - amplitude - freq - zero(%) - rise(%) - one(%) - fall(%) - offset ACL_RAMP_CH {name} {unit} {ramptime} {fsample} {ampl} {freq} {t0} {t01} {t1} {t10} {offset} PR_RAMP_AUTO {name} {ramp} {sw0} {reduction} {sw1} # rampName - nameRelay_slow - slope reduction factor - nameRelay_stab ACL_RAMP_CH_AUTO {name} {sw0} {reduction} {sw1} PR_ROTATE {name} {P} {Q} {phase} {ramp=1} # nameOut - rampTime - inI - inQ - phase ACL_ROTATE {name} {ramp} {P} {Q} {phase} # PR2ACL WARNING: if phase is a channel, add it with key ACL_ROTATE_{PHI,DDM,PRIMARY} PR_ROTATE_CH {name} {input} {unit} {function} # OBSOLETE key #PR_ROTATE_CH {name} {input} {unit} {function} PR_SINEWAVE_CH {name} {ampl} {freq} {phase} {offset} {unit} {method} {fsample=} {ramptime=1} # nameOut - unit - rampTime - samplingFreq - amplitude - freq - phase - offset ACL_SINEWAVE_CH {name} {unit} {ramptime} {fsample} {ampl} {freq} {phase} {offset} PR_SMS {*} # List of channels ACL_SMS {*} # WARNING: not yet enabled PR_SUM {name} {*} # nameOut - unit - rampTime - weight, nameIn - ... ACL_SUM_CH {name} {*} # PR2ACL WARNING: set manually UNIT, RAMPTIME PR_SUM_CH {name} {*} # nameOut - unit - rampTime - weight, nameIn - ... ACL_SUM_CH {name} {*} # PR2ACL WARNING: set manually UNIT, RAMPTIME PR_SUM_SET {name} {unit} {ramptime=1} # OBSOLETE #PR_SUM_SET {name} {unit} {ramptime} # PR2ACL WARNING: OBSOLETE KEY: add unit "{unit}" and ramptime "{ramptime}" directly in the ACL_SUM_CH channel PR_SWITCH {name} {tweight} {entry1} {entry2} # nameOut - unit - relayName - nameIn1 - nameIn2 ACL_SWITCH_CH {name} {tweight} {entry1} {entry2} # PR2ACL WARNING: set manually UNIT PR_TWEIGHT {output} {t01} {t10} {input} {th01} {th10} {fsample=} {state} {cond} # nameOut - unit - samplingFreq - duration_0to1 - duration_1to0 - start state - channelIn - threshold_0to1 - threshold_1to0 - falling_or_rising_edge ACL_RELAY_CH {output} {fsample} {t01} {t10} {state} {input} {th01} {th10} {cond} # PR2ACL WARNING: set manually UNIT PR_TWEIGHT_CH {name} {tweight} {function} # #PR_TWEIGHT_CH {name} {tweight} {function} # PR2ACL WARNING: OBSOLETE KEY: use _INV output of a standard ACL_RELAY_CH PR_CHBUF_D {prefix} {*} # prefix - list of channels published as double (suffix _D) ACL_CHBUF_D {prefix} {*} PR_CHBUF_F {prefix} {*} # prefix - list of channels published as float (no suffix) ACL_CHBUF_F {prefix} {*} PR_CHBUF_I {prefix} {gain} {*} # prefix - list of channels published as integer (suffix _I) ACL_CHBUF_I {prefix} {gain} {*} PR_DAQ_FIFO {prefix} {*} # prefix - list of channels sent to DAQ (as float) ACL_DAQ_FIFO {prefix} {*} PR_MAIN_LX {prefix} {timeout} {cpuid} {unused_parameter} # sms prefix - cm timeout - real-time CPU id - load delay (s) ACL_MAIN_LX {prefix} {timeout} {cpuid} 1.0 PR_TIMING {frequency} {delay} # loop frequency (Hz) - loop delay (s) ACL_TIMING {frequency} {delay} PR_GPS_T0 {gps} # GPS reference time ACL_GPS_T0 {gps} TOLM_PROCESSOR_DAQ_FIFO_PACKET_WITH_FREQUENCY {pagename} {frequency} {delay} {prefix} {*} # packetName - packetFreq - delay - channelPrefix - list of channels in the packet TOLM_PROCESSOR_DAQ_FIFO_PACKET_WITH_FREQUENCY {pagename} {frequency} {delay} {prefix} {*} TOLM_PROCESSOR_OUTPUT_PACKET_WITH_FREQUENCY {pagename} {frequency} {delay} {prefix} {*} # packetName - packetFreq - delay - channelPrefix - list of channels in the packet TOLM_PROCESSOR_OUTPUT_PACKET_WITH_FREQUENCY {pagename} {frequency} {delay} {prefix} {*} TOLM_PROCESSOR_PACKET_APPEND {pagename} {*} # packetName - list of channels TOLM_PROCESSOR_PACKET_APPEND {pagename} {*} ''' # parse table table = table.splitlines() #separate table at each line table = [line for line in table if line.strip()] # skip empty lines assert len(table) % 3 == 0, 'number of lines in table should be multiple of 3' print 'number of conversions in table: ',len(table)/3 keywords = {} comments = {} for old_syntax, new_comment, new_syntax in chunks(table, 3): keyword = Struct() keyword.args = [] keyword.defaults = [] keyword.template = new_syntax.replace(' ', '\t') old_syntax = old_syntax.split() keyword.variable = False for arg in old_syntax[1:]: assert arg[0] == '{' and arg[-1] == '}', 'input arguments must be enclosed with {}' arg = arg[1:-1] # strip {} if arg == '*': keyword.variable = True break arg, _, default = arg.partition('=') keyword.args.append(arg) keyword.defaults.append(default) keywords[old_syntax[0]] = keyword comments[old_syntax[0]] = new_comment print keywords print comments # command line parsing if len(sys.argv) != 3: sys.exit('Wrong number of arguments. Usage:\n%s inputfile outputfile' % sys.argv[0]) inname, outname = sys.argv[1:3] if os.path.exists(outname): # be conservative try: raw_input('File %s already exists, continue? (Enter to proceed, CTRL-C to abort)' % outname) except KeyboardInterrupt: sys.exit('%s aborted' % sys.argv[0]) # do actual conversion with open(inname) as infile, open(outname, 'w') as outfile: outfile.write("## --------- Configuration file converted with PR2ACL.py script --------- ##\n") outfile.write("# ---------- Check any PR2ACL WARNINGs for needed manual edits ---------- #\n") outfile.write("# ------------ Comment headers are added above the keyword ------------- #\n\n") cpt = 0 for iline, line in enumerate(infile, 1): head, hash, comment = line.partition('#') # split off comment splitline = shlex.split(head) if splitline and splitline[0] in keywords: key = splitline[0] if cpt is 0: lastkey = key cpt = cpt + 1 keyword = keywords[key] if keyword.variable: n = len(keyword.args) + 1 # keyword + normal args varargs = splitline[n:] splitline = splitline[:n] # swap F/Q if key in ('PR_FILTER_GC_ZEROS', 'PR_FILTER_GC_POLES', 'PR_FILTER_1ST_POLES', 'PR_FILTER_1ST_ZEROS', 'PR_FILTER_2ND_POLES', 'PR_FILTER_2ND_ZEROS'): assert len(varargs) % 2 == 0, 'F/Q need to come in pairs' varargs = chain.from_iterable(i[::-1] for i in chunks(varargs, 2)) else: varargs = [] # collect all args in a dict args = dict(zip(keyword.args, splitline[1:])) # fill missing arguments at the end with defaults n = len(args) args.update(zip(keyword.args[n:], keyword.defaults[n:])) # add quotes if needed args = dict((k, add_quotes(v)) for k, v in args.iteritems()) args['*'] = ''.join('\t' + add_quotes(va) for va in varargs) # add comment line if key == lastkey: # print 'key: "',key, '" is lastkey: "',lastkey,'"' print '' else: commentline = comments[key] commentline += '\n' outfile.write(commentline) lastkey = key # fill template with arguments newline = keyword.template.format(**args) if hash: # add back comment newline += '\t#' + comment newline += '\n' else: newline = line outfile.write(newline) print("Conversion completed! Check the header of the new ACL configuration file!\n")