Example #1
1
    def find_service_time(self, n, c):
        """
        Finds the service time function
        """

        if self.mu[c][n][0] == 'Uniform':
            return lambda : uniform(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == 'Deterministic':
            return lambda : self.mu[c][n][1]
        if self.mu[c][n][0] == 'Triangular':
            return lambda : triangular(self.mu[c][n][1], self.mu[c][n][2], self.mu[c][n][3])
        if self.mu[c][n][0] == 'Exponential':
            return lambda : expovariate(self.mu[c][n][1])
        if self.mu[c][n][0] == 'Gamma':
            return lambda : gammavariate(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == 'Normal':
            return lambda : gauss(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == 'Lognormal':
            return lambda : lognormvariate(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == 'Weibull':
            return lambda : weibullvariate(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == 'Custom':
            P, V = zip(*self.parameters[self.mu[c][n][1]])
            probs = list(P)
            cum_probs = [sum(probs[0:i+1]) for i in range(len(probs))]
            values = list(V)
            return lambda : self.custom_pdf(cum_probs, values)
        return False
Example #2
0
 def __init__(self, env, orderWindow, paymentWindow, pickupWindow):
     self.env = env
     self.orderWindow = orderWindow
     self.paymentWindow = paymentWindow
     self.pickupWindow = pickupWindow
     Car.carNumber += 1
     self.name = Car.carNumber
     self.orderTime = random.weibullvariate(3, 1.5)
     self.paymentTime = random.weibullvariate(2, 1.5)
     self.foodPrepTime = random.weibullvariate(6, 2.0)
     self.pickupTime = random.weibullvariate(2, 1.5)
     self.foodPrep = self.env.timeout(self.foodPrepTime)
     self.totalTime = 0
 def calculateDegreeDistribution(self, shape, other=float(0)):
     for node in range(0, self.nodeCount):
         if self.graphType == 1:
             degree  = abs(int(random.expovariate(1/other)))
         elif self.graphType == 2:
             degree = abs(int(random.expovariate(1/other)))
         elif self.graphType == 3:
             degree = abs(int(random.weibullvariate(shape, other)))
         print "Node: Degree ", node, degree
         self.nodeDict[node] = degree
         if (degree == 0) or (degree == 1):
             self.zeroNodes.append(node)
     # if self.graphType == 3:
     #     sortedDict = sorted(self.nodeDict.items(), key=operator.itemgetter(1), reverse=False)
     #     print "Sorted Dict", sortedDict
     #     for node in range(0, int(self.nodeCount * .27338129)): # .27338129 is the percentage of nodes with 0 or 1 in real graph
     #         key = sortedDict[node][0]
     #         value = random.random()
     #         if value <= .86842015:
     #             self.nodeDict[key] = 0
     #         else:
     #             self.nodeDict[key] = 1
     for node in self.zeroNodes:
         chance = random.uniform(0,1)
         if chance <= 0.50:
             self.nodeDict[node] = 2
         else:
             self.nodeDict[node] = 3
     print "New NodeDict items", sorted(self.nodeDict.items(), key=operator.itemgetter(1), reverse=False)
def my_Funh():
    random.seed()
    print('random = ', random.random())
    print('getstate = ', random.getstate())
    state = random.getstate()
    random.setstate(state)
    print('setstate = ',random.random())
    print('getrandbits = ',random.getrandbits(6))
    print('randrange = ',random.randrange(3, 9))
    print('randint = ',random.randint(3, 9))
    x = 2,1,3,5,4,6,7,8,9,10,6

    print('choice = ',random.choice(x) + random.choice(x)+random.choice(x))
    mylist = [1, 2, 3,4,5,6,7,8,9,0]
    random.shuffle(mylist)

    print('shuffle =',*mylist)

    print("sample:", *random.sample(x, 8))
    print('uniform = ', random.uniform(20, 60))
    print('triangular = ',random.triangular(20, 60, 30))
    print('betavariate =',random.betavariate(5, 10))
    print('expovariate = ',random.expovariate(1.5))
    print('gammavariate =',random.gammavariate(100, 2))
    print('gauss =',random.gauss(100, 50))
    print('lognormvariate =',random.lognormvariate(0, 0.25))
    print('normalvariate =',random.normalvariate(0, 0.25))
    print('vonmisesvariate = ',random.vonmisesvariate(0,4))
    print('paretovariate = ',random.paretovariate(3))
    print('weibullvariate = ',random.weibullvariate(1, 1.5))
    b = input('New ? (y / n) = ')
    if b == 'y':
        my_Funh()
    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.weibullvariate(alpha=self.alpha, beta=self.beta))
Example #6
0
def GenerarViento(viento):
    maximo_fi = 360
    minimo_fi = 0.01
    delta_angulo = round(normalvariate(2, 0.7) * 10, 2)
    if viento['estado']:
        if viento['direccion'] + delta_angulo >= maximo_fi:
            viento['estado'] = False
            viento['direccion'] -= delta_angulo
        else:
            viento['direccion'] += delta_angulo
    else:
        if viento['direccion'] - delta_angulo <= minimo_fi:
            viento['estado'] = True
            viento['direccion'] += delta_angulo
        else:
            viento['direccion'] -= delta_angulo
    # Para trampear la velocidad del viento y que meta algunos valores excesivos
    # para llenar la tabla de desconexiones hago que:
    # Haya un 30 % de probabilidades de aƱadir 15 a la velocidad media de la zona
    loteria = randint(1, 10)
    if loteria < 3:
        extra = 15
    else:
        extra = 0
    viento['velocidad'] = round(weibullvariate(viento['velmedia'] + extra, 2),
                                2)
    return
Example #7
0
def waitTillFailure(proc):

	global gvStartTime, gvDone, gvStatsLock, gvTotalFL

	# Calculate when the next failure should take place
	nextFailure = int(round(random.weibullvariate(WEIBULL_SCALE, WEIBULL_SHAPE)))

	time.sleep(nextFailure)

	# Caluclate the time which the app ran for during this instance
	timeDiff = time.time() - gvStartTime

	process = psutil.Process(proc.pid)
	for child in process.children(recursive=True):
		child.kill()
	os.killpg(os.getpgid(proc.pid), signal.SIGKILL);
	print(os.path.basename(__file__) + ": Failure at " + str(timeDiff + gvStartTime))

	# Acquire the lock on calculate stats
	gvStatsLock.acquire()

	# No need to calculate if the entire run has already ended
	if (gvDone is False):
		calculateStats(timeDiff)
		gvTotalFL += 1

	# Release the lock on calculate stats
	gvStatsLock.release()
 async def random_weibull_variate_command(self, ctx, alpha: float,
                                          beta: float):
     """Alpha is the scale parameter, beta is the shape."""
     try:
         await ctx.send(random.weibullvariate(alpha, beta))
     except Exception as ex:
         await self._error(ctx, ex)
def distribuicoesChegadas(env):
    dist = 0
    valores = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5,
               12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5, 24.5, 25.5, 26.5, 27.5, 28.5,
               29.5,
               30.5, 31.5, 32.5, 33.5, 34.5, 35.5, 36.5, 37.5, 38.5, 39.5, 40.5, 61, 87.5]
    probabilidades = [0.085, 0.211, 0.106, 0, 0.010, 0, 0, 0, 0, 0.010, 0.031, 0.010, 0.053, 0.010, 0, 0.031, 0.031,
                      0.021, 0.031, 0.010, 0.021, 0.021, 0.021, 0.031, 0, 0.010, 0.010, 0, 0.010, 0.010, 0.031, 0.021,
                      0, 0,
                      0.031, 0, 0.031, 0.010, 0, 0.010, 0, 0.021, 0, 0.010, 0, 0.010, 0, 0, 0.010, 0.021, 0.010]

    if (env.now >= 14400) and (env.now < 23400):  # HorƔrio de almoco entre 11h e 13h30
        x = random.gammavariate(0.315, 1)
        y = random.gammavariate(2.08, 1)
        dist = 108 * x / (x + y)

    elif (env.now >= 7200) and (env.now < 9000):  # Intervalo da manha entre 9h e 9h30
        dist = random.lognormvariate(1.5287, -1.528)

    elif ((env.now >= 27600) and (env.now < 28800)) or ((env.now >= 34200) and (env.now < 35400)) or \
            ((env.now >= 39600) and (
                    env.now < 43200)):  # Intervalos da tarde de 14h40 a 15h, de 16h30 a 16h50 e de 18h Ć s 19h
        dist = numpy.random.choice(valores, 1, p=probabilidades)

    elif ((env.now >= 0) and (env.now < 7200)) or ((env.now >= 9000) and (env.now < 14400)) or (
            (env.now >= 23400) and (env.now < 27600)) \
            or ((env.now >= 28800) and (env.now < 34200)) or ((env.now >= 35400) and (env.now < 39600)) or (
            (env.now >= 43200) and (env.now < 50400)):  # Demais intervalos
        dist = random.weibullvariate(22.8, 0.755)
    return dist
Example #10
0
 def find_distributions(self, n, c, source):
     """
     Finds distribution functions
     """
     if source[c][n] == 'NoArrivals':
         return lambda : 'Inf'
     if source[c][n][0] == 'Uniform':
         return lambda : uniform(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Deterministic':
         return lambda : source[c][n][1]
     if source[c][n][0] == 'Triangular':
         return lambda : triangular(source[c][n][1], source[c][n][2], source[c][n][3])
     if source[c][n][0] == 'Exponential':
         return lambda : expovariate(source[c][n][1])
     if source[c][n][0] == 'Gamma':
         return lambda : gammavariate(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Lognormal':
         return lambda : lognormvariate(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Weibull':
         return lambda : weibullvariate(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Custom':
         P, V = zip(*self.parameters[source[c][n][1]])
         probs = list(P)
         cum_probs = [sum(probs[0:i+1]) for i in range(len(probs))]
         values = list(V)
         return lambda : self.custom_pdf(cum_probs, values)
     if source[c][n][0] == 'Empirical':
         if isinstance(source[c][n][1], str):
             empirical_dist = self.import_empirical_dist(source[c][n][1])
             return lambda : choice(empirical_dist)
         return lambda : choice(source[c][n][1])
     return False
Example #11
0
 def find_distributions(self, n, c, source):
     """
     Finds distribution functions
     """
     if source[c][n] == 'NoArrivals':
         return lambda: 'Inf'
     if source[c][n][0] == 'Uniform':
         return lambda: uniform(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Deterministic':
         return lambda: source[c][n][1]
     if source[c][n][0] == 'Triangular':
         return lambda: triangular(source[c][n][1], source[c][n][2], source[
             c][n][3])
     if source[c][n][0] == 'Exponential':
         return lambda: expovariate(source[c][n][1])
     if source[c][n][0] == 'Gamma':
         return lambda: gammavariate(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Lognormal':
         return lambda: lognormvariate(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Weibull':
         return lambda: weibullvariate(source[c][n][1], source[c][n][2])
     if source[c][n][0] == 'Custom':
         P, V = zip(*self.parameters[source[c][n][1]])
         probs, values = list(P), list(V)
         return lambda: nprandom.choice(values, p=probs)
     if source[c][n][0] == 'UserDefined':
         return lambda: self.check_userdef_dist(source[c][n][1])
     if source[c][n][0] == 'Empirical':
         if isinstance(source[c][n][1], str):
             empirical_dist = self.import_empirical(source[c][n][1])
             return lambda: choice(empirical_dist)
         return lambda: choice(source[c][n][1])
Example #12
0
def intf_DISTWEIBULL(E):
    """Takes VALs from v1 and v2, and returns a value randomly generated
    by a function that produces values which are distributed in a Weibull
    distribution. This is often used to model processes related to failure
    rates, survival analysis, and reliability. The v2 VAL is Lambda which is
    the scale parameter for this kind of distribution. The v1 VAL is k which is
    the shape parameter. Both must be greater than zero. If k is 1 this is
    equivalent to the exponential distribution. If k is 2 it is equivalent to
    the Rayleigh distribution. A value of k < 1 indicates that the failure rate
    decreases over time. This happens if there is significant "infant
    mortality", or defective items failing early and the failure rate
    decreasing over time as the defective items are weeded out of the
    population. A value of k = 1 indicates that the failure rate is constant
    over time. This might suggest random external events are causing mortality,
    or failure. A value of k > 1 indicates that the failure rate increases with
    time. This happens if there is an "aging" process, or parts that are more
    likely to fail as time goes on.
        |[.75 1 distweibull::!] 100000 repeat 100000 2list mean -> 0.751247734665
    """
    if not inc.VAL(E, 1) or not inc.VAL(E, 2):
        print("Input Error: distweibull")
        print(intf_DISTWEIBULL.__doc__)
        return  # Without doing much of anything.
    v1 = E.The.StackPop().val  # k, beta, shape
    v2 = E.The.StackPop().val  # Lambda, alpha, scale
    import random
    out = random.weibullvariate(v2, v1)
    out = objectifier.StackOB_VAL(out)
    E.The.StackPush(out)
Example #13
0
def distribuicoesChegadas(env):
    dist = 0
    valores = [
        0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2.5, 3.5, 4.5, 5.5,
        6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5,
        18.5, 19.5, 20.5, 21.5, 22.5, 23.5, 24.5, 25.5, 26.5, 27.5, 28.5, 29.5,
        30.5, 31.5, 32.5, 33.5, 34.5, 35.5, 36.5, 37.5, 38.5, 39.5, 40.5, 61,
        87.5
    ]
    probabilidades = [
        0.085, 0.211, 0.106, 0, 0.010, 0, 0, 0, 0, 0.010, 0.031, 0.010, 0.053,
        0.010, 0, 0.031, 0.031, 0.021, 0.031, 0.010, 0.021, 0.021, 0.021,
        0.031, 0, 0.010, 0.010, 0, 0.010, 0.010, 0.031, 0.021, 0, 0, 0.031, 0,
        0.031, 0.010, 0, 0.010, 0, 0.021, 0, 0.010, 0, 0.010, 0, 0, 0.010,
        0.021, 0.010
    ]

    if (env.now >= 14400) and (env.now < 23400):
        x = random.gammavariate(0.315, 1)
        y = random.gammavariate(2.08, 1)
        dist = 108 * x / (x + y)

    elif (env.now >= 7200) and (env.now < 9000):
        dist = random.lognormvariate(1.5287, -1.528)

    elif ((env.now >= 27600) and (env.now < 28800)) or ((env.now >= 34200) and (env.now < 35400)) or \
            ((env.now >= 39600) and (env.now < 43200)):
        dist = numpy.random.choice(valores, 1, p=probabilidades)

    elif ((env.now >= 0) and (env.now < 7200)) or ((env.now >= 9000) and (env.now < 14400)) or ((env.now >= 23400) and (env.now < 27600)) \
            or ((env.now >= 28800) and (env.now < 34200)) or ((env.now >= 35400) and (env.now < 39600)) or ((env.now >= 43200) and (env.now < 50400)):
        dist = random.weibullvariate(22.8, 0.755)
    return dist
Example #14
0
 def gen_lifetime(self, shape, scale):
     '''Generates a random lifetime for the part using Weibull random numbers.
     If 0 < shape < 1, the part exhibits infant mortality (more failures early in parts' life)
     If shape = 0, the part exhibits constant mortality
     If shape > 1, the part exhibits wear-out (more failures late in parts' life)
     '''
     self.lifetime = self.mttf * random.weibullvariate(alpha=scale, beta=shape)
Example #15
0
def generate_random_number(f):
    """ćƒ©ćƒ³ćƒ€ćƒ å€¤ć‚’1000個ē”Ÿęˆ
        å„é–¢ę•°ć®ćƒ‘ćƒ©ćƒ”ćƒ¼ć‚æćÆé©å½“ć«ę±ŗ悁ꉓ恔怂
    """
    if f == 'random':
        return [random.random() for n in range(1000)]
    elif f == 'uniform':
        return [random.uniform(10, 20) for n in range(1000)]
    elif f == 'triangular':
        return [random.triangular(0, 1) for n in range(1000)]
    elif f == 'betabariate':
        return [random.betavariate(4, 7) for n in range(1000)]
    elif f == 'expovariate':
        return [random.expovariate(1 / 0.5) for n in range(1000)]
    elif f == 'gammavariate':
        return [random.gammavariate(4, 7) for n in range(1000)]
    elif f == 'gauss':
        return [random.gauss(1, 0.2) for n in range(1000)]
    elif f == 'gauss':
        return [random.gauss(1, 0.2) for n in range(1000)]
    elif f == 'lognormvariate':
        return [random.lognormvariate(1, 0.2) for n in range(1000)]
    elif f == 'normalvariate':
        return [random.normalvariate(1, 0.2) for n in range(1000)]
    elif f == 'vonmisesvariate':
        return [random.vonmisesvariate(math.pi / 2, 5) for n in range(1000)]
    elif f == 'paretovariate':
        return [random.paretovariate(100) for n in range(1000)]
    elif f == 'weibullvariate':
        return [random.weibullvariate(4, 2) for n in range(1000)]
Example #16
0
def _generate_numbers(distribution, length):
    """
    Generate random numbers of length according to the distribution.
    :param distribution: A list which holds information about a distribution and its parameters,
    first element is always the name, the rest depends on the distribution.
    Ex: exponential distribution = distribution = ['EXP', lambda]
    :param length: The length of random numbers to be generated
    :return: A list of random numbers
    """
    name, *parameters = distribution
    random_numbers = []
    if name == 'EXP':
        lambda_, = parameters
        for i in range(length):
            num = random.expovariate(lambda_)
            random_numbers.append(num)
    if name == 'WEIBULL':
        scale_, shape_ = parameters
        for i in range(length):
            num = random.weibullvariate(scale_, shape_)
            random_numbers.append(num)
    if name == 'LOGNORM':
        mu_, sigma_ = parameters
        for i in range(length):
            num = random.lognormvariate(mu_, sigma_)
            random_numbers.append(num)
    if name == 'NORMAL':
        mu_, sigma_ = parameters
        for i in range(length):
            num = random.normalvariate(mu_, sigma_)
            random_numbers.append(num)
    return random_numbers
Example #17
0
 def valueAt(self, evaluationTime):
     alpha = evaluateAt(self.alpha, evaluationTime)
     beta = evaluateAt(self.beta, evaluationTime)
     while 1:
         value = random.weibullvariate(alpha, beta)
         if value >= 0.0 and value <= 1.0:
             break
     return value
Example #18
0
def get_incubation_period(num_ppl):
    # The time from exposure until symptoms appear (i.e., the incubation period) is
    # drawn from a Weibull distribution with a mean of 6.4 days and a standard deviation of 2.3
    # days (Backer et al. 2020)
    k = (2.3 / 6.4)**(-1.086)
    l = 6.4 / (math.gamma(1 + 1 / k))
    return np.around([random.weibullvariate(l, k)
                      for _ in np.arange(num_ppl)]).astype(np.int32)
Example #19
0
 def valueAt(self, evaluationTime):
     alpha = evaluateAt(self.alpha, evaluationTime)
     beta = evaluateAt(self.beta, evaluationTime)
     while 1:
         value = random.weibullvariate(alpha, beta)
         if value >= 0.0 and value <= 1.0:
             break
     return value
Example #20
0
def create_daystosymptoms_column(num_ppl):
    # The time from exposure until symptoms appear (i.e., the incubation period) is
    # drawn from a Weibull distribution with a mean of 6.4 days and a standard deviation of 2.3
    # days (Backer et al. 2020)
    k = (2.3 / 6.4)**(-1.086)
    L = 6.4 / (math.gamma(1 + 1 / k))
    return np.array(
        [random.weibullvariate(L, k) for ppl in np.arange(num_ppl)])
def waitTillFailure(proc, failureTime):

    global gvStartTime, gvDone, gvStatsLock, gvCurrentApp, gvTotalFL

    # Calculate when the next failure should take place
    nextFailure = failureTime
    if failureTime == 0:
        nextFailure = int(random.weibullvariate(WEIBULL_SCALE, WEIBULL_SHAPE))

    # Holds the reason for exisitng the while loop below
    switch = False

    # Loop until its time to inject a failure
    while ((time.time() - gvStartTime) <= nextFailure):
        # Every iteration, poll the currently running DMTCP process
        # to learn if it has died. If it has, that means it is time
        # to switch to the HW app.
        if (proc.poll() is not None):
            # Set the reason for quitting the loop as switch and break
            switch = True
            break

    # Caluclate the time which the app ran for during this instance
    timeDiff = time.time() - gvStartTime

    # Kill the process if failure is the reason for quitting the loop
    if switch is False:
        # --kill may block while the application is ckpting
        #subprocess.call(DMTCP_COMMAND + ' --kill', shell=True)
        proc.send_signal(9)
        nextFailure = 0
    else:
        nextFailure = nextFailure - timeDiff

    # Acquire the lock on calculate stats
    gvStatsLock.acquire()

    # No need to calculate if the entire run has already ended
    if (gvDone is False):

        calculateStats(timeDiff)

        # If switching, move on to the HW app
        # Else had a failure, so run the LW app
        # And increment the number of failures
        if switch is False:
            gvTotalFL[gvCurrentApp] += 1
        if (gvCurrentApp == (NUM_APPS - 1)):
            gvCurrentApp = 0
        else:
            gvCurrentApp += 1

        gvStartTime = time.time()

    # Release the lock on calculate stats
    gvStatsLock.release()

    return nextFailure
Example #22
0
def add_instances(unique_words, labels, words, num_to_word, pictures):

    print("Started add_instances")
    num_low = 0
    num_high = 0
    maxi = 0
    labels = list(labels)
    words = list(words)

    # There is probably a faster way of doing this
    """
   # This was taking far too long to justify doing each time. Uncomment if the data gets switched

   # Find the word with the highest frequency ('the' in our case, 5826 instances)
   # We scale the other frequencies up relative to their distance from this value
   for item in range(unique_words):
      count = labels.count(item)
      if count > maxi:
         maxi = count
   print("Got the maximum frequency")
   
   """

    maxi = 5826

    for item in range(unique_words):
        # locations of the pictures of this word
        indices = [i for i, x in enumerate(labels) if x == item]
        count = len(indices)
        num_to_add = int(math.sqrt(math.sqrt(maxi - count)))
        word = num_to_word[item]
        # we want to sample from however many different images we ahve as much as we can
        cur_pic = 0
        for _ in range(num_to_add):
            im = pictures[indices[cur_pic]]

            # mess with the image a little
            off1, off2, off3, off4 = [random.randint(0, 4) for _ in range(4)]
            im = im.transform(
                (im.size[0], im.size[1]), Image.EXTENT,
                (0 + off1, 0 + off2, im.size[0] - off3, im.size[1] - off4))
            roll_to_rotate = random.randint(1, 6)
            if roll_to_rotate > 2:
                amount_to_rotate = random.weibullvariate(1, 1.5)
                im.rotate(amount_to_rotate)

            # add the image to out set
            words.append(
                normalize_grayscale(np.array(im, dtype=np.float32).flatten()))
            labels.append(item)

            # advance to a new image if there is one
            cur_pic += 1
            if cur_pic == count:
                cur_pic = 0

    print(maxi)
    return (np.array(words), np.array(labels))
Example #23
0
def ejercicio02(n):
    """
    Esperanza con Distribucion Weibull.
    """
    a = 0
    for _ in xrange(n):
        a += random.weibullvariate(1, 1)

    return a/float(n)
def weibull():
    WEIBULL_USAGE = '''Usage: /weibull?alpha=&lt;integer&gt;&beta=&lt;integer&gt;[k=&lt;integer&gt;&amp;test=true|false]'''

    func = lambda args: random.weibullvariate(alpha=float(args['alpha']), beta=float(args['beta'])) + float(request.args.get('k'))

    alpha = request.args.get('alpha')
    beta = request.args.get('beta')

    return get_response(request, WEIBULL_USAGE, func, None, alpha=alpha, beta=beta)
Example #25
0
def getIndex(listLength, numOfDigits):
    # index = random.normalvariate(listLength/2, 3)
    index = random.weibullvariate(listLength / 2, numOfDigits * 0.5)
    index = math.ceil(index)
    if index > listLength - 1:
        index = listLength - 1
    if index < 0:
        index = 0
    return int(index)
Example #26
0
    def procCounter(self):  # This slot takes no params
        for j in range(1, 10):
            random_time = random.weibullvariate(1, 2)
            time.sleep(random_time)
            self.intReady.emit(j, self.idd)
            print('Worker {0} in thread {1}'.format(self.idd,
                                                    self.thread().idd))

        self.finished.emit(self.idd)
Example #27
0
def facturacion(personas):
    global dt
    global a
    R = random.random()  #obtener numero aleatorio
    #tiempo=np.random.weibull(a , 7.76)
    tiempo = int(random.weibullvariate(3.91, 7.76))
    yield env.timeout(tiempo)  #deja correr el tiempo n minutos
    print("\o/ Facturacion lista a %s en %.2f minutos" % (personas, tiempo))
    dt = dt + tiempo  #acumula los tiempos
Example #28
0
 def windSpeed(
     self, timeofday
 ):  #source: http://www.wind-power-program.com/wind_statistics.htm
     self.currWindSpeed += (
         random.random() -
         0.5) * 2 * self.windVariance * random.weibullvariate(
             1, 0.5 + random.random())
     if self.currWindSpeed < 0:
         self.currWindSpeed = 0
     return self.currWindSpeed
Example #29
0
def exposure_period():
    
    SCALE_PAR = 1.10
    SHAPE_PAR = 2.21
    OFFSET = 0.5
    
    t = int(round((random.weibullvariate(SCALE_PAR, SHAPE_PAR) + OFFSET)
                  * TIME_TO_TIMESTEP))
    
    return t
Example #30
0
 def generate_weibull(self, scale, shape):
     count = 0
     tasks = list()
     while count < self.__amount:
         weight = random.weibullvariate(scale, shape)
         t = Task(count, weight, randint(1, 4),
                  (weight * randint(1, scale)))
         tasks.append(t)
         count += 1
     return tasks
Example #31
0
def exposure_period():
    
    SCALE_PAR = 1.10
    SHAPE_PAR = 2.21
    OFFSET = 0.5
    
    t = int(round((random.weibullvariate(SCALE_PAR, SHAPE_PAR) + OFFSET)
                  * TIME_TO_TIMESTEP))
    
    return t
Example #32
0
    def step(self, action):
        air_mass = self.map * CYL_VOLUME * AIR_DENSITY  # mg
        #fuel_mass = 25.0 * (action[0] + 1.0) # mg
        fuel_mass = 25 + 25.0 * action[0]  # mg
        #fuel_mass = action[0] * 100.0 # mg
        #fuel_mass = action[0] # mg
        #self.afr = min(max(air_mass/(fuel_mass+1.0), MIN_AFR), MAX_AFR)
        self.far = min(max(fuel_mass / air_mass, MIN_FAR), MAX_FAR)

        self.steps += 1
        done = (self.steps % 10 == 0)
        #done = True
        # MAP random walk
        #if (self.steps % 10 == 0):
        #    self.map = min(max(self.map + random.uniform(-0.2, 0.2), MIN_MAP), MAX_MAP)
        #reward = 0.0 - ((self.afr - AFR_TARGET)**2)
        #reward = 0.0 - (abs(self.afr - AFR_TARGET))

        # help it to find the right AFR
        #predicted_afr = air_mass/(fuel_mass+1.0)
        predicted_far = fuel_mass / air_mass
        #reward = 0.0 - ((self.afr - AFR_TARGET)**2) - ((predicted_afr - AFR_TARGET)**2)
        #reward = 0.0 - 100.0 * ((self.far - FAR_TARGET)**2) - 100.0 * ((predicted_far - FAR_TARGET)**2)
        #reward = 0.0 - 100.0 * (abs(self.far - FAR_TARGET)) - 100.0 * (abs(predicted_far - FAR_TARGET))
        #reward = 0.0 - 1000.0 * ((self.far - FAR_TARGET)**2)
        #reward = 0.0 - 10000.0 * abs(self.far - FAR_TARGET)
        #reward = max(0.0 - 10000.0 * abs(self.far - FAR_TARGET), -200) # clamp the reward
        #reward = 0.0 - 10000.0 * ((self.far - FAR_TARGET)**2)
        reward = max(0.0 - 10000.0 * ((self.far - FAR_TARGET)**2),
                     -5)  # clamp the reward

        if (self.steps % 100 == 0):
            #if (self.steps % 1 == 0):
            afr = 1 / (self.far + 0.000001)
            afr_err = afr - AFR_TARGET
            far_err = self.far - FAR_TARGET
            print(
                f'step:{self.steps:8d} action:{action[0]:8.3f} map:{self.map:8.3f} air_mass:{air_mass:8.3f} fuel_mass:{fuel_mass:8.3f} far:{self.far:8.4f} far_err:{far_err:8.4f} afr:{afr:8.3f} afr_err:{afr_err:8.3f} rew:{reward:8.4f}'
            )

        # maybe change throttle position
        #if (self.steps % 100 == 0):
        #if self.map < 0.5:
        #    self.map = MAX_MAP
        #else:
        #    self.map = MIN_MAP
        #self.map = min(max(self.map + random.uniform(-0.2, 0.2), MIN_MAP), MAX_MAP)
        # scale, shape
        map_dot = (-1 if (self.steps % 2 == 0) else 1) * random.weibullvariate(
            0.05, 1.0)
        #print(f'map_dot:{map_dot:8.3f}')

        self.map = min(max(self.map + map_dot, MIN_MAP), MAX_MAP)

        return self.observation(), reward, done, {}
Example #33
0
def time_to_failure():
    """Return time until next failure for a machine."""
    if not useWeibull:
        nextFailure = int(random.expovariate(BREAK_MEAN))
    else:
        # The Weibull distr. generates many errors.
        #nextFailure = int(np.random.weibull(WEIBULL_K)*98.0) # Gives MTBF to be 200
        #nextFailure = int(exponweib.rvs(1.0, WEIBULL_SHAPE, scale=WEIBULL_SCALE))
        nextFailure = int(random.weibullvariate(WEIBULL_SCALE, WEIBULL_SHAPE))
        #print("WEIBULL SCALE: %f, SHAPE: %f, nextFailure: %d" %(WEIBULL_SCALE, WEIBULL_SHAPE, nextFailure))
    return nextFailure
Example #34
0
def generate_currency_conv():
    def daterange(start_date, end_date):
        for n in range(int((end_date - start_date).days)):
            yield start_date + datetime.timedelta(n)

    while True:
        root_value = random.weibullvariate(1, 3)

        for cur_day in daterange(low_date, high_date):
            yield {"day_value": cur_day, "to_aud": root_value}
            root_value += random.gauss(0, root_value / 100)
Example #35
0
    def node_event_append(self):
        num_node = self.nodeperrack*self.numrack
        #print "num_node", num_node
        for nodeid in range (num_node):
            fail_flag=random.random()
            if fail_flag>0.0:
                #for tmp in range (self.diskpernode):
                fail_time = random.weibullvariate(2890.8, 1.0)
                #disk_id = tmp+nodeid*self.diskpernode
                if fail_time <= self.mission_time:
                    self.events_queue.append((fail_time, nodeid, 1))

        for nodeid in range(num_node):
            #for tmp in range (self.diskpernode):
            fail_flag=random.random()
            if fail_flag>0.0:
                fail_time = random.weibullvariate(91250., 1.0)
                   #disk_id = tmp+nodeid*self.diskpernode
                if fail_time <= self.mission_time:
                    self.events_queue.append((fail_time, nodeid, 2))
Example #36
0
def random_guessing(fileparse):
    prevs = []
    num = 0
    sort_key = lambda x:int(x[0]) if x[0].isdigit() else (float('inf'),x[0])
    corefs = sorted(fileparse.nps.items(), key = sort_key)
    
    for cid in [k for k,v in corefs if not v.get('ref')]:
        if len(prevs) > num and cid.isdigit():
            choice = min(len(prevs), int(round(random.weibullvariate(1.2,7))) + 1)
            fileparse.nps[cid]['ref'] = prevs[-choice]
        if cid.isdigit():
            prevs.append(cid)
Example #37
0
    def generate_fire_recurrence(self):
        """ Finds the time to next fire (fire recurrence) based on the scale parameter (63.5% of
        fire Weibull distribution) and the shape parameter (describes the skew of the histogram, shape = 3.5
        represents a normal distribution).
        
        Rounds the time to next fire to 4 significant figures, for neatness.
        
        :returns: time_to_next_fire as a float"""

        self.time_to_next_fire = round(
            weibullvariate(self.scale_parameter, self.shape_parameter), 2)
        return self.time_to_next_fire
Example #38
0
    def generate_fire_recurrence(self):

        """ Finds the time to next fire (fire recurrence) based on the scale parameter (63.5% of
        fire Weibull distribution) and the shape parameter (describes the skew of the histogram, shape = 3.5
        represents a normal distribution).

        Rounds the time to next fire to 4 significant figures, for neatness.

        :returns: time_to_next_fire as a float"""

        self.time_to_next_fire = round(weibullvariate(self.scale_parameter, self.shape_parameter),2)
        return self.time_to_next_fire
Example #39
0
def WeibullDistribution():
	results = []
	k = 2
	lamada = 1

	sampleNum = 6000
	for i in range(sampleNum):
		results.append(random.weibullvariate(lamada,k))
	cdf = Cdf.MakeCdfFromList(results)
	myplot.Clf()
	myplot.Cdf(cdf,complement=True,xscale = 'log',yscale = 'log')
	# myplot.Cdf(cdf)
	myplot.show()
Example #40
0
def randomXValue(tag, params):
    if tag == "normal":
        mu = number(params.get("mu", 0.0))
        sigma = number(params.get("sigma", 1.0))
        return XValue(lambda: random.normalvariate(mu, sigma))
    if tag == "pnormal":
        mu = number(params.get("mu", 0.0))
        sigma = number(params.get("sigma", 1.0))
        return XValue(lambda: max(random.normalvariate(mu, sigma), 0.0))        
    elif tag == "uniform":
        mn = number(params.get("min", 0.0)) 
        mx = number(params.get("max", 1.0))
        return XValue(lambda: random.uniform(mn, mx))
    elif tag == "triangular":
        low = number(params.get("low", 0.0)) 
        high = number(params.get("high", 1.0))
        mode = number(params.get("mode", 1.0))
        return XValue(lambda: random.triangular(low, high, mode))
    elif tag == "beta":
        alpha = number(params.get("alpha", 0.0)) 
        beta = number(params.get("beta", 1.0))
        return XValue(lambda: random.betavariate(alpha, beta))
    elif tag == "gamma":
        alpha = number(params.get("alpha", 0.0)) 
        beta = number(params.get("beta", 1.0))
        return XValue(lambda: random.gammavariate(alpha, beta))
    elif tag == "lognormal":
        mu = number(params.get("mu", 0.0))
        sigma = number(params.get("sigma", 1.0))
        return XValue(lambda: random.lognormvariate(mu, sigma))
    elif tag == "vonmises":
        mu = number(params.get("mu", 0.0))
        kappa = number(params.get("kappa", 1.0))
        return XValue(lambda: random.vonmisesvariate(mu, kappa))
    elif tag == "pareto":
        alpha = number(params.get("alpha", 0.0))
        return XValue(lambda: random.paretovariate(alpha))
    elif tag == "weibull":
        alpha = number(params.get("alpha", 0.0)) 
        beta = number(params.get("beta", 1.0))
        return XValue(lambda: random.weibullvariate(alpha, beta))
    elif tag == "exponential":
        lamda = number(params.get("lambda", 1.0))
        return XValue(lambda: random.expovariate(lamda))
    else:
        raise InvalidXMLException("unsupported attribute value")
Example #41
0
 def visit_screener(self):
     """
         After cleaning
         
         Aggregated:
         
         Lognormal with:
             logarithmic mean: -2.125
             logarithmic std dev: 0.428
         
         Weibull with:
             shape = 2.29  (beta in python)
             scale = 0.142 (alpha in python)
         
         Separated:
         Medical Screening -> Gamma distribution with
                              shape: 4.876
                              rate: 32.55
         Ciprofloxacin Screening -> Gamma distribution with
                              shape: 6.258
                              rate: 47.165
         Doxycycline Screening -> Lognormal distribution with
                             logarithmic mean: -2.165
                             logarithmic std dev: 0.413
     """       
     name = 'screener'
     if self.debug:
         print self.name, "at ",name, simpy.now()
     arrive = simpy.now()
     yield simpy.request, self, self.resources[name]
     wait = simpy.now() - arrive
     self.monitors[name].observe(wait)
     #time = random.lognormvariate(mu=-2.125, sigma=0.428)
     time = random.weibullvariate(alpha=0.142, beta=2.29)
     tib = self.numberOfForms * time
     yield simpy.hold,self,tib
     yield simpy.release, self, self.resources[name]
     
     
     if 'MEDIC' in self.forms:
         for i in self.visit_medic():
             yield i
     else:
         for i in self.visit_dispenser():
             yield i
Example #42
0
 def find_distributions(self, n, c, kind):
     """
     Finds distribution functions
     """
     if self.source(c, n, kind) == 'NoArrivals':
         return lambda : float('Inf')
     if self.source(c, n, kind)[0] == 'Uniform':
         return lambda : uniform(self.source(c, n, kind)[1],
                                 self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Deterministic':
         return lambda : self.source(c, n, kind)[1]
     if self.source(c, n, kind)[0] == 'Triangular':
         return lambda : triangular(self.source(c, n, kind)[1],
                                    self.source(c, n, kind)[2],
                                    self.source(c, n, kind)[3])
     if self.source(c, n, kind)[0] == 'Exponential':
         return lambda : expovariate(self.source(c, n, kind)[1])
     if self.source(c, n, kind)[0] == 'Gamma':
         return lambda : gammavariate(self.source(c, n, kind)[1],
                                      self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Lognormal':
         return lambda : lognormvariate(self.source(c, n, kind)[1],
                                        self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Weibull':
         return lambda : weibullvariate(self.source(c, n, kind)[1],
                                        self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Normal':
         return lambda : truncated_normal(self.source(c, n, kind)[1],
                                          self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Custom':
         values = self.source(c, n, kind)[1]
         probs = self.source(c, n, kind)[2]
         return lambda : random_choice(values, probs)
     if self.source(c, n, kind)[0] == 'UserDefined':
         return lambda : self.check_userdef_dist(self.source(c, n, kind)[1])
     if self.source(c, n, kind)[0] == 'Empirical':
         if isinstance(self.source(c, n, kind)[1], str):
             empirical_dist = self.import_empirical(self.source(c, n, kind)[1])
             return lambda : random_choice(empirical_dist)
         return lambda : random_choice(self.source(c, n, kind)[1])
     if self.source(c, n, kind)[0] == 'TimeDependent':
         return lambda t : self.check_timedependent_dist(self.source(c, n, kind)[1], t)
     if self.source(c, n, kind)[0] == 'Sequential':
         return lambda : next(self.generators[kind][n][c])
Example #43
0
 def run(self, res, sto, pri):
     while True:
         ttf = weibullvariate(alpha, beta)   # time until failure
         yield hold, self, ttf
         failure = now()                     # failure time
         HardDrive.numFailed += 1
         HardDrive.downTime.observe(HardDrive.numFailed)
         if HardDrive.numFailed == critLevel:
             critical.signal()
             HardDrive.numFailed = 0
             HardDrive.downTime.observe(HardDrive.numFailed)
         else:
             yield waitevent, self, critical
         yield get, self, sto, 1
         yield request, self, res, pri
         self.size = self.got[0].capacity
         ttr = meanTtr + expovariate(1.0 / meanTtr)
         yield hold, self, ttr
         yield release, self, res
def generate_order(env, res, order, patID, data):
    tfactor = 60  # Minutes to seconds
    while True:
        # Generate some really random processes
        if order == 'food':
            lamb = 5 + 20*(patID % 6)  # In minutes
            k = 3  # Hunger increases over time
            delay = random.weibullvariate(lamb*tfactor, k)
        else:
            a, b = 10, 20+20*(patID % 6)
            mu = random.randint(a, b)  # Random mean in minutes
            sd = 10  # Standard deviation in minutes
            delay = abs(random.normalvariate(mu*tfactor, sd*tfactor))
        yield env.timeout(delay)  # Interarival time
        # Delay is complete, order arrived
        # Start process and return queue time and process time
        (t_arrival, qtime, ptime) = yield env.process(process_order(env,res,order,patID))
        # Update data
        data.append((patID, order, clockTime(t_arrival), round(qtime,3), round(ptime,3)))
def generateRandomNumber( distribution, duration ):
    randomNumber = -1 

    if distribution == "Lognormal":
        mu = 4
        sigma = 1
        randomNumber = random.lognormvariate(mu, sigma)
    elif distribution == "Exponential":
        lam = 0.02
        randomNumber = random.expovariate(lam)
    elif distribution == "Poisson":
        lam = 10
        randomNumber = numpy.random.poisson(lam)
    elif distribution == "Weibull":
        scale = 4
        shape = 0.6
        randomNumber = random.weibullvariate(scale, shape)


    return int(randomNumber)
Example #46
0
File: qsim.py Project: ido/cobalt
    def gen_failure_list(self, scale, shape, startdate, enddate):
        '''generate a synthetic failure time list based on weibull distribution
         and start/end date time'''
        failure_moments = []
        ttf_list = []

        start = date_to_sec(startdate)
        end = date_to_sec(enddate)

        cur_failure = start

        while True:
            ttf = random.weibullvariate(scale,shape)
            cur_failure += ttf
            if cur_failure < end:
                ttf_list.append(ttf)
                failure_moments.append(sec_to_date(cur_failure))
            else:
                break
        return failure_moments, ttf_list
Example #47
0
    def find_service_time(self, n, c):
        """
        Finds the service time function
        """

        if self.mu[c][n][0] == "Uniform":
            return lambda: uniform(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == "Deterministic":
            return lambda: self.mu[c][n][1]
        if self.mu[c][n][0] == "Triangular":
            return lambda: triangular(self.mu[c][n][1], self.mu[c][n][2], self.mu[c][n][3])
        if self.mu[c][n][0] == "Exponential":
            return lambda: expovariate(self.mu[c][n][1])
        if self.mu[c][n][0] == "Gamma":
            return lambda: gammavariate(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == "Normal":
            return lambda: gauss(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == "Lognormal":
            return lambda: lognormvariate(self.mu[c][n][1], self.mu[c][n][2])
        if self.mu[c][n][0] == "Weibull":
            return lambda: weibullvariate(self.mu[c][n][1], self.mu[c][n][2])
        return False
Example #48
0
 def visit_dispenser(self):
     """
         Best fit obtained after cleaning the data:
         Weibull Distribution with:
             shape: 1     (beta in python)
             scale: 0.311 (alpha in python)
     """       
     name = 'dispenser'
     if self.debug:
         print self.name, "at ",name, simpy.now()
     
     arrive = simpy.now()
     yield simpy.request, self, self.resources[name]
     wait = simpy.now() - arrive
     self.monitors[name].observe(wait)
     time = random.weibullvariate(alpha=0.311, beta=1)
     tib = self.numberOfForms * time
     yield simpy.hold,self,tib
     yield simpy.release, self, self.resources[name]
     
     for i in self.visit_exit():
         yield i
Example #49
0
 def find_distributions(self, n, c, kind):
     """
     Finds distribution functions
     """
     if self.source(c, n, kind) == 'NoArrivals':
         return lambda : float('Inf')
     if self.source(c, n, kind)[0] == 'Uniform':
         return lambda : uniform(self.source(c, n, kind)[1],
                                 self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Deterministic':
         return lambda : self.source(c, n, kind)[1]
     if self.source(c, n, kind)[0] == 'Triangular':
         return lambda : triangular(self.source(c, n, kind)[1],
                                    self.source(c, n, kind)[2],
                                    self.source(c, n, kind)[3])
     if self.source(c, n, kind)[0] == 'Exponential':
         return lambda : expovariate(self.source(c, n, kind)[1])
     if self.source(c, n, kind)[0] == 'Gamma':
         return lambda : gammavariate(self.source(c, n, kind)[1],
                                      self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Lognormal':
         return lambda : lognormvariate(self.source(c, n, kind)[1],
                                        self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Weibull':
         return lambda : weibullvariate(self.source(c, n, kind)[1],
                                        self.source(c, n, kind)[2])
     if self.source(c, n, kind)[0] == 'Custom':
         P, V = zip(*self.source(c, n, kind)[1])
         probs, values = list(P), list(V)
         return lambda : nprandom.choice(values, p=probs)
     if self.source(c, n, kind)[0] == 'UserDefined':
         return lambda : self.check_userdef_dist(self.source(c, n, kind)[1])
     if self.source(c, n, kind)[0] == 'Empirical':
         if isinstance(self.source(c, n, kind)[1], str):
             empirical_dist = self.import_empirical(self.source(c, n, kind)[1])
             return lambda : nprandom.choice(empirical_dist)
         return lambda : nprandom.choice(self.source(c, n, kind)[1])
Example #50
0
    def xnoiseRythmSequence(self, parameters, barLength ):
        rythmSequence = []
        onsetTime = None
        randomParamScaler = parameters.rythmRegularity[trackId] * 2 + 0.5
        whichRandomGenerator = random.randint(0, 4)
        maximumNumberOfNotes = int( (parameters.density[trackId]) * GenerationConstants.MAX_NOTES_PER_BAR)

        for i in range(maximumNumberOfNotes):
            while onsetTime in rythmSequence:
                if whichRandomGenerator == 0:
                    onsetTime = random.expovariate(GenerationConstants.RANDOM_EXPO_PARAM * randomParamScaler)
                elif whichRandomGenerator == 1:
                    onsetTime = 1 - random.expovariate(GenerationConstants.RANDOM_EXPO_PARAM * randomParamScaler)
                elif whichRandomGenerator == 2:
                    onsetTime = random.gauss(GenerationConstants.RANDOM_GAUSS_PARAM1,
                                                            GenerationConstants.RANDOM_GAUSS_PARAM2 * (3 - randomParamScaler))
                elif whichRandomGenerator == 3:
                    onsetTime = random.betavariate(GenerationConstants.RANDOM_BETA_PARAM * randomParamScaler,
                                                                    GenerationConstants.RANDOM_BETA_PARAM * randomParamScaler)
                elif whichRandomGenerator == 4:
                    onsetTime = random.weibullvariate(GenerationConstants.RANDOM_WEIBULL_PARAM1,
                                                                          GenerationConstants.RANDOM_WEIBULL_PARAM2 * randomParamScaler)

                onsetTime = int(onsetTime * (int(( barLength - 1) / GenerationConstants.DOUBLE_TICK_DUR))) * GenerationConstants.DOUBLE_TICK_DUR

            if onsetTime < 0:
                onsetTime = 0
            elif onsetTime > ( barLength - GenerationConstants.DOUBLE_TICK_DUR):
                onsetTime = ( barLength - GenerationConstants.DOUBLE_TICK_DUR)
            else:
                onsetTime = onsetTime

            rythmSequence.append(onsetTime)

        rythmSequence.sort()
        return rythmSequence
Example #51
0
 def next(self):
     return 1000 * (random.weibullvariate(0.1, 0.345))
Example #52
0
def weibull(alpha, beta):
    return lambda: random.weibullvariate(alpha, beta)
Example #53
0
def make_word(words=None):
    if words is None:
        words = int(random.weibullvariate(8, 3))
    return random.choice(loremipsum.words)
Example #54
0
def make_sentence(words=None):
    if words is None:
        words = int(random.weibullvariate(8, 3))
    return ' '.join(random.choice(loremipsum.words) for _ in range(words))
Example #55
0
 def sample(self):
     return {self.value: random.weibullvariate(self.alpha, self.beta)}
Example #56
0
 def draw(self):
     v = random.weibullvariate(self.scale, self.shape)
     if v < self.location:
         return self.location
     return v
Example #57
0
def FPP(log=Logger.logger(0), N = 10000, dt = 1./24000, distributionParameter = [30], plotAll = True, efield = False):
    
    #check if rate file or rate is present
    if len(distributionParameter)  ==  1:
        try: 
            data = np.loadtxt(distributionParameter[0],delimiter = ' ')
            log.info("Rate data loaded")
            BGsim = True
            STNdata = []
            tick = []
            for n in data:
                STNdata.append(n[1])
                tick.append(n[0])
            Ratetime = pylab.cumsum(tick)
            BGdt = tick[1]
            timeSteps = int(Ratetime[-1]/dt)  
        except:
            float(distributionParameter[0])
            Ratetime = 1.
            timeSteps = int(Ratetime/dt)
            BGsim = False
    else:
        Ratetime = 1.
        BGsim = False
        timeSteps = int(Ratetime/dt)
        
    maxrate = 1./0.009
    times = []
    for n in range(timeSteps):
        times.append(dt*n)

    # check for current file, if none present use impules
    try:
        It = np.loadtxt('C:\\Users\\Kristian\\Dropbox\\phd\\Data\\apcurrent24k.dat',delimiter = ',')

        #/home/uqkweegi/Documents/Data/apcurrent24k.dat',delimiter = ',')
    except:
        log.error('no current file present')
        It = np.array(1)

    log.info('Current loaded')
    It = np.multiply(np.true_divide(It,It.min()),250e-9)          #normalize
    currentLength = len(It)
    
    #calculate extracellular effects
    epsilon = 8.85e-12                                #Permitivity of free space
    rho = 10.**5 * 10.**6                     #density of neurons in STN m^-3
    r = np.power(np.multiply(3./4*N/(np.pi*rho),np.array([random.uniform(0,1) for _ in range(N)])),1./3)   #create a power law distribution of neuron radii
    r.sort()
    if efield:
        rijk = [[random.uniform(0,1)-0.5 for _ in range(N)],[random.uniform(0,1)-0.5 for _ in range(N)],[random.uniform(0,1)-0.5 for _ in range(N)]] #create vector direction of field 
        #if plotAll:
        #    vi = pylab.plot(rijk[0])
        #    vj = pylab.plot(rijk[1])
        #    vk = pylab.plot(rijk[2])
        #    pylab.show()
    R3 = 0.96e3
    C3 = 2.22e-6
    C2 = 9.38e-9
    C3 = 1.56e-6
    C2 = 9.38e-9
    R4 = 100.e6
    R2N = np.multiply(1./(4*np.pi*epsilon),r)
    R1 = 2100.;
    t_impulse = np.array([dt*n for n in range(100)])

    log.info('initialization complete')

    Vt = pylab.zeros(len(times))
    Vi = Vt
    Vj = Vt
    Vk = Vt

    # start simulation
    #-------------------------------------------------------------------------------#
    for neuron in range(N):
        R2 = R2N[neuron]
        ppwave = pylab.zeros(len(times))
        if BGsim:
            absoluteTimes = np.random.exponential(1./(maxrate*STNdata[0]),1)
        else:
            if len(distributionParameter)  ==  1:
                absoluteTimes = np.random.exponential(1./(distributionParameter[0]),1)
            else:
                absoluteTimes = [random.weibullvariate(distributionParameter[0],distributionParameter[1])]
        while absoluteTimes[-1] < times[-1]-currentLength*dt:
            wave_start = int(absoluteTimes[-1]/dt)
            wave_end = wave_start+currentLength
            if wave_end > len(times):
                break
            ppwave[wave_start:wave_end] = np.add(ppwave[wave_start:wave_end],It)
            if BGsim:
                isi = np.random.exponential(1./(maxrate*STNdata[int(absoluteTimes[-1]/BGdt)]),1)
            else:
                if len(distributionParameter)  ==  1:
                    isi = np.random.exponential(1./(distributionParameter[0]),1)
                else:
                    isi = random.weibullvariate(distributionParameter[0],distributionParameter[1])
            absoluteTimes = np.append(absoluteTimes,[absoluteTimes[-1]+isi])
        # calculate neuron contribution
        #------------------------------------------------------------------------------#
        extracellular_impulse_response = np.multiply(np.multiply(np.exp(np.multiply(t_impulse,-20*17*((C2*R1*R2 + C2*R1*R3 + C2*R1*R4 - C3*R1*R3 + C3*R2*R3 + C3*R3*R4))/(2*C2*C3*R1*R3*(R2 + R4)))),(np.add(np.cosh(np.multiply(t_impulse,(C2**2*R1**2*R2**2 + 2*C2**2*R1**2*R2*R3 + 2*C2**2*R1**2*R2*R4 + C2**2*R1**2*R3**2 + 2*C2**2*R1**2*R3*R4 + C2**2*R1**2*R4**2 + 2*C2*C3*R1**2*R2*R3 - 2*C2*C3*R1**2*R3**2 + 2*C2*C3*R1**2*R3*R4 - 2*C2*C3*R1*R2**2*R3 - 2*C2*C3*R1*R2*R3**2 - 4*C2*C3*R1*R2*R3*R4 - 2*C2*C3*R1*R3**2*R4 - 2*C2*C3*R1*R3*R4**2 + C3**2*R1**2*R3**2 - 2*C3**2*R1*R2*R3**2 - 2*C3**2*R1*R3**2*R4 + C3**2*R2**2*R3**2 + 2*C3**2*R2*R3**2*R4 + C3**2*R3**2*R4**2)**(1/2)/(2*C2*C3*R1*R3*(R2 + R4)))),np.divide(np.sinh(np.multiply(t_impulse,(C2**2*R1**2*R2**2 + 2*C2**2*R1**2*R2*R3 + 2*C2**2*R1**2*R2*R4 + C2**2*R1**2*R3**2 + 2*C2**2*R1**2*R3*R4 + C2**2*R1**2*R4**2 + 2*C2*C3*R1**2*R2*R3 - 2*C2*C3*R1**2*R3**2 + 2*C2*C3*R1**2*R3*R4 - 2*C2*C3*R1*R2**2*R3 - 2*C2*C3*R1*R2*R3**2 - 4*C2*C3*R1*R2*R3*R4 - 2*C2*C3*R1*R3**2*R4 - 2*C2*C3*R1*R3*R4**2 + C3**2*R1**2*R3**2 - 2*C3**2*R1*R2*R3**2 - 2*C3**2*R1*R3**2*R4 + C3**2*R2**2*R3**2 + 2*C3**2*R2*R3**2*R4 + C3**2*R3**2*R4**2)**(1/2)/(2*C2*C3*R1*R3*(R2 + R4))))*(C2*R1*R2 - C2*R1*R3 + C2*R1*R4 + C3*R1*R3 - C3*R2*R3 - C3*R3*R4),(C2**2*R1**2*R2**2 + 2*C2**2*R1**2*R2*R3 + 2*C2**2*R1**2*R2*R4 + C2**2*R1**2*R3**2 + 2*C2**2*R1**2*R3*R4 + C2**2*R1**2*R4**2 + 2*C2*C3*R1**2*R2*R3 - 2*C2*C3*R1**2*R3**2 + 2*C2*C3*R1**2*R3*R4 - 2*C2*C3*R1*R2**2*R3 - 2*C2*C3*R1*R2*R3**2 - 4*C2*C3*R1*R2*R3*R4 - 2*C2*C3*R1*R3**2*R4 - 2*C2*C3*R1*R3*R4**2 + C3**2*R1**2*R3**2 - 2*C3**2*R1*R2*R3**2 - 2*C3**2*R1*R3**2*R4 + C3**2*R2**2*R3**2 + 2*C3**2*R2*R3**2*R4 + C3**2*R3**2*R4**2)**(1/2))))),-R4/(C2*(R2 + R4)));
        electrode_ppwave = np.convolve(ppwave,extracellular_impulse_response,'same');
        if efield:  #add fields
            amp = 1/np.sqrt((np.square(rijk[0][neuron])+np.square(rijk[1][neuron])+np.square(rijk[2][neuron])))
            rijk[0][neuron] = rijk[0][neuron]*amp
            rijk[1][neuron] = rijk[1][neuron]*amp
            rijk[2][neuron] = rijk[2][neuron]*amp
            Vi = np.add(Vi,np.multiply(electrode_ppwave,rijk[0][neuron]))
            Vj = np.add(Vj,np.multiply(electrode_ppwave,rijk[1][neuron]))
            Vk = np.add(Vk,np.multiply(electrode_ppwave,rijk[2][neuron]))
        else:       #add scalar
            Vt = np.add(Vt,electrode_ppwave)
        if np.mod(neuron,1000) == 999:
            log.info(str(neuron+1)+" neurons calculated")
    #------------------------------------------------------------------------------#        
    # end simulation
    
    log.info('neuron contribution to MER complete')
    
    #remove bias
    if efield:
        Vt = np.sqrt(np.add(np.square(Vi),np.square(Vj),np.square(Vk)))   
    Vt = np.subtract(Vt,np.mean(Vt))

    #apply hardware filters
    flow = 5500*2.
    fhigh = 500.
    b,a = signal.butter(18,flow*dt,'low')
    Vt = signal.lfilter(b, a, Vt)
    b,a = signal.butter(1,fhigh*dt,'high')
    Vt = signal.lfilter(b, a, Vt)

    #produce plots
    if plotAll:
        volts = pylab.plot(times,Vt)
        if BGsim:
            stnrate = pylab.plot(Ratetime,np.multiply(STNdata,200))
        pylab.show()
        nfft=2**int(math.log(len(Vt),2))+1
        sr = 1/dt
        Pxi,freqs=pylab.psd(x=Vt,Fs=sr,NFFT=nfft/10,window=pylab.window_none, noverlap=100)
        pylab.show()
        return freqs, Pxi
        psd = pylab.loglog(freqs, Pxi)
        pylab.show()
    return Vt, times
 def sample(self):
     return weibullvariate(self.alpha,self.beta)
Example #59
0
random.getrandbits(20)

state = random.getstate()
x1 = random.random()
random.setstate(state)
x2 = random.random()
assert x1==x2

tries = 8000
stat = [0,0,0,0,0,0]
 
for i in range(tries):
    dice = random.randint(1,6)
    stat[dice-1] += 1
    
print("STATISTICS ON {0} DICE THROWS".format(tries))
print("-----------------------------")
for i in range(0, 6):
    percent = (float(stat[i]) * 100.) / float(tries)
    print("{0} : {1} ({2:.1f}%)".format(i+1, stat[i], percent))

random.triangular(10,20,17)
random.normalvariate(10, 4)
random.lognormvariate(3, 1.6)
random.expovariate(3)
random.vonmisesvariate(2, 1)
random.gauss(10,4)
random.betavariate(10,4)
random.paretovariate(5)
random.weibullvariate(10,6)