def _generate_hsl_colour_dictionary(keys, lightness=85): """Given keys, generates dictionary of key -> light colour Arguments: keys {list} -- List of key names Keyword Arguments: lightness {int} -- How light to make the colour (default: {85}) Returns: colour_dict{dict} -- Dictionary which maps the class name to a colour """ colours = [ "#c4e5ff", "#c0ffbc", "#ffe8b2", "#ffb8b5", "#f9f9b1", "#e8bcff" ] colour_dict = {} if len(keys) > len(colours): for key in keys: colour_dict[key] = "hsl({hue},{saturation}%,{lightness}%)".format( hue=360 * r(), saturation=25 + 70 * r(), lightness=lightness + 10 * r()) else: iterator = CyclicIterator(colours) colour_dict = {key: iterator.next() for key in keys} return colour_dict
def fill_red_or_blue(self, i, j, n_blue, n_red): if ((n_red * self.redGrowth + n_blue * self.blueGrowth) * r()) > 2: if n_red * self.redGrowth * r() > n_blue * self.blueGrowth * r(): self.set(i, j, RED) else: self.set(i, j, BLUE) else: self.kill(i, j)
def RD(self, i, j): if 0 == cr[i][j]: if ((i < 2) or (j < 2)): cr[i][j] = 1 elif (0 == r(999)): cr[i][j] = r(256) else: cr[i][j] = self.RD(i - r(2), j - r(2)) return cr[i][j]
def BL(self, i, j): if 0 == cb[i][j]: if ((i<2)or(j<2)): cb[i][j] = 1 elif (0 == r(999)): cb[i][j] = r(256) else: cb[i][j] = self.BL(i - r(2), j -r(2)) return cb[i][j]
def GR(self, i, j): if 0 == cg[i][j]: if ((i<2)or(j<2)): cg[i][j] = 1 elif (0 == r(999)): cg[i][j] = r(256) else: cg[i][j] = self.GR(i - r(2), j -r(2)) return cg[i][j]
def RD(self, i, j): if 0 == cr[i][j]: if ((i<2)or(j<2)): cr[i][j] = 1 elif (0 == r(999)): cr[i][j] = r(256) else: cr[i][j] = self.RD(i - r(2), j -r(2)) return cr[i][j]
def BL(self, i, j): if 0 == cb[i][j]: if ((i < 2) or (j < 2)): cb[i][j] = 1 elif (0 == r(999)): cb[i][j] = r(256) else: cb[i][j] = self.BL(i - r(2), j - r(2)) return cb[i][j]
def GR(self, i, j): if 0 == cg[i][j]: if ((i < 2) or (j < 2)): cg[i][j] = 1 elif (0 == r(999)): cg[i][j] = r(256) else: cg[i][j] = self.GR(i - r(2), j - r(2)) return cg[i][j]
def test_1d_world_link(): x, y = r(10), r(10) d1 = Data(label='d1', x=x) d2 = Data(label='d2', y=y) dc = DataCollection([d1, d2]) dc.add_link(LinkSame(d2.get_world_component_id(0), d1.id['x'])) assert d2.get_world_component_id(0) in d1.components np.testing.assert_array_equal(d1[d2.get_world_component_id(0)], x) np.testing.assert_array_equal(d1[d2.get_pixel_component_id(0)], x)
def test_1d_world_link(): x, y = r(10), r(10) d1 = Data(label='d1', x=x) d2 = Data(label='d2', y=y) dc = DataCollection([d1, d2]) dc.add_link(LinkSame(d2.world_component_ids[0], d1.id['x'])) assert d2.world_component_ids[0] in d1.externally_derivable_components np.testing.assert_array_equal(d1[d2.world_component_ids[0]], x) np.testing.assert_array_equal(d1[d2.pixel_component_ids[0]], x)
def test_1d_world_link(): x, y = r(10), r(10) d1 = Data(label='d1', x=x) d2 = Data(label='d2', y=y, coords=IdentityCoordinates(n_dim=1)) dc = DataCollection([d1, d2]) dc.add_link(LinkSame(d2.world_component_ids[0], d1.id['x'])) assert d2.world_component_ids[0] in d1.externally_derivable_components np.testing.assert_array_equal(d1[d2.world_component_ids[0]], x) np.testing.assert_array_equal(d1[d2.pixel_component_ids[0]], x)
def click_random(pos, timestamp=0.5, action="left", offset=5): hWnd = win32gui.FindWindow(None, windowName) if offset > 0: lParam = win32api.MAKELONG(pos[0] + hMargin + r(-offset, offset), pos[1] + vMargin + r(-offset, offset)) else: lParam = win32api.MAKELONG(pos[0] + hMargin, pos[1] + vMargin) win32gui.PostMessage(hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam) win32gui.PostMessage(hWnd, win32con.WM_LBUTTONUP, 0, lParam) time.sleep(timestamp)
def get_test_circle(noise): from numpy.random import random as r noise_factor = noise data = np.ones((200, 3)) for i in range(50): x = (i - 25) / float(25) data[i, 0] = -1 data[i, 1] = x * (noise_factor + (1 - noise_factor) * 2 * r()) data[i, 2] = np.sqrt(1.01 - x**2) * (noise_factor + (1 - noise_factor) * 2 * r()) for i in range(50): x = (i - 25) / float(25 / 2) data[i + 100, 0] = 1 data[i + 100, 1] = x * (noise_factor + (1 - noise_factor) * 2 * r()) data[i + 100, 2] = np.sqrt(4.5 - x**2) * (noise_factor + (1 - noise_factor) * 2 * r()) for i in range(50): x = (i - 25) / float(25) data[i + 50, 0] = -1 data[i + 50, 1] = x * (noise_factor + (1 - noise_factor) * 2 * r()) data[i + 50, 2] = -np.sqrt(1.01 - x**2) * (noise_factor + (1 - noise_factor) * 2 * r()) for i in range(50): x = (i - 25) / float(25 / 2) data[i + 150, 0] = 1 data[i + 150, 1] = x * (noise_factor + (1 - noise_factor) * 2 * r()) data[i + 150, 2] = -np.sqrt(4.5 - x**2) * (noise_factor + (1 - noise_factor) * 2 * r()) return data
def test_2d_world_link(): """Should be able to grab pixel coords after linking world""" x, y = r(10), r(10) cat = Data(label='cat', x=x, y=y) im = Data(label='im', inten=r((3, 3)), coords=IdentityCoordinates(n_dim=2)) dc = DataCollection([cat, im]) dc.add_link(LinkSame(im.world_component_ids[0], cat.id['x'])) dc.add_link(LinkSame(im.world_component_ids[1], cat.id['y'])) np.testing.assert_array_equal(cat[im.pixel_component_ids[0]], x) np.testing.assert_array_equal(cat[im.pixel_component_ids[1]], y)
def test_2d_world_link(): """Should be able to grab pixel coords after linking world""" x, y = r(10), r(10) cat = Data(label='cat', x=x, y=y) im = Data(label='im', inten=r((3, 3))) dc = DataCollection([cat, im]) dc.add_link(LinkSame(im.get_world_component_id(0), cat.id['x'])) dc.add_link(LinkSame(im.get_world_component_id(1), cat.id['y'])) np.testing.assert_array_equal(cat[im.get_pixel_component_id(0)], x) np.testing.assert_array_equal(cat[im.get_pixel_component_id(1)], y)
def test_3d_world_link(): """Should be able to grab pixel coords after linking world""" x, y, z = r(10), r(10), r(10) cat = Data(label='cat', x=x, y=y, z=z) im = Data(label='im', inten=r((3, 3, 3))) dc = DataCollection([cat, im]) dc.add_link(LinkSame(im.world_component_ids[2], cat.id['x'])) dc.add_link(LinkSame(im.world_component_ids[1], cat.id['y'])) dc.add_link(LinkSame(im.world_component_ids[0], cat.id['z'])) np.testing.assert_array_equal(cat[im.pixel_component_ids[2]], x) np.testing.assert_array_equal(cat[im.pixel_component_ids[1]], y) np.testing.assert_array_equal(cat[im.pixel_component_ids[0]], z)
def startBossFight(self, increaseDelay=False, uncontrolled=False): if self.imgSearcher.searchForImage(self.imgImp.accessoryError): return False time1 = time.perf_counter() if not self.imgSearcher.searchForImageLoop(self.imgImp.battleReady, True, time1): return False if increaseDelay: randomTime = 10 + r(5, 10) time.sleep(randomTime) if not self.imgSearcher.searchForImageLoop(self.imgImp.battleStart, True, time1): return False time1 = time.perf_counter() print("Waiting for battle to load") while not self.imgSearcher.searchForImage(self.imgImp.pauseBattle): if self.imgSearcher.searchForImage( self.imgImp.gameStart) or time.perf_counter( ) - time1 > self.cc.configs.refreshBossScreen: return False if self.imgSearcher.searchForImage(self.imgImp.equipFull): print("Oh, no, time to sell gear!") self.imgSearcher.click_random([298, 518]) time.sleep(1) if not self.sellEquips(): return False return True elif self.imgSearcher.searchForImage(self.imgImp.bossDeadError): print("On, no, boss is already dead!") self.imgSearcher.click_random([298, 518]) return False result = self.fightBoss(uncontrolled) return result
def create_other_lattice(self, density): """ initialize the lattice with a bunch of different types of cells (represented as different colors) :param density: """ lattice = r(self.x, self.y) if density != 1: for bug in np.ravel(lattice): if r() > density: lattice[lattice == bug] = 0 # killdict is a hashtable containing the killing effectiveness for each color killdict = d(list) # type: defaultdict[Any, float] killdict[0] = 0 for color in np.ravel(lattice): killdict[color] = r() killdict[0] = 0 return lattice, killdict
def get_test_circle(noise): from numpy.random import random as r noise_factor=noise data=np.ones((200,3)) for i in range(50): x=(i-25)/float(25) data[i,0]=-1;data[i,1]=x*(noise_factor+(1-noise_factor)*2*r());data[i,2]=np.sqrt(1.01-x**2)*(noise_factor+(1-noise_factor)*2*r()) for i in range(50): x=(i-25)/float(25/2) data[i+100,0]=1;data[i+100,1]=x*(noise_factor+(1-noise_factor)*2*r());data[i+100,2]=np.sqrt(4.5-x**2)*(noise_factor+(1-noise_factor)*2*r()) for i in range(50): x=(i-25)/float(25) data[i+50,0]=-1;data[i+50,1]=x*(noise_factor+(1-noise_factor)*2*r());data[i+50,2]=-np.sqrt(1.01-x**2)*(noise_factor+(1-noise_factor)*2*r()) for i in range(50): x=(i-25)/float(25/2) data[i+150,0]=1;data[i+150,1]=x*(noise_factor+(1-noise_factor)*2*r());data[i+150,2]=-np.sqrt(4.5-x**2)*(noise_factor+(1-noise_factor)*2*r()) return data
def kill_red(self, i, j, n_blue, thresh): """ if number of blue cells * their killing advantage * random number > 2, kill this red bacteria (replace with empty site) :param i: :param j: :param n_blue: :param thresh: """ if n_blue * r() * self.blueAdvantage > thresh and not self.defKillers: self.kill(i, j)
def click_random(self, pos, timestamp=0.5, action="left", offset=5, windowName=""): if windowName is "": windowName = self.windowName hWnd = win32gui.FindWindow(None, windowName) if windowName is "LDPlayer": win32gui.EnumChildWindows(hWnd, self.findCorrectChild, "TheRender") clickX = pos[0] clickY = pos[1] else: self.hWnd = hWnd clickX = pos[0] + self.hMargin clickY = pos[1] + self.vMargin if offset > 0: lParam = win32api.MAKELONG(clickX + r(-offset, offset), clickY + r(-offset, offset)) else: lParam = win32api.MAKELONG(clickX, clickY) win32gui.SendMessage(self.hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam) win32gui.SendMessage(self.hWnd, win32con.WM_LBUTTONUP, 0, lParam) time.sleep(timestamp)
def clickRandomCard(self): firstCard = [200, 350] secondCard = [500, 350] thirdCard = [800, 350] fourthCard = [100, 350] randomNumber = r(1, 4) if randomNumber is 1: self.imgSearcher.click_exact(firstCard) elif randomNumber is 2: self.imgSearcher.click_exact(secondCard) elif randomNumber is 3: self.imgSearcher.click_exact(thirdCard) elif randomNumber is 4: self.imgSearcher.click_exact(fourthCard) time.sleep(5) return
def evolve(self, n_steps=1): """ main function, moves the lattice forward n steps in time :param n_steps: """ for t in range(n_steps): self.generation += 1 # pick lattice site i, j = self.random_site # random death happens if slider>random float in [0,1] if self.slider > r(): self.random_death(i, j) # else killing/filling a la IBM happens else: n_blue, n_enemy, n_red, neighborhood = \ self.get_neighborhood(i, j) # site is filled with red bact if self.onlyRedBlue and self.is_red(i, j): self.kill_red(i, j, n_blue, self.thresh) # site is filled with a blue bacteria elif self.onlyRedBlue and self.is_blue(i, j): self.kill_blue(i, j, n_red, self.thresh) elif n_enemy > 0 and not self.is_empty(i, j): if self.has_enough_enemies(i, j, neighborhood): self.kill(i, j) # FILLING ....... ######### elif self.is_empty(i, j): if self.onlyRedBlue and n_red + n_blue > 0: self.fill_red_or_blue(i, j, n_blue, n_red) elif n_enemy > 0: if not self.fill_with_neighbor_color( i, j, neighborhood): continue
def fightBoss(self, uncontrolled=False): if self.imgSearcher.searchForImage(self.imgImp.accessoryError): return False bossTimerReal = self.cc.configs.bossTimer time1 = time.perf_counter() if self.cc.configs.randomizedDamage: bossTimerReal = self.cc.configs.bossTimer + r(-10, 10) while not self.imgSearcher.searchForImage(self.imgImp.battleExit, True): print("Fight Boss!") if self.imgSearcher.searchForImage(self.imgImp.gameStart): return False if self.imgSearcher.searchForImage(self.imgImp.connectionNotice): return False if self.imgSearcher.searchForImage(self.imgImp.bossCalculating): return False if self.imgSearcher.searchForImage(self.imgImp.noticeMessage): self.imgSearcher.click_random([298, 518]) if self.cc.configs.run and self.imgSearcher.searchForImage( self.imgImp.pauseWindow): self.imgSearcher.click_random([298, 518]) if (self.cc.configs.controlledDamage and not uncontrolled ) and time.perf_counter() - time1 > bossTimerReal: print("Time's over, fight's over!") self.exitBossFight() return True self.fightWithSkillsAndUlt() if time.perf_counter() - time1 > self.cc.configs.unstuck: self.imgSearcher.click_random([298, 518]) print( "Oops, took too long to finish the boss, might be stuck!") return False self.stats.bossKilled() return True
def advance(self, ssa=1., weight=False, force_angle=None, tau_star=10., lag=0, **kwargs): ''' roll to see if photon's +12 to scattering prevents grue from eating it. Roll to see if absorbed (since all photons begin at cloud top, this begins each sequence) Roll to see which direction scattered F/B based on HG Azimuth uniform Roll to see distance Beer-Lambert Law ''' from numpy.random import random as r from numpy import append, array, log, tile, pi from time import sleep from lib import henyey_greenstein dbg((ssa, force_angle, tau_star), 5) if not self.live: return #_roll to see how far until next interaction____________________ self.tau = -log(1 - r(1)[0]) #_THIS IS NOT TAAAAUUUUU #_update current location point = (self.history[:, -1] + self.tau * self.k).reshape(3, 1) self.history = append(self.history, point, axis=1) self.plot(**kwargs) #_check if escaped top or bottom, update flags if self.history[2, -1] < 1e-8: self.die('top', **kwargs) return elif self.history[2, -1] > tau_star: self.die('base', **kwargs) return #_roll to see if absorbed_______________________________________ if r(1)[0] > ssa: self.die('absorbed', **kwargs) return #_roll to see in what direction________________________________ if force_angle == None: phi = 2 * pi * r(1)[0] #_randomize azimuth theta = henyey_greenstein(r(1)[0], **kwargs) #_now theta else: #_force specific scattering angles for testing phi = force_angle[0] * d2r theta = force_angle[1] * d2r self.__turn__(theta, phi, **kwargs) #_update k self.scattered += 1 #_update number of times scattered dbg(self.traveled(origin=False), 5)
def generate_matrix(n): ans = [] for i in range(n): ans.append(list(r(n))) return ans
def generate_ans(n): return list(r(n))
width_min = min(column(Xinputs, 1)) for i in range(len(Xinputs)): Xinputs[i][0] = scale(Xinputs[i][0], len_max, len_min) Xinputs[i][1] = scale(Xinputs[i][1], width_max, width_min) # seperate some test data splice = 25 Xtrain = Xinputs[:-splice] Ytrain = Yout[:-splice] Xtest = Xinputs[-splice:] Ytest = Yout[-splice:] if not model: weights = r(3, 3) else: with open(model_path, 'rb') as f: weights = numpy.load(f) # training loop time for i in range(len(Xtrain)): output, hot_one = fp(Xtrain[i], weights) weight_adjust(Xtrain[i], hot_one, Ytrain[i], weights) if i % 20 == 0: calc_loss = loss(output, Ytrain[i]) print(calc_loss) if model: with open(model_path, 'wb') as f: numpy.save(f, weights)
return list # split in 2 left = list[0:len(list) // 2] right = list[len(list) // 2:] leftSorted = mergeSort(left) rightSorted = mergeSort(right) return merge_sort(leftSorted, rightSorted) #Now generated a series of lists of 10**i random elements from 10 to 100000. #They are then sorted using quicksort at first, then mergesort. for i in range(6)[1:]: s=10**i x.append(s) a = r(10**i, size=s) a = list(a) quick.append(timeit.timeit('quick_sort(a)', number=10, globals=globals())) merge.append(timeit.timeit('mergeSort(a)', number=10, globals=globals())) #Can be observed how much Quick Sort is faster than Merge Sort. #This is because Merge Sort is a stable sorting algorithm, meaning that it keeps track of the original positions of the elements inside the array. #These requires higher use of memory for Merge Sort. #So, even if in the worst case scenario Quick Sort requires much more operations than Merge Sort, it rarely happens to have at random a reversely sorted list, ora an already sorted one, or a list of only one element repeated. plt.plot(x, merge, 'g--', label='Merge Sort', ) plt.plot(x, quick, 'r:', label='Quick Sort', linewidth = 3) plt.xscale('log') #used log scale to represent the growth of necessary time of execution to sort. plt.xlabel('Array Size') plt.ylabel('Execution Time (s)') plt.title('Merge Sort vs Quick sort') plt.xticks(x, [str(e)+ ' elements' for e in x])
def has_enough_enemies(self, i, j, neighborhood): return self.enemy_weight(i, j, neighborhood) * r() > 2
def kill_blue(self, i, j, n_red, thresh): if n_red * r() * self.redAdvantage > thresh and not self.defKillers: self.set(i, j, 0)