def SetCorrectIOPTarget(self): """Evaluate for MD progression. Reset IOP target accordingly""" #IOP target is reset stepwise if CumulativeMDR is > 2dB exam = Examination (self.PatientAttribute, self.medicalRecords) exam.Ophthalmology() if self.medicalRecords['Diagnosed'] == True : if self.params['FirstProgression'] == 1 and self.PatientAttribute['CumulativeMDR'] > 2: self.params['SecondProgression'] =1 #Need to reset CumulativeMDR to reflect van Gestel's definition self.PatientAttribute['CumulativeMDR'] = 0 elif self.PatientAttribute['CumulativeMDR'] > 2: self.params['FirstProgression'] = 1 self.PatientAttribute['CumulativeMDR'] = 0 #if no conversion: IOP target = 24 #conversion occurs: IOP target is set according to progression param if self.params['Conversion'] == True: if self.PatientAttribute['MD'] > UpperMild : self.PatientAttribute['IOPTarget'] = int(random.triangular(16,18,21)) elif self.PatientAttribute['MD'] < LowerSever: self.PatientAttribute['IOPTarget'] = int(random.triangular(10,12,14)) else: self.PatientAttribute['IOPTarget'] = int(random.triangular(14,16,18)) else: self.PatientAttribute['IOPTarget'] = int(random.triangular(18,22,24)) #Reset VF countdown. Wait till new VF measurement self.params['VFCountdown'] = 0
def TriangTrunc(TC1, spread1, N, linf=float('-inf'), lsup=float('inf')): if TC1 == 0: return np.asarray([0]*N) if TC1 == 1 and lsup == 1: return np.asarray([1]*N) # define variables for trapezoidal distribution A = TC1*(1-spread1) B = TC1*(1+spread1) dist = nr.triangular(A, TC1, B, N) # remove all that's not in the proper range - we end with a distribution with a length < N truncdist = [i for i in dist if i >= linf] truncdist = [i for i in truncdist if i <= lsup] # Create the "same" triangular distribution with the missing number of samples, and remove all that's not in the range. # "while" -> do that until you have N samples. while len(truncdist) < N: adddist = nr.triangular(A, TC1, B, N-len(truncdist)) truncadddist = [i for i in adddist if i >= linf] truncadddist = [i for i in truncadddist if i <= lsup] # concatenate both triangular distributions truncdist = truncdist + truncadddist return np.asarray(truncdist)
def SetCorrectIOPTarget(self): exam = Examination (self.PatientAttribute, self.medicalRecords) exam.Ophthalmology() if self.medicalRecords['Diagnosed'] == True : if self.params['Conversion'] == True: if self.PatientAttribute['MD'] > UpperMild : self.PatientAttribute['IOPTarget'] = int(random.triangular(16,18,21)) elif self.PatientAttribute['MD'] < LowerSever: self.PatientAttribute['IOPTarget'] = int(random.triangular(10,12,14)) else: self.PatientAttribute['IOPTarget'] = int(random.triangular(14,16,18)) else: self.PatientAttribute['IOPTarget'] = int(random.triangular(18,22,24)) if self.params['FirstProgression'] == 1 and self.PatientAttribute['CumulativeMDR'] > 2: self.params['SecondProgression'] =1 self.PatientAttribute['CumulativeMDR'] = 0 elif self.PatientAttribute['CumulativeMDR'] > 2: self.params['FirstProgression'] = 1 self.PatientAttribute['CumulativeMDR'] = 0 # # if self.params['FirstProgression'] == 1 and self.params['SecondProgression'] == 1: # self.PatientAttribute['IOPTarget'] = ThirdProgressionTarget # elif self.params['FirstProgression'] == 1: # self.PatientAttribute['IOPTarget'] = SecondProgressionTarget # else: # self.PatientAttribute['IOPTarget'] = FirstProgressionTarget # self.params['VFCountdown'] = 0
def testDrawVarying (): #data = np.array ([8,5,4,2]) data0 = rnd.exponential (10, 30) data1 = rnd.triangular (4, 5, 5, 20) data2 = rnd.triangular (10,11,11, 10) data3 = rnd.triangular (14,14,15, 5) data4 = rnd.triangular (0,1,1, 10) data = np.concatenate ((data0,data1,data2,data3,data4), axis=0) #data = data0 data = rnd.beta (5,2,1000) data = [10 * x for x in data] #data0 = rnd.triangular (5, 5, 10, 100) #data1 = rnd.triangular (10, 20, 20, 100) #data2 = rnd.triangular (20, 21, 21, 0) #data = np.concatenate ((data0, data1, data2), axis=0) #data = rnd.triangular (0, 10, 15, 200) data = np.sort (data) #data = np.ceil (data, None) blocks = bucket (data, limit=0.1, depth=3, individualSigma = 2.0, maxExtremas=0, minHeight=0.0) draw (data, blocks=blocks)
def matrices(UP_list, CF, variables_techno, variables_interv): MA = lil_matrix((len(UP_list), len(UP_list))) MB = lil_matrix((CF.shape[1], len(UP_list))) if len(variables_techno["lognormal"]) > 0: MA[array(variables_techno["lognormal"][:, 0], int), array(variables_techno["lognormal"][:, 1], int)] = sign( variables_techno["lognormal"][:, 2]) * random.lognormal( array(variables_techno["lognormal"][:, 3], float32), array(variables_techno["lognormal"][:, 4], float32)) if len(variables_techno["normal"]) > 0: MA[array(variables_techno["normal"][:, 0], int), array(variables_techno["normal"][:, 1], int)] = random.normal( array(variables_techno["normal"][:, 2], float32), array(variables_techno["normal"][:, 3], float32)) if len(variables_techno["triangle"]) > 0: MA[array(variables_techno["triangle"][:, 0], int), array(variables_techno["triangle"][:, 1], int)] = sign( variables_techno["triangle"][:, 2]) * random.triangular( array(variables_techno["triangle"][:, 3], float32), abs(array(variables_techno["triangle"][:, 2], float32)), array(variables_techno["triangle"][:, 4], float32)) if len(variables_techno["deterministe"]) > 0: MA[array(variables_techno["deterministe"][:, 0], int), array(variables_techno["deterministe"][:, 1], int )] = variables_techno["deterministe"][:, 2] if len(variables_interv["lognormal"]) > 0: MB[array(variables_interv["lognormal"][:, 0], int), array(variables_interv["lognormal"][:, 1], int)] = sign( variables_interv["lognormal"][:, 2]) * random.lognormal( array(variables_interv["lognormal"][:, 3], float32), array(variables_interv["lognormal"][:, 4], float32)) if len(variables_interv["normal"]) > 0: MB[array(variables_interv["normal"][:, 0], int), array(variables_interv["normal"][:, 1], int)] = random.normal( array(variables_interv["normal"][:, 2], float32), array(variables_interv["normal"][:, 3], float32)) if len(variables_interv["triangle"]) > 0: MB[array(variables_interv["triangle"][:, 0], int), array(variables_interv["triangle"][:, 1], int)] = sign( variables_interv["triangle"][:, 2]) * random.triangular( array(variables_interv["triangle"][:, 3], float32), abs(array(variables_interv["triangle"][:, 2], float32)), array(variables_interv["triangle"][:, 4], float32)) if len(variables_interv["agregated"]) > 0: MB[array(variables_interv["agregated"][:, 0], int), array( variables_interv["agregated"][:, 1], int )] = variables_interv["agregated"][:, 2] * random.lognormal( array(variables_interv["agregated"][:, 3], float32), array(variables_interv["agregated"][:, 4], float32)) if len(variables_interv["deterministe"]) > 0: MB[array(variables_interv["deterministe"][:, 0], int), array(variables_interv["deterministe"][:, 1], int )] = variables_interv["deterministe"][:, 2] return MA, MB
def _draw_fire_development(self): # {{{ ''' Generate fire. Alpha t square on the left, then constant in the middle, then fading on the right. At the end read hrrs at given times. ''' hrrpua_d = self.conf['hrrpua'] hrr_alpha = self.conf['hrr_alpha'] ''' Fire area is draw from pareto distrubution regarding the BS PD-7974-7. There is lack of vent condition - underventilated fires ''' p = pareto(b=0.668, scale=0.775) fire_area = p.rvs(size=1)[0] fire_origin = self.fire_origin orig_area = self.s.query( "SELECT (width * depth)/10000 as area FROM aamks_geom WHERE name='{}'" .format(fire_origin[0]))[0]['area'] if fire_area > orig_area: fire_area = orig_area self.hrrpua = int( triangular(hrrpua_d['min'], hrrpua_d['mode'], hrrpua_d['max'])) hrr_peak = int(self.hrrpua * 1000 * fire_area) self.alpha = int( triangular(hrr_alpha['min'], hrr_alpha['mode'], hrr_alpha['max']) * 1000) self._psql_log_variable('hrrpeak', hrr_peak / 1000) self._psql_log_variable('alpha', self.alpha / 1000.0) # left t_up_to_hrr_peak = int((hrr_peak / self.alpha)**0.5) interval = int(round(t_up_to_hrr_peak / 10)) times0 = list(range(0, t_up_to_hrr_peak, interval)) + [t_up_to_hrr_peak] hrrs0 = [int((self.alpha * t**2)) for t in times0] # middle t_up_to_starts_dropping = 15 * 60 times1 = [t_up_to_starts_dropping] hrrs1 = [hrr_peak] # right t_up_to_drops_to_zero = t_up_to_starts_dropping + t_up_to_hrr_peak interval = int( round((t_up_to_drops_to_zero - t_up_to_starts_dropping) / 10)) times2 = list( range(t_up_to_starts_dropping, t_up_to_drops_to_zero, interval)) + [t_up_to_drops_to_zero] hrrs2 = [ int((self.alpha * (t - t_up_to_drops_to_zero)**2)) for t in times2 ] times = list(times0 + times1 + times2) hrrs = list(hrrs0 + hrrs1 + hrrs2) return times, hrrs
def sample(self): ((x1, x2), (y1, y2)) = self.surface.box x, y, _ = self.point if self.index == 0: point = np.array([triangular(x1, x, x2), y1+EDGE_DISTANCE, 0]) elif self.index == 1: point = np.array([x1+EDGE_DISTANCE, triangular(y1, y, y2), 0]) elif self.index == 2: point = np.array([triangular(x1, x, x2), y2-EDGE_DISTANCE, 0]) else: point = np.array([x2+EDGE_DISTANCE, triangular(y1, y, y2), 0]) return point + self.surface.z*unit_z()
def StableSetting (self): if self.Attribute['MD'] > UpperMild : self.params['time_next_visit'] = int(random.triangular(6,7,12)) elif self.Attribute['MD'] < LowerSever: self.params['time_next_visit'] = int(random.triangular(1,1,4)) else: self.params['time_next_visit'] = int(random.triangular(4,4.5,6))
def sample(self): ((x1, x2), (y1, y2)) = self.surface.box x, y, _ = self.point if self.index == 0: point = np.array([triangular(x1, x, x2), y1 + EDGE_DISTANCE, 0]) elif self.index == 1: point = np.array([x1 + EDGE_DISTANCE, triangular(y1, y, y2), 0]) elif self.index == 2: point = np.array([triangular(x1, x, x2), y2 - EDGE_DISTANCE, 0]) else: point = np.array([x2 + EDGE_DISTANCE, triangular(y1, y, y2), 0]) return point + self.surface.z * unit_z()
def triangular_process_noise(self, x, dt=1): return { key: x[key] + dt * random.triangular( -self.parameters['process_noise'][key], 0, self.parameters['process_noise'][key]) for key in self.states }
def get_next_generation(self, couples): sorted_couples = sorted(couples, reverse=True) self.best_couples = sorted_couples[:5] new_pop = [] parents_to_keep = 0 for i in range(parents_to_keep): new_pop.append(sorted_couples[i][1][0]) new_pop.append(sorted_couples[i][1][1]) for j in range(len(couples) - parents_to_keep): idx = int(random.triangular(0, 0, len(couples))) parent_1 = sorted_couples[idx][1][0] parent_2 = sorted_couples[idx][1][1] child_1, child_2 = self.mate(parent_1, parent_2) self.mutate(child_1) self.mutate(child_2) new_pop.append(child_1) new_pop.append(child_2) self.pop = new_pop
def generate_events(self, start_time, sim_len): t = start_time count = 0 impulse = np.inf delta_t = 0 prev_max_time = 0 events = [] while t < sim_len: #draw new delays until we are satisfied while prev_max_time > delta_t: delta_t = random.normal(self.mus[0], self.sigmas[0]) #draw new impulses until we are satisfied while impulse > self.max_impulse: fs = random.normal(self.mus[2], self.sigmas[2], 3) durs = random.normal(self.mus[1], self.sigmas[1], 3) durs = np.clip(durs, a_min=0, a_max=None) js = random.triangular(self.jerk[0], self.jerk[1], self.jerk[2], 3) prev_max_time = np.max(durs + 2 * np.divide(fs, js)) impulse = fs.dot(durs) t += delta_t events.append([t, np.array(fs), np.array(js), np.array(durs)]) impulse = np.inf #for i in range(len(events)): # print(i, events[i][0]) return events
def pre(): L = [] N = 100 for i in range(N): L.append(rnd.random() * 10) #print(L) y_uni = rnd.uniform(0, 10, N) y_norm = rnd.normal(0, 10, N) y_trian = rnd.triangular(0, 4, 9, N) y_exp = rnd.exponential(4, N) compare(N, y_uni) compare(N, y_norm) compare(N, y_trian) compare(N, y_exp) x = list(range(N)) plt.plot(x, y_uni, x, y_norm, x, y_trian, x, y_exp) plt.show() wavfile.write('uni.wav', 1000, y_uni) wavfile.write('norm.wav', 1000, y_norm) wavfile.write('trian.wav', 1000, y_trian) wavfile.write('exp.wav', 1000, y_exp) wavfile.write('uni_stereo.wav', 1000, y_uni / np.max(y_uni)) wavfile.write('norm_stereo.wav', 1000, y_norm / np.max(y_norm)) wavfile.write('trian_stereo.wav', 1000, y_trian / np.max(y_trian)) wavfile.write('exp_stereo.wav', 1000, y_exp / np.max(y_exp))
def InitiateCataract(self): key = int((self.Attribute['Age'] -50)/5) cataractRisk = random.triangular(1.5,2.7,4.9) if self.medicalRecords['NumberTrabeculectomy'] == 0: if self.Attribute['Gender'] == 1: if key < 7: RateCataract = (cataract_formation[key]/1000) else: RateCataract = (cataract_formation[7]/1000) else: if key < 7: RateCataract = (cataract_formation_female[key]/1000) else: RateCataract = (cataract_formation_female[7]/1000) else: if self.Attribute['Gender'] == 1: if key < 7: RateCataract = (cataract_formation[key]/1000)*cataractRisk else: RateCataract = (cataract_formation[7]/1000)*cataractRisk else: if key < 7: RateCataract = (cataract_formation_female[key]/1000)*cataractRisk else: RateCataract = (cataract_formation_female[7]/1000)*cataractRisk if random.uniform(0,1) <RateCataract: self.medicalRecords['Cataract'] = True if random.uniform(0,1) < random.beta(123,109) and self.medicalRecords['Cataract'] == True: self.medicalRecords['SurgeryCataract'] += 1 self.medicalRecords['Cataract'] = False
def departure(): """ This generator function simulates the 'departure' of a car, i.e., a car that previously entered the intersection clears the intersection. Once a car has departed, we remove it from the queue, and we no longer track it in the simulation. """ global env, queue while True: # The car that entered the intersection clears the intersection: car_number, t_arrival= queue.popleft() # print("Car #%d departed at time %.3f, leaving %d cars in the queue." # % (car_number, env.now, len(queue))) # Record waiting time statistics: W_stats.count+= 1 W_stats.waiting_time+= env.now - t_arrival # If the light is red or the queue is empty, do not schedule the next # departure. `departure` is a generator, so the `return` statement # terminates the iterator that the generator produces. if light == 'red' or len(queue) == 0: return # Generate departure delay as a random draw from triangular distribution: delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) # Schedule next departure: yield env.timeout(delay)
def get_dist_num(args): dist = args[0] for i in range(len(args[1:])): args[i + 1] = float(args[1:][i]) if dist == 'EXP': return exponential(args[1]) elif dist == 'NOR': return normal(loc=args[1], scale=args[2]) # loc = média , scale = desvio elif dist == 'TRI': return triangular(args[1], args[2], args[3]) elif dist == 'UNI': return uniform(low=args[1], high=args[2]) elif dist == 'BET': return beta(args[1], args[2]) elif dist == 'WEI': return weibull(args[1]) elif dist == 'CAU': # CAU: Cauchy return 0 elif dist == 'CHI': return chisquare(args[1]) elif dist == 'ERL': # ERL: Erlang return 0 elif dist == 'GAM': return gamma(args[1], scale=args[2]) elif dist == 'LOG': return lognormal(mean=args[1], sigma=args[2]) elif dist == 'PAR': return pareto(args[1]) elif dist == 'STU': return standard_t(args[1])
def light(): """ This generator function simulates state changes of the traffic light. For simplicity, the light is either green or red--there is no yellow state. """ global env, light while True: # Section 4.2.1: Change the light to green. light = 'green' print("\nThe light turned green at time %.3f." % env.now) # If there are cars in the queue, schedule a departure event: if len(queue): # Generate departure delay as a random draw from triangular # distribution: delay = random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(env, departure(), delay=delay) # Schedule event that will turn the light red: yield env.timeout(t_green) # Section 4.2.2: Change the light to red. light = 'red' print("\nThe light turned red at time %.3f." % env.now) # Schedule event that will turn the light green: yield env.timeout(t_red)
def get_next_generation(self, couples): sorted_couples = sorted(couples, reverse=True) self.best_couples = sorted_couples[:5] new_pop = [] parents_to_keep = 0 for i in range(parents_to_keep): new_pop.append(sorted_couples[i][1][0]) new_pop.append(sorted_couples[i][1][1]) for j in range(len(couples)-parents_to_keep): idx = int(random.triangular(0,0,len(couples))) parent_1 = sorted_couples[idx][1][0] parent_2 = sorted_couples[idx][1][1] child_1, child_2 = self.mate(parent_1,parent_2) self.mutate(child_1) self.mutate(child_2) new_pop.append(child_1) new_pop.append(child_2) self.pop = new_pop
def triangular_distributed(minval, maxval, mode): """Computes triangular-distributed values with a vector mode parameter. """ # note that the signature of random.triangular and numpy.random.triangular # differs in the position of the mode parameter return asarray([random.triangular(minval, m, maxval) for m in mode])
def recusrive_process(dict_head): if 'BRANCHES' in dict_head: # get branches branches = dict_head['BRANCHES'] # get probs prob_branches = [get_new_dict(x)['PROB'] for x in branches] # assert probs add up to 1 and we only have 2 items assert len(branches) == 2 assert sum(prob_branches) == 1 # determine which to use if random.uniform(0, 1) >= prob_branches[0]: selection = get_new_dict(branches[0]) else: selection = get_new_dict(branches[1]) return recusrive_process(selection) # return final cost if we can, otherwise return recusrive_process elif 'COST' in dict_head: return triangular(dict_head['COST']['LOW'], dict_head['COST']['MODE'], dict_head['COST']['HIGH']) else: raise AssertionError(str(dict_head) + 'had a problem')
def triangular(self, left, top, right): ''' Parameters:\n left: float. \n top: float, must be >= left.\n right: float, must be >= top. ''' return r.triangular(left, top, right, self.size)
def triangular_noise(self, x): return { key: x[key] + random.triangular( -self.parameters['measurement_noise'][key], 0, self.parameters['measurement_noise'][key]) for key in self.outputs }
def __init__(self, nombre, seccion, prob40, prob50, prob55, prob60, confianzai, confianzaf, probprofe): """ :param nombre: Nombre del alumno :type nombre: str :param seccion: Seccion del alumno :type seccion: str :param prob40: probabilidad de tener 40 creditos :type prob40: float :param prob50: probabilidad de tener 50 creditos :type prob50: float :param prob55: probabilidad de tener 55 creditos :type prob55: float :param prob60: probabilidad de tener 60 creditos :type prob60: float :param confianzai: confianza base inicial :type prob40: float :param confianzaf: confianza tope inicial :type prob40: float :param probprofe: probabilidad de ir a hablar con el profe teniendo promedio sobre 5 :type prob40: float """ self.nombre = nombre self.seccion = int(seccion) creditos = random() if creditos <= prob40: self.cantidad_de_creditos = 40 elif creditos > prob40 and creditos <= (prob40 + prob50): self.cantidad_de_creditos = 50 elif creditos > (prob40 + prob50) and creditos <= (prob40 + prob50 + prob55): self.cantidad_de_creditos = 55 else: self.cantidad_de_creditos = 60 # 0 == Eficiente, 1 == Artisitico, 2 == Teorico self.prob_profe = probprofe self.personalidad = randint(0, 2) self.manejo_de_contenidos = 0 self.nota_esperada_t = [] self.nota_esperada_a = [] self.nota_esperada_c = [] self.confianza = uniform(confianzai, confianzaf) self.nivel_programacion = uniform(2, 10) self.progreso = 0 self.horas_dedicadas = 0 self.horas_semana_anterior = 0 self.horas_semana_anteanterior = 0 self.calculo_horas_dedicadas() self.reunion = False self.dias = 0 self.nota_examen = 0 self.promedio = 1 self.v = 0 self.w = 0 self.notas_act = [] self.notas_tar = [] self.notas_cont = [] self.preguntas = int(triangular(1, 3, 10)) self.examen = 0 self.manejos = []
def build_dist(type, n): if type=='l': # ARP: I like the list comprehensions d = [np.mean(r.standard_cauchy(n)) for x in range(x_len)] elif type=='t': d = [np.mean(r.triangular(-15, 0, 15, size=n)) for x in range(x_len)] elif type=='u': d = [np.mean(r.uniform(-15, 15, n)) for x in range(x_len)] return d
def granularize_signal(wav, minGrainSz, modeGrainSz, maxGrainSz): sampleMarker = 0 grainMarkers = [] numSamples = len(wav) while sampleMarker < numSamples: grainSz = floor(rnd.triangular(minGrainSz, modeGrainSz, maxGrainSz)) grainMarkers.append([int(sampleMarker), int(sampleMarker+grainSz)]) sampleMarker = sampleMarker + grainSz return grainMarkers
def MiTriangular(left, mode, right): """Triangular Distribution Function left: Lower Limit mode: Mode right: Upper Limit""" global manflag if not manflag: setManual() return np.triangular(left,mode,right,1)
def _draw_fire_development(self): # {{{ ''' Generate the fire. Alpha t square on the left, then constant in the middle, then fading on the right. At the end read hrrs at given times. ''' hrrpua = self.conf['hrrpua'] hrr_alpha = self.conf['hrr_alpha'] #'TODO:' HRR_PEAK is calculated as if each room was 10 m2, by HRRPUA times 10. It should be better addressed, by choosing room area and vent characteristics hrr_peak = int( triangular(hrrpua['min'], hrrpua['mode'], hrrpua['max']) * 10000) alpha = int( triangular(hrr_alpha['min'], hrr_alpha['mode'], hrr_alpha['max']) * 1000) self._psql_log_variable('hrrpeak', hrr_peak / 1000) self._psql_log_variable('alpha', alpha / 1000.0) # left t_up_to_hrr_peak = int((hrr_peak / alpha)**0.5) interval = int(round(t_up_to_hrr_peak / 10)) times0 = list(range(0, t_up_to_hrr_peak, interval)) + [t_up_to_hrr_peak] hrrs0 = [int((alpha * t**2)) for t in times0] # middle t_up_to_starts_dropping = 15 * 60 times1 = [t_up_to_starts_dropping] hrrs1 = [hrr_peak] # right t_up_to_drops_to_zero = t_up_to_starts_dropping + t_up_to_hrr_peak interval = int( round((t_up_to_drops_to_zero - t_up_to_starts_dropping) / 10)) times2 = list( range(t_up_to_starts_dropping, t_up_to_drops_to_zero, interval)) + [t_up_to_drops_to_zero] hrrs2 = [int((alpha * (t - t_up_to_drops_to_zero)**2)) for t in times2] times = list(times0 + times1 + times2) hrrs = list(hrrs0 + hrrs1 + hrrs2) return (times, hrrs)
def action(actionName, minTime, modeTime, maxTime): min_time = minTime mode_time = modeTime max_time = maxTime #1 heat water to 110 degrees time = triangular(left=min_time, mode=mode_time, right=max_time) print('%s: %s seconds' % (actionName, str(time))) return time
def dump_calibrated_data(fname): data = numpy.load(fname) # Figure out the times covered by the file from the filename # I should start using HDF5 so I can store metadata temp = fname.split('.')[0] temp = temp.split('-') ifo = temp[0] st, dur = int(temp[-2]), int(temp[-1]) et = st + dur maxidx = len(data) width = 45 weights = 1. - ((numpy.arange(-width, width) / float(width))**2) # The VCO frequencies are integers so we could dither them # to avoid quantization error if we wanted to be fancy # but it seems to make no differece if False: from numpy.random import triangular data[:, 1] += triangular(-1., 0., 1., size=len(data)) # Just fit the whole thing at once, to get a single coefficient a, b = numpy.polyfit(data[:, 0], data[:, 1], 1) print "%.1f %u" % (a, b) # Slide through the data fitting PSL to IMC for data around each sample coeffs = [] for idx in xrange(maxidx): idx1 = max(0, idx - width) idx2 = min(idx + width, maxidx) coeffs.append(numpy.polyfit(data[idx1:idx2, 0], data[idx1:idx2, 1], 1, w=weights[idx1 - idx + width:idx2 - idx + width])) coeffs = numpy.array(coeffs) times = numpy.arange(len(coeffs)) + 0.5 connection = datafind.GWDataFindHTTPConnection() cache = connection.find_frame_urls( ifo[0], '%s_R' % ifo, st, et, urltype='file') imc = TimeSeries.read(cache, "%s:IMC-F_OUT_DQ" % ifo, st, et) imc = imc[::16384 / 256] print imc samp_times = numpy.arange(len(imc)) / 256. coeffs0 = numpy.interp(samp_times, times, coeffs[:, 0]) coeffs1 = numpy.interp(samp_times, times, coeffs[:, 1]) - 7.6e7 vco_interp = coeffs0 * imc.data + coeffs1 chan = "%s:IMC-VCO_PREDICTION" % (ifo,) vco_data = TimeSeries(vco_interp, epoch=st, sample_rate=imc.sample_rate.value, name=chan, channel=chan) vco_data.write("%s-vcoprediction-%u-%u.hdf" % (ifo, st, dur), format='hdf')
def time_to_mutation_rate(tree): if not hasattr(GC,"NUMPY_SEEDED"): from numpy.random import seed as numpy_seed numpy_seed(seed=GC.random_number_seed) GC.random_number_seed += 1 GC.NUMPY_SEEDED = True t = read_tree_newick(tree) for node in t.traverse_preorder(): if node.edge_length is not None: node.edge_length *= triangular(left=GC.tree_rate_left,mode=GC.tree_rate_mode,right=GC.tree_rate_right) return str(t)
def resample(self): """ Resamples the distribution """ # Do not store in self.value because that involves a pointer dereference newval = random.triangular(self.value - self.temp, self.value, self.value + self.temp) #while (newval > self.b) or (newval < self.a): # newval = random.triangular(self.value-self.temp, self.value, self.value+self.temp) self.value = newval return newval
def TriangTrunc(TC1, spread1, N, linf, lsup): if lsup < linf: raise Exception('lsup should be larger than linf') if spread1 < 0: raise Exception('spread1 should not be below 0') if TC1 == 0: if N == 1: return 0 else: return np.asarray([0] * N) # define variables for triangular distribution A = TC1 * (1 - spread1) B = TC1 * (1 + spread1) if B < linf or A > lsup: raise Exception('TC1, TC2, linf and lsup are not compatible') dist = nr.triangular(A, TC1, B, N) # remove all that's not in the proper range - we end with a distribution with a length < N truncdist = [i for i in dist if i >= linf] truncdist = [i for i in truncdist if i <= lsup] # Create the "same" triangular distribution with the missing number of samples, and remove all that's not in the range. # "while" -> do that until you have N samples. while len(truncdist) < N: adddist = nr.triangular(A, TC1, B, N - len(truncdist)) truncadddist = [i for i in adddist if i >= linf] truncadddist = [i for i in truncadddist if i <= lsup] # concatenate both triangular distributions truncdist = truncdist + truncadddist if N == 1: return truncdist[0] else: return np.asarray(truncdist)
def TriangTruncDet(min, TC1, max, N, linf, lsup): import numpy.random as nr import numpy as np dist = nr.triangular(min, TC1, max, N) truncdist = [i for i in dist if i >= linf] truncdist = [i for i in truncdist if i <= lsup] while len(truncdist) < N: adddist = nr.triangular(min, TC1, max, N - len(truncdist)) truncadddist = [i for i in adddist if i >= linf] truncadddist = [i for i in truncadddist if i <= lsup] truncdist = truncdist + truncadddist return np.asarray(truncdist) # for testing #import matplotlib.pyplot as plt #plt.hist(TrapezTrunc(TC1=0.2, TC2=0.5, spread1=1.5, spread2=0.4, N=100, linf=0, lsup=1), bins=50)
def identify(self, coin): coin.identified = True random_year = random.triangular(1900, 2017, 2019) if random_year <= 1939: coin.numismatic_value = 1000 self._value1000_coins.append(coin.get_coin()) elif random_year <= 1914: coin.numismatic_value = 2000 self._value2000_coins.append(coin.get_coin()) else: coin.numismatic_value = 0 self._value0_coins.append(coin.get_coin()) hasattr(coin, "Coins")
def getNumTrucks(self, operationType): param = Parameters() if param.WITH_SHIFTS: if operationType == Constants.ENTREGA: return ceil( random.triangular(Constants.MINIMUM_TRUCKS_ENTREGA, Constants.MEDIAN_TRUCKS_ENTREGA, Constants.MAXIMUM_TRUCKS_ENTREGA)) elif operationType == Constants.RECOGIDA: return ceil( random.triangular(Constants.MINIMUM_TRUCKS_RECOGIDA, Constants.MEDIAN_TRUCKS_RECOGIDA, Constants.MAXIMUM_TRUCKS_RECOGIDA)) else: # DUAL return ceil( random.triangular(Constants.MINIMUM_TRUCKS_DUAL, Constants.MEDIAN_TRUCKS_DUAL, Constants.MAXIMUM_TRUCKS_DUAL)) else: return ceil( random.triangular(Constants.MINIMUM_TRUCKS, Constants.MEDIAN_TRUCKS, Constants.MAXIMUM_TRUCKS))
def mutate(self): mutate = ran.random(len(self.INDEX_DATA)) mutate[mutate > self.M_RATE] = 0. mutation_index = mutate.nonzero()[0] self.flat[self.INDEX_DATA[mutation_index]] = ran.triangular( 0., self.flat[self.INDEX_DATA[mutation_index]], 1.) size_2d = L * (L - 1) // 2 - 1 # transfer-mutation from higher rounds_remaining to lower for rounds_remaining in reversed(range(self.R - 1)): mutate_shift = ran.random(size_2d) mutate_shift[mutate_shift > self.M_SHIFT_RATE] = 0. mutation_index = mutate_shift.nonzero()[0] self.flat[self.INDEX_DATA[mutation_index] + rounds_remaining * self.STRIDES[0]] = \ self.flat[self.INDEX_DATA[mutation_index] + (rounds_remaining + 1) * self.STRIDES[0]]
async def newStock(): global users global stockList # A. Names the stock (newStock) adj1 = str(r.choice(AdjAlpha)) adj2 = str(r.choice(AdjAlpha)) # ensures no repeats in adjectives while adj1 == adj2: adj2 = str(r.choice(AdjAlpha)) newStock = adj1 + ' ' + adj2 + ' ' + str(r.choice(NAlpha)) # B. Creates the Ticker symbol (newTicker) pullTicker = [char for char in newStock if char.isupper()] newTicker = '' for char in pullTicker: newTicker += str(char) initialPrice = round(random.triangular(1, 25, 625), 2) # i. Creates the initial mean and stdev for the growth rate randomX = round(random.triangular(-5, 1, 5), 2) randomY = round(random.triangular(0.1, 1, 10), 2) # opens json file and adds the ticker and the price under the stock name if not newTicker in stockList: stockList[newTicker] = {} stockList[newTicker]['stockName'] = newStock stockList[newTicker]['initialPrice'] = initialPrice stockList[newTicker]['price'] = initialPrice stockList[newTicker]['randomX'] = randomX stockList[newTicker]['randomY'] = randomY stockList[newTicker]['buyers'] = {} stockList[newTicker]['pastPrices'] = [] for i in range(50): stockList[newTicker]['pastPrices'].append(0)
def start(): global env while True: # If there are cars in the queue, schedule a departure event: if len(q1) or len(q2) or len(q3) or len(q4): # Generate departure delay as a random draw from triangular # distribution: delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(env, departure(), delay=delay) yield env.timeout(t_green) yield env.timeout(t_red)
def departure(): """ Simulates the departure of a car """ global env, queue while True: car_number, t_arrival= queue.popleft() print("Car #%d departed at time %.3f, leaving %d cars in the queue." % (car_number, env.now, len(queue))) W_stats.count+= 1 W_stats.waiting_time+= env.now - t_arrival if light == 'red' or len(queue) == 0: return # The `return` statement terminates the iterator that the generator produces. delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) yield env.timeout(delay) # Schedule next departure:
def light(): """ Simulates state changes of the traffic light. """ global env, light while True: light= 'green' print("\nThe light turned green at time %.3f." % env.now) if len(queue): delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) start_delayed(env, departure(), delay=delay) yield env.timeout(t_green) light= 'red' print("\nThe light turned red at time %.3f." % env.now) yield env.timeout(t_red)
def primera_vez(): #if not NUMEROS_ALEATORIOS_COMUNES: return triangular(12, 20, 25)
def segunda_vez(): #if not NUMEROS_ALEATORIOS_COMUNES: return triangular(12, 16, 20)
def Lab(): if not NUMEROS_ALEATORIOS_COMUNES: return triangular(25, 60, 60) else: return next(generador_Lab)
def primera_vez(): return triangular(12, 15, 20)
def tiempo_triage(): if not NUMEROS_ALEATORIOS_COMUNES: return triangular(3,5,3) else: return next(generador_tiempo_triage)
def Lab(): return triangular(25, 45, 60)
def tiempo_espera_enfermera(): if not NUMEROS_ALEATORIOS_COMUNES: return triangular(4, 5, 5) else: return next(generador_tiempo_espera_enfermera)
def project(hours_min, hours_max, hours_mode, price_min, price_max, price_mode, delivery_min): hours = int(random.triangular(hours_min, hours_mode, hours_mode)) price = int(random.triangular(price_min, price_mode, price_max)) ideal_devs = workforce_sample(delivery_min) return (hours, price, ideal_devs)
def segunda_vez(): return triangular(12, 16, 20)
def tiempo_medico_FT(): return triangular(15,20,21)
temp = temp.split('-') ifo = temp[0] st, dur = int(temp[-2]), int(temp[-1]) et = st + dur maxidx = len(data) width = 45 weights = 1. - ((arange(-width, width) / float(width))**2) # The VCO frequencies are integers so we could dither them # to avoid quantization error if we wanted to be fancy # but it seems to make no differece if False: from numpy.random import triangular data[:, 1] += triangular(-1., 0., 1., size=len(data)) # Just fit the whole thing at once, to get a single coefficient a, b = polyfit(data[:, 0], data[:, 1], 1) print "%.1f %u" % (a, b) # Slide through the data fitting PSL to IMC for data around each sample coeffs = [] for idx in xrange(maxidx): idx1 = max(0, idx - width) idx2 = min(idx + width, maxidx) coeffs.append(polyfit(data[idx1:idx2, 0], data[idx1:idx2, 1], 1, w=weights[idx1 - idx + width:idx2 - idx + width])) coeffs = array(coeffs) times = arange(len(coeffs)) + 0.5 connection = datafind.GWDataFindHTTPConnection()
def matrices(UP_list,CF, variables_techno, variables_interv): MA=lil_matrix((len(UP_list),len(UP_list))) MB=lil_matrix((CF.shape[1],len(UP_list))) if len(variables_techno["lognormal"])>0: MA[array(variables_techno["lognormal"][:,0],int),array(variables_techno["lognormal"][:,1],int)] =sign(variables_techno["lognormal"][:,2])*random.lognormal(array(variables_techno["lognormal"][:,3],float32),array(variables_techno["lognormal"][:,4],float32)) if len(variables_techno["normal"])>0: MA[array(variables_techno["normal"][:,0],int),array(variables_techno["normal"][:,1],int)] = random.normal(array(variables_techno["normal"][:,2],float32),array(variables_techno["normal"][:,3],float32)) if len(variables_techno["triangle"])>0: MA[array(variables_techno["triangle"][:,0],int),array(variables_techno["triangle"][:,1],int)] = sign(variables_techno["triangle"][:,2])*random.triangular(array(variables_techno["triangle"][:,3],float32),abs(array(variables_techno["triangle"][:,2],float32)),array(variables_techno["triangle"][:,4],float32)) if len(variables_techno["deterministe"])>0: MA[array(variables_techno["deterministe"][:,0],int),array(variables_techno["deterministe"][:,1],int)] = variables_techno["deterministe"][:,2] if len(variables_interv["lognormal"])>0: MB[array(variables_interv["lognormal"][:,0],int),array(variables_interv["lognormal"][:,1],int)] =sign(variables_interv["lognormal"][:,2])*random.lognormal(array(variables_interv["lognormal"][:,3],float32),array(variables_interv["lognormal"][:,4],float32)) if len(variables_interv["normal"])>0: MB[array(variables_interv["normal"][:,0],int),array(variables_interv["normal"][:,1],int)] = random.normal(array(variables_interv["normal"][:,2],float32),array(variables_interv["normal"][:,3],float32)) if len(variables_interv["triangle"])>0: MB[array(variables_interv["triangle"][:,0],int),array(variables_interv["triangle"][:,1],int)] = sign(variables_interv["triangle"][:,2])*random.triangular(array(variables_interv["triangle"][:,3],float32),abs(array(variables_interv["triangle"][:,2],float32)),array(variables_interv["triangle"][:,4],float32)) if len(variables_interv["agregated"])>0: MB[array(variables_interv["agregated"][:,0],int),array(variables_interv["agregated"][:,1],int)] = variables_interv["agregated"][:,2]*random.lognormal(array(variables_interv["agregated"][:,3],float32),array(variables_interv["agregated"][:,4],float32)) if len(variables_interv["deterministe"])>0: MB[array(variables_interv["deterministe"][:,0],int),array(variables_interv["deterministe"][:,1],int)] = variables_interv["deterministe"][:,2] return MA, MB
def departure(): """ This generator function simulates the 'departure' of a car, i.e., a car that previously entered the intersection clears the intersection. Once a car has departed, we remove it from the queue, and we no longer track it in the simulation. """ global env, departure_count, q1, q2, q3, q4 lane_map = {"q1":q1, "q2":q2, "q3":q3, "q4":q4} car_map = {} while True: # The car that entered the intersection clears the intersection: cars = [] if len(q1) > 0: car1 = q1.popleft() car_map["q1"] = car1 cars.append(car1) if len(q2) > 0: car2 = q2.popleft() car_map["q2"] = car2 cars.append(car2) if len(q3) > 0: car3 = q3.popleft() car_map["q3"] = car3 cars.append(car3) if len(q4) > 0: car4 = q4.popleft() car_map["q4"] = car4 cars.append(car4) winners = run_auction(cars, lane_map) losers = filter(lambda x: x not in winners, car_map.keys()) # print len(q1) # print len(q2) # print len(q3) # print len(q4) # print winners # print losers # print car_map # print "*"*100 for loser in losers: lane_map[loser].appendleft(car_map[loser]) for winner in winners: car_number, lane, left_in, combo, budget, t_arrival= car_map[winner] print("Car #%d departed lane %s at time %.3f, leaving %d cars in the queue." % (car_number, lane, env.now, len(lane_map[lane]))) departure_count += 1 # Record waiting time statistics: W_stats.count+= 1 W_stats.waiting_time+= env.now - t_arrival # If the light is red or the queue is empty, do not schedule the next # departure. `departure` is a generator, so the `return` statement # terminates the iterator that the generator produces. if len(q4) == 0 or len(q3) == 0 or len(q2) == 0 or len(q1) == 0: return # Generate departure delay as a random draw from triangular distribution: delay= random.triangular(left=t_depart_left, mode=t_depart_mode, right=t_depart_right) # Schedule next departure: yield env.timeout(delay)
def tiempo_medico_FT(): if not NUMEROS_ALEATORIOS_COMUNES: return triangular(15,20,21) else: return next(generador_tiempo_medico_FT)
def tiempo_espera_enfermera(): return triangular(4, 5, 5)
def testDrawVarying (): #data = np.array ([8,5,4,2]) data0 = rnd.exponential (10, 50) data1 = rnd.triangular (4, 5, 5, 20) data2 = rnd.triangular (10,11,11, 100) data3 = rnd.triangular (14,14,15, 5) data4 = rnd.triangular (0,1,1, 10) data = np.concatenate ((data0,data1,data2,data3,data4), axis=0) uni0 = rnd.uniform (4,12,80) uni1 = rnd.uniform (8,12,30) #data = data0 # data = rnd.beta (6,4,20) # data = [10 * x -3 for x in data] # dataZero = rnd.triangular (0,0,1,1) # data0 = rnd.triangular (5, 5, 10, 100) # data1 = rnd.triangular (10, 20, 20, 100) # data2 = rnd.triangular (20, 21, 21, 0) # data = np.concatenate ((data0, data1, data2), axis=0) # data = rnd.triangular (0, 10, 15, 200) # data = np.concatenate ((dataZero,data), axis=0) # data = [1,1,2,3,4,4,4,4,4,5,5,5,7,7,7] # data = [2,2,2,4,4,6,8,10] # data = [2,2,2,4,5,6,7,7,7,8] # data = [1,1,1,2,2,2,2,4,4,4,4] # data = [-2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0,4.0,4.0, 4.0, 5.0, 5.0, 5.0, 6.0, 6.0] #data = [sin(x/10.0) for x in xrange (0,200)] #print data #return data data = np.sort (data) #data = np.ceil (data, None) addData = [4,4,6,6,8,8,10,10] # data = [2,4,6] data = np.concatenate ((rnd.triangular (-50,100,150, 1500), rnd.triangular (150,200,280, 1500)), axis = 0) data = range (0, 20, 1) # constant increase # data = [10]*20 # uniform # data = rnd.exponential (200, 3000) # data = [d+random.gauss(0,0.1) for d in data] addData = [] # addData = uni0 # addData = [8,10] #data = data4 data.sort () # addData = data0 addData.sort () #blocks = bucket (data, limit=0.05, depth=3) countEstimation = AdaptiveBinning (list(data), sort=True) countEstimation.histogramify () print str (countEstimation) data = np.concatenate ((data, addData), axis=0) data.sort () countEstimation += addData countEstimation.histogramify () print str (countEstimation) np.sort (data) blocks = countEstimation._blocks fig, axs = plt.subplots (2,2, sharex=False, sharey = False) # fig = plt.figure(figsize=(12, 6)) # fig = plt.figure(1) #, figsize=(12, 6)) # plt.subplot (211) # vax = fig.add_subplot(211) draw_true_vs_est (axs[0,0], data, blocks=blocks, countEstimation = countEstimation) #draw2 (data, blocks=blocks, countEstimation = countEstimation) # fig = plt.figure(2) # vax = fig.add_subplot(212) # plt.subplot (212) draw_differences (axs[0,1], data, blocks=blocks, countEstimation = countEstimation) draw_histo_pdf (axs[1,1], data, blocks=blocks, countEstimation = countEstimation) plt.show ()
def triangular_distribution(minimum, maximum, median): x = random.triangular(minimum, median, maximum) return x
def tiempo_triage(): return triangular(3,5,3)