Python random.gauss() Examples

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

Example 1
Project: neat-python   Author: CodeReclaimers   File: attributes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_value(self, config):
        mean = getattr(config, self.init_mean_name)
        stdev = getattr(config, self.init_stdev_name)
        init_type = getattr(config, self.init_type_name).lower()

        if ('gauss' in init_type) or ('normal' in init_type):
            return self.clamp(gauss(mean, stdev), config)

        if 'uniform' in init_type:
            min_value = max(getattr(config, self.min_value_name),
                            (mean - (2 * stdev)))
            max_value = min(getattr(config, self.max_value_name),
                            (mean + (2 * stdev)))
            return uniform(min_value, max_value)

        raise RuntimeError("Unknown init_type {!r} for {!s}".format(getattr(config,
                                                                            self.init_type_name),
                                                                    self.init_type_name)) 
Example 2
Project: neat-python   Author: CodeReclaimers   File: attributes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mutate_value(self, value, config):
        # mutate_rate is usually no lower than replace_rate, and frequently higher -
        # so put first for efficiency
        mutate_rate = getattr(config, self.mutate_rate_name)

        r = random()
        if r < mutate_rate:
            mutate_power = getattr(config, self.mutate_power_name)
            return self.clamp(value + gauss(0.0, mutate_power), config)

        replace_rate = getattr(config, self.replace_rate_name)

        if r < replace_rate + mutate_rate:
            return self.init_value(config)

        return value 
Example 3
Project: team-formation-study-software   Author: NDykhuis   File: agentgroup.py    GNU General Public License v2.0 6 votes vote down vote up
def ultimatum_init(self, distribution='normal', p1=5, p2=1, 
                     delaymean=5, delaysd=2):
    """Initialize parameters of offer distribution.
    
    Arguments:
      distribution: 'normal' or 'uniform'
      p1, p2: mean and sd of normal, or upper and lower bound of uniform
      delaymean, delaysd: time required to make decisions
    """
    self.p1, self.p2, self.delaymean, self.delaysd = p1, p2, delaymean, delaysd
    if distribution == 'normal':
      # p1 is mean, p2 is sd
      self.random = random.gauss
    elif distribution == 'uniform':
      # p1 is lower bound, p2 is upper
      self.random = random.randint 
Example 4
Project: UberLens   Author: adamalawrence   File: hexmath.py    MIT License 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 5
Project: UberLens   Author: adamalawrence   File: hexgrid_class.py    MIT License 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 6
Project: Frank-the-Science-Bot   Author: ViktorWase   File: simpleDatabase.py    Apache License 2.0 6 votes vote down vote up
def createSimpleDataSet( numOfAttr, numOfObj ):
    """
        This creates a simple data base with 3 attributes
        The second one is 2 times the first one with some
        Gauss noise. The third one is just random noise.
    """
    database = []
    for i in range(numOfObj):
        data = dataObject(numOfAttr)

        w=[random.gauss(2.0, 2.0)]
        w.append(w[0]*3+random.gauss(0.0, 0.05))
        w.append(random.random()*6)

        data.setAttributes(w)
        database.append(data)
    return database 
Example 7
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Importance_Weight.py    MIT License 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 8
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: New_Particle.py    MIT License 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 9
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Creating_Particles.py    MIT License 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 10
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Robot_Particles.py    MIT License 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 11
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Add_Noise.py    MIT License 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 12
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Resampling_Wheel.py    MIT License 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 13
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Error.py    MIT License 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 14
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Moving_Robot.py    MIT License 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 15
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Orientation_2.py    MIT License 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 16
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Final_Quiz.py    MIT License 6 votes vote down vote up
def sense(self, add_noise=True):  # do not change the name of this function
        Z = []

        # ENTER CODE HERE
        # HINT: You will probably need to use the function atan2()
        for i in range(len(landmarks)):
            delta_x = landmarks[i][1] - self.x
            delta_y = landmarks[i][0] - self.y
            bearing = atan2(delta_y, delta_x) - self.orientation
            if add_noise:
                bearing += random.gauss(0.0, self.bearing_noise)
            bearing %= 2.0 * pi
            Z.append(bearing)

        return Z  # Leave this line here. Return vector Z of 4 bearings.

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


# --------
#
# extract position from a particle set
# 
Example 17
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 6 votes vote down vote up
def move(self, turning, distance, tolerance = 0.001, max_turning_angle = pi):
        """This function turns the robot and then moves it forward."""
        # apply noise, this doesn't change anything if turning_noise
        # and distance_noise are zero.
        turning = random.gauss(turning, self.turning_noise)
        distance = random.gauss(distance, self.distance_noise)

        # truncate to fit physical limitations
        turning = max(-max_turning_angle, turning)
        turning = min( max_turning_angle, turning)
        distance = max(0.0, distance)

        # Execute motion
        self.heading += turning
        self.heading = angle_trunc(self.heading)
        self.x += distance * cos(self.heading)
        self.y += distance * sin(self.heading) 
Example 18
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 6 votes vote down vote up
def move(self, turning, distance, tolerance = 0.001, max_turning_angle = pi):
        """This function turns the robot and then moves it forward."""
        # apply noise, this doesn't change anything if turning_noise
        # and distance_noise are zero.
        turning = random.gauss(turning, self.turning_noise)
        distance = random.gauss(distance, self.distance_noise)

        # truncate to fit physical limitations
        turning = max(-max_turning_angle, turning)
        turning = min( max_turning_angle, turning)
        distance = max(0.0, distance)

        # Execute motion
        self.heading += turning
        self.heading = angle_trunc(self.heading)
        self.x += distance * cos(self.heading)
        self.y += distance * sin(self.heading) 
Example 19
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 6 votes vote down vote up
def move(self, turning, distance, tolerance = 0.001, max_turning_angle = pi):
        """This function turns the robot and then moves it forward."""
        # apply noise, this doesn't change anything if turning_noise
        # and distance_noise are zero.
        turning = random.gauss(turning, self.turning_noise)
        distance = random.gauss(distance, self.distance_noise)

        # truncate to fit physical limitations
        turning = max(-max_turning_angle, turning)
        turning = min( max_turning_angle, turning)
        distance = max(0.0, distance)

        # Execute motion
        self.heading += turning
        self.heading = angle_trunc(self.heading)
        self.x += distance * cos(self.heading)
        self.y += distance * sin(self.heading) 
Example 20
Project: emergeX   Author: ciscoemerge   File: utils.py    Apache License 2.0 6 votes vote down vote up
def CMajorScaleDistribution(num_samples, batch_size):
	sample_rate = 16000
	seconds = 2
	t = np.linspace(0, seconds, sample_rate*seconds + 1)
	C_major_scale = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88]
	while True:
		try:
			batch_x = []
			batch_y = []
			for i in range(batch_size):
				# select random note
				note = C_major_scale[np.random.randint(len(C_major_scale))]
				sound = np.sin(2*np.pi*t*note)
				noise = [random.gauss(0.0, 1.0) for i in range(sample_rate*seconds + 1)]
				noisy_sound = sound + 0.08 * np.asarray(noise)
				start = np.random.randint(0, len(noisy_sound)-num_samples)
				end = start + num_samples
				batch_x.append(noisy_sound[start:end])
				batch_y.append(sound)

			yield np.asarray(batch_x), np.asarray(batch_y)

		except Exception as e:
			print('Could not produce batch of sinusoids because: {}'.format(e))
			sys.exit(1) 
Example 21
Project: programsynthesishunting   Author: flexgp   File: math_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def sample_guassian(mu, sigma, rectify_min=0, rectify_max=1):
    """Sample from gaussian with mean my and std sigma bounded between rectify_min and rectify_max"""
    import random

    def rectify(num, bot, top):
        """Bound num between bot and top"""
        return min(top, max(num, bot))

    return rectify(random.gauss(mu, sigma), rectify_min, rectify_max) 
Example 22
Project: neat-python   Author: CodeReclaimers   File: cart_pole.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noisy_continuous_actuator_force(action):
    a = action[0] + random.gauss(0, 0.2)
    return 10.0 if a > 0.5 else -10.0 
Example 23
Project: neat-python   Author: CodeReclaimers   File: cart_pole.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noisy_discrete_actuator_force(action):
    a = action[0] + random.gauss(0, 0.2)
    return 10.0 if a > 0.5 else -10.0 
Example 24
Project: neat-python   Author: CodeReclaimers   File: evolve.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mutate(self, config):
        super().mutate(config)
        self.discount += random.gauss(0.0, 0.05)
        self.discount = max(0.01, min(0.99, self.discount)) 
Example 25
Project: genetic-curriculum   Author: Octavian-ai   File: param.py    Apache License 2.0 5 votes vote down vote up
def mutate(self, heat=1.0):
		return type(self)(self.value * random.uniform(0.8/heat, 1.2*heat) + random.gauss(0.0, heat*0.1), self.min, self.max) 
Example 26
Project: team-formation-study-software   Author: NDykhuis   File: agentgroup.py    GNU General Public License v2.0 5 votes vote down vote up
def fake_wait(self):
    """Sleep to simulate time to decide, based on cfg.delay_sim_agents"""
    if Configuration.delay_sim_agents:
      time.sleep(max(random.gauss(self.delaymean, self.delaysd), 0)) 
Example 27
Project: team-formation-study-software   Author: NDykhuis   File: simagent.py    GNU General Public License v2.0 5 votes vote down vote up
def tf_delay_real(self, stage):
    """Wait based on times defined in cfg._agent_delays for stage"""
    #print "tf_delay", self.id
    if (self.cfg._agent_delays[stage] and 
        (self.id < self.cfg.delay_n_sims or not self.cfg.delay_n_sims)):
      rand_delay = random.gauss(self.cfg._agent_delays[stage],
                                self.cfg._agent_delay_dev[stage])
      time.sleep(max(rand_delay, 0.25)) 
Example 28
Project: Quiver-alfred   Author: danielecook   File: sqlite_udf.py    MIT License 5 votes vote down vote up
def gauss_distribution(mean, sigma):
    try:
        return random.gauss(mean, sigma)
    except ValueError:
        return None 
Example 29
Project: PySpaMo   Author: kpj   File: evolutionary_optimization.py    MIT License 5 votes vote down vote up
def mutate(self, obj):
        sigma = 0.05
        return (obj[0] * random.gauss(1, sigma), obj[1] * random.gauss(1, sigma)) 
Example 30
Project: kuryr-kubernetes   Author: openstack   File: lbaasv2.py    Apache License 2.0 5 votes vote down vote up
def _provisioning_timer(self, timeout,
                            interval=_LB_STS_POLL_FAST_INTERVAL):
        # REVISIT(ivc): consider integrating with Retry
        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 31
Project: quip_cnn_segmentation   Author: SBU-BMI   File: polygon.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generatePolygon( ctrX, ctrY, aveRadius, irregularity, spikeyness, numVerts ):
    irregularity = clip( irregularity, 0,1 ) * 2*math.pi / numVerts
    spikeyness = clip( spikeyness, 0,1 ) * aveRadius

    # generate n angle steps
    angleSteps = []
    lower = (2*math.pi / numVerts) - irregularity
    upper = (2*math.pi / numVerts) + irregularity
    sum = 0
    for i in range(numVerts):
        tmp = random.uniform(lower, upper)
        angleSteps.append( tmp )
        sum = sum + tmp

    # normalize the steps so that point 0 and point n+1 are the same
    k = sum / (2*math.pi)
    for i in range(numVerts):
        angleSteps[i] = angleSteps[i] / k

    # now generate the points
    points = []
    angle = random.uniform(0, 2*math.pi)
    for i in range(numVerts):
        r_i = clip( random.gauss(aveRadius, spikeyness), 0, 2*aveRadius )
        x = ctrX + r_i*math.cos(angle)
        y = ctrY + r_i*math.sin(angle)
        points.append( (int(x),int(y)) )

        angle = angle + angleSteps[i]

    return points 
Example 32
Project: Frank-the-Science-Bot   Author: ViktorWase   File: tautology.py    Apache License 2.0 5 votes vote down vote up
def howMuchOfATautologyItIs(database,hyp):
    out = 0.0
    n = database.numAttributes
    for i in range(500):
        lista = [0.0]*n
        for j in range(n):
            lista[j] = gauss(0,10.0)
        tmp = hyp.function(lista)
        out += tmp*tmp
    return 1.0/(out+0.000001) 
Example 33
Project: Frank-the-Science-Bot   Author: ViktorWase   File: rbf.py    Apache License 2.0 5 votes vote down vote up
def randomHypothesis( self, database):
        if (self.xc == None):
            self.xc = [0.0] * self.numFunctions * self.dim
        for i in range(self.numFunctions * self.dim):
            self.xc[i] = random.gauss(0,10)

        if(self.w == None):
            self.w = [0.0] * self.numFunctions
        for i in range(self.numFunctions):
            self.w[i] += random.gauss(0, 5000) 
Example 34
Project: Frank-the-Science-Bot   Author: ViktorWase   File: rbf.py    Apache License 2.0 5 votes vote down vote up
def addRandomJump(self):
        for i in range(self.numFunctions * self.dim):
            self.xc[i] += random.gauss(0,0.5)

        for i in range(self.numFunctions):
            self.w[i] += random.gauss(0, 0.5) 
Example 35
Project: pycaffe-yolo   Author: Zehaos   File: yolo_transformer.py    GNU General Public License v3.0 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 
Example 36
Project: morse-code-trainer   Author: partofthething   File: trainer.py    MIT License 5 votes vote down vote up
def get_length_of_phrase(self):
        """
        Randomly determine number of chars to use.

        Uniform distributions seem to put too many at 1 or 2 characters.
        """

        # random.choice(range(1,7))
        num = int(random.gauss(4, 1.5))
        if num > 7:
            num = 7
        elif num < 1:
            num = 1
        return num 
Example 37
Project: PokemonGo-Bot   Author: PokemonGoF   File: human_behaviour.py    MIT License 5 votes vote down vote up
def gps_noise_rng(radius):
    '''
    Simulates gps noise.
    '''
    noise = gauss(0, radius/3.0)
    noise = min(max(-radius, noise), radius)
    return noise 
Example 38
Project: cbc-beacon-chain   Author: LayerXcom   File: network_delay.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def gaussian_delay(sender, reciever, curr_round):
    """Messages take a random amount of time to deliver
    (from a gaussian distribution)"""
    return round(random.gauss(MU, SIGMA).real) 
Example 39
Project: cbc-beacon-chain   Author: LayerXcom   File: utils.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_random_gaussian_weights(
        num_validators=5,
        mu=60,
        sigma=40,
        min_weight=20
    ):
    """Generates random gaussian weights for validators"""
    return [
        max(min_weight, random.gauss(mu, sigma))
        + 1.0/(BIG_INT + random.uniform(0, 1)) + random.random()
        for _ in range(num_validators)
    ] 
Example 40
Project: SherpaHighLevel   Author: Shedino   File: magfit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 41
Project: SherpaHighLevel   Author: Shedino   File: magfit_delta.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 42
Project: SherpaHighLevel   Author: Shedino   File: magfit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 43
Project: SherpaHighLevel   Author: Shedino   File: magfit_motors.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 44
Project: SherpaHighLevel   Author: Shedino   File: magfit_delta.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 45
Project: SherpaHighLevel   Author: Shedino   File: magfit_motors.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 46
Project: SherpaHighLevel   Author: Shedino   File: magfit_delta.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def noise():
    '''a noise vector'''
    from random import gauss
    v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
    v.normalize()
    return v * opts.noise 
Example 47
Project: MuscleSpindleCircuitsModel   Author: FormentoEmanuele   File: firings_tools.py    MIT License 5 votes vote down vote up
def synth_rat_emg( firings,samplingRate = 1000.,delay_ms=2):
	""" Return the EMG activity given the cell firings.

	Keyword arguments:
		firings -- Cell firings, a 2d numpy array (nCells x time).
		samplingRate -- Sampling rate of the extracted signal in Hz (default = 1000).
		delay_ms -- delay in ms between an action potential (AP) and a motor unit
		action potential (MUAP).
	"""
	EMG = None
	if rank==0:
		nCells = firings.shape[0]
		nSamples = firings.shape[1]

		dt = 1000./samplingRate
		delay = int(delay_ms/dt)

		# MUAP duration between 5-10ms (Day et al 2001) -> 7.5 +-1
		meanLenMUAP = int(7.5/dt)
		stdLenMUAP = int(1/dt)
		nS = [int(meanLenMUAP+rnd.gauss(0,stdLenMUAP)) for i in xrange(firings.shape[0])]
		Amp = [abs(1+rnd.gauss(0,0.2)) for i in xrange(firings.shape[0])]
		EMG = np.zeros(nSamples + max(nS)+delay);
		# create MUAP shape
		for i in xrange(nCells):
			n40perc = int(nS[i]*0.4)
			n60perc = nS[i]-n40perc
			amplitudeMod = (1-(np.linspace(0,1,nS[i])**2)) * np.concatenate((np.ones(n40perc),1/np.linspace(1,3,n60perc)))
			logBase = 1.05
			freqMod = np.log(np.linspace(1,logBase**(4*np.pi),nS[i]))/np.log(logBase)
			EMG_unit = Amp[i]*amplitudeMod*np.sin(freqMod);
			for j in xrange(nSamples):
				if firings[i,j]==1:
					EMG[j+delay:j+delay+nS[i]]=EMG[j+delay:j+delay+nS[i]]+EMG_unit
		EMG = EMG[:nSamples]

	return EMG 
Example 48
Project: PyFOPPL-2   Author: Tobias-Kohn   File: test_distributions.py    MIT License 5 votes vote down vote up
def sample(self):
            return _random.gauss(self.mu, self.sigma) 
Example 49
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Implement_PID_Controller.py    MIT License 5 votes vote down vote up
def move(self, steering, distance, tolerance=0.001, max_steering_angle=np.pi / 4.0):
        """
        steering = front wheel steering angle, limited by max_steering_angle
        distance = total distance driven, most be non-negative
        """
        if steering > max_steering_angle:
            steering = max_steering_angle
        if steering < -max_steering_angle:
            steering = -max_steering_angle
        if distance < 0.0:
            distance = 0.0

        # apply noise
        steering2 = random.gauss(steering, self.steering_noise)
        distance2 = random.gauss(distance, self.distance_noise)

        # apply steering drift
        steering2 += self.steering_drift

        # Execute motion
        turn = np.tan(steering2) * distance2 / self.length

        if abs(turn) < tolerance:
            # approximate by straight line motion
            self.x += distance2 * np.cos(self.orientation)
            self.y += distance2 * np.sin(self.orientation)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
        else:
            # approximate bicycle model for motion
            radius = distance2 / turn
            cx = self.x - (np.sin(self.orientation) * radius)
            cy = self.y + (np.cos(self.orientation) * radius)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
            self.x = cx + (np.sin(self.orientation) * radius)
            self.y = cy - (np.cos(self.orientation) * radius) 
Example 50
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Implement_P_Controller.py    MIT License 5 votes vote down vote up
def move(self, steering, distance, tolerance=0.001, max_steering_angle=np.pi / 4.0):
        """
        steering = front wheel steering angle, limited by max_steering_angle
        distance = total distance driven, most be non-negative
        """
        if steering > max_steering_angle:
            steering = max_steering_angle
        if steering < -max_steering_angle:
            steering = -max_steering_angle
        if distance < 0.0:
            distance = 0.0

        # apply noise
        steering2 = random.gauss(steering, self.steering_noise)
        distance2 = random.gauss(distance, self.distance_noise)

        # apply steering drift
        steering2 += self.steering_drift

        # Execute motion
        turn = np.tan(steering2) * distance2 / self.length

        if abs(turn) < tolerance:
            # approximate by straight line motion
            self.x += distance2 * np.cos(self.orientation)
            self.y += distance2 * np.sin(self.orientation)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
        else:
            # approximate bicycle model for motion
            radius = distance2 / turn
            cx = self.x - (np.sin(self.orientation) * radius)
            cy = self.y + (np.cos(self.orientation) * radius)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
            self.x = cx + (np.sin(self.orientation) * radius)
            self.y = cy - (np.cos(self.orientation) * radius) 
Example 51
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Implement_PD_Controller.py    MIT License 5 votes vote down vote up
def move(self, steering, distance, tolerance=0.001, max_steering_angle=np.pi / 4.0):
        """
        steering = front wheel steering angle, limited by max_steering_angle
        distance = total distance driven, most be non-negative
        """
        if steering > max_steering_angle:
            steering = max_steering_angle
        if steering < -max_steering_angle:
            steering = -max_steering_angle
        if distance < 0.0:
            distance = 0.0

        # apply noise
        steering2 = random.gauss(steering, self.steering_noise)
        distance2 = random.gauss(distance, self.distance_noise)

        # apply steering drift
        steering2 += self.steering_drift

        # Execute motion
        turn = np.tan(steering2) * distance2 / self.length

        if abs(turn) < tolerance:
            # approximate by straight line motion
            self.x += distance2 * np.cos(self.orientation)
            self.y += distance2 * np.sin(self.orientation)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
        else:
            # approximate bicycle model for motion
            radius = distance2 / turn
            cx = self.x - (np.sin(self.orientation) * radius)
            cy = self.y + (np.cos(self.orientation) * radius)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
            self.x = cx + (np.sin(self.orientation) * radius)
            self.y = cy - (np.cos(self.orientation) * radius) 
Example 52
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: PID_Parameter_Optimization.py    MIT License 5 votes vote down vote up
def move(self, steering, distance, tolerance=0.001, max_steering_angle=np.pi / 4.0):
        """
        steering = front wheel steering angle, limited by max_steering_angle
        distance = total distance driven, most be non-negative
        """
        if steering > max_steering_angle:
            steering = max_steering_angle
        if steering < -max_steering_angle:
            steering = -max_steering_angle
        if distance < 0.0:
            distance = 0.0

        # apply noise
        steering2 = random.gauss(steering, self.steering_noise)
        distance2 = random.gauss(distance, self.distance_noise)

        # apply steering drift
        steering2 += self.steering_drift

        # Execute motion
        turn = np.tan(steering2) * distance2 / self.length

        if abs(turn) < tolerance:
            # approximate by straight line motion
            self.x += distance2 * np.cos(self.orientation)
            self.y += distance2 * np.sin(self.orientation)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
        else:
            # approximate bicycle model for motion
            radius = distance2 / turn
            cx = self.x - (np.sin(self.orientation) * radius)
            cy = self.y + (np.cos(self.orientation) * radius)
            self.orientation = (self.orientation + turn) % (2.0 * np.pi)
            self.x = cx + (np.sin(self.orientation) * radius)
            self.y = cy - (np.cos(self.orientation) * radius) 
Example 53
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Segmented_CTE.py    MIT License 5 votes vote down vote up
def sense(self):

        return [random.gauss(self.x, self.measurement_noise), random.gauss(self.y, self.measurement_noise)]

    # --------
    # measurement_prob
    #    computes the probability of a measurement
    # 
Example 54
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Fun_with_Parameters.py    MIT License 5 votes vote down vote up
def sense(self):

        return [random.gauss(self.x, self.measurement_noise),
                random.gauss(self.y, self.measurement_noise)]

    # --------
    # measurement_prob
    #    computes the probability of a measurement
    # 
Example 55
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Importance_Weight.py    MIT License 5 votes vote down vote up
def sense(self):
        Z = []
        for i in range(len(landmarks)):
            dist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)
            dist += random.gauss(0.0, self.sense_noise)
            Z.append(dist)
        return Z 
Example 56
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Creating_Particles.py    MIT License 5 votes vote down vote up
def sense(self):
        Z = []
        for i in range(len(landmarks)):
            dist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)
            dist += random.gauss(0.0, self.sense_noise)
            Z.append(dist)
        return Z 
Example 57
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Robot_Particles.py    MIT License 5 votes vote down vote up
def sense(self):
        Z = []
        for i in range(len(landmarks)):
            dist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)
            dist += random.gauss(0.0, self.sense_noise)
            Z.append(dist)
        return Z 
Example 58
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Resampling_Wheel.py    MIT License 5 votes vote down vote up
def sense(self):
        Z = []
        for i in range(len(landmarks)):
            dist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)
            dist += random.gauss(0.0, self.sense_noise)
            Z.append(dist)
        return Z 
Example 59
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Error.py    MIT License 5 votes vote down vote up
def sense(self):
        Z = []
        for i in range(len(landmarks)):
            dist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)
            dist += random.gauss(0.0, self.sense_noise)
            Z.append(dist)
        return Z 
Example 60
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Orientation_2.py    MIT License 5 votes vote down vote up
def sense(self):
        Z = []
        for i in range(len(landmarks)):
            dist = sqrt((self.x - landmarks[i][0]) ** 2 + (self.y - landmarks[i][1]) ** 2)
            dist += random.gauss(0.0, self.sense_noise)
            Z.append(dist)
        return Z 
Example 61
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 5 votes vote down vote up
def sense(self):
        """This function represents the robot sensing its location. When
        measurements are noisy, this will return a value that is close to,
        but not necessarily equal to, the robot's (x, y) position."""
        return (random.gauss(self.x, self.measurement_noise),
                random.gauss(self.y, self.measurement_noise)) 
Example 62
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 5 votes vote down vote up
def sense(self):
        """This function represents the robot sensing its location. When
        measurements are noisy, this will return a value that is close to,
        but not necessarily equal to, the robot's (x, y) position."""
        return (random.gauss(self.x, self.measurement_noise),
                random.gauss(self.y, self.measurement_noise)) 
Example 63
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 5 votes vote down vote up
def sense(self):
        """This function represents the robot sensing its location. When
        measurements are noisy, this will return a value that is close to,
        but not necessarily equal to, the robot's (x, y) position."""
        return (random.gauss(self.x, self.measurement_noise),
                random.gauss(self.y, self.measurement_noise)) 
Example 64
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 5 votes vote down vote up
def sense(self):
        """This function represents the robot sensing its location. When
        measurements are noisy, this will return a value that is close to,
        but not necessarily equal to, the robot's (x, y) position."""
        return (random.gauss(self.x, self.measurement_noise),
                random.gauss(self.y, self.measurement_noise)) 
Example 65
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: robot.py    MIT License 5 votes vote down vote up
def sense(self):
        """This function represents the robot sensing its location. When
        measurements are noisy, this will return a value that is close to,
        but not necessarily equal to, the robot's (x, y) position."""
        return (random.gauss(self.x, self.measurement_noise),
                random.gauss(self.y, self.measurement_noise)) 
Example 66
Project: vantgrd-py   Author: davideanastasia   File: logistic_regression_adagrad.py    Apache License 2.0 5 votes vote down vote up
def _update(self, y, p, x):
        for idxi, xi in enumerate(x):
            if xi != 0.0:
                grad = self.class_weight_[y] * ((p - y - rnd.gauss(0, 0.1)) * xi + self.regw * self.w_[idxi])
                self.E_[idxi] += (grad * grad)
                self.w_[idxi] -= (self.eta / sqrt(self.E_[idxi] + 1e-8)) * grad 
Example 67
Project: Pixelate   Author: a7i7   File: PixelEffect.py    MIT License 5 votes vote down vote up
def get_pixel(self,x,y):
        r_dev = int(gauss(0,self.MAX_DEVIATION))
        g_dev = int(gauss(0,self.MAX_DEVIATION))
        b_dev = int(gauss(0,self.MAX_DEVIATION))
        return (self.r+r_dev,self.g+g_dev,self.b+b_dev) 
Example 68
Project: PointCNN.MX   Author: chinakook   File: pointcnn.py    MIT License 5 votes vote down vote up
def gauss_clip(mu, sigma, clip):
    v = random.gauss(mu, sigma)
    v = max(min(v, mu + clip * sigma), mu - clip * sigma)
    return v 
Example 69
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: params_ops.py    MIT License 5 votes vote down vote up
def Nt(mu, sigma, limit=3.0):
  """Normally distributed floating point number with truncation."""
  return min(max(random.gauss(mu, sigma), mu-limit*sigma), mu+limit*sigma)


# pylint: enable=invalid-name 
Example 70
Project: mela   Author: emews   File: algorithm.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mutate_Gaussian_float(x):
    global sigma
    x += random.gauss(0, sigma)
    return x

# Returns a tuple of one individual 
Example 71
Project: scenario_runner   Author: carla-simulator   File: atomic_behaviors.py    MIT License 5 votes vote down vote up
def __init__(self, new_steer_noise, new_throttle_noise,
                 noise_mean, noise_std, dynamic_mean_for_steer, dynamic_mean_for_throttle, name="ChangeJittering"):
        """
        Setup actor , maximum steer value and throttle value
        """
        super(ChangeNoiseParameters, self).__init__(name)
        self.logger.debug("%s.__init__()" % (self.__class__.__name__))
        self._new_steer_noise = new_steer_noise
        self._new_throttle_noise = new_throttle_noise
        self._noise_mean = noise_mean
        self._noise_std = noise_std
        self._dynamic_mean_for_steer = dynamic_mean_for_steer
        self._dynamic_mean_for_throttle = dynamic_mean_for_throttle

        self._noise_to_apply = abs(random.gauss(self._noise_mean, self._noise_std)) 
Example 72
Project: note_analysis_2stage_tasks   Author: carolfs   File: simulate_2stage_tasks.py    GNU General Public License v3.0 5 votes vote down vote up
def diffuse_prob(prob):
    """Diffuses a probability between 0.25 and 0.75"""
    prob += random.gauss(0, 0.025)
    if prob < 0.25:
        prob = 0.5 - prob
    elif prob > 0.75:
        prob = 1.5 - prob
    assert prob >= 0.25 and prob <= 0.75
    return prob 
Example 73
Project: MultiKE   Author: nju-websoft   File: initializers.py    MIT License 5 votes vote down vote up
def random_unit_init(shape, name, is_l2_norm, dtype=None):
    with tf.name_scope('random_unit_init'):
        vectors = list()
        for i in range(shape[0]):
            vectors.append([random.gauss(0, 1) for j in range(shape[1])])
    embeddings = tf.Variable(preprocessing.normalize(np.matrix(vectors)), name=name, dtype=dtype)
    return tf.nn.l2_normalize(embeddings, 1) if is_l2_norm else embeddings 
Example 74
Project: facebook-chatbot-python   Author: hult   File: chatbot.py    MIT License 5 votes vote down vote up
def respond_to(self, message):
        # Pick a random word from the incoming message
        input_tokens = nltk.word_tokenize(message)
        keyword = random.choice(input_tokens)

        # Use keyword and input length to seed a response
        input_length = len(input_tokens)
        num_response_words = int(random.gauss(input_length, input_length / 2)) + 1
        print "Basing response on keyword %s and length %d" % (keyword, num_response_words)
        content = self._model.generate(num_response_words, (keyword,))
        return self._format_response(content) 
Example 75
Project: trelby   Author: trelby   File: t_random.py    GNU General Public License v2.0 4 votes vote down vote up
def runRandomOps():
    cnt = 0
    while True:
        rounds = max(1, int(random.gauss(15000, 4000)))
        print "Count %d (%d rounds)" % (cnt, rounds)

        ops = Ops()
        failed = False

        # every 10th time, test operations on an empty script
        if (cnt % 10) == 0:
            ops.add(Op("NEW"))
        else:
            ops.add(Op("LOAD"))

        for i in xrange(rounds):
            if i != 0:
                ops.add(Op.getRandom())

            try:
                ops.run()
                # FIXME: add a --validate option
                ops.sp._validate()
            except KeyboardInterrupt:
                raise
            except:
                print " Failed, saving..."
                save(ops, cnt)
                failed = True

                break

        if not failed:
            try:
                ops.sp._validate()
                s = ops.sp.save()
                u.loadString(s)
            except KeyboardInterrupt:
                raise
            except:
                print " Failed in save/load, saving..."
                save(ops, cnt)

        cnt += 1

# run ops from given file 
Example 76
Project: roboticsControl   Author: beckerpascal   File: pid.py    MIT License 4 votes vote down vote up
def move(self, steering, distance,
                 tolerance=0.001, max_steering_angle=pi/4.0):
            """
            steering = front wheel steering angle, limited by max_steering_angle
            distance = total distance driven, most be non-negative
            """
            if steering > max_steering_angle:
                steering = max_steering_angle
            if steering < -max_steering_angle:
                steering = -max_steering_angle
            if distance < 0.0:
                distance = 0.0

            # make a new copy
            res = robot()
            res.length = self.length
            res.steering_noise = self.steering_noise
            res.distance_noise = self.distance_noise
            res.steering_drift = self.steering_drift

            # apply noise
            steering2 = random.gauss(steering, self.steering_noise)
            distance2 = random.gauss(distance, self.distance_noise)

            # apply steering drift
            steering2 += self.steering_drift

            # Execute motion
            turn = tan(steering2) * distance2 / res.length

            if abs(turn) < tolerance:
                # approximate by straight line motion
                res.x = self.x + (distance2 * cos(self.orientation))
                res.y = self.y + (distance2 * sin(self.orientation))
                res.orientation = (self.orientation + turn) % (2.0 * pi)
            else:
                # approximate bicycle model for motion
                radius = distance2 / turn
                cx = self.x - (sin(self.orientation) * radius)
                cy = self.y + (cos(self.orientation) * radius)
                res.orientation = (self.orientation + turn) % (2.0 * pi)
                res.x = cx + (sin(res.orientation) * radius)
                res.y = cy - (cos(res.orientation) * radius)

            return res 
Example 77
Project: rucio   Author: rucio   File: generateDatasetsforPanda.py    Apache License 2.0 4 votes vote down vote up
def populateDB():
    listrses = list_rses({'T1': '1'})
    print len(listrses), listrses
    # listrses = list_rses()
    # print len(listrses), listrses
    # sys.exit()
    account = 'root'
    project = 'mc12_8TeV'

    dictDistrib = [{'datatype': 'HITS', 'prodstep': 'merge', 'nbfiles': 302, 'totfilesize': 225394185112, 'nbreplicas': 1}, {'datatype': 'HITS', 'prodstep': 'simul', 'nbfiles': 620, 'totfilesize': 97930909866, 'nbreplicas': 1},
                   {'datatype': 'EVNT', 'prodstep': 'evgen', 'nbfiles': 324, 'totfilesize': 7809298802, 'nbreplicas': 3}, {'datatype': 'AOD', 'prodstep': 'merge', 'nbfiles': 52, 'totfilesize': 106942334943, 'nbreplicas': 4},
                   {'datatype': 'AOD', 'prodstep': 'recon', 'nbfiles': 858, 'totfilesize': 182186965627, 'nbreplicas': 1}]

    for d in dictDistrib:
        for day in xrange(0, 180):
            for i in xrange(0, 30):
                scope = project
                prod_step = d['prodstep']
                datatype = d['datatype']
                nbfiles = int(d['nbfiles'])
                filesize = int(int(d['totfilesize']) / float(nbfiles))
                nbfiles = int(random.gauss(nbfiles, nbfiles / 10))
                filesize = int(random.gauss(filesize, filesize / 10))
                nbreplicas = int(d['nbreplicas'])
                dataset_meta = {'project': project, 'stream_name': 'dummy', 'prod_step': prod_step, 'datatype': datatype}
                source_rses = []
                if nbreplicas:
                    iter = 0
                    while (len(source_rses) != nbreplicas and iter != 100):
                        rnd_site = random.choice(listrses)
                        iter += 1
                        if rnd_site not in source_rses:
                            source_rses.append(rnd_site)

                    try:
                        dsn = '%s.%s.%s.%i.%i' % (project, prod_step, datatype, day, i)
                        print '%i Creating %s with %i files of size %i located at %i sites' % (i, dsn, nbfiles, filesize, len(source_rses))
                        add_identifier(scope=scope, name=dsn, type='dataset', issuer=account, statuses={'monotonic': True}, meta=dataset_meta)
                        files = ['file_%s' % uuid() for i in xrange(nbfiles)]
                        listfiles = []
                        for file in files:
                            listfiles.append({'scope': scope, 'name': file, 'size': filesize})
                            for source_rse in source_rses:
                                add_file_replica(source_rse, scope, file, filesize, issuer=account)
                        attach_identifier(scope, name=dsn, dids=listfiles, issuer=account)
                        for source_rse in source_rses:
                            try:
                                add_replication_rule(dids=[{'scope': scope, 'name': dsn}], account=account, copies=1, rse_expression=source_rse,
                                                     grouping='DATASET', weight=None, lifetime=None, locked=False, subscription_id=None, issuer='root')
                            except InvalidReplicationRule, e:
                                print e
                    except RucioException, e:
                        print e


# createRSEs()
# createMetadata() 
Example 78
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Racetrack_Control.py    MIT License 4 votes vote down vote up
def move(self, steering, distance,
             tolerance=0.001, max_steering_angle=pi / 4.0):

        if steering > max_steering_angle:
            steering = max_steering_angle
        if steering < -max_steering_angle:
            steering = -max_steering_angle
        if distance < 0.0:
            distance = 0.0

        # make a new copy
        res = robot()
        res.length = self.length
        res.steering_noise = self.steering_noise
        res.distance_noise = self.distance_noise
        res.steering_drift = self.steering_drift

        # apply noise
        steering2 = random.gauss(steering, self.steering_noise)
        distance2 = random.gauss(distance, self.distance_noise)

        # apply steering drift
        steering2 += self.steering_drift

        # Execute motion
        turn = tan(steering2) * distance2 / res.length

        if abs(turn) < tolerance:

            # approximate by straight line motion

            res.x = self.x + (distance2 * cos(self.orientation))
            res.y = self.y + (distance2 * sin(self.orientation))
            res.orientation = (self.orientation + turn) % (2.0 * pi)

        else:

            # approximate bicycle model for motion

            radius = distance2 / turn
            cx = self.x - (sin(self.orientation) * radius)
            cy = self.y + (cos(self.orientation) * radius)
            res.orientation = (self.orientation + turn) % (2.0 * pi)
            res.x = cx + (sin(res.orientation) * radius)
            res.y = cy - (cos(res.orientation) * radius)

        return res 
Example 79
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Fun_with_Parameters.py    MIT License 4 votes vote down vote up
def move(self, grid, steering, distance,
             tolerance=0.001, max_steering_angle=pi / 4.0):

        if steering > max_steering_angle:
            steering = max_steering_angle
        if steering < -max_steering_angle:
            steering = -max_steering_angle
        if distance < 0.0:
            distance = 0.0

        # make a new copy
        res = robot()
        res.length = self.length
        res.steering_noise = self.steering_noise
        res.distance_noise = self.distance_noise
        res.measurement_noise = self.measurement_noise
        res.num_collisions = self.num_collisions
        res.num_steps = self.num_steps + 1

        # apply noise
        steering2 = random.gauss(steering, self.steering_noise)
        distance2 = random.gauss(distance, self.distance_noise)

        # Execute motion
        turn = tan(steering2) * distance2 / res.length

        if abs(turn) < tolerance:

            # approximate by straight line motion

            res.x = self.x + (distance2 * cos(self.orientation))
            res.y = self.y + (distance2 * sin(self.orientation))
            res.orientation = (self.orientation + turn) % (2.0 * pi)

        else:

            # approximate bicycle model for motion

            radius = distance2 / turn
            cx = self.x - (sin(self.orientation) * radius)
            cy = self.y + (cos(self.orientation) * radius)
            res.orientation = (self.orientation + turn) % (2.0 * pi)
            res.x = cx + (sin(res.orientation) * radius)
            res.y = cy - (cos(res.orientation) * radius)

        # check for collision
        # res.check_collision(grid)

        return res

    # --------
    # sense:
    # 
Example 80
Project: AI-for-Robotics-CS373   Author: zhao-zh10   File: Final_Quiz.py    MIT License 4 votes vote down vote up
def move(self, motion, tolerance = 0.001):  # Do not change the name of this function

        # ADD CODE HERE
        steering_angle = motion[0]
        distance = motion[1]

        if abs(steering_angle) > max_steering_angle:
            raise(ValueError, 'Exceeding max steering angle of a real car.')

        if distance < 0.0:
            raise(ValueError, 'Moving backwards is not valid.')

        # apply noise
        steering_angle_2 = random.gauss(steering_angle, self.steering_noise)
        distance_2 = random.gauss(distance, self.distance_noise)

        # Execute motion
        turn = distance_2 / self.length * tan(steering_angle_2)
        if abs(turn) < tolerance:
            # approximate by straight line motion
            new_x = self.x + distance_2 * cos(self.orientation)
            new_y = self.y + distance_2 * sin(self.orientation)
            new_orientation = (self.orientation + turn) % (2.0 * pi)
        else:
            # approximate bicycle model for motion
            radius = distance_2 / turn
            cx = self.x - sin(self.orientation) * radius
            cy = self.y + cos(self.orientation) * radius
            new_x = cx + sin(self.orientation + turn) * radius
            new_y = cy - cos(self.orientation + turn) * radius
            new_orientation = (self.orientation + turn) % (2.0 * pi)

        # make a new copy
        result = robot(self.length)
        result.set(new_x, new_y, new_orientation)
        result.set_noise(self.bearing_noise, self.steering_noise, self.distance_noise)
        return result  # make sure your move function returns an instance
        # of the robot class with the correct coordinates.

    # --------
    # sense:
    #

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