Python random.gauss() Examples

The following are code examples for showing how to use random.gauss(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: UberLens   Author: adamalawrence   File: hexmath.py    (MIT License) View Source Project 6 votes vote down vote up
def overlay_generator(hexgrid, depth=params.shells, major=params.major):
    # GPolygon.RegularPoly(coord,major,poly,rot,"#000000",strokeOpacity,linethick,"#00ffff",fillalpha)
    s1 = ''
    numhextiles = float(len(hexgrid))
    for idx, hexel in enumerate(hexgrid):
        speckle = random.gauss(1, 0.5)
        rank = int((speckle * idx / numhextiles) * 15)
        invrank = 15 - rank
        blue = hex(rank)[2:]
        red = hex(invrank)[2:]
        tilecolor = red + red + '00' + blue + blue
        ts = "map.addOverlay(GPolygon.RegularPoly(new GLatLng{coord},\
            {major},6,90,\"\#{strokeColor}\",{strokeOpacity},{strokeWeight},\"\#{fillColor}\",{fillalpha}))\
            \n".format(coord=hexel, major=major, strokeColor=tilecolor, strokeOpacity=params.opacity,
                       strokeWeight=params.strokeWeight, fillColor=tilecolor, fillalpha=params.opacity)
        s1 += ts
    return s1 
Example 2
Project: UberLens   Author: adamalawrence   File: hexgrid_class.py    (MIT License) View Source Project 6 votes vote down vote up
def overlay_generator(self, hexgrid, depth=params.shells, major=params.major):
        # GPolygon.RegularPoly(coord,major,poly,rot,"#000000",strokeOpacity,linethick,"#00ffff",fillalpha)
        s1 = ''
        numhextiles = float(len(hexgrid))
        for idx, hexel in enumerate(hexgrid):
            speckle = random.gauss(1, 0.5)
            rank = int((speckle * idx / numhextiles) * 15)
            invrank = 15 - rank
            blue = hex(rank)[2:]
            red = hex(invrank)[2:]
            tilecolor = red + red + '00' + blue + blue
            ts = "map.addOverlay(GPolygon.RegularPoly(new GLatLng{coord},\
                {major},6,90,\"\#{strokeColor}\",{strokeOpacity},{strokeWeight},\"\#{fillColor}\",{fillalpha}))\
                \n".format(coord=hexel, major=major, strokeColor=tilecolor, strokeOpacity=params.opacity,
                           strokeWeight=params.strokeWeight, fillColor=tilecolor, fillalpha=params.opacity)
            s1 += ts
        return s1 
Example 3
Project: deep_srl   Author: luheng   File: reader.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_pretrained_embeddings(filepath):
  embeddings = dict()
  with open(filepath, 'r') as f:
    for line in f:
      info = line.strip().split()
      #lines = [line.strip().split() for line in f.readlines()]
      #embeddings = dict([(line[0], [float(r) for r in line[1:]]) for line in lines])
      embeddings[info[0]] = [float(r) for r in info[1:]]
    f.close()
  embedding_size = len(embeddings.values()[0])
  print 'Embedding size={}'.format(embedding_size)
  embeddings[START_MARKER] = [random.gauss(0, 0.01) for _ in range(embedding_size)]
  embeddings[END_MARKER] = [random.gauss(0, 0.01) for _ in range(embedding_size)]
  if not UNKNOWN_TOKEN in embeddings:
    embeddings[UNKNOWN_TOKEN] = [random.gauss(0, 0.01) for _ in range(embedding_size)]
  return embeddings 
Example 4
Project: CyberScan   Author: medbenali   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 5
Project: hostapd-mana   Author: adde88   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 6
Project: XTREE   Author: ai-se   File: scott_knott.py    (license) View Source Project 6 votes vote down vote up
def _bootstraped():
    def worker(n=1000,
               mu1=10, sigma1=1,
               mu2=10.2, sigma2=1):
        def g(mu, sigma): return random.gauss(mu, sigma)

        x = [g(mu1, sigma1) for i in range(n)]
        y = [g(mu2, sigma2) for i in range(n)]
        return n, mu1, sigma1, mu2, sigma2, \
               'different' if bootstrap(x, y) else 'same'

    # very different means, same std
    print worker(mu1=10, sigma1=10,
                 mu2=100, sigma2=10)
    # similar means and std
    print worker(mu1=10.1, sigma1=1,
                 mu2=10.2, sigma2=1)
    # slightly different means, same std
    print worker(mu1=10.1, sigma1=1,
                 mu2=10.8, sigma2=1)
    # different in mu eater by large std
    print worker(mu1=10.1, sigma1=10,
                 mu2=10.8, sigma2=1) 
Example 7
Project: XTREE   Author: ai-se   File: fi.py    (license) View Source Project 6 votes vote down vote up
def _ediv():
  "Demo code to test the above."
  import random
  bell= random.gauss
  random.seed(1)
  def go(lst):
    print ""; print sorted(lst)[:10],"..."
    for d in  ediv(lst,tiny=2):
      rprint(d); nl()
  X,Y="X","Y"
  l=[(1,X),(2,X),(3,X),(4,X),(11,Y),(12,Y),(13,Y),(14,Y)]
  go(l)
  l[0] = (1,Y)
  go(l)
  go(l*2)
  go([(1,X),(2,X),(3,X),(4,X),(11,X),(12,X),(13,X),(14,X)])
  go([(64,X),(65,Y),(68,X),(69,Y),(70,X),(71,Y),
      (72,X),(72,Y),(75,X),(75,X),
      (80,Y),(81,Y),(83,Y),(85,Y)]*2)
  l=[]
  for _ in range(1000): 
    l += [(bell(20,1),  X),(bell(10,1),Y),
          (bell(30,1),'Z'),(bell(40,1),'W')] 
  go(l)
  go([(1,X)]) 
Example 8
Project: XTREE   Author: ai-se   File: cube.py    (license) View Source Project 6 votes vote down vote up
def _sdiv():
  "Demo code to test the above."
  import random
  bell= random.gauss
  random.seed(1)
  def go(lst,cohen=0.3,
         num1=lambda x:x[0],
         num2=lambda x:x[1]):
    print ""; print sorted(lst)[:10],"..."
    for d in  sdiv(lst,cohen=cohen,num1=num1,num2=num2):
      print d[1][0][0]
  l = [ (1,10), (2,11),  (3,12),  (4,13),
       (20,20),(21,21), (22,22), (23,23), (24,24),
       (30,30),(31,31), (32,32), (33,33),(34,34)]
  go(l,cohen=0.3)
  go(map(lambda x:(x[1],x[1]),l))
  ten     = lambda: bell(10,2)
  twenty  = lambda: bell(20,2)
  thirty  = lambda: bell(30,2)
  l=[]
  for _ in range(1000): 
    l += [(ten(),   ten()), 
          (twenty(),twenty()),
          (thirty(),thirty())]
  go(l,cohen=0.5) 
Example 9
Project: XTREE   Author: ai-se   File: sk.py    (license) View Source Project 6 votes vote down vote up
def _bootstraped():
  def worker(n=1000,
             mu1=10, sigma1=1,
             mu2=10.2, sigma2=1):
    def g(mu, sigma):
      return random.gauss(mu, sigma)
    x = [g(mu1, sigma1) for i in range(n)]
    y = [g(mu2, sigma2) for i in range(n)]
    return n, mu1, sigma1, mu2, sigma2, \
        'different' if bootstrap(x, y) else 'same'
  # very different means, same std
  print worker(mu1=10, sigma1=10,
               mu2=100, sigma2=10)
  # similar means and std
  print worker(mu1=10.1, sigma1=1,
               mu2=10.2, sigma2=1)
  # slightly different means, same std
  print worker(mu1=10.1, sigma1=1,
               mu2=10.8, sigma2=1)
  # different in mu eater by large std
  print worker(mu1=10.1, sigma1=10,
               mu2=10.8, sigma2=1) 
Example 10
Project: CVE-2016-6366   Author: RiskSense-Ops   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 11
Project: pfi-internship2016   Author: hvy   File: randomizer.py    (license) View Source Project 6 votes vote down vote up
def rnd(shape, mean=0.0, stddev=0.01):
    """Return a list with the given shape with random float elements.
    The values are generated from a Gaussian distribution.

    Args:
        shape (tuple, list): A shape to generate random floats for. 1 or 2 dimensional.
        mean (float): Mean of the Gaussian distribution.
        stddev (float): Standard deviation of the distribution.

    Returns:
        list: A list with random float elements with the dimensions specified by `shape`.
    """
    if not isinstance(shape, (tuple, list)):
        raise TypeError('Invalid shape. The shape must be a tuple or a list.')

    dimension = len(shape)

    if dimension is 1:
        # Create a 1 dimensional array with random elements
        return [random.gauss(mean, stddev) for _ in range(shape[0])]
    elif dimension is 2:
        # Create a 2 dimensional matrix with random elements
        return [[random.gauss(mean, stddev) for _ in range(shape[1])] for _ in range(shape[0])]
    else:
        raise NotImplementedError('Random generation with dimensions > 2 is not yet implemented.') 
Example 12
Project: luckyhorse   Author: alexmbird   File: dummy.py    (license) View Source Project 6 votes vote down vote up
def _makeFakeTrade(self):
    "Generate a realistic-looking trade"
    tp    = self._t_price
    tpf   = self._t_price_sigma
    tv    = self._t_vol
    tvf   = self._t_vol_sigma
    t_exec      = self._prev_time + self._frequency
    t_update    = t_exec + random.uniform(0, self.FAKE_LATENCY)
    self._fake_trade_id += 1
    self._prev_time     = t_update
    
    return Trade(
      exchange_id = self.EXCHANGE_ID,
      price       = tp if tpf is None else random.gauss(tp, tpf),
      volume      = tv if tvf is None else random.gauss(tv, tvf),
      ts_exec     = t_exec,
      ts_update   = t_update,
      trade_id    = self._fake_trade_id
    ) 
Example 13
Project: Houston   Author: squaresLab   File: util.py    (license) View Source Project 6 votes vote down vote up
def current(self, deltat=None):
        """Return current wind speed and direction as a tuple
        speed is in m/s, direction in degrees."""
        if deltat is None:
            tnow = time.time()
            deltat = tnow - self.tlast
            self.tlast = tnow

        # update turbulance random walk
        w_delta = math.sqrt(deltat) * (1.0 - random.gauss(1.0, self.turbulance))
        w_delta -= (self.turbulance_mul - 1.0) * (deltat / self.turbulance_time_constant)
        self.turbulance_mul += w_delta
        speed = self.speed * math.fabs(self.turbulance_mul)
        return (speed, self.direction)

    # Calculate drag. 
Example 14
Project: hakkuframework   Author: 4shadoww   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o(bytes([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
#            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
            return o([ x._fix(n+1) for x in [self.__class__(objlist=self.objlist)]*z])
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 15
Project: Imagyn   Author: zevisert   File: synthesizer.py    (license) View Source Project 6 votes vote down vote up
def build_normal_distribution(maximum, minimum, mean, deviation, integer=False):
        """
        Build a normal distribution to use for randomizing values for input into transformation functions\n
        :param maximum: Float or int, The maximum value the value can be]\n
        :param minimum: Float or int, The minimum value the value can be\n
        :param mean: Float, the mean (mu) of the normal distribution\n
        :param deviation: Float, the deviation (sigma) of the normal distribution\n
        :param integer: OPTIONAL, whether the value is required to be an integer, otherwise False\n
        :return: Float or int, The value to insert into the transform function
        """
        value = random.gauss(mean, deviation)

        if integer is True:
            value = round(value)

        if value > maximum:
            value = maximum

        elif value < minimum:
            value = minimum

        return value 
Example 16
Project: trex-http-proxy   Author: alwye   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 17
Project: trex-http-proxy   Author: alwye   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o(bytes([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
#            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
            return o([ x._fix(n+1) for x in [self.__class__(objlist=self.objlist)]*z])
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 18
Project: Udacity_Robotics_cs373   Author: lijiyao111   File: Particle_dumbRobot.py    (license) View Source Project 6 votes vote down vote up
def move(self, turn, forward):
        if forward < 0:
            raise ValueError('Robot cant move backwards')         
        
        # turn, and add randomness to the turning command
        orientation = self.orientation + float(turn) + random.gauss(0.0, self.turn_noise)
        orientation %= 2 * pi
        
        # move, and add randomness to the motion command
        dist = float(forward) + random.gauss(0.0, self.forward_noise)
        x = self.x + (cos(orientation) * dist)
        y = self.y + (sin(orientation) * dist)
        x %= world_size    # cyclic truncate
        y %= world_size
        
        # set particle
        res = robot()
        res.set(x, y, orientation)
        res.set_noise(self.forward_noise, self.turn_noise, self.sense_noise)
        return res 
Example 19
Project: Udacity_Robotics_cs373   Author: lijiyao111   File: Particle_carRobot.py    (license) View Source Project 6 votes vote down vote up
def sense(self, add_noise=1):
        Z=[]
        for i in range(len(landmarks)):
            deltay=landmarks[i][0]-self.y
            deltax=landmarks[i][1]-self.x
            bearing=atan2(deltay, deltax)-self.orientation
            if add_noise:
                bearing += random.gauss(0.0, self.bearing_noise)
            bearing %=2*pi
            Z.append(bearing) 
        return Z

    # copy your code from the previous exercise
    # and modify it so that it simulates bearing noise
    # according to
    #           self.bearing_noise

    ############## ONLY ADD/MODIFY CODE ABOVE HERE ####################

# --------
#
# extract position from a particle set
# 
Example 20
Project: scapy-bpf   Author: guedou   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join(random.choice(self.chars) for _ in xrange(z)))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o([self.__class__(objlist=self.objlist)._fix(n + 1)
                      for _ in xrange(z)])
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 21
Project: sslstrip-hsts-openwrt   Author: adde88   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 22
Project: scapy-radio   Author: BastilleResearch   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join([random.choice(self.chars) for i in range(z)]))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 23
Project: ngas   Author: ICRAR   File: ngamsHighLevelLib.py    (license) View Source Project 6 votes vote down vote up
def acquireDiskResource(ngamsCfgObj,
                        slotId):
    """
    Acquire access right to a disk resource.

    ngamsCfgObj:   NG/AMS Configuration Object (ngamsConfig).

    slotId:        Slot ID referring to the disk resource (string).

    Returns:       Void.
    """
    T = TRACE()

    storageSet = ngamsCfgObj.getStorageSetFromSlotId(slotId)
    if (not storageSet.getMutex()): return

    global _diskMutexSems
    if (not _diskMutexSems.has_key(slotId)):
        _diskMutexSems[slotId] = threading.Semaphore(1)
    code = string.split(str(abs(random.gauss(10000000,10000000))), ".")[0]
    logger.debug("Requesting access to disk resource with Slot ID: %s (Code: %s)",
                 slotId, str(code))
    _diskMutexSems[slotId].acquire()
    logger.debug("Access granted") 
Example 24
Project: isf   Author: w3h   File: asn1.py    (license) View Source Project 6 votes vote down vote up
def _fix(self, n=0):
        o = random.choice(self.objlist)
        if issubclass(o, ASN1_INTEGER):
            return o(int(random.gauss(0,1000)))
        elif issubclass(o, ASN1_IPADDRESS):
            z = RandIP()._fix()
            return o(z)
        elif issubclass(o, ASN1_STRING):
            z = int(random.expovariate(0.05)+1)
            return o("".join(random.choice(self.chars) for _ in xrange(z)))
        elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
            z = int(random.expovariate(0.08)+1)
            return o([self.__class__(objlist=self.objlist)._fix(n + 1)
                      for _ in xrange(z)])
        return ASN1_INTEGER(int(random.gauss(0,1000)))


##############
#### ASN1 ####
############## 
Example 25
Project: ase16   Author: txt   File: stats.py    (license) View Source Project 6 votes vote down vote up
def _bootstraped(): 
  def worker(n=1000,
             mu1=10,  sigma1=1,
             mu2=10.2, sigma2=1):
    def g(mu,sigma) : return random.gauss(mu,sigma)
    x = [g(mu1,sigma1) for i in range(n)]
    y = [g(mu2,sigma2) for i in range(n)]
    return n,mu1,sigma1,mu2,sigma2,\
        'different' if bootstrap(x,y) else 'same'
  # very different means, same std
  print(worker(mu1=10, sigma1=10, 
               mu2=100, sigma2=10))
  # similar means and std
  print(worker(mu1= 10.1, sigma1=1, 
               mu2= 10.2, sigma2=1))
  # slightly different means, same std
  print(worker(mu1= 10.1, sigma1= 1, 
               mu2= 10.8, sigma2= 1))
  # different in mu eater by large std
  print(worker(mu1= 10.1, sigma1= 10, 
               mu2= 10.8, sigma2= 1)) 
Example 26
Project: mlAlgorithms   Author: gu-yan   File: logistics_regression.py    (license) View Source Project 6 votes vote down vote up
def gradient(train,
        labels,
        coef,
        bias,
        learn_rate,
        nepoch):
    for epoch in range(nepoch):
        sum_error = 0.0
        for index in range(len(train)):
            pred = predict(train[index], coef, bias)
            sum_error += (labels[index] - pred)
            bias = (bias + learn_rate * sum_error * pred * (1 - pred))
            for i in range(len(coef)):
                coef[i] = (coef[i] + learn_rate * sum_error * pred * (1 - pred) * train[index][i])
    return coef, bias

#generate standard normal distribution
#TODO the function random.gauss() can not generate stable distribution which causes diffusion gradient 
Example 27
Project: pygame-robotics   Author: ioarun   File: particle-filter-2.py    (license) View Source Project 6 votes vote down vote up
def move(self, turn, forward):
		if forward < 0:
			raise ValueError, 'Cant move backwards'

		self.orientation = self.orientation + turn + random.gauss(0.0, self.turn_noise)
		self.orientation %= 2*pi

		dist = forward + random.gauss(0.0, self.forward_noise)
		self.x = self.x + dist*cos(self.orientation)
		self.y = self.y - dist*sin(self.orientation)

		self.x %= world_size
		self.y %= world_size

		temp = robot()
		temp.set_noise(0.001, 0.1, 0.1)
		temp.set(self.x, self.y, self.orientation)
		temp.set_noise(self.forward_noise, self.turn_noise, self.sense_noise)
		return temp 
Example 28
Project: data-analysis   Author: ymohanty   File: display.py    (license) View Source Project 6 votes vote down vote up
def generateRandomData(self, event=None):
        print "X-Direction:", self.distribution[0]
        print "Y-Direction:", self.distribution[1]
        dx = 3
        dy = 3
        for i in range(int(self.num_pts.get())):
            if self.distribution[0] == "Uniform":
                x = random.randint(dx, self.canvas.winfo_width() - dx)
            else:
                # According to Adam Carlson, there's 99.8% chance that data in a normal distribution is within 3 standard deviations of the mean.
                # mu = mean, sigma = standard deviation. Look and infer.
                x = random.gauss(mu=(self.canvas.winfo_width() - dx) / 2, sigma=self.canvas.winfo_width() / 6)
            if self.distribution[1] == "Uniform":
                y = random.randint(dy, self.canvas.winfo_height() - dy)
            else:
                y = random.gauss(mu=(self.canvas.winfo_height() - dy) / 2, sigma=self.canvas.winfo_height() / 6)

            # make sure that the coords are not out of bounds!
            x %= self.canvas.winfo_width() - dx / 2
            y %= self.canvas.winfo_height() - dy / 2

            pt = self.canvas.create_oval(x - dx, y - dy, x + dx, y + dy, fill=self.colorOption.get(), outline='')
            self.objects.append(pt)

    # handle the clear command 
Example 29
Project: Computer-Graphic-Toolbox   Author: KerouichaReda   File: perlin.py    (license) View Source Project 6 votes vote down vote up
def _generate_gradient(self):
        # Generate a random unit vector at each grid point -- this is the
        # "gradient" vector, in that the grid tile slopes towards it

        # 1 dimension is special, since the only unit vector is trivial;
        # instead, use a slope between -1 and 1
        if self.dimension == 1:
            return (random.uniform(-1, 1),)

        # Generate a random point on the surface of the unit n-hypersphere;
        # this is the same as a random unit vector in n dimensions.  Thanks
        # to: http://mathworld.wolfram.com/SpherePointPicking.html
        # Pick n normal random variables with stddev 1
        random_point = [random.gauss(0, 1) for _ in range(self.dimension)]
        # Then scale the result to a unit vector
        scale = sum(n * n for n in random_point) ** -0.5
        return tuple(coord * scale for coord in random_point) 
Example 30
Project: cbc-casper   Author: ethereum   File: utils.py    (license) View Source Project 6 votes vote down vote up
def generate_random_gaussian_validator_set(
        protocol,
        num_validators=5,
        mu=60,
        sigma=40,
        min_weight=20
        ):
    """Generates a random validator set."""

    # Give the validators random weights in 0.,BIGINT;
    # this "big" integer's job is to guarantee the "tie-breaking property"
    # that no two subsets of validator's total weights are exactly equal.
    # In prod, we will add a random epsilon to weights given by bond amounts,
    # however, for the purposes of the current work, this will suffice.
    BIGINT = 1000000000000

    names = set(range(num_validators))
    weights = {
        i: max(min_weight, r.gauss(mu, sigma))
        + 1.0/(BIGINT + r.uniform(0, 1)) + r.random()
        for i in names
    }

    return ValidatorSet(weights, protocol) 
Example 31
Project: cbc-casper   Author: ethereum   File: utils.py    (license) View Source Project 6 votes vote down vote up
def validator_generator(config, protocol):
    if config['gen_type'] == 'gauss':

        def gauss_generator():
            return generate_random_gaussian_validator_set(
                protocol,
                config['num_validators'],
                config['mu'],
                config['sigma'],
                config['min_weight']
            )

        return gauss_generator

    if config['gen_type'] == 'weights':
        jitter_weights = {
            i: weight + r.random()
            for i, weight in enumerate(config['weights'])
        }

        def weights_generator():
            return ValidatorSet(jitter_weights, protocol)

        return weights_generator 
Example 32
Project: stn-ocr   Author: Bartzi   File: create_svhn_dataset.py    (license) View Source Project 6 votes vote down vote up
def find_paste_location(self, bbox, already_pasted_bboxes):

        while True:
            x_derivation = random.gauss(0, self.variance) * (self.image_size // 2)
            y_derivation = random.gauss(0, self.variance) * (self.image_size // 2)
            center = Point(x=self.image_size // 2, y=self.image_size // 2)

            bbox.left = max(min(center.x + x_derivation, self.image_size), 0)
            bbox.top = max(min(center.y + y_derivation, self.image_size), 0)

            if bbox.left + bbox.width > self.image_size:
                bbox.left = self.image_size - bbox.width
            if bbox.top + bbox.height > self.image_size:
                bbox.top = self.image_size - bbox.height

            if not any(intersects(bbox, box) for box in already_pasted_bboxes):
                return bbox 
Example 33
Project: kuryr-kubernetes   Author: openstack   File: lbaasv2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def _provisioning_timer(self, timeout):
        # REVISIT(ivc): consider integrating with Retry
        interval = 3
        max_interval = 15
        with timeutils.StopWatch(duration=timeout) as timer:
            while not timer.expired():
                yield timer.leftover()
                interval = interval * 2 * random.gauss(0.8, 0.05)
                interval = min(interval, max_interval)
                interval = min(interval, timer.leftover())
                if interval:
                    time.sleep(interval) 
Example 34
Project: sappho   Author: lily-mayfield   File: particle.py    (MIT License) View Source Project 5 votes vote down vote up
def brownian(cls, dt):
        return random.gauss(0, math.sqrt(dt)) 
Example 35
Project: nameko-amqp-retry   Author: nameko   File: backoff.py    (license) View Source Project 5 votes vote down vote up
def next(self, message, backoff_exchange_name):

        total_attempts = 0
        for deadlettered in message.headers.get('x-death', ()):
            if deadlettered['exchange'] == backoff_exchange_name:
                total_attempts += int(deadlettered['count'])

        if self.limit and total_attempts >= self.limit:
            expired = Backoff.Expired(
                "Backoff aborted after '{}' retries (~{:.0f} seconds)".format(
                    self.limit, self.max_delay / 1000
                )
            )
            six.raise_from(expired, self)

        expiration = self.get_next_schedule_item(total_attempts)

        if self.random_sigma:
            randomised = int(random.gauss(expiration, self.random_sigma))
            group_size = self.random_sigma / self.random_groups_per_sigma
            expiration = round_to_nearest(randomised, interval=group_size)

        # Prevent any negative values created by randomness
        expiration = abs(expiration)

        # store calculation results on self.
        self._next_expiration = expiration
        self._total_attempts = total_attempts

        return expiration 
Example 36
Project: code   Author: ActiveState   File: recipe-393090.py    (MIT License) View Source Project 5 votes vote down vote up
def test():
    for j in xrange(1000):
        vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
        s = 0
        for i in range(200):
            v = gauss(0, random()) ** 7 - s
            s += v
            vals.append(v)
        shuffle(vals)
        assert msum(vals) == lsum(vals) == dsum(vals) == frsum(vals) == lsum_26(vals)
        print '.',
    print 'Tests Passed' 
Example 37
Project: AI-Pacman   Author: AUTBS   File: mazeGenerator.py    (license) View Source Project 5 votes vote down vote up
def generateMaze(seed = None):
  if not seed:
    seed = random.randint(1,MAX_DIFFERENT_MAZES)
  random.seed(seed)
  maze = Maze(16,16)
  gapfactor = min(0.65,random.gauss(0.5,0.1))
  skip = make_with_prison(maze, depth=0, gaps=3, vert=True, min_width=1, gapfactor=gapfactor)
  maze.to_map()
  add_pacman_stuff(maze, 2*(maze.r*maze.c/20), 4, skip)
  return str(maze) 
Example 38
Project: gilc   Author: meco-group   File: invpen.py    (GNU Lesser General Public License v3.0) View Source Project 5 votes vote down vote up
def h(self,xk,uk):
        #---------------
        y = xk[0]
        y += random.gauss(0.0,self.noisestd)
        return y
    #======================= 
Example 39
Project: robograph   Author: csparpa   File: randoms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def output(self):
        if self._params['mu'] is None:
            mu = self.DEFAULT_MU
        else:
            mu = self._params['mu']

        if self._params['sigma'] is None:
            sigma = self.DEFAULT_SIGMA
        else:
            sigma = self._params['sigma']
        return random.gauss(mu, sigma) 
Example 40
Project: PyNEAT   Author: hugofragata   File: node_gene.py    (license) View Source Project 5 votes vote down vote up
def mutate_response(self):
        self.response = random.gauss(0.5 , 0.15) 
Example 41
Project: CyberScan   Author: medbenali   File: volatile.py    (license) View Source Project 5 votes vote down vote up
def _fix(self):
        return int(round(random.gauss(self.mu, self.sigma))) 
Example 42
Project: hostapd-mana   Author: adde88   File: volatile.py    (license) View Source Project 5 votes vote down vote up
def _fix(self):
        return int(round(random.gauss(self.mu, self.sigma))) 
Example 43
Project: TwitPy   Author: timgrossmann   File: time_util.py    (license) View Source Project 5 votes vote down vote up
def randomize_time(mean):
  allowed_range = mean * STDEV
  stdev = allowed_range / 3  # 99.73% chance to be in the allowed range

  t = 0
  while abs(mean - t) > allowed_range:
    t = gauss(mean, stdev)

  return t 
Example 44
Project: empyrical   Author: quantopian   File: test_stats.py    (license) View Source Project 5 votes vote down vote up
def test_sharpe_noise(self, small, large):
        index = pd.date_range('2000-1-30', periods=1000, freq='D')
        smaller_normal = pd.Series(
            [random.gauss(.01, small) for i in range(1000)],
            index=index
        )
        larger_normal = pd.Series(
            [random.gauss(.01, large) for i in range(1000)],
            index=index
        )
        assert self.empyrical.sharpe_ratio(smaller_normal, 0.001) > \
            self.empyrical.sharpe_ratio(larger_normal, 0.001)

    # Regressive downside risk tests 
Example 45
Project: empyrical   Author: quantopian   File: test_stats.py    (license) View Source Project 5 votes vote down vote up
def test_downside_risk_std(self, smaller_std, larger_std):
        less_noise = pd.Series(
            [random.gauss(0, smaller_std) for i in range(1000)],
            index=pd.date_range('2000-1-30', periods=1000, freq='D')
        )
        more_noise = pd.Series(
            [random.gauss(0, larger_std) for i in range(1000)],
            index=pd.date_range('2000-1-30', periods=1000, freq='D')
        )
        assert self.empyrical.downside_risk(less_noise) < \
            self.empyrical.downside_risk(more_noise)

    # Regressive sortino ratio tests 
Example 46
Project: EMFT   Author: 132nd-etcher   File: mission_weather.py    (license) View Source Project 5 votes vote down vote up
def _gauss(mean, sigma) -> int:
        return int(random.gauss(mean, sigma)) 
Example 47
Project: HTM_experiments   Author: ctrl-z-9000-times   File: encoders.py    (license) View Source Project 5 votes vote down vote up
def make_control_vectors(num_cv, pos_stddev, angle_stddev, scale_stddev):
        """
        Argument num_cv is the approximate number of control vectors to create
        Arguments pos_stddev, angle_stddev, and scale_stddev are the standard
                  deviations of the controls effects of position, angle, and 
                  scale.

        Returns pair of control_vectors, control_sdr

        The control_vectors determines what happens for each output. Each
        control is a 4-tuple of (X, Y, Angle, Scale) movements. To move,
        active controls are summed and applied to the current location.
        control_sdr contains the shape of the control_vectors.
        """
        cv_sz = int(round(num_cv // 6))
        control_shape = (6*cv_sz,)

        pos_controls = [
            (random.gauss(0, pos_stddev), random.gauss(0, pos_stddev), 0, 0)
                for i in range(4*cv_sz)]

        angle_controls = [
            (0, 0, random.gauss(0, angle_stddev), 0)
                for angle_control in range(cv_sz)]

        scale_controls = [
            (0, 0, 0, random.gauss(0, scale_stddev))
                for scale_control in range(cv_sz)]

        control_vectors = pos_controls + angle_controls + scale_controls
        random.shuffle(control_vectors)
        control_vectors = np.array(control_vectors)

        # Add a little noise to all control vectors
        control_vectors[:, 0] += np.random.normal(0, pos_stddev/10,    control_shape)
        control_vectors[:, 1] += np.random.normal(0, pos_stddev/10,    control_shape)
        control_vectors[:, 2] += np.random.normal(0, angle_stddev/10,  control_shape)
        control_vectors[:, 3] += np.random.normal(0, scale_stddev/10,  control_shape)
        return control_vectors, SDR(control_shape) 
Example 48
Project: HTM_experiments   Author: ctrl-z-9000-times   File: genetics.py    (license) View Source Project 5 votes vote down vote up
def mutate_standard(self, percent, population):
        """
        Randomly change some parameters.  The change in value uses the populations
        standard deviation.
        """
        def mutate_value(value, pop_values):
            if random.random() > percent:
                return value

            pop_values = [v for v in pop_values if v is not None]
            if len(np.unique(pop_values)) < 3:
                # Use alternative method when diversity is very low.
                return value * 1.5 ** (random.random()*2-1)
            else:
                std = np.std(pop_values)
                return float(random.gauss(value, std))

        for param in self.parameters:
            value      = getattr(self, param)
            pop_values = [getattr(indiv, param) for indiv in population]

            if value is None:
                continue # cant mutate.

            elif isinstance(value, Parameters):
                value.mutate_standard(percent, pop_values)

            elif isinstance(value, tuple):
                new_tup = []
                for index, value_indexed in enumerate(value):
                    pop_values_indexed = [v[index] for v in pop_values]
                    new_value = mutate_value(value_indexed, pop_values_indexed)
                    new_tup.append(new_value)
                setattr(self, param, tuple(new_tup))

            else:   # Mutate a floating point or boolean number.
                setattr(self, param, mutate_value(value, pop_values)) 
Example 49
Project: CVE-2016-6366   Author: RiskSense-Ops   File: volatile.py    (license) View Source Project 5 votes vote down vote up
def _fix(self):
        return int(round(random.gauss(self.mu, self.sigma))) 
Example 50
Project: pycaffe-yolo   Author: Zehaos   File: yolo_transformer.py    (license) View Source Project 5 votes vote down vote up
def color_dithering(self, im):
        """
        Color dithering for data augmentation.
        Including brightness, contrast and saturation dithering.
        """
        if self.__dithering:
            contrast = random.gauss(1, 0.07)
            brightness = random.gauss(0, 5)
            saturation = random.gauss(0, 5)
            saturation_base = random.choice([np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1])])
            img = np.uint8(im*contrast + brightness + saturation_base*saturation)
            return img
        else:
            return im