Python random.triangular() Examples

The following are 23 code examples of random.triangular(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module random , or try the search function .
Example #1
Source File: knapsack01.py    From levis with 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 #2
Source File: crossover.py    From levis with 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 #3
Source File: __main__.py    From slicesim with MIT License 6 votes vote down vote up
def get_dist(d):
    return {
        'randrange': random.randrange, # start, stop, step
        'randint': random.randint, # a, b
        'random': random.random,
        'uniform': random, # a, b
        'triangular': random.triangular, # low, high, mode
        'beta': random.betavariate, # alpha, beta
        'expo': random.expovariate, # lambda
        'gamma': random.gammavariate, # alpha, beta
        'gauss': random.gauss, # mu, sigma
        'lognorm': random.lognormvariate, # mu, sigma
        'normal': random.normalvariate, # mu, sigma
        'vonmises': random.vonmisesvariate, # mu, kappa
        'pareto': random.paretovariate, # alpha
        'weibull': random.weibullvariate # alpha, beta
    }.get(d) 
Example #4
Source File: crossover.py    From levis with 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 #5
Source File: code.py    From evmlab with 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 #6
Source File: points.py    From DeepRL-Grounding with 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 #7
Source File: __init__.py    From kingpin with 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 #8
Source File: util.py    From dungeon_bot with GNU General Public License v2.0 6 votes vote down vote up
def diceroll(string, form_uniform=False, mode_loc = 0.9):
	negative = False
	if string[0] == "-":
		negative = True
		string = string[1:]
	nums = [int(x) for x in string.split("d")]
	total_sum = 0 
	for i in range(0, nums[0]):
		if form_uniform:
			total_sum += int(random.randint(1, nums[1]))
		else:
			if nums[1] <= 1:
				total_sum += 1
			else:
				total_sum += int(random.triangular(1.0, nums[1], mode_loc*nums[1]))

	if negative:
		total_sum *= -1

	return total_sum 
Example #9
Source File: poisson_disc.py    From midlevel-reps with 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 #10
Source File: test_Collect.py    From svim with 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 #11
Source File: test_Collect.py    From svim with 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 #12
Source File: task.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def new_time_bounce(self):
        left_bound = timeutils.current_unix_timestamp() + BOUNCE_TIMEOUT
        right_bound = left_bound + self.bounced * BOUNCE_TIMEOUT
        bounce_time = random.triangular(left_bound, right_bound)
        bounce_time = int(bounce_time)

        return bounce_time 
Example #13
Source File: NuHeader.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_nu_sync(scheduler):
	print("do_nu_sync!", scheduler)
	try:
		fetch_and_flush()
	finally:

		sleeptime = int(random.triangular(1*60, (10*60), (5*60)))
		next_exec = datetime.datetime.now() + datetime.timedelta(seconds=sleeptime)
		schedule_next_exec(scheduler, next_exec)

		print("NU Sync executed. Next exec at ", next_exec) 
Example #14
Source File: util.py    From dungeon_bot with GNU General Public License v2.0 5 votes vote down vote up
def random_in_range_for_coolity(left, right, mode_pos=0.5):
	if left == right:
		return left
	mode = clamp( mode_pos * right, left, right )
	return triangular( left, right, mode ) 
Example #15
Source File: util.py    From dungeon_bot with GNU General Public License v2.0 5 votes vote down vote up
def triangular(low=0.0, high=1.0, mode=None): #dont ask
	u = random.random()
	if mode is None:
		c = 0.5
	elif mode == high:
		c = 1
	else:
		c = (mode - low) / (high - low)
	if u > c:
			u = 1.0 - u
			c = 1.0 - c
			low, high = high, low
	return low + (high - low) * (u * c) ** 0.5 
Example #16
Source File: test_Collect.py    From svim with 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 #17
Source File: target.py    From blindpie with MIT License 5 votes vote down vote up
def get_response_times(self, requests_: List[IRequest], max_interval: int = DEFAULT_MAX_INTERVAL, max_threads: int = DEFAULT_MAX_THREADS) -> List[float]:

        with ThreadPoolExecutor(max_workers=max_threads) as thread_pool:
            threads = list()
            for r in requests_:
                delay = triangular(max_interval / 2, max_interval)
                sleep(delay / 1000)
                LOGGER.debug("Delayed for: {:f} ms".format(delay))
                threads.append(thread_pool.submit(self._get_response_time, request=r))
            wait(threads)

        return [t.result() for t in threads] 
Example #18
Source File: hosts.py    From kingpin with 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 #19
Source File: codesmart.py    From evmlab with 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 #20
Source File: backgrounds.py    From stytra with GNU General Public License v3.0 5 votes vote down vote up
def generate(self, point):
        """generates new points
        in an annulus between
        self.r, 2*self.r

        Parameters
        ----------
        point :
            

        Returns
        -------

        """

        rad = random.triangular(self.r, 2 * self.r, 0.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 #21
Source File: crossover.py    From levis with 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 #22
Source File: test_Collect.py    From svim with 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) 
Example #23
Source File: seatingchart.py    From levis with 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