示例#1
0
    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 _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, 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()
示例#4
0
 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)
示例#5
0
 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 = []
示例#6
0
 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)
示例#7
0
文件: FC_sec.py 项目: Night-mk/LP-GAN
 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
示例#8
0
 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_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
示例#10
0
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 _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)
示例#12
0
    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
示例#13
0
 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)
示例#14
0
    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)
示例#15
0
 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)
示例#16
0
 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
示例#17
0
    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()
示例#18
0
    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 _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)
示例#20
0
 def freeParameters(self):
     return [
         Parameter(
             "x",
             0.1,
             err=1,
             bounds=(0, 2),
         ),
         Parameter("y", 0, err=1)
     ]
示例#21
0
    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())
示例#22
0
    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()
示例#23
0
 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
示例#24
0
    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)
示例#25
0
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
示例#26
0
    def __init__(self,
                 in_channels,
                 out_channels,
                 filter_width,
                 filter_height,
                 zero_padding,
                 stride,
                 method='VALID',
                 bias_required=True,
                 bit_length=32):
        super(Conv_sec, 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
        self.bit_length = bit_length

        # 卷积层过滤器初始化 (模型也是要拆成secret sharing)
        '''filter_num = output_channel,就是卷积输出feature map的通道数'''
        # 初始化S1,S2的两个weights
        param_weights = np.random.uniform(
            -1e-2, 1e-2, (self.out_channels, self.in_channels,
                          self.filter_height, self.filter_width))
        param_weights_1 = np.random.uniform(
            -1e-2, 1e-2, (self.out_channels, self.in_channels,
                          self.filter_height, self.filter_width)) / 2
        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)
        if self.bias_required:
            param_bias = np.zeros(self.out_channels)
            param_bias_1 = np.random.randint(
                -2**(bit_length // 4), 2**(bit_length // 4),
                self.out_channels).astype(np.float64)
            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
示例#27
0
def conv_checkgrad():
    """梯度检测"""
    eps = 1e-4

    """手动定义卷积核(weight)和偏置"""
    w = torch.rand(5, 3, 3, 3)  # 5种3通道的3乘3卷积核
    b = torch.rand(5)  # 和卷积核种类数保持一致(不同通道共用一个bias)
    w_numpy = w.detach().numpy()
    b_numpy = b.detach().numpy()

    """定义输入样本"""
    x = torch.tensor(np.random.randn(1, 3, 3, 3).astype(np.float32), requires_grad=True)  # 1张3通道的5乘5的图
    x_numpy = x.detach().numpy()

    """卷积初始化"""
    cl_tensor_1 = torch.nn.Conv2d(3, 5, kernel_size=3, stride=1, padding=0)
    cl_tensor_1.weight = torch.nn.Parameter(w, requires_grad=True)
    cl_tensor_1.bias = torch.nn.Parameter(b, requires_grad=True)

    cl1 = Conv.ConvLayer(3, 5, 3,3, zero_padding=0, stride=1, method='VALID')

    # cl2 = Conv.ConvLayer(3, 5, 3,3, zero_padding=1, stride=1, method='SAME')
    # cl3 = Conv.ConvLayer(3, 5, 3,3, zero_padding=1, stride=1, method='SAME')

    cl1.set_weight(Parameter(w_numpy, requires_grad=True))
    cl1.set_bias(Parameter(b_numpy, requires_grad=True))
    # cl2.set_weight(Parameter(w_numpy, requires_grad=True))
    # cl2.set_bias(Parameter(b_numpy, requires_grad=True))
    # cl3.set_weight(Parameter(w_numpy, requires_grad=True))
    # cl3.set_bias(Parameter(b_numpy, requires_grad=True))

    conv_out_tensor_1 = cl_tensor_1(x)
    conv_out_numpy_1 = cl1.forward(x_numpy) # forward
    # conv_out_numpy_2 = cl2.forward(x_numpy-eps) # forward
    # conv_out_numpy_3 = cl3.forward(x_numpy+eps) # forward

    print('-----对比输出-----')
    print('conv_out_tensor_1: \n', conv_out_tensor_1)
    # print('conv_out_tensor_1.shape: \n', conv_out_tensor_1.shape)
    print('conv_out_numpy_1: \n', conv_out_numpy_1)
    # print('conv_out_numpy_1.shape: \n', conv_out_numpy_1.shape)
    print('conv_out_1 error: \n', conv_out_numpy_1-conv_out_tensor_1.detach().numpy())

    """梯度计算"""
    """定义输出误差"""
    dy_numpy = np.ones(conv_out_numpy_1.shape).astype(np.float32)
    dy = torch.tensor(dy_numpy, requires_grad=True).float()

    x_grad = cl1.gradient(dy_numpy)
示例#28
0
    def handle_spinboxValueChanged(self, value):
        """Handle a change of the parameter 'nmode'
        
        Arguments:
            - value {[type]} -- [description]
        """
        nmodesold = self.parameters["nmodes"].value
        tminold = self.parameters["logtmin"].value
        tmaxold = self.parameters["logtmax"].value
        tauold = np.logspace(tminold, tmaxold, nmodesold)
        Gold = np.zeros(nmodesold)
        for i in range(nmodesold):
            Gold[i] = self.parameters["logJ%02d" % i].value
            del self.parameters["logJ%02d" % i]

        nmodesnew = value
        self.set_param_value("nmodes", nmodesnew)
        taunew = np.logspace(tminold, tmaxold, nmodesnew)

        Gnew = np.interp(taunew, tauold, Gold)

        for i in range(nmodesnew):
            self.parameters["logJ%02d" % i] = Parameter(
                "logJ%02d" % i,
                Gnew[i],
                "Log of Mode %d compliance" % i,
                ParameterType.real,
                opt_type=OptType.opt)

        if self.autocalculate:
            self.parent_dataset.handle_actionCalculate_Theory()
        self.update_parameter_table()
示例#29
0
    def set_param_value(self, name, value):
        """Change other parameters when nmodes is changed, else call parent function"""
        if name == 'nmodes':
            nmodesold = self.parameters["nmodes"].value
            tminold = self.parameters["logtmin"].value
            tmaxold = self.parameters["logtmax"].value
            tauold = np.logspace(tminold, tmaxold, nmodesold)
            Gold = np.zeros(nmodesold)
            for i in range(nmodesold):
                Gold[i] = self.parameters["logG%02d" % i].value
                del self.parameters["logG%02d" % i]

            nmodesnew = value
            message, success = super().set_param_value("nmodes", nmodesnew)
            taunew = np.logspace(tminold, tmaxold, nmodesnew)

            Gnew = np.interp(taunew, tauold, Gold)

            for i in range(nmodesnew):
                self.parameters["logG%02d" % i] = Parameter(
                    "logG%02d" % i,
                    Gnew[i],
                    "Log of Mode %d amplitude" % i,
                    ParameterType.real,
                    opt_type=OptType.opt)
            if CmdBase.mode == CmdMode.GUI:
                self.spinbox.setValue(value)
        else:
            message, success = super().set_param_value(name, value)
        
        return message, success
示例#30
0
 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.powerlaw
     self.parameters["a"] = Parameter(
         "a", 1.0, "Prefactor", ParameterType.real, opt_type=OptType.opt)
     self.parameters["b"] = Parameter(
         "b", 1.0, "Exponent", ParameterType.real, opt_type=OptType.opt)
     self.Qprint("%s: a*x^b" % self.thname)