def calcul(self, query, varMap): l = Var(str(self.child)) # print (str(self.child)) l.setValue(1) opposite = 0 ptr = { "+": self.op_add, "|": self.op_or, "^": self.op_xor, "!+": self.opn_add, "!|": self.opn_or, "!^": self.opn_xor } op = "+" for x in query: if ( op == None and self.isOperator(x) == True ): op = x elif ( self.isOperator(x) == False ): if ( x != "!" ): if ( opposite == 1 ): op = "!" + op val = ptr[op](l, varMap[x], varMap).getValue() l.setValue(val) opposite = 0 op = None else : opposite = 1 return (l)
def __init__ (self, *args): # {{{ from pygeode.tools import combine_axes from pygeode.var import combine_meta import numpy as np assert self.op is not None, "can't instantiate UfuncVar directly" ivars = [i for i,v in enumerate(args) if isinstance(v, Var)] vars = [args[i] for i in ivars] axes = combine_axes(vars) self.args = args self.ivars = ivars # dtype = common_dtype(args) # create some dummy scalar args to test the dtype dummy_dtypes = ['int64' if isinstance(a,(int, long)) else 'float64' if isinstance(a,float) else 'complex128' if isinstance(a,complex) else a.dtype for a in args] dummy_args = [np.array(1,dtype=d) for d in dummy_dtypes] dtype = self.op(*dummy_args).dtype # TODO: Type check arguments. numpy arrays probably shouldn't be allowed # Generate a default name symbol = self.symbol names = [(arg.name or '??') if isinstance(arg,Var) else str(arg) for arg in args] # Strip out parentheses if there's only one name? if len(names) == 1: if names[0].startswith('(') and names[0].endswith(')'): names[0] = names[0][1:-1] if symbol is None: name = self.op.__name__ + '(' + ','.join(names) + ')' elif isinstance(symbol,(list,tuple)): assert len(names) == 1 name = symbol[0] + names[0] + symbol[1] else: assert isinstance(symbol, str) name = '(' + symbol.join(names) + ')' # Special case: applying a scalar to a Var object with a simple name. # In this case, keep the original name. if len(args) == 2 and len(vars) == 1: # One scalar, one var if '(' not in vars[0].name and ')' not in vars[0].name: if self.symbol in ('+','-','*','/'): # Basic arithmetic only name = vars[0].name # # Copy any common generic metadata # self.atts = common_dict(v.atts for v in vars) # self.plotatts = common_dict(v.plotatts for v in vars) Var.__init__(self, axes, dtype=dtype) # Copy any common generic metadata combine_meta(vars, self) # Use our locally derived name (override combine_meta) self.name = name
def create_used_var(self, var_name): """Creates Var instance. Sets the instance to this object's used_variable. Args: var_name: the variable name used Returns: A Var instance """ self.used_variable = Var(name=var_name) return self.used_variable
def opn_or(self, l, r, varMap): result = Var(l.getName()) if ( l.getValue() == 1 or r.getValue() == 0 ): result.setValue( 1 ) elif ( l.getValue() == 0 or r.getValue() == 1 ): result.setValue( 0 ) elif ( l.getValue() == -1 and r.getValue() == -1 ): result.setValue( -1 ) else: result.setValue( 0 ) return (result)
def divide_vars(self, var_decl): self.var_list = {} for _stmt in var_decl.split('\n'): stmt = _stmt.strip() if len(stmt) > 0: tmp = stmt.split(' ') var_type = tmp[0] name = tmp[-1][:-1] #skip ';' self.var_list[name] = Var(var_type)
def __init__(self, canvas, row, col, my=True, tag="empty"): self.c = canvas self.row = row self.col = col self.my = my self.var = Var() self.tag = tag self.index = None self.draw()
def __init__(self, canvas, my=True): self.c = canvas self.my = my self.var = Var() if my: x = self.var.lr_span else: x = self.var.lr_span + self.var.center_span + self.var.see_field_width self.index = self.c.create_rectangle(x, self.var.top_span, \ x + self.var.see_field_width, \ self.var.top_span + self.var.see_field_height, \ fill = self.var.see_color, outline = self.var.see_color)
def divide_params(self, func_decl): self.param_name = [] #这个字段用来按顺序专门记录各个参数名 self.param_list = {} para_decl = re.findall(Context.PARENTHESE_PATTERN, func_decl)[0].strip('()') for _stmt in para_decl.split(','): stmt = _stmt.strip() if len(stmt) > 0: tmp = stmt.split(' ') var_type = tmp[0] name = tmp[-1] self.param_list[name] = Var(var_type) self.param_name.append(name)
def __init__(self, canvas, number, direction='h', my=True): #number: 0 - 4, 1..2 - 3, 3..5 - 2, 6..9 - 1 палубный self.c = canvas self.my = my self.var = Var() self.number = number self.direction = direction self.see_blocks = [] self.mini_blocks = [] self.live = "live" #demage, kill self.block_status = [] self.status = "none" self.x = 0 self.y = 0 self.drawed = False self.selected = False self.draw_mini()
def newvar(self, name, setnames=None, header=None, par=False): """Create a new variable and add it to the model. Args: name (str): Name of variable or parameter setnames (list): List of set names header (str): GEMPACK header par (bool): True if a parameter Returns: Var: new object. """ _add_name(name, self.dat_names) item = Var(name, setnames, header, par=par) self.dats[name] = item if par: self.par_names.append(name) else: self.var_names.append(name) return item
import re from query import Query from var import Var A = Var('A') B = Var('B') C = Var('C') A.setValue(1) B.setValue(0) C.setValue(0) varMap = { "A" : A, "B" : B, "C" : C } query = "(A+B)|(B+C)" test = Query(query) print(query) tmp = query for (name, value) in varMap.items(): tmp = str.replace(tmp, name, str(value.getValue())) print(tmp) result = test.run(varMap) print("result brut = " + str(result)) def interpretResult( right, search, result ): undetermined = "!?[A-Z][|^]"
# encoding: utf-8 ''' vars.py description: variables for plotting ''' ## modules from var import Var ## Event variables ## --------------------------------------- nmuons = Var( name='nmuons', path='event', xmin=0, xmax=5, log=False, ) ## Muon variables ## --------------------------------------- mu_pt = Var( name='mu_pt', path='muons', xmin=0, xmax=150, rebin=10, log=False, )
def parse(f): def add_var(d, v): # Do nothing if var is none. Gracefully handles first variable, # and after that point var is never None if v is None: return if v.ctype == 'string' and v.size is None: raise ValueError('String %s has no length' % v.name) if v.address is None: raise ValueError('Var %s has no address' % v.name) if v.vartype is None: raise ValueError('Var %s has no type' % v.name) d.vars.append(v) device = None var = None group = None custom = False cur_address = 0 cur_interval = 0 cur_filter = None cur_iwrite = None for line in f: line = line.strip() if line == '': pass elif line[0] == '$': pass elif line[0] == '@': line_result = line.split(',', 3) for i in range(len(line_result)): line_result[i] = line_result[i].strip('@' + string.whitespace) if device is None: device = Device(line_result[0]) group = line_result[0] else: err = 'Duplicate device line in file (Had %s, now have %s)' \ % (device.name, line_result[0]) raise ValueError(err) device.id = int(line_result[1]) if line_result[2] == '/dev/ttyUSB0': device.path = 'autodetect' else: device.path = line_result[2] device.baud_rate = int(line_result[3]) elif line[0] == ';': line = line.strip(';' + string.whitespace) if line.startswith('group:'): line_result = line[6:].split(',', 2) for i in range(len(line_result)): line_result[i] = line_result[i].strip() group = line_result[0] if device is None: raise ValueError('Group %s has no device' % group) else: if bools[line_result[1]] == True: if group not in device.write_only_groups: device.write_only_groups.append(group) else: if group in device.write_only_groups: raise ValueError('Group %s is already write only' % group) elif line.startswith('filter:'): line_result = line[7:].strip() cur_filter = line_result elif line.startswith('no_initial_write'): cur_iwrite = True elif line[0] == '#': line_result = line.split(',', 3) for i in range(len(line_result)): line_result[i] = line_result[i].strip('#' + string.whitespace) cur_address = int(line_result[0]) cur_interval = int(line_result[1]) custom = bools[line_result[2]] elif custom == True: line_result = line.split(',', 5) for i in range(len(line_result)): line_result[i] = line_result[i].strip() (g, v) = line_result[2].split('/', 1) if device is None: raise ValueError('Var %s has no device' % g) var = Var(g, v) var.vartype = line_result[1] if line_result[1] == 'string': var.ctype = 'string' else: var.ctype = ctypes[line_result[1]] var.size = int(line_result[0]) var.readonly = bools[line_result[4]] var.address = cur_address cur_address += int(line_result[0]) var.interval = cur_interval if cur_filter is not None: var.filter = cur_filter cur_filter = None if cur_iwrite is not None: var.iwrite = False cur_iwrite = None add_var(device, var) if device.path is None: raise ValueError('Device %s has no path' % device.name) if device.id is None and device.path == 'autodetect': raise ValueError('Device %s is autodetect but no id' % device.name) return device
bins_invM_3 = generateLogBins(8,130,200) bins_invM_4 = generateLogBins(6,90,200) bins_Zpeak = [50,70,74,77,80,82,83,84,85,86,87,88,89,90,91,92,93,94,95,97,99,102,105,110,130] bins_Zpeak2 = [50,80,100,130] bins_met = generateLogBins(15,1,1000) bins_met_2 = generateLogBins(50,25,2000) """ bins_pt_2 = generateLogBins(20, 30, 1000) ## Event variables ## --------------------------------------- averageIntPerXing = Var( name='averageIntPerXing', path='event', xmin=0, xmax=45, log=False, ) actualIntPerXing = Var( name='actualIntPerXing', path='event', xmin=0, xmax=45, log=False, ) NPV = Var( name='NPV', path='event',
class Model(GlobalEntity): """An "Model" entity. Inherits from GlobalEntity. Attributes: properties: a dictionary of the entity's properties used_variable: the model variable (score, segment, ...) used by this model entity """ def __init__(self, **properties): """Inits used_variable to None. Calls GlobalEntity constructor with: - unique attribute name: name - label: Model - properties """ properties['name'] = self.name_normalizer(properties['name']) super(Model, self).__init__(uniq_attr_name='name', label='Model', **properties) self.used_variable = None def name_normalizer(self, raw_model_name): """Normalizes the Model's name. Converts to all upper case. Args: raw_model_name: the Model name before normalization Returns: The normalized name (string). """ return raw_model_name.upper() def create_used_var(self, var_name): """Creates Var instance. Sets the instance to this object's used_variable. Args: var_name: the variable name used Returns: A Var instance """ self.used_variable = Var(name=var_name) return self.used_variable def pluto_handler(self, pluto_entity): """Creates the relevant entities in the data store. Creates the following in the data store: - Model node - Used Var node (if needed) - (Pluto Entity)-[:CONSUMES]->(Model) relationship OR (Pluto Entity)-[:CONSUMES]->(Var)->[:CONSUMES]->(Model) Args: pluto_entity: The Pluto entity object (Rule, Rule Variable, Local Variable). Needs to be bound to a remote node. """ self.create_node() used_var_name = self.used_variable.properties['name'] if used_var_name.startswith('model_'): pluto_entity.create_unique_relationship('CONSUMES', self.node, variable=used_var_name) else: self.create_used_var_node_and_relationship() pluto_entity.create_unique_relationship('CONSUMES', self.used_variable.node) def create_used_var_node_and_relationship(self): """Creates Model Variable node and relationship to this Node (model). Returns: The created Variable node (bound to remote node). """ var_node = self.used_variable.create_node() self.create_unique_relationship('CONSUMES', var_node) return var_node
def main(fileName): start = time.clock() var = Var() var.openFile(fileName) var.output_something() var.analysis_text() # for Martix and dict var.initMartix() var.makeDict() var.initStamp() # stamp for the element like R # var.printMartix() # var.printGBCDUI() var.backMartix() if var.ToSolveDC: var.solveDC(plotFlag=1) if var.ToSolveTran: var.solveTran() if var.ToSolveAC: var.solveAC() # var.printMartix() # var.printGBCDUI() # var.printX() var.closeFile() end = time.clock() print end - start
#! /usr/bin/env python3 # _*_ coding: utf-8 _*_ import pygame # pygame from var import Var # for const from ship import Ship # ship from scores import Scores from sounds import Sounds import game_functions as gf # Game functions from pygame.sprite import Group pygame.init() ai_var = Var() screen = pygame.display.set_mode([ai_var.screen_width, ai_var.screen_height]) pygame.display.set_caption("Alien War") ship = Ship(screen) sc = Scores(screen, ai_var) sd = Sounds() timer = pygame.time.Clock() bullets = Group() aliens = Group() def main(): while sc.game_active: # Game Started gf.check_events(ship, ai_var, screen, bullets, sc, sd) # Check events ship.update(ai_var) # Update the status of the ship bullets.update() aliens.update(sc) gf.update_aliens(aliens, screen, ai_var, bullets, sc, ship, sd) gf.remove(bullets, aliens, screen)
# encoding: utf-8 ''' vars.py description: variables for all the channels ''' ## modules from var import Var from funcs import generateLogBins ## Cutflows ## --------------------------------------- cutflow_weighted = Var(name='cutflow_weighted_mumu', log=False) cutflow = Var(name='cutflow_mumu', log=False) cutflow_weighted_mu_pairs = Var(name='cutflow_weighted_mumu_mu_pairs', log=False) cutflow_mu_pairs = Var(name='cutflow_mumu_mu_pairs', log=False) cutflow_presel = Var(name='cutflow_presel', log=False) cutflow_weighted_presel = Var(name='cutflow_weighted_presel', log=False) cutflow_ZCR = Var(name='cutflow_ZCR', log=False) cutflow_weighted_ZCR = Var(name='cutflow_weighted_ZCR', log=False) bins_pt = generateLogBins(10, 30, 400) bins_pt_4lep = generateLogBins(5, 30, 200) bins_pt_2 = generateLogBins(8, 30, 400) #bins_mVis = generateLogBins(25,20,900) # ttbar CR #bins_mVis = generateLogBins(15,60,200) # bins for CRs #bins_mVis = generateLogBins(20,30,3000) # bins for plotting #bins_mVis = generateLogBins(5,200,900) #bins for SRs bins_mVis = generateLogBins(23, 200, 1350) #bins for SRs
def __init__(self, vars, iaxis=None): import pygeode.axis from pygeode.tools import common_dtype from pygeode.var import combine_meta import numpy as np # Use first var segment for the axes axes = list(vars[0].axes) naxes = len(axes) # For now, assume all segments have the same order of axes assert all(v.naxes == naxes for v in vars) for i in range(naxes): assert all(axes[i].isparentof(v.axes[i]) for v in vars) if iaxis is None: iaxis = set(i for v in vars for i in range(naxes) if v.axes[i] not in axes) assert len(iaxis) <= 1, "more than one varying axis id=%s for %s; can't concatenate"%(iaxis,repr(vars[0])) # Degenerate case: all segments have identical axes if len(iaxis) == 0: from warnings import warn warn ('all axes are identical. Creating a fake "concat" axis', stacklevel=2) iaxis = naxes axes.append(pygeode.axis.NamedAxis(len(vars), name='concat')) # Standard case: exactly one concatenation axis else: iaxis = iaxis.pop() if not iaxis is naxes: # Get a numerical dimension number iaxis = vars[0].whichaxis(iaxis) # Update the list of axes with the concatenated axis included values = [v.axes[iaxis].values for v in vars] values = np.concatenate(values) axes[iaxis] = axes[iaxis].withnewvalues(values) # Get the data type dtype = common_dtype(vars) Var.__init__(self, axes, dtype=dtype) # Grab metadata from the input variables combine_meta (vars, self) # # Assign a name (and other attributes??) to the var # name = set(v.name for v in vars if v.name != '') # if len(name) == 1: self.name = name.pop() # # # Combine the attributes (if applicable) # atts = common_dict([v.atts for v in vars]) # self.atts = atts # # Combine the plot attributes (if applicable) # plotatts = common_dict([v.plotatts for v in vars]) # self.plotatts = plotatts # Other stuff self.vars = vars self.iaxis = iaxis
# encoding: utf-8 ''' vars.py description: variables for plotting ''' ## modules from var import Var ## Event variables ## --------------------------------------- nmuons = Var( name='nmuons', path='event', xmin=0, xmax=5, log=False, ) n_vx = Var( name='n_vx', path='event', xmin=0, xmax=14, # rebin = 0, log=False, ) ## Muon variables ## ---------------------------------------
def parse(f): def add_var(d, v): # Do nothing if var is none. Gracefully handles first variable, # and after that point var is never None if v is None: return if v.ctype == 'string' and v.size is None: raise ValueError('String %s has no length' % v.name) if v.address is None: raise ValueError('Var %s has no address' % v.name) if v.vartype is None: raise ValueError('Var %s has no type' % v.name) d.vars.append(v) device = None var = None group = None custom = False cur_address = 0 cur_interval = 0 cur_filter = None cur_iwrite = None for line in f: line = line.strip() if line == '': pass elif line[0] == '$': pass elif line[0] == '@': line_result = line.split(',',3) for i in range(len(line_result)): line_result[i] = line_result[i].strip('@'+string.whitespace) if device is None: device = Device(line_result[0]) group = line_result[0] else: err = 'Duplicate device line in file (Had %s, now have %s)' \ % (device.name, line_result[0]) raise ValueError(err) device.id = int(line_result[1]) if line_result[2] == '/dev/ttyUSB0': device.path = 'autodetect' else: device.path = line_result[2] device.baud_rate = int(line_result[3]) elif line[0] == ';': line = line.strip(';'+string.whitespace) if line.startswith('group:'): line_result = line[6:].split(',',2) for i in range(len(line_result)): line_result[i] = line_result[i].strip() group = line_result[0] if device is None: raise ValueError('Group %s has no device' % group) else: if bools[line_result[1]] == True: if group not in device.write_only_groups: device.write_only_groups.append(group) else: if group in device.write_only_groups: raise ValueError('Group %s is already write only' % group) elif line.startswith('filter:'): line_result = line[7:].strip() cur_filter = line_result elif line.startswith('no_initial_write'): cur_iwrite = True elif line[0] == '#': line_result = line.split(',',3) for i in range(len(line_result)): line_result[i] = line_result[i].strip('#'+string.whitespace) cur_address = int(line_result[0]) cur_interval = int(line_result[1]) custom = bools[line_result[2]] elif custom == True: line_result = line.split(',',5) for i in range(len(line_result)): line_result[i] = line_result[i].strip() (g,v) = line_result[2].split('/',1) if device is None: raise ValueError('Var %s has no device' % g) var = Var(g, v) var.vartype = line_result[1] if line_result[1] == 'string': var.ctype = 'string' else: var.ctype = ctypes[line_result[1]] var.size = int(line_result[0]) var.readonly = bools[line_result[4]] var.address = cur_address cur_address += int(line_result[0]) var.interval = cur_interval if cur_filter is not None: var.filter = cur_filter cur_filter = None if cur_iwrite is not None: var.iwrite = False cur_iwrite = None add_var(device, var) if device.path is None: raise ValueError('Device %s has no path' % device.name) if device.id is None and device.path == 'autodetect': raise ValueError('Device %s is autodetect but no id' % device.name) return device
def parse(netlist): var = Var() var.string2file(netlist) var.analysis_text() # for Martix and dict var.initMartix() var.makeDict() var.initStamp() # stamp for the element like R # var.printMartix() # var.printGBCDUI() var.backMartix() if var.ToSolveDC: var.solveDC(plotFlag=1) if var.ToSolveTran: var.solveTran() if var.ToSolveAC: var.solveAC() # var.printMartix() # var.printGBCDUI() # var.printX() var.closeFile() result = {} if hasattr(var, 'voltage_tag'): result['voltage'] = var.voltage_tag if hasattr(var, 'current_tag'): result['current'] = var.current_tag if hasattr(var, 'phase_tag'): result['phase'] = var.phase_tag return result