Python random.triangular() Examples

The following are code examples for showing how to use random.triangular(). 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: synthetic-data-tutorial   Author: theodi   File: generate.py    MIT License 6 votes vote down vote up
def generate_arrival_times() -> list:
    """ Generate and return arrival times.
        Hardcoding times to first week of April 2019
    """
    arrival_times = []

    # first 7 days in April 2019
    days_dates = [1, 2, 3, 4, 5, 6, 7]
    # have more people come in at the weekend - higher weights 
    day_weights = [0.5, 0.6, 0.7, 0.8, 0.9, 1, 1]
    days = random.choices(days_dates, day_weights, k=num_of_rows)
    # this is just so each day has a different peak time
    days_time_modes = {day: random.random() for day in days_dates}

    for day in days:
        start = datetime(2019, 4, day, 00, 00, 00)
        end = datetime(2019, 4, day, 23, 59, 59)

        random_num = random.triangular(0, 1, days_time_modes[day])
        random_datetime = start + (end - start) * random_num
        arrival_times.append(random_datetime.strftime('%Y-%m-%d %H:%M:%S'))

    return arrival_times 
Example 2
Project: cbeams   Author: tartley   File: animate.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, color):
        self.color = color # as an integer

        # Center point.
        self.y, self.x = terminal.rand_coord()

        # The max radius we will reach.
        term_size = terminal.get_max_dimension()
        self.size = 2 + min(term_size * 2, random.expovariate(32 / term_size))

        # How close 'outer' gets to its max size before 'inner' starts to grow.
        # From 0 to 1
        self.thickness = random.triangular(0.3, 0.95)

        # Outer and inner radii.
        self.outer = 0.0
        self.inner = 0.0
        # The value of 'inner' on the last frame.
        self.inner_last = self.inner 
Example 3
Project: levis   Author: rawg   File: knapsack01.py    MIT License 6 votes vote down vote up
def create_data(config={}):
    """Create data and write to a JSON file."""
    max_weight = config.setdefault("max_weight", 15)
    items = []

    if "num_items" in config:
        num_items = config["num_items"]
        del config["num_items"]
    else:
        num_items = 32

    # Generate items
    digits = int(math.ceil(math.log(num_items, 16)))
    fmt = "%0" + str(digits) + "X"

    for i in range(0, num_items):
        name = fmt % (i + 1)
        weight = random.triangular(1.0, max_weight // 3, max_weight)
        value = random.random() * 100

        items.append({"name": name, "weight": weight, "value": value})

    config["items"] = items

    configuration.write_file(config) 
Example 4
Project: levis   Author: rawg   File: crossover.py    MIT License 6 votes vote down vote up
def single_point(parent1, parent2, locus=None):
    """Return a new chromosome created with single-point crossover.

    This is suitable for use with list or value encoding, and will work with
    chromosomes of heterogenous lengths.

    Args:
        parent1 (List): A parent chromosome.
        parent2 (List): A parent chromosome.
        locus (int): The locus at which to crossover or ``None`` for a randomly
            selected locus.

    Returns:
        List[List]: Two new chromosomes descended from the given parents.
    """
    if len(parent1) > len(parent2):
        parent1, parent2 = parent2, parent1

    if locus is None:
        locus = int(random.triangular(1, len(parent1) / 2, len(parent1) - 2))

    child1 = parent1[0:locus] + parent2[locus:]
    child2 = parent2[0:locus] + parent1[locus:]

    return [child1, child2] 
Example 5
Project: levis   Author: rawg   File: crossover.py    MIT License 6 votes vote down vote up
def cut_and_splice(parent1, parent2, loci=None):
    """Return a new chromosome created with cut and splice crossover.

    This is suitable for use with list or value encoding, and will work with
    chromosomes of heterogeneous lengths.

    Args:
        parent1 (List): A parent chromosome.
        parent2 (List): A parent chromosome.
        loci (Tuple[int, int]): A crossover locus for each parent.

    Returns:
        List[List]: Two new chromosomes descended from the given parents.
    """
    if loci is None:
        loci = []
        loci[0] = int(random.triangular(1, len(parent1) / 2, len(parent1) - 2))
        loci[1] = int(random.triangular(1, len(parent2) / 2, len(parent2) - 2))

    child1 = parent1[0:loci[0]] + parent2[loci[0]:]
    child2 = parent2[0:loci[1]] + parent1[loci[1]:]

    return [child1, child2] 
Example 6
Project: evmlab   Author: ethereum   File: code.py    GNU General Public License v3.0 6 votes vote down vote up
def random_code_byte_sequence(self, length=None):
        # todo: add gauss histogramm random.randgauss(min,max,avg) - triangle is not really correct here
        length = length or int(random.triangular(self.MIN_CONTRACT_SIZE, 2 * self.AVERAGE_CONTRACT_SIZE + self.MIN_CONTRACT_SIZE))  # use gauss

        rnd_prolog = WeightedRandomizer(self.LIKELYHOOD_PROLOG_BY_OPCODE_INT)
        rnd_epilog = WeightedRandomizer(self.LIKELYHOOD_EPILOG_BY_OPCODE_INT)  # not completely true as this incorps. pro/epilog
        rnd_corpus = WeightedRandomizer(self.LIKELYHOOD_BY_OPCODE_INT)

        b = []
        for _ in range(128):
            b.append(rnd_prolog.random())
        for _ in range(length - 128 * 2):
            b.append(rnd_corpus.random())
        for _ in range(128):
            b.append(rnd_epilog.random())

        return bytes(b) 
Example 7
Project: identifiera-sarkasm   Author: risnejunior   File: preprocess_data.py    GNU General Public License v3.0 6 votes vote down vote up
def modify_samples(samples, random_data, add_snitch, random_labels):
	minval = 1
	maxval = cfg.vocabulary_size - 1
	pb = Progress_bar(len(samples)-1)
	for sample in samples:

		int_vector = sample['int_vector']
		sample_class = sample['sample_class']

		if random_data:
			int_vector = [rt(minval, maxval) for _ in range(cfg.max_sequence)] 
		
		if add_snitch: 
			int_vector.extend([cfg.vocabulary_size-1])

		if random_labels:
			sample_class = random.randint(1,2)

		
		sample['int_vector'] = int_vector
		sample['sample_class'] = sample_class
		pb.tick() 
Example 8
Project: kingpin   Author: pinterest   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _get_waiting_in_secs(waiting_in_secs,
                             num_retries,
                             max_waiting_in_secs):
        """Retrieve the waiting time in seconds.

        This method uses exponential back-off in figuring out the number of
        seconds to wait; however, the max wait time shouldn't be more than
        what is specified via max_waiting_in_seconds.

        Args:
            waiting_in_secs: waiting time in seconds.
            num_retries: number of retries, starting from 0.
            max_waiting_in_secs: maximum waiting time in seconds.

        Returns:
            The number of seconds to wait.

        """
        # make the backoff going up even faster
        waiting_in_secs *= 2**num_retries
        jitter = waiting_in_secs * 0.2
        waiting_in_secs += random.triangular(-jitter, jitter)
        return min(waiting_in_secs, max_waiting_in_secs) 
Example 9
Project: svim   Author: eldariont   File: test_Collect.py    GNU General Public License v3.0 6 votes vote down vote up
def generate_random_cigar_string(self, readlength):
        """Generate random cigar string for a read of a given length. Simulate small mismatches and indels but nothing larger than 10bp."""
        softclip_left = round(triangular(0, readlength, min(1000, readlength * 0.5)))
        non_clipped = readlength - softclip_left
        softclip_right = round(triangular(0, non_clipped, min(1000, non_clipped * 0.5)))
        non_clipped = readlength - softclip_left - softclip_right
        sequence = ""
        read_bases_consumed = 0
        while read_bases_consumed < non_clipped:
            #choose next operation
            if len(sequence) == 0 or sequence[-1] == "I" or sequence[-1] == "D":
                next_operation = "M"
                next_length = round(triangular(1, non_clipped - read_bases_consumed, min(30, non_clipped - read_bases_consumed)))
                read_bases_consumed += next_length
            else:
                next_operation = choice("ID")
                if next_operation == "I":
                    next_length = round(triangular(1, min(10, non_clipped - read_bases_consumed), 1))
                    read_bases_consumed += next_length
                else:
                    next_length = round(triangular(1, 10, 1))
            sequence += str(next_length) + next_operation
        return "{0}S{1}{2}S".format(softclip_left, sequence, softclip_right) 
Example 10
Project: svim   Author: eldariont   File: test_Collect.py    GNU General Public License v3.0 6 votes vote down vote up
def generate_random_cigar_string_hardclipped(self, readlength):
        """Generate random cigar string for a read of a given length.
        Simulate small mismatches and indels but nothing larger than 10bp. Simulate hard-clipping and return tuple (left-clipped, right-clipped, cigar)"""
        hardclip_left = round(triangular(0, readlength, min(1000, readlength * 0.5)))
        non_clipped = readlength - hardclip_left
        hardclip_right = round(triangular(0, non_clipped, min(1000, non_clipped * 0.5)))
        non_clipped = readlength - hardclip_left - hardclip_right
        sequence = ""
        read_bases_consumed = 0
        while read_bases_consumed < non_clipped:
            #choose next operation
            if len(sequence) == 0 or sequence[-1] == "I" or sequence[-1] == "D":
                next_operation = "M"
                next_length = round(triangular(1, non_clipped - read_bases_consumed, min(30, non_clipped - read_bases_consumed)))
                read_bases_consumed += next_length
            else:
                next_operation = choice("ID")
                if next_operation == "I":
                    next_length = round(triangular(1, min(10, non_clipped - read_bases_consumed), 1))
                    read_bases_consumed += next_length
                else:
                    next_length = round(triangular(1, 10, 1))
            sequence += str(next_length) + next_operation
        return (hardclip_left, hardclip_right, "{0}H{1}{2}H".format(hardclip_left, sequence, hardclip_right)) 
Example 11
Project: midlevel-reps   Author: alexsax   File: poisson_disc.py    MIT License 6 votes vote down vote up
def generate(self, point):
        """
        generates new points
        in an annulus between
        self.r, 2*self.r
        """

        rad = random.triangular(self.r, 2*self.r, .3*(2*self.r - self.r))
        # was random.uniform(self.r, 2*self.r) but I think
        # this may be closer to the correct distribution
        # but easier to build

        angs = [random.uniform(0, 2*pi)]

        if self.dim > 2:
            angs.extend(random.uniform(-pi/2, pi/2) for _ in range(self.dim-2))

        angs[0] = 2*angs[0]

        return self.convert(point, rad, angs) 
Example 12
Project: team-formation-study-software   Author: NDykhuis   File: agentgroup.py    GNU General Public License v2.0 5 votes vote down vote up
def randbiases(self):
    """Assign bias to each neighbor edge randomly"""
    for n in self.nbrs:
      #self.bias[n] = np.random.normal()    # does not use the same random seed
      # multiplier for utility of working with someone
      bias = random.triangular(1.0, self.cfg.biasrange, 1.0)
      bias = bias**random.choice((-1.0, 1.0))
      self.bias[n.id] = bias 
Example 13
Project: otreeutils   Author: WZBSocialScienceCenter   File: models.py    Apache License 2.0 5 votes vote down vote up
def creating_session(self):   # oTree 2 method name (used to be before_session_starts)
        if self.round_number == 1:
            # for each player, set a random initial balance in the first round
            for p in self.get_players():
                p.initial_balance = c(random.triangular(1, 20, 10))
                p.balance = p.initial_balance 
Example 14
Project: HyperStream   Author: IRC-SPHERE   File: 2017-06-20_v1.0.0.py    MIT License 5 votes vote down vote up
def _execute(self, sources, alignment_stream, interval):
        if alignment_stream is None:
            raise ToolExecutionError("Alignment stream expected")

        for ti, _ in alignment_stream.window(interval, force_calculation=True):
            yield StreamInstance(ti, random.triangular(low=self.low, high=self.high, mode=self.mode)) 
Example 15
Project: tracegen   Author: secworks   File: tracegen.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_index(num_samples):
    return int((num_samples * DIFF_POS) + random.triangular(-RAND_DIFF_WIDTH, RAND_DIFF_WIDTH))


#-------------------------------------------------------------------
# get_base_samples()
#
# Generate a trace wit num_samples. The values in the samples
# simulates the average base noise level.
#------------------------------------------------------------------- 
Example 16
Project: levis   Author: rawg   File: crossover.py    MIT License 5 votes vote down vote up
def single_point_bin(parent1, parent2, length=None, locus=None):
    """Return a new chromosome through a single-point crossover.

    This is suitable for use with binary encoding.

    Args:
        parent1 (List): A parent chromosome.
        parent2 (List): A parent chromosome.
        locus (int): The crossover point or ``None`` to choose one at random.
            If ``None``, then ``length`` must be the number of bits used in the
            parent chromosomes.
        length(int): The number of bits used. Not used if a locus is provided.

    Returns:
        List[int]: Two new chromosomes descended from the given parents.

    Raises:
        ValueError: if neither ``locus`` or ``length`` is specified.
    """

    if locus is None and length is None:
        raise ValueError("Either the length or a locus is required.")

    if locus is None:
        locus = int(random.triangular(1, length / 2, length - 2))

    if length is None:
        length = 2 * locus

    maskr = 2 ** locus - 1
    maskl = (2 ** length - 1) & ~maskr

    child1 = parent1 & maskl | parent2 & maskr
    child2 = parent2 & maskl | parent1 & maskr

    return [child1, child2] 
Example 17
Project: Simulations   Author: harrymunro   File: termini_simulation_animation.py    MIT License 5 votes vote down vote up
def dwell():
	# a few different options here - lognormal is normally most representative of human error and general dwell times
	#t = random.randint(120, 240) # uniformly distributed
        t = random.lognormvariate(math.log(dwelltime), 1) # lognormally distributed
        #t = random.triangular(dwelltime * 0.9, dwelltime * 1.1, dwelltime) # triangular distribution (low, high, mid)
        #t = dwelltime # fixed dwell
	return t

# define empty dictionary 
Example 18
Project: evmlab   Author: ethereum   File: codesmart.py    GNU General Public License v3.0 5 votes vote down vote up
def random_code_byte_sequence(self, length=None):
        # todo: add gauss histogramm random.randgauss(min,max,avg) - triangle is not really correct here
        length = length or int(random.triangular(self.MIN_CONTRACT_SIZE, 2 * self.AVERAGE_CONTRACT_SIZE + self.MIN_CONTRACT_SIZE))  # use gauss

        b = [random.choice(constantinople_skewed_set) for _ in range(length)]

        return bytes(b) 
Example 19
Project: remorse   Author: joe-ds   File: general-transmit.py    GNU General Public License v3.0 5 votes vote down vote up
def makedata():
    '''Generates the necessary "data"'''
    coord = (random.triangular((-90),90,0), random.triangular((-180),180,0))
    names = ['J.B.', 'E.A.', 'K.M.', 'D.M', 'W.R.']
    actions = ['EAD', 'TAR', 'OAE', 'AD']
    name = random.choice(names)
    action = random.choice(actions)

    pcoord = "{:6f}\t{:6f}\n{} :: {}".format(coord[0], coord[1], name, action)
    return pcoord 
Example 20
Project: ishihara_generator   Author: franciscouzo   File: ishihara.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_circle(image_width, image_height, min_diameter, max_diameter):
    radius = random.triangular(min_diameter, max_diameter,
                               max_diameter * 0.8 + min_diameter * 0.2) / 2

    angle = random.uniform(0, math.pi * 2)
    distance_from_center = random.uniform(0, image_width * 0.48 - radius)
    x = image_width  * 0.5 + math.cos(angle) * distance_from_center
    y = image_height * 0.5 + math.sin(angle) * distance_from_center

    return x, y, radius 
Example 21
Project: pygame-pal   Author: pygametoys   File: battle.py    GNU General Public License v3.0 5 votes vote down vote up
def calc_magic_damage(
        self,
        magic_strength,
        defense,
        elemental_resistance,
        poison_resistance,
        resistance_multiplier,
        magic_id
    ):
        magic_id = self.objects[magic_id].magic.magic_number
        magic_strength *= random.triangular(10, 11)
        magic_strength //= 10
        damage = self.calc_base_damage(magic_strength, defense)
        damage //= 4
        damage += self.magics[magic_id].base_damage
        if self.magics[magic_id].elemental != 0:
            elem = self.magics[magic_id].elemental
            if elem > NUM_MAGIC_ELEMENTAL:
                damage *= 10 - poison_resistance / resistance_multiplier
            elif elem == 0:
                damage *= 5
            else:
                damage *= 10 - elemental_resistance[elem - 1] / resistance_multiplier
            damage = int(round(damage / 5))
            if elem <= NUM_MAGIC_ELEMENTAL:
                damage *= 10 + self.battle_fields[self.num_battle_field].magic_effect[elem - 1]
                damage //= 10
        return damage 
Example 22
Project: identifiera-sarkasm   Author: risnejunior   File: common_funs.py    GNU General Public License v3.0 5 votes vote down vote up
def generate(self, minval, maxval, steps):
		vals = [round(rt(minval, maxval), 5) for _ in range(steps)]
		for val in vals:
			yield val 
Example 23
Project: kingpin   Author: pinterest   File: hosts.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, host_provider, expire_time=600, retry_time=60,
                 invalidation_threshold=0.2):
        """Initialize the host selection.

        Args:
            host_provider: A ``HostProvider``, used to get the current list
                of live hosts.
            expire_time: An integer, expire time in seconds.
            retry_time: An integer, retry time in seconds.
            invalidation_threshold: A float, when the number of entries
                being invalidated divided by the number of all valid hosts
                is above this threshold, we stop accepting invalidation
                requests. We do this to stay on the conservative side to
                avoid invalidating hosts too fast to starve requests.

        """
        assert host_provider.initialized
        # Current host.
        self._current = None
        # Last host, works even when current host invalided.
        self._last = None
        # Time when we selected the current host.
        self._select_time = None
        # Adjust expire time by +/- 10%, but 0 is special for testing purpose.
        self._expire_time = expire_time
        if expire_time:
            self._expire_time = expire_time + int(
                random.triangular(-expire_time * 0.1, expire_time * 0.1))
        self._retry_time = retry_time
        self._invalidation_threshold = invalidation_threshold
        # Host name -> time when marked bad.
        self._bad_hosts = {}
        self._host_provider = host_provider 
Example 24
Project: PSiTE   Author: hchyang   File: __sub_wessim2.py    GNU General Public License v3.0 5 votes vote down vote up
def pickFragment(pickedproberegion, ins, bind):
    probechrom = pickedproberegion[1]
    probestart = int(pickedproberegion[2])
    probeend = int(pickedproberegion[3])
    probelength = probeend - probestart
    minimummatch = int(probelength * bind / 100)
    overlap = int(random.triangular(minimummatch, probelength, probelength))
    margin = max(ins - overlap, 0)
    rangestart = probestart - margin
    rangeend = probeend + margin
    seqstart = random.randint(rangestart, rangeend - ins)
    return probechrom, seqstart, seqstart + ins 
Example 25
Project: MyInsightRepo   Author: PseudoAj   File: gas.py    MIT License 5 votes vote down vote up
def genGasRow(self,rcrdDict,startTime,endTime):

        # variable to store the row
        curRcrd = []

        # get all the attributes
        service_id = rcrdDict.get('service_id')
        user_name = rcrdDict.get('user_name')
        type = rcrdDict.get('type')
        strtTime = rcrdDict.get('strtTime')
        state = rcrdDict.get('state')
        consumption = float(random.triangular(0,0.00045))

        # append the attributes to one list
        curRcrd.append(service_id)
        curRcrd.append(user_name)
        curRcrd.append(type)
        curRcrd.append(startTime)
        curRcrd.append(state)
        curRcrd.append(consumption)
        curRcrd.append(endTime)

        # return the list
        return curRcrd

    # Method to write the data into kafka 
Example 26
Project: MyInsightRepo   Author: PseudoAj   File: electricity.py    MIT License 5 votes vote down vote up
def genElecRow(self,rcrdDict,startTime,endTime):

        # variable to store the row
        curRcrd = []

        # get all the attributes
        service_id = rcrdDict.get('service_id')
        user_name = rcrdDict.get('user_name')
        type = rcrdDict.get('type')
        strtTime = rcrdDict.get('strtTime')
        state = rcrdDict.get('state')
        consumption = float(random.triangular(0,0.30))

        # append the attributes to one list
        curRcrd.append(service_id)
        curRcrd.append(user_name)
        curRcrd.append(type)
        curRcrd.append(startTime)
        curRcrd.append(state)
        curRcrd.append(consumption)
        curRcrd.append(endTime)

        # return the list
        return curRcrd

    # Method to write the data into kafka 
Example 27
Project: MyInsightRepo   Author: PseudoAj   File: water.py    MIT License 5 votes vote down vote up
def genWtrRow(self,rcrdDict,startTime,endTime):

        # variable to store the row
        curRcrd = []

        # get all the attributes
        service_id = rcrdDict.get('service_id')
        user_name = rcrdDict.get('user_name')
        type = rcrdDict.get('type')
        strtTime = rcrdDict.get('strtTime')
        state = rcrdDict.get('state')
        consumption = float(random.triangular(0,0.023))

        # append the attributes to one list
        curRcrd.append(service_id)
        curRcrd.append(user_name)
        curRcrd.append(type)
        curRcrd.append(startTime)
        curRcrd.append(state)
        curRcrd.append(consumption)
        curRcrd.append(endTime)

        # return the list
        return curRcrd

    # Method to write the data into kafka 
Example 28
Project: MyInsightRepo   Author: PseudoAj   File: electricity.py    MIT License 5 votes vote down vote up
def genElecRow(self,rcrdDict,startTime,endTime):

        # variable to store the row
        curRcrd = []

        # get all the attributes
        service_id = rcrdDict.get('service_id')
        user_name = rcrdDict.get('user_name')
        type = rcrdDict.get('type')
        strtTime = rcrdDict.get('strtTime')
        state = rcrdDict.get('state')
        consumption = float(random.triangular(0,0.30))

        # append the attributes to one list
        curRcrd.append(service_id)
        curRcrd.append(user_name)
        curRcrd.append(type)
        curRcrd.append(startTime)
        curRcrd.append(state)
        curRcrd.append(consumption)
        curRcrd.append(endTime)

        # return the list
        return curRcrd



    # Method to generate the hashmaps 
Example 29
Project: MyInsightRepo   Author: PseudoAj   File: generator.py    MIT License 5 votes vote down vote up
def genRow(self,rcrdDict,startTime,endTime):

        # variable to store the row
        curRcrd = []

        # determine the consumptionrate
        if self.topic == "gas":
            cnsmptnRate = 0.00045
        elif self.topic == "water":
            cnsmptnRate = 0.023
        else:
            cnsmptnRate = 0.30

        # get all the attributes
        service_id = rcrdDict.get('service_id')
        user_name = rcrdDict.get('user_name')
        type = rcrdDict.get('type')
        strtTime = rcrdDict.get('strtTime')
        state = rcrdDict.get('state')
        consumption = float(random.triangular(0,float(cnsmptnRate)))

        # append the attributes to one list
        curRcrd.append(service_id)
        curRcrd.append(user_name)
        curRcrd.append(type)
        curRcrd.append(startTime)
        curRcrd.append(state)
        curRcrd.append(consumption)
        curRcrd.append(endTime)

        # return the list
        return curRcrd

    # Method to write the data to a certain file 
Example 30
Project: svim   Author: eldariont   File: test_Collect.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_read(self, qname, flag):
        rname = "chr1"
        pos = int(uniform(1,249250620))
        mapq = int(triangular(0, 60, 50))
        length = int(triangular(100, 20000, 15000))
        cigar = self.generate_random_cigar_string(length)
        seq = self.generate_random_sequence(length)

        read_info = (qname, flag, rname, pos, mapq, cigar, "*", 0, 0, seq, "*", "")

        return read_info 
Example 31
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_rate():
    import random
    return random.random() * random.triangular(100,1000,100) 
Example 32
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_age():
    import random
    return int(random.triangular(15,90,35)) 
Example 33
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_rating():
    import random
    return int(random.triangular(1,10,6)) 
Example 34
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_state():
    import random
    return ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'][int(random.triangular(0,49,2))] 
Example 35
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_name():
    import random
    return ['Frank','Dean','Dan','Sammy','James','Andrew','Scott','Steven','Kristen','Stephen','William','Craig','Stacy','Stuart','Christopher','Alan','Megan','Brian','Kevin','Kate','Molly','Derek','Martin','Thomas','Neil','Barry','Ian','Ashley','Iain','Gordon','Alexander','Graeme','Peter','Darren','Graham','George','Kenneth','Allan','Lauren','Douglas','Keith','Lee','Katy','Grant','Ross','Jonathan','Gavin','Nicholas','Joseph','Stewart'][int(random.triangular(0,49,2))] 
Example 36
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_age():
    import random
    return int(random.triangular(15,90,35)) 
Example 37
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_rating():
    import random
    return int(random.triangular(1,10,6)) 
Example 38
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_state():
    import random
    return ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'][int(random.triangular(0,49,2))] 
Example 39
Project: IAA_Sessions   Author: zaratsian   File: spark_test_script.py    MIT License 5 votes vote down vote up
def sim_name():
    import random
    return ['Frank','Dean','Dan','Sammy','James','Andrew','Scott','Steven','Kristen','Stephen','William','Craig','Stacy','Stuart','Christopher','Alan','Megan','Brian','Kevin','Kate','Molly','Derek','Martin','Thomas','Neil','Barry','Ian','Ashley','Iain','Gordon','Alexander','Graeme','Peter','Darren','Graham','George','Kenneth','Allan','Lauren','Douglas','Keith','Lee','Katy','Grant','Ross','Jonathan','Gavin','Nicholas','Joseph','Stewart'][int(random.triangular(0,49,2))] 
Example 40
Project: dungeonRunner   Author: spheppner   File: dungeonRunner.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pos, maxspeed=150, minspeed=20, color=(255,255,0),maxduration=2.5,gravityy=3.7,sparksmin=5,sparksmax=20, a1=0,a2=360):

        for s in range(random.randint(sparksmin,sparksmax)):
            v = pygame.math.Vector2(1,0) # vector aiming right (0°)
            a = random.triangular(a1,a2)
            v.rotate_ip(a)
            g = pygame.math.Vector2(0, - gravityy)
            speed = random.randint(minspeed, maxspeed)     #150
            duration = random.random() * maxduration
            Spark(pos=pygame.math.Vector2(pos.x, pos.y), angle=a, move=v*speed,
                  max_age = duration, color=color, gravity = g) 
Example 41
Project: team-formation-study-software   Author: NDykhuis   File: graph.py    GNU General Public License v2.0 4 votes vote down vote up
def initagents(self):
    """Initialize agents and edges with skills and attributes."""
    cfg = self.cfg
    n = cfg.n
    G = self.G
    
    if cfg.skillseed is not None:
      currstate = random.getstate()
      random.seed(cfg.skillseed)
    
    for n, dat in G.nodes_iter(data=True):
      # Set attributes of the agent
      dat['id'] = n
      dat['group'] = n      # Agent is its own group
      dat['switches'] = 0
      dat['nowpay'] = 0
    
      # Set skills
      lev = random.randint(1, min(cfg.nskills, cfg.maxskills))
      skills = [1]*lev + [0]*(cfg.nskills-lev)
      random.shuffle(skills)
      dat['skills'] = skills
    
      dat['acceptances'] = []
      
    # Set weight on edges and bias
    for _, _, edat in G.edges(data=True):
      #edat['weight'] = 0.0
      #edat['weight'] = random.triangular(-4.0, 4.0, 0.0)
      #edat['weight'] = random.random()
      edat['weight'] = 1.0
      
      edat['bias'] = random.triangular(-2.0, 2.0, 0.0)
      
      ## NOTE THAT THIS WILL ONLY WORK WITH MUTUAL BIAS
      #self.bias[n] = np.random.normal()    # does not use the same random seed
      #edat['bias'] = random.triangular(1.0, cfg.biasrange, 1)**random.choice((-1.0, 1.0))   # multiplier for utility of working with someone
    
    if cfg.skillseed is not None:
      random.setstate(currstate)
    
    skills = [0]*cfg.nskills
    for n, dat in G.nodes_iter(data=True):
      askill = dat['skills']
      for i in range(len(skills)):
        skills[i] += askill[i]
    print "Total skills:", skills
      
    for n, dat in G.nodes_iter(data=True):
      # Calculate agent value based on the default task structure
      dat['worth'] = sum( [(i+1)*10*dat['skills'][i] for i in range(cfg.nskills)] ) 
Example 42
Project: levis   Author: rawg   File: seatingchart.py    MIT License 4 votes vote down vote up
def render(self, chromosome, filepath):
        """Render a chromosome to an SVG file."""
        import svgwrite

        margin = 100
        unit = 200
        radius = 50
        pad = 10

        width = (self.width + 1) * unit + margin * 2
        height = (self.height + 1) * unit + margin * 2

        doc = svgwrite.Drawing(filename=filepath, size=(width, height))

        # Color theme to match the talk...
        colors = ["#ff9999", "#9999ff", "#99ff99", "#ffffff"]

        # Fill colors at random
        def channel():
            return int(random.triangular(0, 255, 175))

        while len(colors) < len(self.roles):
            colors.append("#%02x%02x%02x" % (channel(), channel(), channel()))

        # Map row, col to pixels
        def origin(row, col):
            x = row * unit + margin
            y = col * unit + margin
            return (x, y)

        def color_of_group(group):
            idx = self.roles.index(group)
            return colors[idx]

        def color_of_person(person_id):
            group = self.people[person_id][1]
            return color_of_group(group)

        # Render seating assignments
        for seat, person in enumerate(chromosome):
            row, col = self.map.point_at(seat)

            x, y = origin(row, col)
            x, y = (x + radius, y + radius)

            doc.add(doc.circle(
                center=(x, y),
                r=radius,
                stroke_width=8,
                stroke="#000",
                fill=color_of_person(person)
            ))

        doc.save()

# pylint: disable=too-many-locals 
Example 43
Project: svim   Author: eldariont   File: test_Collect.py    GNU General Public License v3.0 4 votes vote down vote up
def generate_split_read_with_sa_tags(self, qname, flag):
        length = int(triangular(100, 20000, 15000))
        seq = self.generate_random_sequence(length)

        suppl_rname = "chr1"
        suppl_pos = int(uniform(1,249250620))
        suppl_mapq = int(triangular(0, 60, 50))
        suppl_hardclipped_left, suppl_hardclipped_right, suppl_cigar = self.generate_random_cigar_string_hardclipped(length)

        prim_rname = "chr1"
        prim_pos = int(uniform(1,249250620))
        prim_mapq = int(triangular(0, 60, 50))
        prim_cigar = self.generate_random_cigar_string(length)

        supplementary_read_info = ( qname,
                                    flag + 2048,
                                    suppl_rname,
                                    suppl_pos,
                                    suppl_mapq,
                                    suppl_cigar,
                                    "*",
                                    0,
                                    0,
                                    seq[suppl_hardclipped_left:-suppl_hardclipped_right],
                                    "*",
                                    "SA:Z:{rname},{pos},{strand},{cigar},{mapq},{nm};".format(rname=prim_rname,
                                                                                              pos=prim_pos,
                                                                                              strand=("-" if flag & 16 else "+"),
                                                                                              cigar=prim_cigar,
                                                                                              mapq=prim_mapq,
                                                                                              nm=0))
        primary_read_info = (   qname,
                                flag,
                                prim_rname,
                                prim_pos,
                                prim_mapq,
                                prim_cigar,
                                "*",
                                0,
                                0,
                                seq,
                                "*",
                                "SA:Z:{rname},{pos},{strand},{cigar},{mapq},{nm};".format(rname=suppl_rname,
                                                                                          pos=suppl_pos,
                                                                                          strand=("-" if flag & 16 else "+"),
                                                                                          cigar=suppl_cigar.replace("H", "S"),
                                                                                          mapq=suppl_mapq,
                                                                                          nm=0))
        return (primary_read_info, supplementary_read_info)