def get_draw_start_pos(self): return (int( util.clamp(self.x - self.width / 2, 0, self.world_width - self.width)), int( util.clamp(self.y - self.height / 2, 0, self.world_height - self.height)))
def move_cursor(self): move = vec() move.x = self.game.keydown['RIGHT'] - self.game.keydown['LEFT'] move.y = self.game.keydown['DOWN'] - self.game.keydown['UP'] # change the inventory index self.inv_index[0] += int(move.x) self.inv_index[1] += int(move.y) self.inv_index[0] = utils.clamp(self.inv_index[0], 0, self.inv_size[0] - 1) self.inv_index[1] = utils.clamp(self.inv_index[1], 0, self.inv_size[1] - 1) # move the cursor self.cursor_pos += move * 24 self.cursor_pos.x = utils.clamp(self.cursor_pos.x, 24, 120) self.cursor_pos.y = utils.clamp(self.cursor_pos.y, 40, 136) # restart animation if curser is moved if move != (0, 0): self.anim_timer = 0 self.anim_frame = 0 # assign an item to a slot player = self.game.player x = self.inv_index[1] y = self.inv_index[0] if self.game.keydown['A']: if self.inv_items[x][y]: # put the item into slot A # if there is already an item, put it in slot B # if the item is already in slot B, clear slot B lastA = player.items['A'] player.items['A'] = self.inv_items[x][y] if player.items['A'] and player.items['B'] == None: player.items['B'] = player.items['A'] if player.items['B'] == self.inv_items[x][y]: player.items['B'] = lastA if player.items['B'] == player.items['A']: player.items['B'] = None else: # if no item is at x, y # TODO play sound pass if self.game.keydown['B']: if self.inv_items[x][y]: # put the item into slot B lastB = player.items['B'] player.items['B'] = self.inv_items[x][y] if player.items['B'] and player.items['A'] == None: player.items['A'] = player.items['B'] if player.items['A'] == self.inv_items[x][y]: player.items['A'] = lastB if player.items['A'] == player.items['B']: player.items['A'] = None else: # if no item is at x, y # TODO play sound pass
def set_reach(self) -> None: weapons = [] for loc in [19, 20, 27, 28]: w = self.fighter.equip_loc.get(loc) if w.weapon: weapons.append(w) r_w = self.fighter.equip_loc.get(19) l_w = self.fighter.equip_loc.get(20) if self.fighter.dom_hand == 'R': self.fighter.reach = clamp( inch_conv(self.fighter.er + r_w.length, 1), 2) if len(weapons) > 1: self.fighter.reach_oh = clamp( inch_conv(self.fighter.er + l_w.length, 1), 2) else: self.fighter.reach_oh = self.fighter.reach else: self.fighter.reach = clamp( inch_conv(self.fighter.er + l_w.length, 1), 2) if len(weapons) > 1: self.fighter.reach_oh = clamp( inch_conv(self.fighter.er + r_w.length, 1), 2) else: self.fighter.reach_oh = self.fighter.reach self.fighter.reach_leg = clamp( inch_conv( (self.fighter.height * self.fighter.location_ratios[17]) + self.fighter.equip_loc.get(27).length, 1), 2)
def pan(self, dx, dy): """Pan the camera in the direction specified by (dx, dy).""" self.x = int( util.clamp(self.x + dx, self.width / 2, self.world_width - self.width / 2)) self.y = int( util.clamp(self.y + dy, self.height / 2, self.world_height - self.height / 2))
def solve_one_to_one_3x3(): input_keys = [-1, -2, -3, -4] output_keys = [0] switch_keys = [1, 2, 3] node_keys = [4, 5, 6] nodes = [] modulating_nodes_dict = { 'activation_function': lambda x: clamp(x,-10,10), 'integration_function': mult, 'activity': 0, 'output': 0, 'bias':1 } node_weights = {4: [(-1, 1), (-4, 1)], 5: [(-2, 1), (-4, 1)], 6: [(-3, 1), (-4, 1)]} for i in node_keys: node_dict = copy.deepcopy(modulating_nodes_dict) node_dict['weights'] = node_weights[i] nodes.append(Neuron(i, node_dict)) switch_std_weights = { 1: [(-1, 10), (-1, 0), (-1, -10)], 2: [(-2, 10), (-2, 0), (-2, -10)], 3: [(-3, 10), (-3, 0), (-3, -10)] } switch_mod_weights = { 1: [(4, 1 / 3)], 2: [(5, 1 / 3)], 3: [(6, 1 / 3)] } for key in switch_keys: nodes.append(SwitchNeuron(key, switch_std_weights[key], switch_mod_weights[key])) node_0_std = { 'activation_function': lambda x: clamp(x,-10,10), 'integration_function': sum, 'activity': 0, 'output': 0, 'weights': [(1, 1), (2, 1), (3, 1)], 'bias' : 0 } nodes.append(Neuron(0, node_0_std)) net = SwitchNeuronNetwork(input_keys, output_keys, nodes) agent = Agent(net,lambda x: x,lambda x: convert_to_action(x)) return agent
def paint(self, painter, option, index): painter.save() # # set background color painter.setPen(QPen(Qt.NoPen)) # # Get RAM information: s_index = self.proxy.mapToSource(index) mem_used_idx = self.model.get_key_index("AllocMem") mem_free_idx = self.model.get_key_index("FreeMem") mem_real_idx = self.model.get_key_index("RealMemory") mem_used = self.model._data[s_index.row()][mem_used_idx] mem_free = self.model._data[s_index.row()][mem_free_idx] mem_real = self.model._data[s_index.row()][mem_real_idx] if mem_used.isdigit(): mem_used = int(mem_used) else: mem_used = 0 if mem_real.isdigit(): mem_real = int(mem_real) else: mem_real = 0 # # Load information: # load_avg_idx = self.model.get_key_index("load_avg") # num_proc_idx = self.model.get_key_index("num_proc") # load_avg = self.model._data[s_index.row()][load_avg_idx] # num_proc = self.model._data[s_index.row()][num_proc_idx] # try: load_avg = float(load_avg) # except: load_avg = 0.0 # try: num_proc = float(num_proc) # except: num_proc = 1.0 # # Set color based on ram and load: # # TODO: Color setting should come from confing file or user condiguration! if mem_used and mem_real: color = QColor() sat = utilities.clamp(mem_used/mem_real, 0.0, 1.0) sat = utilities.fit(sat, 0.0, 1.0, 0.1, 0.85) hue = 1.0 #utilities.clamp(load_avg/num_proc, 0.0, 1.0) hue = utilities.fit(hue, 0.0, 1.0, .25, .9) color.setHsvF(hue, sat , 1) # Mark in red hosts with used ram above 0.9 (or other SGE_HOST_RAM_WARNING constant) # if mem_used > mem_real * constants.SGE_HOST_RAM_WARNING: # color.setHsvF(1, 1 , 1) painter.setBrush(QBrush(color)) # # Set selection color: if option.state & QStyle.State_Selected: painter.setBrush(QBrush(Qt.gray)) painter.drawRect(option.rect) painter.setPen(QPen(Qt.gray)) value = index.data(Qt.DisplayRole) if value.isValid(): text = value.toString() painter.drawText(option.rect, Qt.AlignLeft, text) painter.restore()
def access_cell(self, x, y): actualX = 0 actualY = 0 if (x >= 0 and x < self.cols): actualX = x else: if self.edgeRule == WRAP_GRID: actualX = x % self.cols else: actualX = utilities.clamp(x, 0, self.cols - 1) if (y >= 0 and y < self.rows): actualY = y else: if self.edgeRule == WRAP_GRID: actualY = y % self.rows else: actualY = utilities.clamp(y, 0, self.rows - 1) return actualX, actualY
def get_gemstone(key: str, level: int) -> Gemstone: level = utilities.clamp(level, 1, 9) - 1 base = gemstones[key] gemstone = Gemstone() gemstone.name = base['name'] + f' {base["tiers"][level]["name"]}' gemstone.description = base['description'] gemstone.level = level + 1 gemstone.effect = base['effect'] gemstone.amount = base['tiers'][level]['amount'] gemstone.weight = 1 return gemstone
def solve_one_to_many(): input_keys = [-1, -2, -3, -4] output_keys = [0,1] node_keys = [3,4,5] switch_keys = [7,8,9,10,11,12] nodes = [] node_weights = {3: [(-1, 1), (-4, 1)], 4: [(-2, 1), (-4, 1)], 5: [(-3, 1), (-4, 1)]} modulating_nodes_dict = { 'activation_function': lambda x: clamp(x,-1,1), 'integration_function': mult, 'activity': 0, 'output': 0, 'bias' : 1 } for i in node_keys: node_dict = copy.deepcopy(modulating_nodes_dict) node_dict['weights'] = node_weights[i] nodes.append(Neuron(i, node_dict)) slow, fast = 0,0 switch_std_w = {} while fast < len(switch_keys): switch_std_w[switch_keys[fast]] = [(input_keys[slow], 1), (input_keys[slow], -1)] fast += 1 switch_std_w[switch_keys[fast]] = [(input_keys[slow], 1), (input_keys[slow], -1)] fast+=1 slow+=1 w1, w2 = 0.5, 1 switch_mod_w = {7: [(3,w2)], 8: [(7,w1)], 9: [(4,w2)], 10:[(9,w1)], 11: [(5,w2)], 12: [(11,w1)]} for key in switch_keys: nodes.append(SwitchNeuron(key,switch_std_w[key],switch_mod_w[key])) out_w = {0 : [(8,1), (10,1), (12,1)], 1: [(7,1), (9,1), (11,1)]} out_dict = { 'activation_function': heaviside, 'integration_function': sum, 'activity': 0, 'output': 0, 'bias' : 0 } for key in output_keys: params = copy.deepcopy(out_dict) params['weights'] = out_w[key] nodes.append(Neuron(key,params)) net = SwitchNeuronNetwork(input_keys,output_keys,nodes) return net
def move_cursor(self): move = vec() move.x = self.game.keydown['RIGHT'] - self.game.keydown['LEFT'] move.y = self.game.keydown['DOWN'] - self.game.keydown['UP'] # change the inventory index self.inv_index[0] += int(move.x) self.inv_index[1] += int(move.y) self.inv_index[0] = utils.clamp(self.inv_index[0], 0, self.inv_size[0] - 1) self.inv_index[1] = utils.clamp(self.inv_index[1], 0, self.inv_size[1] - 1) # move the cursor self.cursor_pos += move * 24 self.cursor_pos.x = utils.clamp(self.cursor_pos.x, 24, 120) self.cursor_pos.y = utils.clamp(self.cursor_pos.y, 40, 136) # restart animation if curser is moved if move != (0, 0): self.anim_timer = 0 self.anim_frame = 0
def solve_tmaze(): input_keys = [-1,-2,-3,-4,-5] output_keys = [0] node_keys = [1,2,3] nodes = [] #Aggregating neuron params = { 'activation_function' : lambda x : x, 'integration_function' : sum, 'activity': 0, 'output' : 0, 'weights' : [(-1,-1), (-5,1)], 'bias':0 } nodes.append(Neuron(1,params)) m_params = { 'activation_function': lambda x: clamp(x, -0.8,0), 'integration_function': mult, 'activity': 0, 'output': 0, 'weights': [(1, 1), (-4, 1)], 'bias' : 1 } nodes.append(Neuron(2,m_params)) std_weights = [(-3,5), (-3,-5)] mod_weights = [(2,-1.25*0.5)] nodes.append(SwitchNeuron(3,std_weights,mod_weights)) o_params = { 'activation_function': tanh, 'integration_function': sum, 'activity': 0, 'output': 0, 'weights': [(3,1)], 'bias' : 0 } nodes.append(Neuron(0,o_params)) net = SwitchNeuronNetwork(input_keys,output_keys,nodes) #For input, append the bias to -1 input agent = Agent(net, append_bias, convert_to_direction) return agent
def _create_walls(self, percent=0.06, rsd=0.2): """Randomly place some walls The actual number of walls is drawn from a normal distribution. :param float percent: Mean percent of walls to be created :param float rsd: Relative standard deviation """ walls = set() # collect all possible walls for x, y in itertools.product(range(self.columns), range(self.rows)): if (self.wrap or y != 0) and not self._nodes[x, y].edges[Direction.down]: walls.add(Wall(Vector2d(x, y), Wall.Orientation.horizontal)) if (self.wrap or x != 0) and not self._nodes[x, y].edges[Direction.left]: walls.add(Wall(Vector2d(x, y), Wall.Orientation.vertical)) mean = len(walls) * percent count = clamp(int(random.gauss(mean, rsd * mean)), 0, len(walls)) walls = random.sample(walls, count) return walls
def _rotate(self, grid, percent=0.8, rsd=0.1): """Rotate a random selection of tiles The actual number of rotated tile is drawn from a normal distribution. :param grid.GridContainer grid: Grid of :class:`Tile` objects :param float percent: Mean percent of tiles to be rotated :param float rsd: Relative standard deviation """ rotatable = set() # collect all rotatable tiles for x, y in itertools.product(range(self.columns), range(self.rows)): if grid[x, y].link not in (LinkType.cross_intersection, LinkType.empty): rotatable.add(grid[x, y]) mean = len(rotatable) * percent count = clamp(int(random.gauss(mean, rsd * mean)), 1, len(rotatable)) for tile in random.sample(rotatable, count): if tile.link == LinkType.straight: tile.orientation = tile.orientation.rotate() else: tile.orientation = tile.orientation.rotate( random.choice(range(1, 4))) return count
def strPot_to_angle(strPot, potRange, angleRange): strPot = clamp(potRange, strPot) potSpan = potRange[1] - potRange[0] angleSpan = angleRange[1] - angleRange[0] angle = (((strPot - potRange[0]) * potSpan)/ angleSpan ) + angleRange[0]
#Temporary file, will be removed on clean-up. import re from utilities import clamp if __name__ == "__main__": correct = 0 trials = 0 with open('temp.txt') as f: lines = [line.rstrip() for line in f] for line in lines: reg = re.search("output \((.*?),\), got \[(.*?)\]", line) if reg: trials += 1 groups = reg.groups() if abs(clamp(float(groups[0])) - clamp(float(groups[1]))) < 0.3: correct += 1 print("Correct: {} out of {}".format(correct, trials))
def readAin(pinName, jointRange): raw = readInt(pinName) raw = clamp(jointRange, raw) return getPercentageIntoRange(jointRange, float(raw))
def affect_confusion(self, amount: int) -> int: start = self.confusion self.confusion = utilities.clamp( self.confusion + amount, 0, self.confusion_limit + self.bonus_confusion_limit) return self.confusion - start
def affect_shock(self, amount: int) -> int: start = self.shock self.shock = utilities.clamp(self.shock + amount, 0, self.shock_limit + self.bonus_shock_limit) return self.shock - start
def iterate(self, iterNumber): prevCells = copy.deepcopy(self.cells) for row in range(self.rows): for col in range(self.cols): stateNumber = 0 A = B = S = 0 state = "" state = self._state(prevCells, row - 1, col - 1) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row - 1, col) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row - 1, col + 1) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row, col - 1) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row, col + 1) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row + 1, col - 1) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row + 1, col) if state == "Infected": A += 1 elif state == "Ill": B += 1 state = self._state(prevCells, row + 1, col + 1) if state == "Infected": A += 1 elif state == "Ill": B += 1 if self._state(prevCells, row, col) == "Healthy": self.cells[row][col] = utilities.clamp(int(math.floor((A / float(self.k1)) + (B / float(self.k2)))), \ 0, self.stateCount) elif self._state(prevCells, row, col) == "Ill": self.cells[row][col] = 0 else: S = self.access_cell(prevCells, row-1, col-1) + \ self.access_cell(prevCells, row-1, col) + \ self.access_cell(prevCells, row-1, col+1) + \ self.access_cell(prevCells, row, col-1) + \ self.access_cell(prevCells, row, col) + \ self.access_cell(prevCells, row, col+1) + \ self.access_cell(prevCells, row+1, col-1) + \ self.access_cell(prevCells, row+1, col) + \ self.access_cell(prevCells, row+1, col+1) self.cells[row][col] = utilities.clamp(int(math.floor(S / (A + B + 1) + self.g)), \ 0, self.stateCount) print("Iteration #{0} completed.".format(iterNumber))