Example #1
0
def call_systematics(args,
                     result=sys.stdout,
                     running=True,
                     log=lambda x: sys.stdout.write(str(x) + '\n')):
    """calling systematics from a list of arguments"""

    input, output = args[0:2]

    start_opts = 2
    if output and output.startswith('-'):
        start_opts = 1
        output = input

    opts = {}
    for arg in args[start_opts:]:
        if '=' in arg:
            key, values = arg.split('=')
            key = key.replace('-', '')
            values = values.strip()
            if values[0] in ["'", '"'] and values[-1] == values[0]:
                values = values[1:-1]
            values = values.split(',')
            if key == 'together':
                if key in opts:
                    opts[key].append(tuple(values))
                else:
                    opts[key] = [tuple(values)]
            elif key == 'result':
                result = open(values[0], 'w')
            elif key in ['start_event', 'stop_event', 'only_beam']:
                opts[key] = banner_mod.ConfigFile.format_variable(
                    values[0], int, key)
            elif key in ['write_banner', 'ion_scalling']:
                opts[key] = banner_mod.ConfigFile.format_variable(
                    values[0], bool, key)
            else:
                if key in opts:
                    opts[key] += values
                else:
                    opts[key] = values
        else:
            raise SystematicsError, "unknow argument %s" % arg

    #load run_card and extract parameter if needed.
    if 'from_card' in opts:
        if opts['from_card'] != ['internal']:
            card = banner.RunCard(opts['from_card'][0])
        else:
            for i in range(10):
                try:
                    lhe = lhe_parser.EventFile(input)
                    break
                except OSError, error:
                    print error
                    time.sleep(15 * (i + 1))
            else:
                raise

            card = banner.RunCard(banner.Banner(lhe.banner)['mgruncard'])
            lhe.close()
except:
    outPath = pjoin(os.path.dirname(os.path.realpath(eventFile)),
                    '%s_rwgt.%s' % (evtFileName, evtFileExt))

i = 0
while os.path.exists(outPath):
    i = i + 1
    if outSpecified and i == 1:
        logging.warning(
            "The chosen filename %s for the output already exists." %
            os.path.basename(outPath))
    outPath = pjoin(os.path.dirname(os.path.realpath(eventFile)),
                    '%s_rwgt_%i.%s' % (evtFileName, i, evtFileExt))

try:
    evtBanner = banner.Banner(eventFile)
    evtFile = lhe_parser.EventFile(eventFile)
except:
    logging.error("Could not read event file %s." % eventFile)

# Start by loading the model of the banner
try:
    model_name = evtBanner.get_detail('model')
    model_name = model_name.split('-')[0]
    # For now use the model 'sm' no matter what since it is only used for the particle naming scheme
    model_name = 'sm'
    user_model = import_ufo.import_full_model(
        pjoin(proc_path, os.pardir, 'models', model_name))
except:
    logging.error("Could not load the model %s used for generating the event file"\
                 %evtBanner.get_detail('model'))
Example #3
0
    def __init__(
        self,
        input_file,
        output_file,
        start_event=0,
        stop_event=sys.maxint,
        write_banner=False,
        mur=[0.5, 1, 2],
        muf=[0.5, 1, 2],
        alps=[1],
        pdf='errorset',  #[(id, subset)]
        dyn=[-1, 1, 2, 3, 4],
        together=[('mur', 'muf', 'dyn')],
        remove_wgts=[],
        keep_wgts=[],
        start_id=None,
        lhapdf_config=misc.which('lhapdf-config'),
        log=lambda x: sys.stdout.write(str(x) + '\n')):

        # INPUT/OUTPUT FILE
        if isinstance(input_file, str):
            self.input = lhe_parser.EventFile(input_file)
        else:
            self.input = input_file
        self.output_path = output_file
        if output_file != None:
            if isinstance(output_file, str):
                if output_file == input_file:
                    directory, name = os.path.split(output_file)
                    new_name = pjoin(directory, '.tmp_' + name)
                    self.output = lhe_parser.EventFile(new_name, 'w')
                else:
                    self.output = lhe_parser.EventFile(output_file, 'w')
            else:
                self.output = output_file
        self.log = log

        #get some information from the run_card.
        self.banner = banner_mod.Banner(self.input.banner)
        self.force_write_banner = bool(write_banner)
        self.orig_dyn = self.banner.get('run_card', 'dynamical_scale_choice')
        self.orig_pdf = self.banner.run_card.get_lhapdf_id()
        matching_mode = self.banner.get('run_card', 'ickkw')

        #check for beam
        beam1, beam2 = self.banner.get_pdg_beam()
        if abs(beam1) != 2212 and abs(beam2) != 2212:
            self.b1 = 0
            self.b2 = 0
            pdf = 'central'
            #raise SystematicsError, 'can only reweight proton beam'
        elif abs(beam1) != 2212:
            self.b1 = 0
            self.b2 = beam2 // 2212
        elif abs(beam2) != 2212:
            self.b1 = beam1 // 2212
            self.b2 = 0
        else:
            self.b1 = beam1 // 2212
            self.b2 = beam2 // 2212

        if isinstance(self.banner.run_card, banner_mod.RunCardLO):
            self.is_lo = True
            if not self.banner.run_card['use_syst']:
                raise SystematicsError, 'The events have not been generated with use_syst=True. Cannot evaluate systematics error on these events.'
        else:
            self.is_lo = False
            if not self.banner.run_card['store_rwgt_info']:
                raise SystematicsError, 'The events have not been generated with store_rwgt_info=True. Cannot evaluate systematics error on these events.'

        # MUR/MUF/ALPS PARSING
        if isinstance(mur, str):
            mur = mur.split(',')
        self.mur = [float(i) for i in mur]
        if isinstance(muf, str):
            muf = muf.split(',')
        self.muf = [float(i) for i in muf]

        if isinstance(alps, str):
            alps = alps.split(',')
        self.alps = [float(i) for i in alps]

        # DYNAMICAL SCALE PARSING + together
        if isinstance(dyn, str):
            dyn = dyn.split(',')
        self.dyn = [int(i) for i in dyn]
        # For FxFx only mode -1 makes sense
        if matching_mode == 3:
            self.dyn = [-1]
        # avoid sqrts at NLO if ISR is possible
        if 4 in self.dyn and self.b1 and self.b2 and not self.is_lo:
            self.dyn.remove(4)

        if isinstance(together, str):
            self.together = together.split(',')
        else:
            self.together = together

        # START/STOP EVENT
        self.start_event = int(start_event)
        self.stop_event = int(stop_event)
        if start_event != 0:
            self.log("#starting from event #%s" % start_event)
        if stop_event != sys.maxint:
            self.log("#stopping at event #%s" % stop_event)

        # LHAPDF set
        if isinstance(lhapdf_config, list):
            lhapdf_config = lhapdf_config[0]
        lhapdf = misc.import_python_lhapdf(lhapdf_config)
        if not lhapdf:
            log('fail to load lhapdf: doe not perform systematics')
            return
        lhapdf.setVerbosity(0)
        self.pdfsets = {}
        if isinstance(pdf, str):
            pdf = pdf.split(',')

        if isinstance(pdf, list) and isinstance(pdf[0], (str, int)):
            self.pdf = []
            for data in pdf:
                if data == 'errorset':
                    data = '%s' % self.orig_pdf
                if data == 'central':
                    data = '%s@0' % self.orig_pdf
                if '@' in data:
                    #one particular dataset
                    name, arg = data.rsplit('@', 1)
                    if int(arg) == 0:
                        if name.isdigit():
                            self.pdf.append(lhapdf.mkPDF(int(name)))
                        else:
                            self.pdf.append(lhapdf.mkPDF(name))
                    elif name.isdigit():
                        try:
                            self.pdf.append(lhapdf.mkPDF(int(name) + int(arg)))
                        except:
                            raise Exception, 'Individual error sets need to be called with LHAPDF NAME not with LHAGLUE NUMBER'
                    else:
                        self.pdf.append(lhapdf.mkPDF(name, int(arg)))
                else:
                    if data.isdigit():
                        pdfset = lhapdf.mkPDF(int(data)).set()
                    else:
                        pdfset = lhapdf.mkPDF(data).set()
                    self.pdfsets[pdfset.lhapdfID] = pdfset
                    self.pdf += pdfset.mkPDFs()
        else:
            self.pdf = pdf

        for p in self.pdf:
            if p.lhapdfID == self.orig_pdf:
                self.orig_pdf = p
                break
        else:
            self.orig_pdf = lhapdf.mkPDF(self.orig_pdf)
        if not self.b1 == 0 == self.b2:
            self.log("# events generated with PDF: %s (%s)" %
                     (self.orig_pdf.set().name, self.orig_pdf.lhapdfID))
        # create all the function that need to be called
        self.get_all_fct()  # define self.fcts and self.args

        # For e+/e- type of collision initialise the running of alps
        if self.b1 == 0 == self.b2:
            try:
                from models.model_reader import Alphas_Runner
            except ImportError:
                root_path = pjoin(root, os.pardir, os.pardir)
                try:
                    import internal.madevent_interface as me_int
                    cmd = me_int.MadEventCmd(root_path, force_run=True)
                except ImportError:
                    import internal.amcnlo_run_interface as me_int
                    cmd = me_int.Cmd(root_path, force_run=True)
                if 'mg5_path' in cmd.options and cmd.options['mg5_path']:
                    sys.path.append(cmd.options['mg5_path'])
                from models.model_reader import Alphas_Runner

            if not hasattr(self.banner, 'param_card'):
                param_card = self.banner.charge_card('param_card')
            else:
                param_card = self.banner.param_card

            asmz = param_card.get_value('sminputs', 3, 0.13)
            nloop = 2
            zmass = param_card.get_value('mass', 23, 91.188)
            cmass = param_card.get_value('mass', 4, 1.4)
            if cmass == 0:
                cmass = 1.4
            bmass = param_card.get_value('mass', 5, 4.7)
            if bmass == 0:
                bmass = 4.7
            self.alpsrunner = Alphas_Runner(asmz, nloop, zmass, cmass, bmass)

        # Store which weight to keep/removed
        self.remove_wgts = []
        for id in remove_wgts:
            if id == 'all':
                self.remove_wgts = ['all']
                break
            elif ',' in id:
                min_value, max_value = [int(v) for v in id.split(',')]
                self.remove_wgts += [
                    i for i in range(min_value, max_value + 1)
                ]
            else:
                self.remove_wgts.append(id)
        self.keep_wgts = []
        for id in keep_wgts:
            if id == 'all':
                self.keep_wgts = ['all']
                break
            elif ',' in id:
                min_value, max_value = [int(v) for v in id.split(',')]
                self.remove_wgts += [
                    i for i in range(min_value, max_value + 1)
                ]
            else:
                self.remove_wgts.append(id)

        # input to start the id in the weight
        self.start_wgt_id = int(start_id[0]) if (start_id
                                                 is not None) else None
        self.has_wgts_pattern = False  # tag to check if the pattern for removing
Example #4
0
            if c.dept() == dept and c.number() != '495':
                out += ' [%s %s]' % (c.number(), c.grade)
        out += '\n'

    return out


if len(sys.argv) == 2:
    server = sys.argv[1]
else:
    print __doc__
    sys.exit(1)

logging.basicConfig(level=logging.INFO)

b = banner.Banner(server)
b.setTerm()

reportfile = open('reportfile.txt', 'w')

try:
    while True:
        id = raw_input()
        logging.info('Working student ' + id)
        b.setStudentID(id)
        raw_transcript = b.transcriptSource()

        # Debug test - saves current student data file for crash recovery
        tempfile = open("temp" + str(id) + ".txt", "w")
        tempfile.write(raw_transcript.encode("UTF-8"))