def bn_test(): """定义输入""" x_numpy = np.random.randn(1, 5, 2, 2).astype(np.float32) x = torch.tensor(x_numpy, requires_grad=True) """定义参数""" w_numpy = np.random.normal(1.0, 0.02, size=(5)).astype(np.float32) w = torch.tensor(w_numpy, requires_grad=True) b_numpy = np.zeros(5).astype(np.float32) b = torch.tensor(b_numpy, requires_grad=True) # 初始化 # pytorch (需要添加affine=False参数) # affine定义了BN层的参数γ和β是否是可学习的(不可学习默认是常数1和0). 通常需要设置为True,但测试时numpy的γ=1和β=0,故此时需要将参数设置为False # bn_tensor = torch.nn.BatchNorm2d(5, affine=False) bn_tensor = torch.nn.BatchNorm2d(5, affine=True) bn_tensor.weight = torch.nn.Parameter(w, requires_grad=True) bn_tensor.bias = torch.nn.Parameter(b, requires_grad=True) # numpy bn_numpy = BN.BatchNorm(5) bn_numpy.set_gamma(Parameter(w_numpy, requires_grad=True)) bn_numpy.set_beta(Parameter(b_numpy, requires_grad=True)) """计算前向传播""" bn_out_tensor = bn_tensor(x) bn_out_numpy = bn_numpy.forward(x_numpy, 'train') """计算反向传播""" # 误差参数初始化 dy_numpy = np.random.random(bn_out_numpy.shape).astype(np.float32) dy = torch.tensor(dy_numpy, requires_grad=True) # 反向计算 # pytorch bn_out_tensor.backward(dy) x_grad_tensor = x.grad w_grad_tensor = bn_tensor.weight.grad b_grad_tensor = bn_tensor.bias.grad # numpy x_grad_numpy = bn_numpy.gradient(dy_numpy) w_grad_numpy = bn_numpy.gamma.grad b_grad_numpy = bn_numpy.beta.grad """打印输出""" print('-----对比输出-----') print('bn_out_tensor: \n', bn_out_tensor) print('bn_out_tensor.shape: \n', bn_out_tensor.shape) print('bn_out_numpy: \n', bn_out_numpy) print('bn_out_numpy.shape: \n', bn_out_numpy.shape) print('bn_out_error: \n', bn_out_numpy - bn_out_tensor.detach().numpy()) print('-----对比x_grad-----') print('x_grad_tensor: \n', x_grad_tensor) print('x_grad_numpy: \n', x_grad_numpy) print('x_grad_error: \n', x_grad_numpy - x_grad_tensor.detach().numpy()) print('-----对比w_grad-----') print('w_grad_tensor: \n', w_grad_tensor) print('w_grad_numpy: \n', w_grad_numpy) print('w_grad_error: \n', w_grad_numpy - w_grad_tensor.detach().numpy()) print('-----对比b_grad-----') print('b_grad_tensor: \n', b_grad_tensor) print('b_grad_numpy: \n', b_grad_numpy) print('b_grad_error: \n', b_grad_numpy - b_grad_tensor.detach().numpy())
def __init__(self, in_channels, out_channels, filter_size, zero_padding, stride, method='SAME', bias_required=True): super(Deconv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.filter_size = filter_size self.zero_padding = zero_padding self.stride = stride self.method = method self.bias_required = bias_required # 定义参数 param_weights = np.random.uniform(-1e-2, 1e-2, (self.out_channels, self.in_channels, self.filter_size, self.filter_size)) self.weights = Parameter(param_weights, requires_grad=True) if self.bias_required: param_bias = np.zeros(self.out_channels) self.bias = Parameter(param_bias, requires_grad=True) else: self.bias = None
def __init__(self, name='', parent_dataset=None, axarr=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {''}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, axarr) self.function = self.LogNormal # main theory function self.has_modes = False # True if the theory has modes self.parameters['logW0'] = Parameter( name='logW0', value=5, description='Normalization constant', type=ParameterType.real, opt_type=OptType.opt) self.parameters['logM0'] = Parameter( name='logM0', value=5, description='Log mean molecular weight', type=ParameterType.real, opt_type=OptType.opt) self.parameters['sigma'] = Parameter(name='sigma', value=1, description='Standard deviation', type=ParameterType.real, opt_type=OptType.opt, bracketed=True, min_value=0)
def __init__(self, in_num, out_num, bias_required=True, bit_length=32): super(FullyConnect_sec, self).__init__() # input_shape = [batchsize, channel_num, height, width](卷积层) # or [batchsize, input_num](全连接层) self.in_num = in_num # output_shape = [batchsize, out_num] 其实单个output就是个一维数组,列向量 self.out_num = out_num self.bias_required = bias_required self.bit_length = bit_length '''使用xavier初始化''' # 初始化全连接层为输入的weights # param_weights = np.random.standard_normal((self.in_num, self.out_num))/100 param_weights = self.xavier_init(self.in_num, self.out_num, (self.in_num, self.out_num)) param_weights_1 = self.xavier_init(self.in_num, self.out_num, (self.in_num, self.out_num)) param_weights_2 = param_weights - param_weights_1 # self.weights = Parameter(param_weights, requires_grad=True) self.weights_1 = Parameter(param_weights_1, requires_grad=True) self.weights_2 = Parameter(param_weights_2, requires_grad=True) # bias初始化为列向量 # param_bias = np.random.standard_normal(self.out_num)/100 if self.bias_required: param_bias = self.xavier_init(self.in_num, self.out_num, (self.out_num)) param_bias_1 = self.xavier_init(self.in_num, self.out_num, (self.out_num)) param_bias_2 = param_bias - param_bias_1 # self.bias = Parameter(param_bias, requires_grad=True) self.bias_1 = Parameter(param_bias_1, requires_grad=True) self.bias_2 = Parameter(param_bias_2, requires_grad=True) else: # self.bias = None self.bias_1 = None self.bias_2 = None
def __init__(self, name="", parent_dataset=None, ax=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, ax) self.function = self.TheoryTTSShiftAutomatic self.parameters["T"] = Parameter( name="T", value=25, description="Temperature to shift to, in °C", type=ParameterType.real, opt_type=OptType.const, display_flag=False) self.parameters["vert"] = Parameter(name="vert", value=True, description="Shift vertically", type=ParameterType.boolean, opt_type=OptType.const, display_flag=False) self.Mwset, self.Mw, self.Tdict = self.get_cases() self.current_master_curve = None self.current_table = None self.current_file_min = None self.shiftParameters = {} self.aT_vs_T = {} for k in self.tables.keys(): self.shiftParameters[k] = (0.0, 0.0 ) # log10 of horizontal, then vertical
def __init__(self, name="", parent_dataset=None, ax=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, ax) self.function = self.two_exponentials self.parameters["a1"] = Parameter( "a1", 0.9, "Prefactor 1", ParameterType.real, opt_type=OptType.opt) self.parameters["T1"] = Parameter( "T1", 1.0, "Exponential time constant 1", ParameterType.real, opt_type=OptType.opt) self.parameters["a2"] = Parameter( "a2", 0.1, "Prefactor 2", ParameterType.real, opt_type=OptType.opt) self.parameters["T2"] = Parameter( "T2", 10.0, "Exponential time constant 2", ParameterType.real, opt_type=OptType.opt) self.Qprint("%s: a1*exp(-x/T1) + a2*exp(-x/T2)" % self.thname)
def _MSHspec(self,source,i,dist): """Set parameters for the MSH 15-52 source Parameters: - self - This CatalogSourceExtractor object - source - The Source object we are modifying - i - The spectral index of the source from the catalog - dist - Distance from source to ROI center - not used Return value: - none - Sets the Spectrum component of the provided Source object Usage: self._VXspec(self,source,i,dist) Description: This method sets the necessary parameters for a MSH 15-52 source. By default all parameters of the source are fixed. Note: The index values (i) in the catalog are given as positive values (i.e. used in the form of flux = E^-i dE). However the convention in the model editor seems to be to use negative values so the index sign is flipped when creating the source. If it is desirable to use positive index values, simply swap out the current index parameter assignment for the one commented out. """ integral = Parameter(name="Integral",value = 0.291, scale = 1e-8, min = 0.0001, max = 10000.0, free = False) index = Parameter(name="Index",value = -i, scale = 1.0, min = -5.0, max = -1.0, free = False) #flip the sign, positive in catalog but negative here # index = Parameter(name="Index",value = i, scale = -1.0, min = 1.0, max = 5.0, free = False) # use this one if you want to have positive index values lowerLimit = Parameter(name="LowerLimit",value = 1000, scale = 1.0, min = 30.0, max = 5e5, free = False) upperLimit = Parameter(name="UpperLimit",value = 1e5, scale = 1.0, min = 30.0, max = 5e5, free = False) spectrum = Spectrum(type='PowerLaw2',parameters=[integral,index,lowerLimit,upperLimit]) source.setSpectrum(spectrum)
def __init__(self, name='', parent_dataset=None, axarr=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {''}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, axarr) self.function = self.calculate # main theory function self.has_modes = False # True if the theory has modes self.parameters["G0"] = Parameter( "G0", 1e6, "Modulus c*kB*T/N", ParameterType.real, opt_type=OptType.opt, min_value=0) self.parameters["tau0"] = Parameter( "tau0", 1e-3, "segment relaxation time", ParameterType.real, opt_type=OptType.opt, min_value=0) self.parameters["M0"] = Parameter( "M0", 0.2, "segment molar mass", ParameterType.real, opt_type=OptType.opt, min_value=0.01)
def __init__(self, name="", parent_dataset=None, ax=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, ax) self.MAX_DEGREE = 10 self.function = self.polynomial self.parameters["n"] = Parameter( name="n", value=1, description="Degree of Polynomial", type=ParameterType.integer, opt_type=OptType.const, display_flag=False) for i in range(self.parameters["n"].value + 1): self.parameters["A%02d" % i] = Parameter( "A%02d" % i, 1.0, "Coefficient order %d" % i, ParameterType.real, opt_type=OptType.opt) self.Qprint("%s: A00 + A01*x + A02*x^2 + ..." % self.thname)
def __init__(self, in_channels, out_channels, filter_width, filter_height, zero_padding, stride, method='VALID', bias_required=True): super(ConvLayer, self).__init__() # input_array 4d tensor [batch, channel, height, width] self.in_channels = in_channels # filter参数 self.filter_width = filter_width # 过滤器的宽度 self.filter_height = filter_height # 过滤器的高度 self.out_channels = out_channels # 过滤器组的数量(每组filter算一个),输出通道数量 self.zero_padding = zero_padding # 补0圈数 self.stride = stride # 步幅 self.method = method self.bias_required = bias_required # 卷积层过滤器初始化 '''filter_num = output_channel,就是卷积输出feature map的通道数''' param_weights = np.random.uniform( -1e-2, 1e-2, (self.out_channels, self.in_channels, self.filter_height, self.filter_width)) self.weights = Parameter(param_weights, requires_grad=True) if self.bias_required: param_bias = np.zeros(self.out_channels) self.bias = Parameter(param_bias, requires_grad=True) else: self.bias = None
def __init__(self, name="", parent_dataset=None, ax=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, ax) self.function = self.DebyeModesFrequency self.has_modes = False self.MAX_MODES = 40 self.view_modes = True wmin = self.parent_dataset.minpositivecol(0) wmax = self.parent_dataset.maxcol(0) nmodes = int(np.round(np.log10(wmax / wmin))) self.parameters["einf"] = Parameter("einf", 0.0, "Unrelaxed permittivity", ParameterType.real, opt_type=OptType.opt, min_value=0) self.parameters["logwmin"] = Parameter( "logwmin", np.log10(wmin), "Log of frequency range minimum", ParameterType.real, opt_type=OptType.opt) self.parameters["logwmax"] = Parameter( "logwmax", np.log10(wmax), "Log of frequency range maximum", ParameterType.real, opt_type=OptType.opt) self.parameters["nmodes"] = Parameter( name="nmodes", value=nmodes, description="Number of Debye modes", type=ParameterType.integer, opt_type=OptType.const, display_flag=False) # Interpolate modes from data w = np.logspace(np.log10(wmin), np.log10(wmax), nmodes) eps = np.abs( np.interp(w, self.parent_dataset.files[0].data_table.data[:, 0], self.parent_dataset.files[0].data_table.data[:, 1])) for i in range(self.parameters["nmodes"].value): self.parameters["logDe%02d" % i] = Parameter( "logDe%02d" % i, np.log10(eps[i]), "Log of Mode %d amplitude" % i, ParameterType.real, opt_type=OptType.opt) # GRAPHIC MODES self.graphicmodes = [] self.artistmodes = [] self.setup_graphic_modes()
def __init__(self, name='', parent_app=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {''}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_app) self.parameters['xmin'] = Parameter(name='xmin', value=-np.Infinity, description='Minimum x', type=ParameterType.real) self.parameters['xmax'] = Parameter(name='xmax', value=np.Infinity, description='Maximum x', type=ParameterType.real) self.parameters['ymin'] = Parameter(name='ymin', value=-np.Infinity, description='Minimum y', type=ParameterType.real) self.parameters['ymax'] = Parameter(name='ymax', value=np.Infinity, description='Maximum y', type=ParameterType.real)
def __init__(self, name='', parent_app=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {''}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_app) #self.function = self.findpeaks # main Tool function self.parameters['threshold'] = Parameter( name='threshold', value=0.3, description='threshold for peak detection', type=ParameterType.real) self.parameters['minimum_distance'] = Parameter( name='minimum_distance', value=5, description='minimum distance (in datapoints) between peaks', type=ParameterType.integer) self.parameters["minpeaks"] = Parameter( name="minpeaks", value=False, description="Find minimum peaks", type=ParameterType.boolean, display_flag=False) self.parameters["parabola"] = Parameter( name="parabola", value=False, description="Fit Parabola to peak", type=ParameterType.boolean, display_flag=False) self.seriesarray = [] self.axarray = []
class Mul(Node): def __init__(self, A, B): self.node_name = "Mul{}".format(rand_str()) if type(A) is not Parameter: A = A.get_output() self.A = A if type(B) is not Parameter: B = B.get_output() self.B = B NeuralNetwork.NeuralNetwork.add_node(self) NeuralNetwork.NeuralNetwork.add_param(self.A) NeuralNetwork.NeuralNetwork.add_param(self.B) self.out = Parameter(is_placeholder=True, name=self.node_name + "_out") def forward(self): res = self.A.get_data().dot(self.B.get_data()) self.out.set_data_(res) return self.out def get_output(self): return self.out def backward(self): inc_grad = self.out.get_grad() self.A.set_grad_(inc_grad.dot(self.B.get_data().T)) self.B.set_grad_(self.A.get_data().T.dot(inc_grad)) return def __str__(self): return self.node_name
def _PL2spec(self, source, F, i, dist, sig): """Set parameters for a PowerLaw2 sepctrum source Parameters: - self - This CatalogSourceExtractor object - source - The Source object we are modifying - F - The integrated flux of the source calculated from the catalog parameters - i - The spectral index of the source from the catalog - dist - Distance from source to ROI center - sig - Source significance from catalog Return value: - none - Sets the Spectrum component of the provided Source object Usage: self._PL2spec(self,source,F,i,dist,sig) Description: This method sets the necessary parameters for a LogParabola spectrum source. By default the parameters of the source are fixed unless the source is within the radius limit defined by the user for variable sources (which defaults to the extraction region from the FT1 file) and the source is above the specified significance limit (default 4). In that case the Integral and Index parameters are allowed to vary. Note: The index values (i) in the catalog are given as positive values (i.e. used in the form of flux = E^-i dE). However the convention in the model editor seems to be to use negative values so the index sign is flipped when creating the source. If it is desirable to use positive index values, simply swap out the current index parameter assignment for the one commented out. """ fscale = int(floor(log10(F))) pfValue = F / 10**fscale integral = Parameter(name="Integral", value=pfValue, scale=10**fscale, min=0.0001, max=10000.0, free=False) index = Parameter( name="Index", value=-i, scale=1.0, min=-5.0, max=-1.0, free=False) #flip the sign, positive in catalog but negative here # index = Parameter(name="Index",value = i, scale = -1.0, min = 1.0, max = 5.0, free = False) # use this one if you want to have positive index values lowerLimit = Parameter(name="LowerLimit", value=100, scale=1.0, min=30.0, max=5e5, free=False) upperLimit = Parameter(name="UpperLimit", value=1e5, scale=1.0, min=30.0, max=5e5, free=False) if (dist <= self.radLim and dist <= self.radius and sig >= self.catParams['sigLimit']): index.setFree(True) integral.setFree(True) spectrum = Spectrum( type='PowerLaw2', parameters=[integral, index, lowerLimit, upperLimit]) source.setSpectrum(spectrum)
class ReLU(Node): def __init__(self, A): self.node_name = "ReLU{}".format(rand_str()) if type(A) is not Parameter: A = A.get_output() self.A = A NeuralNetwork.NeuralNetwork.add_node(self) NeuralNetwork.NeuralNetwork.add_param(self.A) self.out = Parameter(is_placeholder=True, name=self.node_name + "_out") def forward(self): res = relu(self.A.get_data()) self.out.set_data_(res) return self.out def get_output(self): return self.out def backward(self): inc_grad = self.out.get_grad() local_grad = relu_grad(self.A.get_data()) self.A.set_grad_(inc_grad * local_grad) return def __str__(self): return self.node_name
def __init__(self, name='', parent_app=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {''}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_app) self.parameters['x'] = Parameter(name='x', value='x', description='Expression for abscissa', type=ParameterType.string) self.parameters['y'] = Parameter(name='y', value='y', description='Expression for ordinate', type=ParameterType.string) safe_list = [ 'sin', 'cos', 'tan', 'arccos', 'arcsin', 'arctan', 'arctan2', 'deg2rad', 'rad2deg', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'around', 'round_', 'rint', 'floor', 'ceil', 'trunc', 'exp', 'log', 'log10', 'fabs', 'mod', 'e', 'pi', 'power', 'sqrt' ] self.safe_dict = {} for k in safe_list: self.safe_dict[k] = globals().get(k, None)
def initUI(self): if self.mainWindow: self.setAcceptDrops(True) self.setWindowTitle('Sistre') openAction = QtGui.QAction('Open', self) openAction.triggered.connect(self.showFileDialog) exitAction = QtGui.QAction('Exit', self) exitAction.triggered.connect(QtGui.qApp.quit) filemenu = self.menuBar().addMenu('File') filemenu.addAction(openAction) filemenu.addSeparator() filemenu.addAction(exitAction) self.parameterDialog = Parameter(self) parameterAction = QtGui.QAction('Parameter', self) parameterAction.triggered.connect(self.showParameterDialog) viewmenu = self.menuBar().addMenu('View') viewmenu.addAction(parameterAction) createGrpFromSelAction = QtGui.QAction('Create from selection', self) createGrpFromSelAction.triggered.connect( self.createGroupFromSelection) createGrpDialogAction = QtGui.QAction('Create...', self) createGrpDialogAction.triggered.connect(self.showCreateGroupDialog) groupmenu = self.menuBar().addMenu('Group') groupmenu.addAction(createGrpFromSelAction) groupmenu.addAction(createGrpDialogAction) self.glRenderArea = GLRenderArea(self) self.centralTab = QtGui.QTabWidget() self.centralTab.addTab(self.glRenderArea, '3D View') self.centralTab.addTab(QtGui.QWidget(), '2D View') self.timerBar = TimerBar(self) self.leftLayout = QtGui.QVBoxLayout() self.leftLayout.addWidget(self.centralTab) self.leftLayout.addWidget(self.timerBar) self.itemList = ItemList(self) self.itemList.itemListPick.connect(self.glRenderArea.itemListPick) self.itemList.itemConfigChanged.connect( self.glRenderArea.itemConfigChanged) # self.itemList.itemConfigChanged.connect(self.graphRenderArea.itemConfigChanged) self.centralLayout = QtGui.QHBoxLayout() self.centralLayout.addLayout(self.leftLayout) self.centralLayout.addWidget(self.itemList) self.centralWidget = QtGui.QWidget() self.centralWidget.setLayout(self.centralLayout) self.setCentralWidget(self.centralWidget) self.show()
def __init__(self, name="", parent_dataset=None, axarr=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, axarr) self.function = self.calculate_giesekus self.has_modes = True self.parameters["nmodes"] = Parameter( name="nmodes", value=2, description="Number of modes", type=ParameterType.integer, opt_type=OptType.const, display_flag=False) self.parameters["nstretch"] = Parameter( name="nstretch", value=2, description="Number of strecthing modes", type=ParameterType.integer, opt_type=OptType.const, display_flag=False) for i in range(self.parameters["nmodes"].value): self.parameters["G%02d" % i] = Parameter( name="G%02d" % i, value=1000.0, description="Modulus of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, bracketed=True, min_value=0) self.parameters["tauD%02d" % i] = Parameter( name="tauD%02d" % i, value=10.0, description="Terminal time of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, bracketed=True, min_value=0) self.parameters["alpha%02d" % i] = Parameter( name="alpha%02d" % i, value=0.5, description="Dimensionless mobility factor of mode %02d" % i, type=ParameterType.real, opt_type=OptType.opt, bracketed=True, min_value=0, max_value=1) self.MAX_MODES = 40 self.init_flow_mode()
def __init__(self, name="", parent_dataset=None, axarr=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, axarr) self.function = self.calculate_PomPom self.has_modes = True self.parameters["nmodes"] = Parameter( name="nmodes", value=2, description="Number of modes", type=ParameterType.integer, opt_type=OptType.const, display_flag=False) for i in range(self.parameters["nmodes"].value): self.parameters["G%02d" % i] = Parameter( name="G%02d" % i, value=1000.0, description="Modulus of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, min_value=0) self.parameters["tauB%02d" % i] = Parameter( name="tauB%02d" % i, value=10.0, description="Backbone relaxation time of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, min_value=0) self.parameters["q%02d" % i] = Parameter( name="q%02d" % i, value=1, description="Number of dangling arms of mode %02d" % i, type=ParameterType.integer, opt_type=OptType.opt, min_value=1, max_value=100) self.parameters["ratio%02d" % i] = Parameter( name="ratio%02d" % i, value=2, description= "Ratio of orientation to stretch relaxation times of mode %02d" % i, type=ParameterType.real, opt_type=OptType.const, min_value=1, max_value=5) self.MAX_MODES = 40 self.init_flow_mode()
def set_param_value(self, name, value): """[summary] [description] Arguments: - name {[type]} -- [description] - value {[type]} -- [description] """ if (name == "nmodes"): oldn = self.parameters["nmodes"].value message, success = super(BaseTheoryPomPom, self).set_param_value( name, value) if not success: return message, success if (name == "nmodes"): for i in range(self.parameters["nmodes"].value): self.parameters["G%02d" % i] = Parameter( name="G%02d" % i, value=1000.0, description="Modulus of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, min_value=0) self.parameters["tauB%02d" % i] = Parameter( name="tauB%02d" % i, value=10.0, description="Backbone relaxation time of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, min_value=0) self.parameters["q%02d" % i] = Parameter( name="q%02d" % i, value=1, description="Number of dangling arms of mode %02d" % i, type=ParameterType.integer, opt_type=OptType.opt, min_value=1, max_value=100) self.parameters["ratio%02d" % i] = Parameter( name="ratio%02d" % i, value=2, description= "Ratio of orientation to stretch relaxation times of mode %02d" % i, type=ParameterType.real, opt_type=OptType.const, min_value=1, max_value=5) if (oldn > self.parameters["nmodes"].value): for i in range(self.parameters["nmodes"].value, oldn): del self.parameters["G%02d" % i] del self.parameters["tauB%02d" % i] del self.parameters["ratio%02d" % i] del self.parameters["q%02d" % i] return '', True
def _LPspec(self, source, f, i, p, b, dist, sig): """Set parameters for a LogParabola sepctrum source Parameters: - self - This CatalogSourceExtractor object - source - The Source object we are modifying - F - The integrated flux of the source calculated from the catalog parameters - i - The spectral index of the source from the catalog - p - The pivot energy of the source from the catalog - used to set the Eb parameter - b - The beta index from the catalog - dist - Distance from source to ROI center - sig - Source significance from catalog Return value: - none - Sets the Spectrum component of the provided Source object Usage: self._LPspec(self,source,f,i,p,b,dist,sig) Description: This method sets the necessary parameters for a PowerLaw2 spectrum source. By default the parameters of the source are fixed unless the source is within the radius limit defined by the user for variable sources (which defaults to the extraction region from the FT1 file) and the source is above the specified significance limit (default 4). In that case the norm, alpha, and beta parameters are allowed to vary. Note: The index values (i & b) in the catalog are given as positive values (i.e. used in the form of flux = E^-i dE). However the convention in the model editor seems to be to use negative values so the index sign is flipped when creating the source. If it is desirable to use positive index values, simply swap out the current index parameter assignment for the one commented out. """ fscale = int(floor(log10(f))) pfValue = f / 10**fscale norm = Parameter(name="norm", value=pfValue, scale=10**fscale, min=0.0001, max=10000.0, free=False) alpha = Parameter( name="alpha", value=-i, scale=1.0, min=-5.0, max=0, free=False) # flip the sign, positive in catalog but negative here beta = Parameter( name="beta", value=-b, scale=1.0, min=-10.0, max=0, free=False) # flip the sign, positive in catalog but negative here # alpha = Parameter(name="alpha",value = i, scale = -1.0, min = 0, max = 5.0, free = False) # use this one if you want to have positive index values # beta = Parameter(name="beta",value = b, scale = -1.0, min = 0, max = 10.0, free = False) # use this one if you want to have positive index values Eb = Parameter( name="Eb", value=p, scale=1.0, min=30., max=5e5, free=False) # flip the sign, positive in catalog but negative here if (dist <= self.radLim and dist <= self.radius and sig >= self.catParams['sigLimit']): alpha.setFree(True) beta.setFree(True) integral.setFree(True) spectrum = Spectrum(type='LogParabola', parameters=[norm, alpha, beta, Eb]) source.setSpectrum(spectrum)
def freeParameters(self): return [ Parameter( "x", 0.1, err=1, bounds=(0, 2), ), Parameter("y", 0, err=1) ]
def __init__(self, name='', parent_dataset=None, axarr=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {''}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, axarr) self.reactname = "MultiMetCSTR %d" % ( rch.MMCSTR_global.mulmetCSTRnumber) rch.MMCSTR_global.mulmetCSTRnumber += 1 self.function = self.Calc self.simexists = False self.dist_exists = False self.ndist = 0 self.has_modes = False # True if the theory has modes self.autocalculate = False self.do_priority_seniority = False self.parameters['num_to_make'] = Parameter( name='num_to_make', value=1000, description='Number of molecules made in the simulation', type=ParameterType.real, opt_type=OptType.const) self.parameters['mon_mass'] = Parameter( name='mon_mass', value=28, description= 'Mass, in a.m.u., of a monomer (usually set to 28 for PE)', type=ParameterType.real, opt_type=OptType.const) self.parameters['Me'] = Parameter( name='Me', value=1000, description='Entanglement molecular weight', type=ParameterType.real, opt_type=OptType.const) self.parameters['nbin'] = Parameter( name='nbin', value=50, description='Number of molecular weight bins', type=ParameterType.real, opt_type=OptType.const) self.NUMCAT_MAX = 30 # default parameters value self.init_param_values() self.signal_request_dist.connect(rgt.request_more_dist) self.signal_request_polymer.connect(rgt.request_more_polymer) self.signal_request_arm.connect(rgt.request_more_arm) self.signal_mulmet_dialog.connect(rgt.launch_mulmet_dialog) self.do_xrange('', visible=self.xrange.get_visible())
def __init__(self, name="", parent_dataset=None, ax=None): """ **Constructor** Keyword Arguments: - name {[type]} -- [description] (default: {""}) - parent_dataset {[type]} -- [description] (default: {None}) - ax {[type]} -- [description] (default: {None}) """ super().__init__(name, parent_dataset, ax) self.function = self.MaxwellModesTime self.has_modes = True self.MAX_MODES = 40 self.view_modes = True tmin = self.parent_dataset.minpositivecol(0) tmax = self.parent_dataset.maxcol(0) nmodes = int(np.round(np.log10(tmax / tmin))) self.parameters["logtmin"] = Parameter( "logtmin", np.log10(tmin), "Log of time range minimum", ParameterType.real, opt_type=OptType.opt) self.parameters["logtmax"] = Parameter( "logtmax", np.log10(tmax), "Log of time range maximum", ParameterType.real, opt_type=OptType.opt) self.parameters["nmodes"] = Parameter( name="nmodes", value=nmodes, description="Number of Maxwell modes", type=ParameterType.integer, opt_type=OptType.const, display_flag=False) # Interpolate modes from data tau = np.logspace(np.log10(tmin), np.log10(tmax), nmodes) G = np.abs( np.interp(tau, self.parent_dataset.files[0].data_table.data[:, 0], self.parent_dataset.files[0].data_table.data[:, 1])) for i in range(self.parameters["nmodes"].value): self.parameters["logG%02d" % i] = Parameter( "logG%02d" % i, np.log10(G[i]), "Log of Mode %d amplitude" % i, ParameterType.real, opt_type=OptType.opt) # GRAPHIC MODES self.graphicmodes = None self.artistmodes = None self.setup_graphic_modes()
def getStepParamList(jobName, stepName): try: paramDetail = Parameter.getParamByJob(jobName, path=__path__) paramOption = Parameter.getParamOptions(stepName, path=__path__, logPath=__logPath__) data = {} data['paramDetail'] = paramDetail data['paramOption'] = paramOption return jsonify(data) except Exception as e: return str(e), 500
def __init__(self, A): self.node_name = "ReLU{}".format(rand_str()) if type(A) is not Parameter: A = A.get_output() self.A = A NeuralNetwork.NeuralNetwork.add_node(self) NeuralNetwork.NeuralNetwork.add_param(self.A) self.out = Parameter(is_placeholder=True, name=self.node_name + "_out")
def _addNewSource(self, ra, dec): """Add new source to the model Parameters: - self - This DS9Connector object - ra - The RA of the center of the ds9 region to be added as a source - dec - The Dec of the cetner of the ds9 region to be added as a source Return value: - none Description: This method adds a default Source object (PowerLaw spectrum) at the RA and Dec passed to it. The source name is constructed from the RA and Dec and proceeded with the 'ME_' designation to show it was added via ds9 and the model editor. Access to the SourceLibraryDocumentEditor object is controlled via a thread lock to prevent race conditions. As this method causes modifications in the GUI, it must be run on the main thread. """ # print "Entering _addNewSource" # create a name name = "ME_" + str(ra) + "_" + str(dec) # make a default PL source source = Source(name=name) # set the RA/dec raParam = Parameter(name="RA", value=ra, scale=1.0, min=0.0, max=360.0, free=False) decParam = Parameter(name="DEC", value=dec, scale=1.0, min=-90.0, max=90.0, free=False) spatialModel = SpatialModel(type="SkyDirFunction", parameters=[raParam, decParam]) source.setSpatialModel(spatialModel) # print "Locking editor" # add source to model list with self.docLock: sourceLibraryDocument = self.sourceLibraryDocumentEditor.get() sourceLibraryDocument.addSource(source) self.sourceLibraryDocumentEditor.set(sourceLibraryDocument) self.sourceLibraryDocumentEditor.commit() # print "Unlocked editor" #get Source index of new source and set as selected source self.sourceLibraryDocumentEditor.selectSource(name)
def main(): scenario_list = Parameter().list_scenarios n_scenario = Parameter().scenarios strategy = Environment.NEAR duty_cicle = False while True: option = input('\nOpções:\n' + ' 1. Imprime cenários\n' + ' 2. Executar todos os cenários\n' + ' 3. Escolher cenários\n' + ' 4. Escolher número de visitas\n' + ' 5. Duty-cicle\n' + ' 0. Sair\n') if option == '0': exit() elif option == '1': print(scenario_list) elif option == '2': execute_scenarios(1, n_scenario, strategy, duty_cicle) elif option == '3': ok = False while not ok: start, end = input('Imprima intervalo de cenários: ').split() start, end = int(start), int(end) if start > end: start, end = end, start if end <= n_scenario: ok = True execute_scenarios(start, end, strategy, duty_cicle) elif option == '4': turns = int(input('\nNúmero de visitas: ')) print(scenario_list) scenario = int(input('\nCenário: ')) parameter = Parameter() parameter.current = scenario - 1 results = execute_turn(parameter, strategy, turns, duty_cicle) more = 'Número de viagens Sink: ' + str(turns) + '\n' #more += 'Duty-cycle: ' #if duty_cicle: # more += 'habilitado' #else: # more += 'desabilitado' print_results(parameter, scenario, results, more) elif option == '5': if duty_cicle: dc = input('\nDesabilitar duty-cicle? [S/n]') if dc in ['s', 'S', '']: duty_cicle = False else: dc = input('\nHabilitar duty-cicle? [S/n]') if dc in ['s', 'S', '']: duty_cicle = True
def set_param_value(self, name, value): """[summary] [description] Arguments: - name {[type]} -- [description] - value {[type]} -- [description] """ if (name == "nmodes"): oldn = self.parameters["nmodes"].value self.spinbox.setMaximum(int(value)) message, success = super(BaseTheoryGiesekus, self).set_param_value( name, value) if not success: return message, success if (name == "nmodes"): for i in range(self.parameters["nmodes"].value): self.parameters["G%02d" % i] = Parameter( name="G%02d" % i, value=1000.0, description="Modulus of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, bracketed=True, min_value=0) self.parameters["tauD%02d" % i] = Parameter( name="tauD%02d" % i, value=10.0, description="Terminal time of mode %02d" % i, type=ParameterType.real, opt_type=OptType.nopt, display_flag=False, bracketed=True, min_value=0) self.parameters["alpha%02d" % i] = Parameter( name="alpha%02d" % i, value=0.5, description="Constant of proportionality of mode %02d" % i, type=ParameterType.real, opt_type=OptType.opt, display_flag=True, bracketed=True, min_value=0, max_value=1) if (oldn > self.parameters["nmodes"].value): for i in range(self.parameters["nmodes"].value, oldn): del self.parameters["G%02d" % i] del self.parameters["tauD%02d" % i] del self.parameters["alpha%02d" % i] return '', True
def main(): # create param param = Parameter(Constant.SEED) param.create_input() # set input to problem ilp = Ilp(param) # solve by ilp ilp.solve_by_ilp("cplex") # print result ilp.print_result()
def execute_scenarios(init, end, strategy, duty_cicle): parameter = Parameter() counter = init parameter.current = init - 1 while parameter.current < end: results = execute_turn(parameter, strategy, 1, duty_cicle) more = 'Duty-cycle: ' if duty_cicle: more += 'habilitado' else: more += 'desabilitado' print_results(parameter, counter, results, '') parameter.next() counter += 1
def loadFromFile(self, filename): """ Reads a list of parameters from file. Returns whether it has succeeded in doing so. :type filename: basestring :rtype: bool """ directory, lastPathComponent = os.path.split(filename) self.name = lastPathComponent # TODO: write tests for this method in order to better specify its behaviour noErrors = True try: if filename.startswith('.DS'): noErrors = False else: with open(filename, "r") as parameterFile: try: for line in parameterFile: param = Parameter.parameterFromString(line) if param: self.append(param) except Exception: noErrors = False except Exception: noErrors = False return noErrors
def setLimits(self, limits): self.forward = collections.OrderedDict() ## name: value self.reverse = collections.OrderedDict() ## value: name if isinstance(limits, dict): for k, v in limits.iteritems(): self.forward[k] = v self.reverse[v] = k else: for v in limits: n = unicode(v) self.forward[n] = v self.reverse[v] = n Parameter.setLimits(self, limits) #print self.name(), self.value(), limits if self.value() not in self.reverse and len(self.reverse) > 0: self.setValue(self.reverse.keys()[0])
def initUI(self): if self.mainWindow: self.setAcceptDrops(True) self.setWindowTitle('Sistre') openAction = QtGui.QAction('Open', self) openAction.triggered.connect(self.showFileDialog) exitAction = QtGui.QAction('Exit', self) exitAction.triggered.connect(QtGui.qApp.quit) filemenu = self.menuBar().addMenu('File') filemenu.addAction(openAction) filemenu.addSeparator() filemenu.addAction(exitAction) self.parameterDialog = Parameter(self) parameterAction = QtGui.QAction('Parameter', self) parameterAction.triggered.connect(self.showParameterDialog) viewmenu = self.menuBar().addMenu('View') viewmenu.addAction(parameterAction) createGrpFromSelAction = QtGui.QAction('Create from selection', self) createGrpFromSelAction.triggered.connect(self.createGroupFromSelection) createGrpDialogAction = QtGui.QAction('Create...', self) createGrpDialogAction.triggered.connect(self.showCreateGroupDialog) groupmenu = self.menuBar().addMenu('Group') groupmenu.addAction(createGrpFromSelAction) groupmenu.addAction(createGrpDialogAction) self.glRenderArea = GLRenderArea(self) self.centralTab = QtGui.QTabWidget() self.centralTab.addTab(self.glRenderArea, '3D View') self.centralTab.addTab(QtGui.QWidget(), '2D View') self.timerBar = TimerBar(self) self.leftLayout = QtGui.QVBoxLayout() self.leftLayout.addWidget(self.centralTab) self.leftLayout.addWidget(self.timerBar) self.itemList = ItemList(self) self.itemList.itemListPick.connect(self.glRenderArea.itemListPick) self.itemList.itemConfigChanged.connect(self.glRenderArea.itemConfigChanged) # self.itemList.itemConfigChanged.connect(self.graphRenderArea.itemConfigChanged) self.centralLayout = QtGui.QHBoxLayout() self.centralLayout.addLayout(self.leftLayout) self.centralLayout.addWidget(self.itemList) self.centralWidget = QtGui.QWidget() self.centralWidget.setLayout(self.centralLayout) self.setCentralWidget(self.centralWidget) self.show()
def fromJson(cls, jsonObject): obj = jsonObject['_ParameterSet__params'] if obj: params = {} for key, value in obj.items(): params[int(key)] = Parameter.fromJson(value) ans = ParameterSet(len(params)) ans.addParams(params) return ans
def start_element(self, name, attrs): """ Function called when the start of an XML element is found """ if name == "module": self.current_module = Module(attrs['name']) self.current_module.add_id(attrs['id']) elif name == "dependency": self.in_dependency = True elif name == "param": self.current_param = Parameter() elif name == "description": self.in_description = True elif name == "value": self.in_value = True elif name == "command": self.in_command = True elif name == "id": self.in_id = True elif name == "child": self.in_child = True self.parent = self.current_module
def GetSolution(self, remove=True): solution = None if (len(self.__queue) == 0): return solution solution = self.__solutionBase if (remove): solTuple = self.__queue.pop(0) else: solTuple = self.__queue[0] #split to get each idx:val parameters = solTuple[0].split(',') params = [] #iterate through the elements in the list for p in parameters: param = Parameter() param.set_index(p.split(':')[0]) param.set_type("double") param.set_value(p.split(':')[1]) params.append(param) solution.setParameters(params) return solution
def __init__(self): Parameter.__init__(self) self.__display = False self.__fixed = False self.__x_index = None self.__y_index = None
import sys import os import re import random from Parameter import Parameter from File import File # def generate_unicode(): # unicode_path = File.generateFilePath('Unicode') # File.clearFile(unicode_path) # for i in range(random.randint(1000,1290)): # Parameter_str = Parameter.rand_char_str() # File.writeFile(Parameter_str+'\n', unicode_path) # return unicode_path # # unicode_path = generate_unicode(); #a = File.readFile(unicode_path); #File.clearFile('test.sql') #for i in File.readFile(unicode_path): # str_sql = 'update api_session set extra_info = "'+i.split('\n')[0]+'" where id = 445;'+'\n' # File.writeFile(str_sql,'test.sql') #print Parameter.rand_char_str('cn')+"\n" #print Parameter.rand_char_str('num')+"\n" #print Parameter.rand_char_str('tel')+"\n" print Parameter.rand_char_str('time')
class Screen(QtGui.QMainWindow): def __init__(self, data, mainWindow = False): super(Screen, self).__init__() self.data = data self.mainWindow = mainWindow if self.mainWindow: pass # print 'mainWindow' # self.data.loadData('.', 'Repro_geste_standard_assis_Trial1.c3d') # self.screenList = [] else: pass # print 'new sub window' self.initUI() def initUI(self): if self.mainWindow: self.setAcceptDrops(True) self.setWindowTitle('Sistre') openAction = QtGui.QAction('Open', self) openAction.triggered.connect(self.showFileDialog) exitAction = QtGui.QAction('Exit', self) exitAction.triggered.connect(QtGui.qApp.quit) filemenu = self.menuBar().addMenu('File') filemenu.addAction(openAction) filemenu.addSeparator() filemenu.addAction(exitAction) self.parameterDialog = Parameter(self) parameterAction = QtGui.QAction('Parameter', self) parameterAction.triggered.connect(self.showParameterDialog) viewmenu = self.menuBar().addMenu('View') viewmenu.addAction(parameterAction) createGrpFromSelAction = QtGui.QAction('Create from selection', self) createGrpFromSelAction.triggered.connect(self.createGroupFromSelection) createGrpDialogAction = QtGui.QAction('Create...', self) createGrpDialogAction.triggered.connect(self.showCreateGroupDialog) groupmenu = self.menuBar().addMenu('Group') groupmenu.addAction(createGrpFromSelAction) groupmenu.addAction(createGrpDialogAction) self.glRenderArea = GLRenderArea(self) self.centralTab = QtGui.QTabWidget() self.centralTab.addTab(self.glRenderArea, '3D View') self.centralTab.addTab(QtGui.QWidget(), '2D View') self.timerBar = TimerBar(self) self.leftLayout = QtGui.QVBoxLayout() self.leftLayout.addWidget(self.centralTab) self.leftLayout.addWidget(self.timerBar) self.itemList = ItemList(self) self.itemList.itemListPick.connect(self.glRenderArea.itemListPick) self.itemList.itemConfigChanged.connect(self.glRenderArea.itemConfigChanged) # self.itemList.itemConfigChanged.connect(self.graphRenderArea.itemConfigChanged) self.centralLayout = QtGui.QHBoxLayout() self.centralLayout.addLayout(self.leftLayout) self.centralLayout.addWidget(self.itemList) self.centralWidget = QtGui.QWidget() self.centralWidget.setLayout(self.centralLayout) self.setCentralWidget(self.centralWidget) self.show() def showFileDialog(self): fileDialog = QtGui.QFileDialog(parent = self, caption = 'Open video file') if fileDialog.exec_() == QtGui.QDialog.Accepted: self.data.loadData(str(fileDialog.selectedFiles()[0])) def showParameterDialog(self): self.parameterDialog.show() def showCreateGroupDialog(self): pass def createGroupFromSelection(self): newGroup = self.data.createGroupFromSelection(list(self.glRenderArea.selectedMarkers)) self.glRenderArea.addGroup(newGroup) def dragEnterEvent(self, event): if event.mimeData().hasUrls(): event.accept() else: event.ignore() def dropEvent(self, event): if len(event.mimeData().urls()) > 0: url = event.mimeData().urls()[0] path = url.toLocalFile().toLocal8Bit().data() self.data.loadData(path) else: event.ignore() def dataLoaded(self): self.setWindowTitle(self.data.dataPath + self.data.dataFile + ' - Sistre') self.glRenderArea.clearItemConfig() self.timerBar.setPauseButtonChecked(self.data.paused) self.timerBar.setMaximum(self.data.totalFrame) self.timerBar.setValue(self.data.currentFrame) self.itemList.setItemData(self.data) def dataPauseToggled(self): self.timerBar.setPauseButtonChecked(self.data.paused) def dataFrameUpdated(self): self.timerBar.setValue(self.data.currentFrame)
class ModuleXMLParser: """ ModuleXMLParser will parse a list of modules and returns it. """ def __init__(self): self.module_list = [] self.param_list = [] self.current_module = None self.current_param = None self.cdata = "" self.parent = None self.in_description = False self.in_command = False self.in_value = False self.in_id = False self.in_child = False self.in_dependency = False def start_element(self, name, attrs): """ Function called when the start of an XML element is found """ if name == "module": self.current_module = Module(attrs['name']) self.current_module.add_id(attrs['id']) elif name == "dependency": self.in_dependency = True elif name == "param": self.current_param = Parameter() elif name == "description": self.in_description = True elif name == "value": self.in_value = True elif name == "command": self.in_command = True elif name == "id": self.in_id = True elif name == "child": self.in_child = True self.parent = self.current_module def end_element(self, name): """ Function called when the end of an XML element is found """ if name == "description": self.in_description = False if self.current_param: # Parser is inside a parameter, add the description to it self.current_param.add_description(self.cdata) else: self.current_module.add_description(self.cdata) self.cdata = "" elif name == "dependency": self.current_module.dependencies.append(int(self.cdata)) self.in_dependency = False self.cdata = "" elif name == "value": self.in_value = False self.current_param.add_value(self.cdata) self.cdata = "" elif name == "command": self.in_command = False self.current_module.add_command(self.cdata) self.cdata = "" elif name == "id": self.in_id = False self.current_param.add_id(self.cdata) self.cdata = "" elif name == "param": self.param_list.append(self.current_param) self.current_param = None elif name == "module": self.module_list.append(self.current_module) elif name == "child": # TODO: Allow having more than one child self.parent.children = self.current_module self.current_module = self.parent self.in_child = False def char_data(self, data): """ Function called when some character data within an XML element is found """ data = data.strip() if data: if self.in_description or self.in_id or self.in_command or self.in_value or self.in_dependency: self.cdata = self.cdata + data def parse(self, text): """ Sets up expat with the correct custom parser functions and parses text """ parser = expat.ParserCreate() parser.StartElementHandler = self.start_element parser.EndElementHandler = self.end_element parser.CharacterDataHandler = self.char_data parser.Parse(text, 1) return (self.module_list, self.param_list)
def __init__(self, *args, **kargs): Parameter.__init__(self, *args, **kargs) if self.opts['type'] == 'color': self.value = self.colorValue
def colorValue(self): return pg.mkColor(Parameter.value(self))
def _parse_read_object(self,name): if len( self.indices ) > 0: prev_index = self.indices[0] self.parameters[self.pidx].is_custom_obj = True value = self._get_nextval() if self.parameters[self.pidx].is_array and self.parameters[self.pidx].is_custom_obj: customParam = Parameter( value ) customParam.is_custom_obj = True self.parameters[self.pidx].values.append( customParam ) self.parameters[self.pidx].flag = True if self.parameters[self.pidx].is_list and self.parameters[self.pidx].is_custom_obj: customParam = Parameter(value) customParam.is_custom_obj = True self.parameters[self.pidx].values.append(customParam) # If this is the final parameter just read the remaining data as member variables if len(self.parameters)-1 == self.pidx: while len(self.indices) > 0: # Read till the end of the index table if self._nextval_is_an_integer( prev_index ): prev_index = self.indices[0] self._set_fuzzable( self.indices_read+self.columns, FUZZ_DIGIT ) self._add_intval() continue else: prev_index = self.indices[0] value = self._get_nextval() if self.parameters[self.pidx].is_array or self.parameters[self.pidx].is_list: # Am I reading an array of objects? if self._is_object_subtype(value): # Did I just read in an object subtype? self._indice_rollback(prev_index) break # Stop reading object and move onto the next object in the array if self._is_list_type( value ): if self.parameters[self.pidx].flag is False: self._indice_rollback(prev_index) self._parse_read_list(self._get_typename(value), False) elif self._is_an_object(value): # Is the value I just read in a subtype for another class prev_index = self.indices[0] else: self._add_stringval(value) self._set_fuzzable( prev_index, FUZZ_STRING ) else: # There are more parameters so we must be careful with the parsing while len(self.indices) > 0: if self._nextval_is_an_integer( prev_index ): self._set_fuzzable( self.indices_read+self.columns, FUZZ_DIGIT ) prev_index = self.indices[0] self._add_intval() else: prev_index = self.indices[0] value = self._get_nextval() if self.parameters[self.pidx].is_array or self.parameters[self.pidx].is_list: if self._is_object_subtype(value): self._indice_rollback(prev_index) break; if self._is_end_of_object( prev_index, value ): if self.parameters[self.pidx].is_list or self.parameters[self.pidx].is_array: self.pidx += 1 self._indice_rollback(prev_index) self._parse_value( self.parameters[self.pidx].typename ) else: if not self._get_typename(self.parameters[self.pidx+1].typename) in NUMERICS: self._indice_rollback(prev_index) break elif self._is_an_object( value ): continue else: # store value self._set_fuzzable( prev_index, FUZZ_STRING ) prev_index = self.indices[0] self._add_stringval(value) self.parameters[self.pidx].flag = False
def __init__(self, **opts): self.forward = collections.OrderedDict() ## name: value self.reverse = collections.OrderedDict() ## value: name if 'values' in opts: opts['limits'] = opts['values'] Parameter.__init__(self, **opts)
def initialize(self, filepath): try: if (not os.path.exists(filepath)): filepath = "../" + filepath xmldoc = minidom.parse(filepath) pNode = xmldoc.childNodes[0] for node in pNode.childNodes: if node.nodeType == node.ELEMENT_NODE: c = Parameter() for node_param in node.childNodes: if (node_param.nodeType == node_param.ELEMENT_NODE): if (node_param.localName == "type"): c.set_type(node_param.firstChild.data) if (node_param.localName == "value"): c.set_value(node_param.firstChild.data) if (node_param.localName == "min_value"): c.set_min_value(node_param.firstChild.data) if (node_param.localName == "max_value"): c.set_max_value(node_param.firstChild.data) if (node_param.localName == "index"): c.set_index(node_param.firstChild.data) if (node_param.localName == "name"): c.set_name(node_param.firstChild.data) if (node_param.localName == "gap"): c.set_gap(node_param.firstChild.data) try: self.assign_parameter(c) self.__numParams += 1 values = 1 + int(round((c.get_max_value() - c.get_min_value()) / c.get_gap())) self.__maxRange = max(values, self.__maxRange) except Exception, e: traceback.print_tb(sys.exc_info()[2]) u.logger.warning("Problem calculating max range: " + str(e)) pass u.logger.debug("Number of parameters " + str(self.__numParams) + "(" + str(len(self.__params)) + ")")