def test_mpArray_init_(self): n = random.randint(1,5000) #x = [random.random() for i in range(n)] #self.assertRaises(TypeError, mpArray.mpArray, x) y = [mpmath.rand() for i in range(n)] arr = mpArray.mpArray(y) self.assertTrue(numpy.all(arr==y)) z = [mpmath.mpc(mpmath.rand(),mpmath.rand()) for i in range(n)] z_real = [zz.real for zz in z] z_imag = [zz.imag for zz in z] arr = mpArray.mpArray(z) self.assertTrue(numpy.all(arr==z)) self.assertTrue(numpy.all(arr.real() == z_real)) self.assertTrue(numpy.all(arr.imag() == z_imag)) start = time.clock() x=[mpmath.mpc('0','0')]*n t1 = time.clock() - start start = time.clock() x=[mpmath.mpc('0','0') for i in range(n)] t2 = time.clock() -start if self.verbose: print("[]*",n,t1,"vs.[for i in range(n)]",n,t2)
def testQmapSystem(self): dim = random.randint(1,20) print dim qmin = -mpmath.rand() qmax = mpmath.rand() pmin = -mpmath.rand() pmax = mpmath.rand() domain = [[qmin,qmax],[pmin,pmax]] qmapsys = QmapSystem(map=self.map, type='U', dim=dim, domain=domain)
def get_random_opinion(): """ Static function for obtaining a random opinion compliant with the subjective logic requirement """ while True: r1 = mpmath.rand() r2 = mpmath.rand() if r1 + r2 < 1: return Opinion(r1, r2, mpmath.mpf("1") - (r1 + r2), "1/2")
def scaled_dirichlet(n: int, u: float) -> List[float]: assert n > 0 if n == 1: return np.asarray([u], dtype=DTYPE) random_vals = [mpmath.rand() for _ in range(n)] intermediate = [-mpmath.log(1 - x) for x in random_vals] divisor = sum(intermediate) result = [x * u / divisor for x in intermediate] return result
def simanneal(montecarloList): print(montecarloList[0].coordinates) eiwitstreng = montecarloList[0] print(eiwitroute(eiwitstreng)) #visualPath(eiwitstreng) temperature = 5 aantal = 0 start_time = time.clock() highscorestreng = eiwitstreng.coordinates[:] highscorescore = deepcopy(eiwitstreng.score) while (temperature > 1): #temperature = calctemp(temperature) nieuweroute = routeaanpas(eiwitstreng, eiwitroute(eiwitstreng)) scoredifference = finalScore(nieuweroute, eiwitstreng) - counterFirst( eiwitstreng.streng) if scoredifference >= 0: print("de score nu:", eiwitstreng.score + scoredifference) eiwitstreng.score += scoredifference eiwitstreng.coordinates = nieuweroute start_time = time.clock() print(temperature) if eiwitstreng.score > highscorescore: highscorestreng = eiwitstreng.coordinates[:] highscorescore = deepcopy(eiwitstreng.score) elif scoredifference < 0 and (-scoredifference / temperature) < rand(): eiwitstreng.score += scoredifference eiwitstreng.coordinates = nieuweroute print(scoredifference) print("de scoredifference:", math.exp(scoredifference / temperature), ',', rand()) aantal += 1 temperature *= 0.99995 eiwitstreng.coordinates = highscorestreng eiwitstreng.score = highscorescore print(eiwitstreng.score) print(aantal) visualPath(eiwitstreng) print(highscorescore)
def test_mpArray_div(self): n = random.randint(1,5000) x1 = [mpmath.mpc(mpmath.rand(), mpmath.rand()) for i in range(n)] x2 = [mpmath.mpc(mpmath.rand(), mpmath.rand()) for i in range(n)] arr1 = mpArray.mpArray(x1) arr2 = mpArray.mpArray(x2) start = time.clock() x3 = [x1[i] / x2[i] for i in range(n)] t1 = time.clock() - start start = time.clock() arr3 = arr1 / arr2 t2 = time.clock() -start self.assertTrue(numpy.all(x3==arr3)) if self.verbose: print("-----------------------") print("number of ",n,"data mul(list) time:", t1) print("number of ",n,"data mul(mpArray) time:", t2)
def __test_getEigen(self): dim = random.randint(1,20) qmin = -mpmath.rand() qmax = mpmath.rand() pmin = -mpmath.rand() pmax = mpmath.rand() domain = [[qmin,qmax],[pmin,pmax]] qmapsys = QmapSystem(map=self.map, type='U', dim=dim, domain=domain) evals, evecs = qmapsys.getEigen() for evec in evecs: self.assertTrue(mpmath.fabs(evec.norm() -mpmath.mpf(1) ) < 1e-32) for i in range(len(evecs)): vals = [ evecs[i].inner(evecs[j]) for j in range(len(evecs)) ] self.assertTrue(mpmath.fabs(mpmath.fabs(vals[i]) - 1.0) < 1e-32) vals.pop(i) index = [x < 1e-32 for x in vals] self.assertFalse(numpy.all(index)) for evec in evecs: evec.hsmrep(10,10)
def get_random(min, max, max_decimal_places): """ Returns a pseudo-random mpmath.mpf value between min and max (inclusive) with at most max_decimal_places. Assumes max is greater than min. """ #step 1: make sure min and max have the right number of dps #e.g. min: 4.5 ; max: 7.8 ; dps: 1 min = mpmath.mpf(schop(min, max_decimal_places)) max = mpmath.mpf(schop(max, max_decimal_places)) #step 2: instead of dealing with -ve numbers directly, we bump #them positive and bump the random number back later bump_value = mpmath.fabs(min) + 1 bump_back = False if min < 1: min += bump_value max += bump_value bump_back = True #step 3: take 0.5*10^(-dp) away from min, add the same to max #this is so rounding will give min and max a fair go #e.g. min: 4.45 ; max: 7.85 ; dps: 1 min -= mpmath.mpf(0.5) * mpmath.power(10, -max_decimal_places) max += mpmath.mpf(0.5) * mpmath.power(10, -max_decimal_places) #step 4: get a random number between [min, max) using normal rand() #e.g. intermediary: [0, 1) * 3.4 + 4.45 = [4.45, 7.85) intermediary = mpmath.rand() * (max - min) + min #step 5: bump back if necesary if bump_back: intermediary -= bump_value #step 6: round that number to dps #e.g. ret can't be < 4.5 because intermediary >= 4.45 # ret can't be > 7.8 because intermediary < 7.85 ret = mpmath.mpf(sround(intermediary, max_decimal_places)) return ret
def getRandomNumber(): return rand()
def getMultipleRandoms(n): ''' Returns n random numbers. ''' for _ in arange(0, n): yield rand()
def mp_rand_dist(l): v = np.array([mp.rand() for i in range(l)]) return v / v.sum()
def setUp(self): mpmath.mp.dps = 40 k=mpmath.rand()*mpmath.mpf("10") self.map = maps.StandardMap(k=k)
def experiment(path): csv = open(path + '/summary.csv', 'w') numagents = 50 for perclink in range(5, 26, 5): #for num_b in range(25,251,25): for num_b in range(2, 30, 3): agents = [] for i in range(numagents): agents.append(Agent("Agent" + repr(i), mpmath.rand())) for ag1 in agents: for ag2 in agents: if ag1 != ag2 and int(mpmath.floor( mpmath.rand() * 100)) < perclink: ag1.addNeighbour(ag2) chosen_agent = int(mpmath.floor(mpmath.rand() * numagents)) t = AberdeenExperimentBothOperatorsSameExploration( path + '/exp-' + repr(numagents) + '-' + repr(perclink) + '-' + repr(num_b) + '-' + repr(chosen_agent), "Agent" + repr(chosen_agent)) print >> sys.stderr, 'exp-' + repr(numagents) + '-' + repr( perclink) + '-' + repr(num_b) + '-' + repr(chosen_agent) + "\n" for ag in agents: t.add_agent(ag) t.save() t.bootstrap(num_b) t.save() print "bootstrapped" for i in range(25): #for i in range(5): print "iteration num: " + repr(i) t.run_experiment() t.save() [r1, r2, r3, r4, r1b, r2b, r3b, r4b] = t.distance_ratio_results() mean1 = "" # operator AT2013 - conference std1 = "" mean2 = "" # operator AT2013 extended parallel std2 = "" mean3 = "" # operator AT2013 extended half std3 = "" mean4 = "" # operator UAI referee std4 = "" #distance between expected values as suggested by Lance mean1b = "" # operator AT2013 - conference std1b = "" mean2b = "" # operator AT2013 extended parallel std2b = "" mean3b = "" # operator AT2013 extended half std3b = "" mean4b = "" # operator UAI referee std4b = "" if r1.get_mean_std() != None: mean1 = r1.get_mean_std()[0] std1 = r1.get_mean_std()[1] if r2.get_mean_std() != None: mean2 = r2.get_mean_std()[0] std2 = r2.get_mean_std()[1] if r3.get_mean_std() != None: mean3 = r3.get_mean_std()[0] std3 = r3.get_mean_std()[1] if r4.get_mean_std() != None: mean4 = r4.get_mean_std()[0] std4 = r4.get_mean_std()[1] if r1b.get_mean_std() != None: mean1b = r1b.get_mean_std()[0] std1b = r1b.get_mean_std()[1] if r2b.get_mean_std() != None: mean2b = r2b.get_mean_std()[0] std2b = r2b.get_mean_std()[1] if r3b.get_mean_std() != None: mean3b = r3b.get_mean_std()[0] std3b = r3b.get_mean_std()[1] if r4b.get_mean_std() != None: mean4b = r4b.get_mean_std()[0] std4b = r4b.get_mean_std()[1] csv.write( '"{0}","{1}","{2}","{3}","{4}","{5}","{6}","{7}","{8}","{9}","{10}","{11}","{12}","{13}","{14}","{15}","{16}","{17}","{18}"\n' .format(perclink, num_b, chosen_agent, mean1, std1, mean2, std2, mean3, std3, mean4, std4, mean1b, std1b, mean2b, std2b, mean3b, std3b, mean4b, std4b)) csv.flush() csv.close()
def _truth(self): if mpmath.rand() < eval(self.probability): return True else: return False
def event(*args): global loader global scaler global queue_loader global queue_scaler global ListOfQueueLoader global ListOfQueueScaler global kendaraan delay = {'loading': 0, 'scaling': 0} if args[0]['event_name'] == 'StartOperating': for vehicle in range(kendaraan): FEL.append({ 'event_name': 'Arrival', 'time': args[0]['time'], 'dump_truck': vehicle }) elif args[0]['event_name'] == 'Arrival': pass if loader < active_loader: rand_loading_time = rand() loading_time = 0 for cdf_scalingtime in loadingtime['cdf']: if cdf_scalingtime > rand_loading_time: loading_time = loadingtime['time'][ loadingtime['cdf'].index(cdf_scalingtime)] break FEL.append({ 'event_name': 'EndOfLoading', 'time': time_add(args[0]['time'], loading_time), 'dump_truck': args[0]['dump_truck'] }) loader = loader + 1 else: ListOfQueueLoader.append(args[0]) queue_loader += 1 delay = {'loading': 0, 'scaling': 0} elif args[0]['event_name'] == 'EndOfLoading': if scaler < active_scaler: rand_scaling_time = rand() scaling_time = 0 for cdf_scalingtime in scalingtime['cdf']: if cdf_scalingtime > rand_scaling_time: scaling_time = scalingtime['time'][ scalingtime['cdf'].index(cdf_scalingtime)] break FEL.append({ 'event_name': 'EndOfScaling', 'time': time_add(args[0]['time'], scaling_time), 'dump_truck': args[0]['dump_truck'] }) scaler = scaler + 1 else: ListOfQueueScaler.append(args[0]) queue_scaler += 1 if len(ListOfQueueLoader) > 0: rand_loading_time = rand() loading_time = 0 for cdf_loadingtime in loadingtime['cdf']: if cdf_loadingtime > rand_loading_time: loading_time = loadingtime['time'][ loadingtime['cdf'].index(cdf_loadingtime)] break delay = { 'loading': (args[0]['time'].hour * 60 + args[0]['time'].minute) - (ListOfQueueLoader[0]['time'].hour * 60 + ListOfQueueLoader[0]['time'].minute), 'scaling': 0 } FEL.append({ 'event_name': 'EndOfLoading', 'time': time_add(args[0]['time'], loading_time), 'dump_truck': ListOfQueueLoader[0]['dump_truck'] }) ListOfQueueLoader = ListOfQueueLoader[1:] queue_loader -= 1 else: delay = {'loading': 0, 'scaling': 0} loader -= 1 elif args[0]['event_name'] == 'EndOfScaling': if len(ListOfQueueScaler) > 0: rand_loading_time = rand() service_time = 0 for cdf_interarrival in loadingtime['cdf']: if cdf_interarrival > rand_loading_time: service_time = loadingtime['time'][ loadingtime['cdf'].index(cdf_interarrival)] break delay = { 'loading': 0, 'scaling': (args[0]['time'].hour * 60 + args[0]['time'].minute) - (ListOfQueueScaler[0]['time'].hour * 60 + ListOfQueueScaler[0]['time'].minute) } FEL.append({ 'event_name': 'EndOfScaling', 'time': time_add(args[0]['time'], service_time), 'dump_truck': ListOfQueueScaler[0]['dump_truck'] }) ListOfQueueScaler = ListOfQueueScaler[1:] queue_scaler -= 1 else: delay = {'loading': 0, 'scaling': 0} rand_next_arrival = rand() next_traveltime = 0 for cdf_traveltime in traveltime['cdf']: if cdf_traveltime > rand_next_arrival: next_traveltime = traveltime['time'][traveltime['cdf'].index( cdf_traveltime)] break FEL.append({ 'event_name': 'Arrival', 'time': time_add(args[0]['time'], next_traveltime), 'dump_truck': args[0]['dump_truck'] }) pass elif args[0]['event_name'] == 'EndOperating': delay = {'loading': 0, 'scaling': 0} FEL.remove(args[0]) return delay
def getMultipleRandoms( n ): for i in arange( 0, real( n ) ): yield rand( )
def getMultipleRandoms( n ): '''Returns n random numbers.''' for i in arange( 0, real_int( n ) ): yield rand( )
def getRandomNumber( ): return rand( )