How to use xargs method in fMBT

Best Python code snippet using fMBT_python

xargs.py

Source:xargs.py Github

copy

Full Screen

1#!/usr/bin/env python22# Copyright 2019 Wilke Schwiedop. All rights reserved.3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08from __future__ import print_function9import argparse10import collections11import itertools12import os13# TODO docs.python.org suggests https://pypi.org/project/subprocess32/14# for POSIX users15import shlex16import subprocess17import sys18class GNUXargsQuirks(argparse.Action):19 def __init__(self, option_strings, dest, **kwargs):20 super(GNUXargsQuirks, self).__init__(option_strings, dest, **kwargs)21 def __call__(self, parser, namespace, values, option_string=None):22 setattr(namespace, self.dest, values)23 if self.dest == 'replace_str':24 namespace.max_args = None25 namespace.max_lines = None26 elif self.dest == 'max_lines':27 namespace.max_args = None28 namespace.replace_str = None29 elif self.dest == 'max_args':30 namespace.max_lines = None31 if namespace.max_args == 1 and namespace.replace_str:32 namespace.max_args = None33 else:34 namespace.replace_str = None35 elif self.dest == 'max_chars':36 pass37 else:38 assert False, "dest '%s' not handled" % self.dest39xargs = argparse.ArgumentParser(prog='xargs')40xargs.add_argument('-a', '--arg-file', metavar='file', nargs=1, default='-', help='read arguments from FILE, not standard input')41xargs.add_argument('-E', metavar='eof-str', dest='eof_str', help='set logical EOF string; if END occurs as a line of input, the rest of the input is ignored (ignored if -0 or -d was specified)')42xargs.add_argument('-e', '--eof', metavar='eof-str', nargs='?', dest='eof_str', help='equivalent to -E END if END is specified; otherwise, there is no end-of-file string')43xargs.add_argument('-0', '--null', dest='delimiter', action='store_const', const='\0', help='items are separated by a null, not whitespace; disables quote and backslash processing and logical EOF processing')44xargs.add_argument('-d', '--delimiter', metavar='delimiter', dest='delimiter', help='items in input stream are separated by CHARACTER, not by whitespace; disables quote and backslash processing and logical EOF processing')45xargs.add_argument('-I', metavar='replace-str', dest='replace_str', action=GNUXargsQuirks, help='same as --replace=R')46xargs.add_argument('-i', '--replace', metavar='replace-str', nargs='?', const='{}', dest='replace_str', action=GNUXargsQuirks, help='replace R in INITIAL-ARGS with names read from standard input; if R is unspecified, assume {}')47xargs.add_argument('-L', metavar='max-lines', dest='max_lines', type=int, action=GNUXargsQuirks, help='use at most MAX-LINES non-blank input lines per command line')48xargs.add_argument('-l', '--max-lines', metavar='max-lines', nargs='?', const=1, dest='max_lines', type=int, action=GNUXargsQuirks, help='similar to -L but defaults to at most one non-blank input line if MAX-LINES is not specified')49xargs.add_argument('-n', '--max-args', metavar='max-args', dest='max_args', type=int, action=GNUXargsQuirks, help='use at most MAX-ARGS arguments per command line')50xargs.add_argument('-s', '--max-chars', metavar='max-chars', dest='max_chars', type=int, action=GNUXargsQuirks, help='limit length of command line to MAX-CHARS')51xargs.add_argument('-P', '--max-procs', metavar='max-procs', default=1, dest='max_procs', type=int, help='run at most MAX-PROCS processes at a time')52xargs.add_argument('--process-slot-var', metavar='name', help='set environment variable VAR in child processes')53xargs.add_argument('-p', '--interactive', action='store_true', help='prompt before running commands')54xargs.add_argument('-t', '--verbose', action='store_true', help='print commands before executing them')55xargs.add_argument('-x', '--exit', action='store_true', help='exit if the size (see -s) is exceeded')56xargs.add_argument('-r', '--no-run-if-empty', action='store_true', help='if there are no arguments, then do not run COMMAND; if this option is not given, COMMAND will be run at least once')57xargs.add_argument('--show-limits', action='store_true', help='show limits on command-line length')58xargs.add_argument('--version', action='version', version='%(prog)s 0.0.1', help='output version information and exit')59xargs.add_argument('command', nargs='?', default='echo')60xargs.add_argument('initial_arguments', nargs=argparse.REMAINDER)61class PeekableIterator():62 def __init__(self, iterator):63 self.iterator = iterator64 self.peeked = False65 self.item = None66 def peek(self):67 """68 Return the next item but does not advance the iterator further.69 Raise StopIteration if there is no such item.70 """71 if not self.peeked:72 self.item = next(self.iterator)73 self.peeked = True74 return self.item75 def next(self):76 """77 Return the next item and advance the iterator.78 Raise StopIteration if there is no such item.79 """80 if self.peeked:81 self.peeked = False82 return self.item83 return next(self.iterator)84 def __iter__(self):85 return self86def read_lines_eof(eof_str, input):87 # type (str, Iterable[str]) -> Iterable[str]88 """Read lines from input until a line equals eof_str or EOF is reached"""89 return iter(input.next, eof_str + '\n')90def str_memsize(*strings):91 # type: (*str) -> int92 """Calculate the amount of memory required to store the strings in an argv."""93 return sum(len(s) + 1 for s in strings)94def is_complete_line(line):95 # type: (str) -> bool96 return len(line) > 1 and line[-2] not in (' ', '\t')97def argsplit_ws(lines):98 # type: (Iterable[str]) -> Iterator[str]99 """Split lines into arguments and append metainfo to each argument."""100 for line in lines:101 # TODO this might require some more testing102 for arg in shlex.split(line):103 yield arg104def argsplit_delim(delim, lines):105 # type: (str, Iterable[str]) -> Iterator[str]106 """Split lines into arguments and append metainfo to each argument."""107 buf = []108 for c in itertools.chain.from_iterable(lines):109 if c == delim:110 yield "".join(buf)111 buf = []112 else:113 buf.append(c)114 if buf:115 yield "".join(buf)116def read_n_xargs_lines(linec, line_iter):117 # type: (int, Iterator[str]) -> Iterator[str]118 while linec > 0:119 line = next(line_iter)120 yield line121 if is_complete_line(line):122 linec -= 1123def take_chars(charc, iterator):124 # type: (int, Iterator[str]) -> Iterator[str]125 charc -= str_memsize(iterator.peek())126 while charc >= 0:127 yield next(iterator)128 charc -= str_memsize(iterator.peek())129def take(n, iterator):130 # type: (int, Iterator[Any]) -> Iterator[Any]131 for _ in range(n):132 yield next(iterator)133def group_args_lines(max_lines, input):134 # type: (int, Iterator[str]) -> Iterator[List[str]]135 while True:136 it = argsplit_ws(read_n_xargs_lines(max_lines, input))137 buf = [next(it)] # raise StopIteration if iterator is empty138 buf.extend(it)139 yield buf140def group_args(max_chars, max_args, arg_iter):141 # type: (Optional[int], Optional[int], Iterator[str]) -> Iterator[List[str]]142 arg_iter = PeekableIterator(arg_iter)143 while arg_iter.peek() or True: # raise StopIteration if iterator is empty144 it = arg_iter145 if max_chars:146 it = take_chars(max_chars, it)147 if max_args:148 it = take(max_args, it)149 yield list(it)150def replace_args(initial_arguments, replace_str, additional_arguments):151 # type: (Sequence[str], str, Iterable[str]) -> Iterator[str]152 additional_arguments = list(additional_arguments)153 for arg in initial_arguments:154 if arg == replace_str:155 for x in additional_arguments:156 yield x157 else:158 yield arg159def build_cmdlines_replace(command, initial_arguments, replace_str, arggroup_iter):160 # type: (str, Sequence[str], str, Iterator[Iterator[str]]) -> Iterator[List[str]]161 """162 Build command-lines suitable for subprocess.Popen,163 replacing instances of replace_str in initial_arguments.164 """165 cmdline = [command]166 for additional_arguments in arggroup_iter:167 cmdline.extend(168 replace_args(169 initial_arguments,170 replace_str,171 additional_arguments172 )173 )174 yield cmdline175 cmdline = cmdline[:1]176def build_cmdlines(command, initial_arguments, arggroup_iter):177 # type: (str, Sequence[str], Iterator[Iterator[str]]) -> Iterator[List[str]]178 """Build command-lines suitable for subprocess.Popen."""179 cmdline = [command]180 cmdline.extend(initial_arguments)181 for additional_arguments in arggroup_iter:182 cmdline.extend(additional_arguments)183 yield cmdline184 cmdline = cmdline[:1+len(initial_arguments)]185def check_items(p, on_false, cmdline_iter):186 for cmdline in cmdline_iter:187 if p(cmdline):188 yield cmdline189 else:190 on_false()191def tee_cmdline(cmdline_iter):192 # type: (Iterator[List[str]]) -> Iterator[List[str]]193 """Go over each cmdline and print them to stderr."""194 for cmdline in cmdline_iter:195 print(*cmdline, file=sys.stderr)196 yield cmdline197def prompt_user(cmdline_iter):198 # type: (Iterator[List[str]]) -> Iterator[List[str]]199 """Prompt the user for each cmdline."""200 with open("/dev/tty", 'r') as tty:201 for cmdline in cmdline_iter:202 print(*cmdline, end=' ?...', file=sys.stderr)203 response = tty.readline()204 if response[0] not in ('y', 'Y'):205 continue206 yield cmdline207def wait_open_slot(processes):208 # type: (List[Optional[Any]])-> int209 while processes:210 for i, p in enumerate(processes):211 # process doesn't yet exist or has finished212 if p is None or p.poll() is not None:213 return i214 _pid, _err = os.wait()215def map_errcode(rc):216 # type: int -> int217 """map the returncode of a child-process to the returncode of the main process."""218 if rc == 0:219 return 0220 if rc >= 0 and rc <= 125:221 return 123222 if rc == 255:223 return 124224 if rc < 0:225 return 125226 return 1227def main(xargs_args):228 # phase 1: read input229 if xargs_args.arg_file == '-':230 xargs_input = sys.stdin231 cmd_input = open(os.devnull, 'r')232 else:233 xargs_input = xargs_args.arg_file234 cmd_input = sys.stdin235 236 if xargs_args.eof_str:237 xargs_input = read_lines_eof(xargs_args.eof_str, xargs_input)238 # phase 2: parse and group args239 if xargs_args.max_lines:240 assert not xargs_args.max_args241 assert not xargs_args.delimiter242 assert xargs_args.exit243 arggroup_iter = group_args_lines(xargs_args.max_lines, xargs_input)244 else:245 if xargs_args.delimiter:246 arg_iter = argsplit_delim(xargs_args.delimiter, xargs_input)247 else:248 arg_iter = argsplit_ws(xargs_input)249 # if exit is True, max_chars is checked later250 arggroup_iter = group_args(251 xargs_args.max_chars if not xargs_args.exit else None,252 xargs_args.max_args,253 arg_iter254 )255 arggroup_iter = PeekableIterator(arggroup_iter)256 if xargs_args.no_run_if_empty:257 try:258 x = arggroup_iter.peek()259 # TODO not even sure how the interaction with -I is supposed to work260 # echo | xargs -I {} echo {} : dont run261 # echo | xargs -I {} echo {} "x" : dont run262 # echo | xargs -I {} echo "x" : dont run263 # echo x | xargs -I {} echo : run264 # echo xx | xargs -I {} -d 'x' echo {} : run 3 times ('', '', '\n')265# if not x or not x[0]:266 if not x:267 return 0268 except StopIteration:269 return 0270 else:271 try:272 arggroup_iter.peek()273 except StopIteration:274 arggroup_iter = [[]]275 # phase 3: build command-lines276 if xargs_args.replace_str:277 cmdline_iter = build_cmdlines_replace(278 xargs_args.command,279 xargs_args.initial_arguments,280 xargs_args.replace_str,281 arggroup_iter282 )283 else:284 cmdline_iter = build_cmdlines(285 xargs_args.command,286 xargs_args.initial_arguments,287 arggroup_iter288 )289 if xargs_args.max_chars is not None and xargs_args.exit:290 cmdline_iter = check_items(291 lambda c: str_memsize(*c) < xargs_args.max_chars,292 lambda: sys.exit(1),293 cmdline_iter294 )295 if xargs_args.interactive:296 cmdline_iter = prompt_user(cmdline_iter)297 elif xargs_args.verbose:298 cmdline_iter = tee_cmdline(cmdline_iter)299 # phase 4: execute command-lines300 if xargs_args.max_procs > 1:301 ps = [None] * xargs_args.max_procs302 environ = os.environ.copy()303 for cmdline in cmdline_iter:304 i = wait_open_slot(ps)305 if ps[i] is not None and ps[i].returncode:306 break307 if xargs_args.process_slot_var:308 environ[xargs_args.process_slot_var] = str(i)309 ps[i] = subprocess.Popen(cmdline, stdin=cmd_input, env=environ)310 return max(map_errcode(p.wait()) for p in ps if p is not None)311 else:312 for cmdline in cmdline_iter:313 p = subprocess.Popen(cmdline, stdin=cmd_input)314 if p.wait():315 return map_errcode(p.returncode)316 return 0317if __name__ == "__main__":318 xargs_args = xargs.parse_args()319 if xargs_args.delimiter:320 xargs_args.delimiter = xargs_args.delimiter.decode('string_escape')321 if len(xargs_args.delimiter) > 1:322 # TODO error323 sys.exit(1)324 if xargs_args.max_chars and not xargs_args.replace_str:325 base = str_memsize(xargs_args.command, *xargs_args.initial_arguments)326 if base > xargs_args.max_chars:327 # TODO error328 sys.exit(1)329 xargs_args.max_chars -= base330 # TODO warnings when appropriate331 # -d disables -e332 if xargs_args.delimiter and xargs_args.eof_str:333 xargs_args.eof_str = None334 # -I implies -L 1 (and transitively -x)335 if xargs_args.replace_str and xargs_args.max_lines != 1:336 xargs_args.max_lines = 1337 # -I implies -d '\n'338 if xargs_args.replace_str and xargs_args.delimiter != '\n':339 xargs_args.delimiter = '\n'340 # -L implies -x341 if xargs_args.max_lines is not None and not xargs_args.exit:342 xargs_args.exit = True343 # -p implies -t344 if xargs_args.interactive and not xargs_args.verbose:345 xargs_args.verbose = True346 # (undocumented)347 # if -d then -L equals -n348 if xargs_args.delimiter and xargs_args.max_lines:349 xargs_args.max_args = xargs_args.max_lines350 xargs_args.max_lines = None351 # TODO? -I implies -r352 if xargs_args.replace_str and not xargs_args.no_run_if_empty:353 xargs_args.no_run_if_empty = True...

Full Screen

Full Screen

testXSecComputer.py

Source:testXSecComputer.py Github

copy

Full Screen

1#!/usr/bin/env python32"""3.. module:: testXSecComputer4 :synopsis: Compares the output of XSecComputer with a given value.5 6.. moduleauthor:: Wolfgang Magerl <wolfgang.magerl@gmail.com>7.. moduleauthor:: Wolfgang Waltenberger <wolfgang.waltenberger@gmail.com>8 9"""10import sys,os11sys.path.insert(0,"../")12from smodels.tools import xsecComputer, toolBox13from smodels.tools.xsecComputer import LO, NLL14from smodels.tools.physicsUnits import TeV, fb15from smodels.theory import crossSection16import tempfile17import unittest18import argparse19import logging.config20class XSecTest(unittest.TestCase):21 # use different logging config for the unit tests.22 logging.config.fileConfig( "./logging.conf" )23 from smodels.tools.smodelsLogging import setLogLevel,logger24 25 setLogLevel ( "warn" )26 toolBox.ToolBox().compile() ## make sure the tools are compiled27 def testLOGlu(self):28 """ test the computation of LO cross section, pythia6 """29 self.logger.info ( "test LO xsecs @ 8 TeV" )30 slhafile= "./testFiles/slha/simplyGluino.slha"31 computer = xsecComputer.XSecComputer ( LO, 2000, 6 )32 w = computer.compute(8*TeV, slhafile ).getDictionary()33 # print ( w )34 w8lo= w[(1000021, 1000021)]['8 TeV (LO)'].asNumber( fb )35 self.assertAlmostEqual(w8lo/264., 1., 2 ) 36 def testNLLGlu(self):37 """ test the computation of NLL cross section """38 self.logger.info ( "test NLL xsecs @ 8 TeV" )39 slhafile="./testFiles/slha/simplyGluino.slha"40 computer = xsecComputer.XSecComputer ( NLL, 2000, 6 )41 w = computer.compute( 8*TeV, slhafile ).getDictionary()42 w8nll= w[(1000021, 1000021)]['8 TeV (NLO+NLL)'].asNumber( fb )43 self.assertAlmostEqual(w8nll / 573., 1., 2 )44 def testLOGlu13(self):45 """ test the computation of LO cross section, pythia6 """46 self.logger.info ( "test LO xsecs @ 13 TeV" )47 slhafile="./testFiles/slha/simplyGluino.slha"48 computer = xsecComputer.XSecComputer ( LO, 3000, 6 )49 w = computer.compute( 13*TeV, slhafile ).getDictionary()50 w13lo= w[(1000021, 1000021)]['13 TeV (LO)'].asNumber( fb )51 self.assertAlmostEqual(w13lo / 2237., 1., 1 )52 def testNLLGlu13(self):53 """ test the computation of NLL cross section with pythia6 """54 self.logger.info ( "test NLL xsecs @ 13 TeV" )55 slhafile="./testFiles/slha/simplyGluino.slha"56 computer = xsecComputer.XSecComputer ( NLL, 3000, 6 )57 w = computer.compute( 13*TeV, slhafile ).getDictionary()58 w13nll= w[(1000021, 1000021)]['13 TeV (NLO+NLL)'].asNumber( fb )59 self.assertAlmostEqual(w13nll / 4320. , 1., 2 )60 61 def testXSecMain(self):62 """ test the main routine for computation of LO and NLL cross section for several sqrts"""63 64 slhafile="./testFiles/slha/simplyGluino.slha"65 f = open(slhafile,'r')66 fdata = f.read()67 fdata = fdata[:fdata.find('XSECTION')]68 f.close()69 fnew = tempfile.mkstemp()70 os.close(fnew[0])71 tmpfile = fnew[1]72 fnew = open(tmpfile,'w')73 fnew.write(fdata)74 fnew.close() 75 self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )76 #Set overall options:77 #Options for cross section calculation:78 xargs = argparse.Namespace()79 xargs.sqrts = [[8.,13.]]80 xargs.ncpus = 181 xargs.noautocompile = True82 xargs.nevents = 200083 #Compute LO xsecs:84 xargs.query = False85 xargs.NLL = False86 xargs.NLO = False87 xargs.LOfromSLHA = False88 xargs.keep = False89 xargs.tofile = True90 xargs.alltofile = False91 xargs.pythia6 = True92 xargs.filename = tmpfile93 xargs.colors = False94 xargs.ssmultipliers = None95 xargs.verbosity = "warning"96 #Compute LO cross sections97 xsecComputer.main(xargs)98 #Compute NLL cross sections99 xargs.NLL = True100 xargs.LOfromSLHA = True101 xsecComputer.main(xargs)102 #Read xsecs:103 xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)104 os.remove(tmpfile)105 106 #Check 8 TeV xsecs:107 lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)108 nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)109 self.assertAlmostEqual(lo/264.,1.,2)110 self.assertAlmostEqual(nll/573.6,1.,2)111 #Check 13 TeV xsecs:112 lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)113 nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)114 self.assertAlmostEqual(lo / 2230., 1., 1 )115 self.assertAlmostEqual(nll / 4308., 1., 1 )116 def testSSMultipliers(self):117 """ test the signal strength multipliers """118 119 slhafile="./testFiles/slha/simplyGluino.slha"120 f = open(slhafile,'r')121 fdata = f.read()122 fdata = fdata[:fdata.find('XSECTION')]123 f.close()124 fnew = tempfile.mkstemp()125 os.close(fnew[0])126 tmpfile = fnew[1]127 fnew = open(tmpfile,'w')128 fnew.write(fdata)129 fnew.close() 130 self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )131 #Set overall options:132 #Options for cross section calculation:133 xargs = argparse.Namespace()134 xargs.sqrts = [[8.,13.]]135 xargs.ncpus = 1136 xargs.noautocompile = True137 xargs.nevents = 5000138 #Compute LO xsecs:139 xargs.query = False140 xargs.NLL = False141 xargs.NLO = False142 xargs.LOfromSLHA = False143 xargs.keep = False144 xargs.tofile = True145 xargs.alltofile = False146 xargs.pythia6 = True147 xargs.filename = tmpfile148 xargs.colors = False149 xargs.ssmultipliers = { (1000021,1000021): 4. }150 # xargs.ssmultipliers = { 1000021: 2. }151 xargs.verbosity = "warning"152 #Compute LO cross sections153 xsecComputer.main(xargs)154 #Compute NLL cross sections155 xargs.NLL = True156 xargs.LOfromSLHA = True157 xsecComputer.main(xargs)158 #Read xsecs:159 xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)160 os.remove(tmpfile)161 162 #Check 8 TeV xsecs:163 lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)164 nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)165 self.assertAlmostEqual(lo/1058.444,1.,1)166 self.assertAlmostEqual(nll/2299.046,1.,1)167 #Check 13 TeV xsecs:168 lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)169 nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)170 self.assertAlmostEqual(lo/8910.76,1.,1 )171 self.assertAlmostEqual(nll/17215.5906, 1.,1)172 173 def testSSJokers(self):174 """ test the signal strength multipliers, with jokers """175 176 slhafile="./testFiles/slha/simplyGluino.slha"177 f = open(slhafile,'r')178 fdata = f.read()179 fdata = fdata[:fdata.find('XSECTION')]180 f.close()181 fnew = tempfile.mkstemp()182 os.close(fnew[0])183 tmpfile = fnew[1]184 fnew = open(tmpfile,'w')185 fnew.write(fdata)186 fnew.close() 187 self.logger.info ("test NLL xsecs @ 8 and 13 TeV" )188 #Set overall options:189 #Options for cross section calculation:190 xargs = argparse.Namespace()191 xargs.sqrts = [[8.,13.]]192 xargs.noautocompile = True193 xargs.ncpus = 1194 xargs.nevents = 5000195 #Compute LO xsecs:196 xargs.query = False197 xargs.NLL = False198 xargs.NLO = False199 xargs.LOfromSLHA = False200 xargs.keep = False201 xargs.tofile = True202 xargs.alltofile = False203 xargs.pythia6 = True204 xargs.filename = tmpfile205 xargs.colors = False206 xargs.ssmultipliers = { ('*100002?','*1000021'): 4. }207 # xargs.ssmultipliers = { 1000021: 2. }208 xargs.verbosity = "warning"209 #Compute LO cross sections210 xsecComputer.main(xargs)211 #Compute NLL cross sections212 xargs.NLL = True213 xargs.LOfromSLHA = True214 xsecComputer.main(xargs)215 #Read xsecs:216 xsecsInfile = crossSection.getXsecFromSLHAFile(tmpfile)217 os.remove(tmpfile)218 219 #Check 8 TeV xsecs:220 lo = xsecsInfile.getXsecsFor('8 TeV (LO)')[0].value.asNumber(fb)221 nll = xsecsInfile.getXsecsFor('8 TeV (NLL)')[0].value.asNumber(fb)222 self.assertAlmostEqual(lo/1056.,1.,2)223 self.assertAlmostEqual(nll/2294.,1.,2)224 #Check 13 TeV xsecs:225 lo = xsecsInfile.getXsecsFor('13 TeV (LO)')[0].value.asNumber(fb)226 nll = xsecsInfile.getXsecsFor('13 TeV (NLL)')[0].value.asNumber(fb)227 self.assertAlmostEqual(lo/8910.76,1.,2 )228 self.assertAlmostEqual(nll/17215.5906, 1.,1)229if __name__ == "__main__":...

Full Screen

Full Screen

symbolic_args_test.py

Source:symbolic_args_test.py Github

copy

Full Screen

12"""34Regression test showing Generator and Event set up when using5Symbolic objects for all var/par references67"""89from PyDSTool import *1011x = Var('x')12p = Par('p')1314x_dot = Fun(-2 * x + p, [x], 'x_dot')15x_cross = Fun(0.01*Sin(x) + x**2 - 10, [x], 'x_cross')16x_reset = Fun(10 * x, [x], 'x_reset')1718xargs = args(name='xgen')19xargs.vars = [x]20xargs.pars = {p: 0}21xargs.ics = {x: 100}22xargs.fnspecs = [x_dot]23xargs.tdomain = [0,365 * 0.1]24#xargs.tdata = [0,1]2526xargs.varspecs = {x:x_dot(x)}2728xargs.algparams = {'init_step':0.01}29xargs.checklevel = 23031# detect when x crosses 1 by decreasing values32xargs.events = Events.makeZeroCrossEvent(x_cross(x), -1,33 {'name':'cross', 'term':True, 'active':True},34 varnames=[x],35 targetlang='c')3637mc = ModelConstructor("mc")38mc.addModelInfo(xargs, 'Dopri_ODEsystem')39mc.mapEvent('xgen', 'cross', 'xgen', {x:x_reset(x)})4041model = mc.getModel()42info(model)4344model.compute(trajname='testin', tdata=xargs.tdomain,45 ics={x: 100})46smpl = model.sample('testin')4748plt.plot(smpl['t'], smpl['x'], 'b-') ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful