Ejemplo n.º 1
0
def mcmc_simulation(org_value,
                    eps,
                    step_size,
                    n_steps,
                    n_burns,
                    dQ,
                    is_two=False):

    values = [0.0 for _ in range(n_steps - n_burns)]
    curV = org_value

    for i in range(n_steps):
        rand_val = random.random()
        newV = curV + (-step_size + 2.0 * step_size * rand_val)
        #
        if is_two:
            prob = math.exp(eps / (2 * dQ) *
                            (abs(curV - org_value) - abs(newV - org_value))
                            )  # prefer smaller values of |curV-org_value|
        else:
            prob = math.exp(
                eps / dQ *
                (abs(curV - org_value) - abs(newV - org_value)))  # not 2*dQ
        if prob > 1.0:
            prob = 1.0
        prob_val = random.random()
        if prob_val <= prob:  # accept newV
            curV = newV

        #
        if i >= n_burns:
            values[i - n_burns] = curV
    #
    return values
Ejemplo n.º 2
0
def square_root(num):
    if not isNumber(num):
        raise(_NON_NUMERIC_ARG)

    target = abs(Decimal(str(num)))
    guesses = 0
    guess = Decimal('0')

    while abs(guess * guess - target) > tolerance:
        guesses += 1
        guess += tolerance
        if guess * guess > target:
            if _debug: print(guesses)  # @IgnorePep8
            if _debug: print(guess)  # @IgnorePep8
            raise(_NO_SOLUTION_FOUND)

    if _debug: print(guesses)  # @IgnorePep8
    return(guess)
Ejemplo n.º 3
0
def abs(obj):
    """Overloads the built-in abs function for convex optimization."""
    try:
        return __builtin__.abs(obj)
    except TypeError:
        if ispos(obj):
            return obj
        elif isneg(obj):
            return -obj
        else:
            return absfunction(obj)
Ejemplo n.º 4
0
def abs(obj):
    """Overloads the built-in abs function for convex optimization."""
    try:
        return __builtin__.abs(obj)
    except TypeError:
        if ispos(obj):
            return obj
        elif isneg(obj):
            return -obj
        else:
            return absfunction(obj)
Ejemplo n.º 5
0
def dw_GetGridDimensions(ptid_map):
    """
    Returns number of cells in 1st and 2nd grid directions.

    input:
    - ptid_map : PCRaster map with unique id's
    """
    # find number of cells in m and n directions
    zero_map = scalar(ptid_map) * 0.0
    allx = dw_pcrToDataBlock(xcoordinate(boolean(cover(zero_map + 1, 1))))
    i = 0
    diff = round(__builtin__.abs(allx[i] - allx[i + 1]), 5)
    diff_next = diff
    while diff_next == diff:
        i += 1
        diff_next = __builtin__.abs(allx[i] - allx[i + 1])
        diff_next = round(diff_next, 5)
    m = i + 1
    n = allx.shape[0] / m
    m, n = n, m
    return m, n
Ejemplo n.º 6
0
def square_root_newton(num, precision=None):
    '''
        See http://mathworld.wolfram.com/NewtonsIteration.html for details.
        See https://mitpress.mit.edu/sicp/full-text/sicp/book/node12.html
            for another discussion of the same algorithm.

        Notice that it is possible to have values for num and precision
            which will result in an infinite loop, due to not being able to
            get "close enough" to the correct answer, as specified by the
            global tolerance variable. This implementation merely detects
            this situation and raises _NO_SOLUTION_FOUND if it occurs.
    '''

    if isInt(precision):
        getcontext().prec = precision

    if not isNumber(num):
        raise(_NON_NUMERIC_ARG)

    target = abs(Decimal(str(num)))
    this_guess = Decimal('1')
    guesses = 0

    while abs(this_guess * this_guess - target) > tolerance:
        guesses += 1
        if _debug: print(this_guess)  # @IgnorePep8
        prior_guess = this_guess
        this_guess = Decimal('0.5') * (this_guess + target/this_guess)
        if this_guess == prior_guess:
            raise(_NO_SOLUTION_FOUND)

    if _debug:
        accuracy = abs(this_guess * this_guess - target)
        print('Guesses: {0}; final_guess: {1}; accuracy: {2}'
              .format(guesses, this_guess, accuracy))  # @IgnorePep8

    if not (this_guess * this_guess - target) <= tolerance:
            raise(_NO_SOLUTION_FOUND)

    return(this_guess)
Ejemplo n.º 7
0
    def on_touch_up(self, touch):
        from reduction.system import reductor
        from reduction.component.board import Board

        if touch.grab_current is self and isinstance(self.parent, Board):
            board_pos = list(self.parent.coords_to_board_pos(touch.pos))

            dp = tuple(map(sub, self.board_pos, board_pos))
            if abs(dp[0]) > abs(dp[1]):
                board_pos[1] = self.board_pos[1]
            else:
                board_pos[0] = self.board_pos[0]

            atoms = list(filter(lambda x: isinstance(x, Atom), self.parent.pieces_at(board_pos)))

            if self.parent.straight_path_clear_between(self.board_pos, board_pos):
                if len(atoms) > 0:
                    print "Can atoms reduce? ", reductor.can_reduce(self, atoms[0])
                    if reductor.can_reduce(self, atoms[0]):
                        self.board_pos = board_pos
                else:
                    self.board_pos = board_pos
            touch.ungrab(self)
            return True
Ejemplo n.º 8
0
def mcmc_simulation(org_value, eps, step_size, n_steps, n_burns, dQ, is_two = False):
    
    values = [0.0 for _ in range(n_steps-n_burns)]
    curV = org_value
    
    for i in range(n_steps):
        rand_val = random.random()
        newV = curV + (-step_size + 2.0*step_size*rand_val)
        #
        if is_two:
            prob = math.exp(eps/(2*dQ)*(abs(curV-org_value) - abs(newV-org_value)))      # prefer smaller values of |curV-org_value| 
        else:
            prob = math.exp(eps/dQ*(abs(curV-org_value) - abs(newV-org_value)))          # not 2*dQ
        if prob > 1.0:
            prob = 1.0
        prob_val = random.random()
        if prob_val <= prob:    # accept newV
            curV = newV
        
        #
        if i >= n_burns:
            values[i-n_burns] = curV
    #
    return values
Ejemplo n.º 9
0
 def normxcorr(self, s, k):
     from __builtin__ import abs
     
     sLen = len(s)
     kLen = len(k)
     cLen = sLen + kLen - 1
 
     c = [0.0] * cLen
     
     for i in xrange(cLen):
         j0 = i - (kLen - 1) if i >= kLen - 1 else 0
         jN = i + 1 if i < sLen - 1 else sLen
 
         s1Sum = 0.0
         s2Sum = 0.0
 
         k1Sum = 0.0
         k2Sum = 0.0
 
         skSum = 0.0
 
         n = jN - j0
         for j in xrange(j0, jN):
             sVal = s[j    ]
             kVal = k[i - j]
 
             s1Sum += sVal
             s2Sum += sVal * sVal
             
             k1Sum += kVal
             k2Sum += kVal * kVal
 
             skSum += sVal * kVal
 
         nom  = skSum - s1Sum * k1Sum / n
         denS = s2Sum - s1Sum * s1Sum / n
         denk = k2Sum - k1Sum * k1Sum / n
         den  = sqrt(denS * denk)
 
         if den > 1e-5 * abs(nom):
             c[i] = nom / den
 
     return c
Ejemplo n.º 10
0
def abs (anObject):
	return __builtin__.abs (evaluate (anObject))
Ejemplo n.º 11
0
    def __init__(self, path):
        
        print ' '
        print 'loading file number:', path
        print ' '
        
        ds = Dataset(path) # df[path]
        # in case of 4d data
        ds.__iDictionary__.addEntry('hmm', 'entry1/data/hmm')
       
        self.Filename   = os.path.basename(path)
            
        self.CountTimes    = list(ds['entry1/instrument/detector/time'])
        self.Bex           = list(ds['entry1/instrument/crystal/bex'])
        #self.Angle         = list(ds['entry1/instrument/crystal/m2om'])
        self.MonCts        = list(ds['entry1/monitor/bm1_counts'])
        self.MonCountTimes = list(ds['entry1/monitor/time']) # NEW
        
        self.ScanVariablename  = str(ds['entry1/instrument/crystal/scan_variable'])
        self.ScanVariable = list(ds['entry1/instrument/crystal/' + self.ScanVariablename])        
        
        self.Angle = copy(self.ScanVariable)
        
        if self.ScanVariablename == 'm2om':
            pass
        else:
            if convert2q.value:
                raise Exception ("Please Untick 'Convert to q'")
                    
        self.DetCts     = [] # more difficult readout
        self.ErrDetCts  = [] # calculated
        self.TransCts   = [] # more difficult readout   
        
        # read parameters from file
     
        self.Wavelength    = float(ds['entry1/instrument/crystal/wavelength'])         
        self.MainDeadTime  = float(ds['entry1/instrument/detector/MainDeadTime' ])
        self.TransDeadTime = float(ds['entry1/instrument/detector/TransDeadTime'])
        self.dOmega        = float(ds['entry1/instrument/crystal/dOmega'])      
        self.gDQv          = float(ds['entry1/instrument/crystal/gDQv'])
        self.ScanVariable  = str(ds['entry1/instrument/crystal/scan_variable'])
        self.TimeStamp     = list(ds['entry1/time_stamp'])
        
              
        # read parameters from file and possibly patch
                
        self.Thick         = TryGet(ds, ['entry1/sample/thickness'                   ], Thickness.value , Thickness_Patching.value ) / 10.0 # mm to cm            
        self.SampleName    = TryGet(ds, ['entry1/sample/name'                        ], SampleName.value , SampleName_Patching.value )
        self.SampleDescr   = TryGet(ds, ['entry1/sample/description'                 ], SampleDescr.value , SampleDescr_Patching.value )
        self.SampleBkg     = TryGet(ds, ['entry1/experiment/bkgLevel'                ], SampleBkg.value , SampleBkg_Patching.value )

    
        
        self.empLevel = empLevel.value
        self.empLevel_Error = empLevel_Error.value
        
        self.defaultMCR = defaultMCR.value
        self.TWideMarker = TWideMarker.value
        self.ActualTime = range(len(self.Angle))
        self.widepoints = 0
        

  
        # tube ids
        tids = []
        if combine_tube0.value:
            tids.append(0)
        if combine_tube1.value:
            tids.append(1)
        if combine_tube2.value:
            tids.append(2)
        if combine_tube3.value:
            tids.append(3)
        if combine_tube4.value:
            tids.append(4)

        # sum selected tubes
        data = zeros(len(self.Angle))
        for tid in tids:
            if ds.hmm.ndim == 4:
                data[:] += ds.hmm[:, 0, :, tid].sum(0) # hmm
            else:
                data[:] += ds.hmm[:, :, tid].sum(0)    # hmm_xy       
                                
        DeadtimeCorrection(data, self.MainDeadTime, self.CountTimes)

        self.DetCts    = list(data)
        self.ErrDetCts = [sqrt(cts) for cts in self.DetCts]

        # transmission counts
        if abs(self.Wavelength - 4.74) < 0.01:
            tid = 10
            #print 'long wavelength'
        elif abs(self.Wavelength - 2.37) < 0.01:
            tid = 9
            #print 'short wavelength'
        else:
            raise Exception('unsupported wavelength')
            
        if ds.hmm.ndim == 4:
            data[:] = ds.hmm[:, 0, :, tid].sum(0) # hmm
        else:
            data[:] = ds.hmm[:, :, tid].sum(0)    # hmm_xy
        
            
        DeadtimeCorrection(data, self.TransDeadTime, self.CountTimes)
        
        self.TransCts  = list(data) 
        
        
        # CONVERT TO COUNTRATES
        self.DetCtr     = range(len(self.DetCts))
        self.ErrDetCtr  = range(len(self.DetCts))
        self.TransCtr   = range(len(self.DetCts))
        self.MonCtr     = range(len(self.DetCts))
                
        
        ctTimes = self.CountTimes
        
        # to ignore all the 0 times in the detector
        
        
        for i in xrange(len(self.DetCts)):    
            if ctTimes[i] < 0.5:                        
                print 'Please Ignore Data Point: ', i+1
                print ''
                ctTimes[i] = ctTimes[i] + 100.0
                        
        for i in xrange(len(ctTimes)):
            ctTime = ctTimes[i]                  
            self.DetCtr[i]     = self.DetCts[i]    / ctTime
            self.ErrDetCtr[i]  = self.ErrDetCts[i] / ctTime
            self.TransCtr[i]   = self.TransCts[i]  / ctTime
    
        ctTimes = self.MonCountTimes
        
        for i in xrange(len(ctTimes)):
            ctTime = ctTimes[i]                  
            self.MonCtr[i]     = self.MonCts[i]    / ctTime
           
        # TAKE ACCOUNT OF BEAMMONITOR
        
        if use_beammonitor.value: 
        
           mcr = self.defaultMCR
           for i in xrange(len(self.Angle)):
               if self.MonCtr[i] <0.0001: #to fix the 0-divison problem
                   self.MonCtr[i] = 1000
               
               f = mcr / self.MonCtr[i]
            
               self.DetCtr[i]    = self.DetCtr[i]    * f
               self.ErrDetCtr[i] = self.ErrDetCtr[i] * f
               self.TransCtr[i]  = self.TransCtr[i]  * f
Ejemplo n.º 12
0
def abs(argv, **kwargs):
    return __builtin__.abs(argv)
Ejemplo n.º 13
0
def abs(x):
    return builtins.abs(x)
Ejemplo n.º 14
0
    n_steps = 20000
    n_burns = 2000  # burn-in

    loc = 0.0
    scale = dQ / eps

    n_bins = 100

    start = time.clock()
    values = mcmc_simulation(loc,
                             eps,
                             step_size,
                             n_steps,
                             n_burns,
                             dQ,
                             is_two=False)
    print "mcmc_simulation - DONE, elapsed", time.clock() - start

    # the histogram of the data with histtype='step'
    x = np.array(values)
    n, bins, patches = P.hist(
        x, n_bins, normed=1,
        histtype='stepfilled')  # bins: ndarray of 51 elements
    P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)

    # add a line showing the expected distribution
    y = np.exp(-abs(bins - loc / scale)) / (2. * scale)
    l = P.plot(bins, y, 'k--', linewidth=1.5)

    P.show()
Ejemplo n.º 15
0
    # test against Laplace(0.0, eps=1.0, dQ=1.0)
    eps = 1.0
    dQ = 1.0
    step_size = 10.0
    n_steps = 20000
    n_burns = 2000      # burn-in
    
    loc = 0.0
    scale = dQ/eps
    
    n_bins = 100
    
    start = time.clock()
    values = mcmc_simulation(loc, eps, step_size, n_steps, n_burns, dQ, is_two=False)
    print "mcmc_simulation - DONE, elapsed", time.clock() - start
    
    # the histogram of the data with histtype='step'
    x = np.array(values)
    n, bins, patches = P.hist(x, n_bins, normed=1, histtype='stepfilled')   # bins: ndarray of 51 elements
    P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
    
    # add a line showing the expected distribution
    y = np.exp(-abs(bins-loc/scale))/(2.*scale)
    l = P.plot(bins, y, 'k--', linewidth=1.5)

    P.show()