def updateModel(self, im, forground_mask): #fgm = self.getForegroundMask(im) fgm = forground_mask rs = random.Random() neighbors = list() neighbors.append([1, 0]) neighbors.append([0, 1]) neighbors.append([-1, 0]) neighbors.append([0, -1]) neighbors.append([1, -1]) neighbors.append([-1, 1]) neighbors.append([1, 1]) neighbors.append([-1, -1]) print("Shape of fgm:", np.shape(fgm)) for y in range(self.height): for x in range(self.width): if fgm[y, x] == False: #here is HG r = rs.randint(1, self.updateFactor) if r == 1: #update at [x,y] n = rs.randint(0, self.N - 1) self.samples[n, y, x] = im[y, x] r = rs.randint(1, self.updateFactor) if r == 1: #do update a neighbor of [x,y]: n = rs.randint(0, self.N - 1) neigh = neighbors[rs.randint(0, 7)] neighY = util.clamp(y + neigh[0], 0, self.height - 1) neighX = util.clamp(x + neigh[1], 0, self.width - 1) self.samples[n, neighY, neighX] = im[y, x]
def baseAtLocation(self, x, y, clampX=False, clampY=False): """Returns the (strandType, index) under the location x,y or None. It shouldn't be possible to click outside a pathhelix and still call this function. However, this sometimes happens if you click exactly on the top or bottom edge, resulting in a negative y value. """ baseIdx = int(floor(x / self.baseWidth)) minBase, maxBase = 0, self.vhelix().numBases() if baseIdx < minBase or baseIdx >= maxBase: if clampX: baseIdx = util.clamp(baseIdx, minBase, maxBase-1) else: return None if y < 0: y = 0 # HACK: zero out y due to erroneous click strandIdx = floor(y * 1. / self.baseWidth) if strandIdx < 0 or strandIdx > 1: if clampY: strandIdx = int(util.clamp(strandIdx, 0, 1)) else: return None if self.strandIsTop(StrandType.Scaffold): strands = StrandType.Scaffold, StrandType.Staple else: strands = StrandType.Staple, StrandType.Scaffold return (strands[int(strandIdx)], baseIdx)
def draw(self, win): if (self.isdead): self.pic = [''' ___ ''', ''' /rip\ ''', ''' OOOOO '''] elif (self.angle < pi * 0.10): self.pic = [''' ___ ''', ''' /lol\=''', ''' OOOOO '''] elif (self.angle < pi * 0.40): self.pic = [''' __// ''', ''' /lol\ ''', ''' OOOOO '''] elif (self.angle < pi * 0.5): self.pic = [''' _|| ''', ''' /lol\ ''', ''' OOOOO '''] elif (self.angle < pi * 0.60): self.pic = [''' ||_ ''', ''' /lol\\''', ''' OOOOO'''] elif (self.angle <= pi * 0.90): self.pic = [''' \\\\__ ''', ''' /lol\\''', ''' OOOOO'''] else: self.pic = [''' ___ ''', '''=/lol\\''', ''' OOOOO'''] # Draw Crosshair if (self.isactive): p = self.muzzle for i in range(10): p += (cos(self.angle) * (self.power * 4.0), -sin(self.angle) * (self.power * 4.0)) dot = p.int() try: if (i == 9): win.addstr(dot.y, dot.x, '✜', curses.color_pair(self.colors)) else: win.addstr(dot.y, dot.x, '·', curses.color_pair(self.colors)) except curses.error: pass # Draw Selected Weapon h, w = win.getmaxyx() if (self.weapon_display_timer > 0): weapon = self.arsenal[self.active_weapon] weaponwin = win.derwin(3, 7, clamp(self.pos.y - 5, 0, h - 3), clamp(self.pos.x - 3, 0, w - 7)) try: weaponwin.box() if (weapon[1] == -1): weaponwin.addstr(1, 3, weapon[0].char) else: weaponwin.addstr(1, 2, weapon[0].char + ':' + str(weapon[1])) except curses.error: pass weaponwin.refresh() # Draw Tanks x_off = -int(max([len(line) for line in self.pic]) / 2) y_off = -tanksize for n, line in enumerate(self.pic): for k, char in enumerate(line): draw = self.pos + (x_off + k, y_off + n) if (char != ' ' and draw.in_box(0, w, 0, h)): win.addstr(draw.y, draw.x, char) if (self.pos == self.pos.clamp(0, w - 1, 0, h - 1)): win.addstr(self.pos.y, self.pos.x, self.name[-1], curses.color_pair(self.colors))
def _on_slider_changed(self, new_value): r = clamp(int(self.bkg_color_r_slider.value), 0, 255) g = clamp(int(self.bkg_color_g_slider.value), 0, 255) b = clamp(int(self.bkg_color_b_slider.value), 0, 255) clr = pygame.Color('black') clr.r, clr.g, clr.b = r, g, b self.level.background_color = clr
def test(self, x, y): x = clamp(int(x), 0, self.w) y = clamp(int(y), 0, self.h) sampled = self.mask[y, x] if sampled > 127: return True return False
def calcBGOffset(self, cameraFocusX, cameraFocusY, windowWidth, windowHeight, backgroundWidth, backgroundHeight): '''Return the amount to offset the background. (cameraFocusX, cameraFocusY) is the spot where the camera is focused to, usually the center of the Avatar. ''' return (-clamp(cameraFocusX - (windowWidth / 2), 0, (backgroundWidth - windowWidth)), -clamp(cameraFocusY - (windowHeight / 2), 0, (backgroundHeight - windowHeight)))
def baseAtPoint(self, pathHelix, pt): """Returns the (strandType, baseIdx) corresponding to pt in pathHelix.""" x, strandIdx = self.helixIndex(pt) vh = pathHelix.vhelix() if vh.evenParity(): strandType = (StrandType.Scaffold, StrandType.Staple)[util.clamp(strandIdx, 0, 1)] else: strandType = (StrandType.Staple, StrandType.Scaffold)[util.clamp(strandIdx, 0, 1)] return (strandType, x)
def baseAtPoint(self, virtualHelixItem, pt): """Returns the (strandType, baseIdx) corresponding to pt in virtualHelixItem.""" x, strandIdx = self.helixIndex(pt) vh = virtualHelixItem.virtualHelix() if vh.isEvenParity(): strandType = (StrandType.Scaffold, StrandType.Staple)[util.clamp(strandIdx, 0, 1)] else: strandType = (StrandType.Staple, StrandType.Scaffold)[util.clamp(strandIdx, 0, 1)] return (strandType, x, strandIdx)
def load(self, filehandle, silent=False): """Load contents from a file handle containing a GIMP palette. If the format is incorrect, a `RuntimeError` will be raised. """ comment_line_re = re.compile(r'^#') field_line_re = re.compile(r'^(\w+)\s*:\s*(.*)$') color_line_re = re.compile(r'^(\d+)\s+(\d+)\s+(\d+)\s*(?:\b(.*))$') fp = filehandle self.clear(silent=True) # method fires events itself line = fp.readline() if line.strip() != "GIMP Palette": raise RuntimeError, "Not a valid GIMP Palette" header_done = False line_num = 0 for line in fp: line = line.strip() line_num += 1 if line == '': continue if comment_line_re.match(line): continue if not header_done: match = field_line_re.match(line) if match: key, value = match.groups() key = key.lower() if key == 'name': self._name = value.strip() elif key == 'columns': self._columns = int(value) else: logger.warning("Unknown 'key:value' pair %r", line) continue else: header_done = True match = color_line_re.match(line) if not match: logger.warning("Expected 'R G B [Name]', not %r", line) continue r, g, b, col_name = match.groups() col_name = col_name.strip() r = float(clamp(int(r), 0, 0xff))/0xff g = float(clamp(int(g), 0, 0xff))/0xff b = float(clamp(int(b), 0, 0xff))/0xff if r == g == b == 0 and col_name == self._EMPTY_SLOT_NAME: self.append(None) else: col = RGBColor(r, g, b) col.__name = col_name self._colors.append(col) if not silent: self.info_changed() self.sequence_changed() self.match_changed()
def load(self, filehandle, silent=False): """Load contents from a file handle containing a GIMP palette. If the format is incorrect, a `RuntimeError` will be raised. """ comment_line_re = re.compile(r'^#') field_line_re = re.compile(r'^(\w+)\s*:\s*(.*)$') color_line_re = re.compile(r'^(\d+)\s+(\d+)\s+(\d+)\s*(?:\b(.*))$') fp = filehandle self.clear(silent=True) # method fires events itself line = fp.readline() if line.strip() != "GIMP Palette": raise RuntimeError("Not a valid GIMP Palette") header_done = False line_num = 0 for line in fp: line = line.strip() line_num += 1 if line == '': continue if comment_line_re.match(line): continue if not header_done: match = field_line_re.match(line) if match: key, value = match.groups() key = key.lower() if key == 'name': self._name = value.strip() elif key == 'columns': self._columns = int(value) else: logger.warning("Unknown 'key:value' pair %r", line) continue else: header_done = True match = color_line_re.match(line) if not match: logger.warning("Expected 'R G B [Name]', not %r", line) continue r, g, b, col_name = match.groups() col_name = col_name.strip() r = float(clamp(int(r), 0, 0xff)) / 0xff g = float(clamp(int(g), 0, 0xff)) / 0xff b = float(clamp(int(b), 0, 0xff)) / 0xff if r == g == b == 0 and col_name == self._EMPTY_SLOT_NAME: self.append(None) else: col = RGBColor(r, g, b) col.__name = col_name self._colors.append(col) if not silent: self.info_changed() self.sequence_changed() self.match_changed()
def find_lost(self): """Finds and moves lost tables into the visible screen region""" max_x = self.floor_view.winfo_width() - 41 max_y = self.floor_view.winfo_height() - 41 for table in self.tables: table.move( util.clamp(table.table["x_pos"], 41, max_x - table.table["width"]), util.clamp(table.table["y_pos"], 41, max_y - table.table["height"]))
def calcBGOffset(self, cameraFocusX, cameraFocusY, windowWidth, windowHeight, backgroundWidth, backgroundHeight): '''Return the amount to offset the background. (cameraFocusX, cameraFocusY) is the spot where the camera is focused to, usually the center of the Avatar. ''' return (-clamp(cameraFocusX-(windowWidth/2), 0, (backgroundWidth-windowWidth)), -clamp(cameraFocusY-(windowHeight/2), 0, (backgroundHeight-windowHeight)) )
def walkTo(self, oldRect, hPower, vPower): self.velocity[0] = clamp(self.velocity[0]+hPower, self.xMin, self.xMax) self.velocity[1] = clamp(self.velocity[1]+vPower, self.yMin, self.yMax) newRect = oldRect.move(*self.velocity) oob = outOfBounds(self.walkMask, self.feetPos, newRect.midtop) if oob: #TODO: more precise return oldRect else: return newRect
def __init__(self, tasks, start, end, direction, tasks_mask=None): ''' TODO Start and end represents 00:00 of that day. ''' if start is not None and end is not None and start > end: raise ValueError() self.task_events = [] self.direction = direction # Points to next event to be read. self.index = 0 def safe_add_1_day(date): if date.is_max(): return date return date.add_days(1) for i in range(len(tasks)): if tasks_mask is not None and not tasks_mask[i]: continue task = tasks[i] self.task_events.append( TaskEvent( i, task.id.value, util.clamp(task.start, start, end), safe_add_1_day(util.clamp(task.end, start, end)), TaskEventType.TASK_START if direction == FillDirection.EARLY else TaskEventType.TASK_END)) self.task_events.append( TaskEvent( i, task.id.value, safe_add_1_day(util.clamp(task.end, start, end)), util.clamp(task.start, start, end), TaskEventType.TASK_END if direction == FillDirection.EARLY else TaskEventType.TASK_START)) if direction == FillDirection.EARLY: self.task_events.sort(key=lambda x: x.date) self.is_before = TaskEventsIterator._is_before_early elif direction == FillDirection.LATE: self.task_events.sort(key=lambda x: x.date, reverse=True) self.is_before = TaskEventsIterator._is_before_late else: raise ValueError()
def load(self, filehandle): """Load contents from a file handle containing a GIMP palette. If the format is incorrect, a `RuntimeError` will be raised. """ comment_line_re = re.compile(r'^#') field_line_re = re.compile(r'^(\w+)\s*:\s*(.*)$') color_line_re = re.compile(r'^(\d+)\s+(\d+)\s+(\d+)\s*(?:\b(.*))$') fp = filehandle self.clear() line = fp.readline() if line.strip() != "GIMP Palette": raise RuntimeError, "Not a valid GIMP Palette" header_done = False line_num = 0 for line in fp: line = line.strip() line_num += 1 if line == '': continue if comment_line_re.match(line): continue if not header_done: match = field_line_re.match(line) if match: key, value = match.groups() key = key.lower() if key == 'name': self.__name = value elif key == 'columns': self.__columns = int(value) else: print "warning: unknown 'key: value' pair '%s'" % line continue else: header_done = True match = color_line_re.match(line) if not match: print "warning: expected R G B [Name]" continue r, g, b, col_name = match.groups() r = float(clamp(int(r), 0, 0xff))/0xff g = float(clamp(int(g), 0, 0xff))/0xff b = float(clamp(int(b), 0, 0xff))/0xff if r == g == b == 0 and col_name == self.__EMPTY_SLOT_NAME: self.append(None) else: col = RGBColor(r, g, b) self.append(col, col_name)
def get_pos_for_color(self, col): nr, ntheta = self.get_normalized_polar_pos_for_color(col) mgr = self.get_color_manager() if mgr: ntheta = mgr.distort_hue(ntheta) nr **= 1.0 / self.SAT_GAMMA alloc = self.get_allocation() wd, ht = alloc.width, alloc.height radius = self.get_radius(wd, ht, self.BORDER_WIDTH) cx, cy = self.get_center(wd, ht) r = radius * clamp(nr, 0, 1) t = clamp(ntheta, 0, 1) * 2 * math.pi x = int(cx + r * math.cos(t)) + 0.5 y = int(cy + r * math.sin(t)) + 0.5 return x, y
def write_color(pixel_color: vector.Vec3, samples_per_pixel: int): r = pixel_color.x g = pixel_color.y b = pixel_color.z scale = 1.0 / samples_per_pixel r = math.sqrt(r * scale) g = math.sqrt(g * scale) b = math.sqrt(b * scale) print("" + str(int(256 * util.clamp(r, 0.0, 0.999))) + " " + str(int(256 * util.clamp(g, 0.0, 0.999))) + " " + str(int(256 * util.clamp(b, 0.0, 0.999))))
def mutate_brain(brain): """ Add random mutations to a brain """ # For all synapses: shift in some direction with random chance for s in brain.synapses: if util.rand(0, 1) <= Agent._MUTATE_SYNAPSE_ODDS: s.weight += Agent._MUTATE_SYNAPSE_SHIFT * util.rand(-1, 1) s.weight = util.clamp(s.weight, -1, 1)
def cluster_analysis(dim, k_cls): X_dim_red = {} print "Reducing dimensions..." util.tic() svd_cls = TruncatedSVD(n_components=dim, algorithm='arpack') svd = make_pipeline(normalizer_svd, svd_cls) X_dim_red['SVD'] = svd.fit_transform(X_tfidf) nmf_cls = NMF(n_components=dim, init='random', random_state=random_state) nmf = make_pipeline(normalizer_nmf, nmf_cls) X_dim_red['NMF'] = nmf.fit_transform(X_tfidf) util.toc() # transform #X_dim_red['SVD'] += np.max(X_dim_red['SVD']) #X_dim_red['SVD'] = X_dim_red['SVD'] ** 2 X_dim_red['NMF'] = util.clamp(-10, np.log(X_dim_red['NMF']), 10) # clustering print "Clustering..." util.tic() kmeans = {} kmeans['SVD'] = KMeans(n_clusters=k_cls, random_state=random_state).fit(X_dim_red['SVD']) kmeans['NMF'] = KMeans(n_clusters=k_cls, random_state=random_state).fit(X_dim_red['NMF']) util.toc() #-------------------------------- ### Evaluation # Purity statistics if k_cls == 6: y_true = group6_true elif k_cls == 20: y_true = group20_true print "Purity stats report:" print "Dimension = %d" % dim print "No. of groups = {}".format(k_cls) for method in ['SVD', 'NMF']: conf_mat = metrics.confusion_matrix(y_true, kmeans[method].labels_) print "======== Method: %s ========" % method print "Confusion Matrix:" print conf_mat #print "Confusion Matrix (w/ best permutation):" #print util.sort_matrix_diagonally(conf_mat) print "Homogeneity_score = {:4f}".format( homogeneity_score(y_true, kmeans[method].labels_)) print "Completeness_score = {:4f}".format( completeness_score(y_true, kmeans[method].labels_)) print "Adjusted_rand_score = {:4f}".format( adjusted_rand_score(y_true, kmeans[method].labels_)) print "Adjusted_mutual_info_score = {:4f}".format( adjusted_mutual_info_score(y_true, kmeans[method].labels_)) return
def getStates(self, timestep): # Timestep returned by Webots is in ms, so we convert delT = 0.001 * timestep # Extract (X, Y) coordinate from GPS position = self.gps.getValues() X = position[0] Y = position[1] # Find the rate of change in each axis, and store the current value of (X, Y) # as previous (X, Y) which will be used in the next call Xdot = (X - self.previousX) / (delT + 1e-9) self.previousX = X Ydot = (Y - self.previousY) / (delT + 1e-9) self.previousY = Y XYdot = np.array([[Xdot], [Ydot]]) # Get heading angle and angular velocity psi = wrapToPi(self.getBearingInRad()) angularVelocity = self.gyro.getValues() psidot = angularVelocity[2] # Get the rotation matrix (2x2) to convert velocities to the vehicle frame rotation_mat = np.array([[np.cos(psi), -np.sin(psi)], [np.sin(psi), np.cos(psi)]]) xdot = (np.linalg.inv(rotation_mat) @ XYdot)[0, 0] ydot = (np.linalg.inv(rotation_mat) @ XYdot)[1, 0] # Clamp xdot above 0 so we don't have singular matrices xdot = clamp(xdot, 1e-5, np.inf) return delT, X, Y, xdot, ydot, psi, psidot
def update(self): self.counter += 1 while self.counter >= config.FPS: self.user_every_second() self.counter -= config.FPS # move towards the target self.x += util.clamp_minmax(0.0 + self.x_accel, 1.0) * self._max_speed self.y += util.clamp_minmax(0.0 + self.y_accel, 1.0) * self._max_speed self.z += util.clamp_minmax(0.0 + self.z_accel, 1.0) * self._max_speed # don't go off screen or below the ground self.x = util.clamp(self.x, 10, config.SCREEN_WIDTH - 10) self.y = util.clamp(self.y, 10, config.SCREEN_HEIGHT - 10) self.z = util.clamp(self.z, 10, config.WORLD_HEIGHT) self.user_update()
def predict(self, user_id, item_id): pred = self.U[user_id].dot(self.VT[:, item_id]) return clamp( pred + self.avg_item.get(item_id, self.global_avg_item) + self.offset_user.get(user_id, self.global_offset_user), 1, 5)
def main(): rospy.loginfo("Starting up...") ## Load options global throttle throttle = THROTTLE args = sys.argv[1:] while len(args) > 0: opt = args.pop(0) if opt == "-t": throttle = clamp( int(args.pop(0)), -100, 100) ## Set up ROS publisher & subscriber global pub pub = rospy.Publisher(PUBLISH_TOPIC, ServoCommand) rospy.Subscriber(SUBSCRIBE_TOPIC, FuriousState, on_update) rospy.init_node(NODE_NAME) ## Initialization global dist_r, dist_l, dist_f global escape dist_r = dist_l = dist_f = MAX_RANGE escape = 0 rospy.loginfo("dist_l, dist_r, steer, dist_f, throt") rospy.spin() ## Shutdown rospy.loginfo("Shutting down normally...")
def applyTool(self, vHelix, fr, to): """ fr (from) and to take the format of (strandType, base) """ fr = list(vHelix.validatedBase(*fr, raiseOnErr=False)) to = list(vHelix.validatedBase(*to, raiseOnErr=False)) if (None, None) in (fr, to): # must start and end on a valid base return False beginBase = (vHelix, fr[0], fr[1]) leftDragLimit, rightDragLimit = self.dragLimitsForDragOpBeginningAtBase(beginBase) to[1] = util.clamp(to[1], leftDragLimit, rightDragLimit) # 1 corresponds to rightwards if to[1] == fr[1]: dragDir = 0 elif to[1] > fr[1]: dragDir = 1 else: dragDir = -1 dragOp = self.operationForDraggingInDirectionFromBase(dragDir, beginBase) op, frOffset, toOffset = dragOp[0:3] if op == self.ConnectStrand: color = dragOp[3] vHelix.connectStrand(fr[0], fr[1]+frOffset, to[1]+toOffset, color=color) elif op == self.ClearStrand: colorL, colorR = dragOp[3:5] vHelix.legacyClearStrand(fr[0], fr[1]+frOffset, to[1]+toOffset, colorL=colorL, colorR=colorR) elif op == self.RemoveXOver: vHelix.removeXoversAt(fr[0], fr[1], newColor=vHelix.palette()[0]) else: assert(op == self.NoOperation)
def quote_context(): if channel is None: self.send_message(reply_target, 'command only available in channel :(') return if len(args) < 1: self.send_message(reply_target, 'missing sequence id :(') return try: seq_id = int(args[0]) except ValueError: self.send_message(reply_target, 'bad sequence id :(') return lines = 20 if len(args) > 1: try: lines = clamp(0, int(args[1]), 100) except ValueError: pass context = self.database.quote_context(reply_target, seq_id, lines) if len(context) == 0: self.send_message(reply_target, 'no context found :(') return link = self.link_gen.make_pastebin('\r\n'.join(context)) self.send_message( reply_target, link if link is not None else 'couldn\'t upload to pastebin :(')
def paint(self, x, y): if(self.ground[x][y]): h, w = len(self.ground[0]), len(self.ground) if(self.style == 'Block'): c = '█' elif(self.style == 'Silhouette'): neighbors = (self.ground[x-1][y], self.ground[(x+1)%w][y], self.ground[x][y-1], self.ground[x][min(y+1,h-1)]) diags =(self.ground[x-1][y-1], self.ground[(x+1)%w][y-1], self.ground[x-1][min(y+1,h-1)], self.ground[(x+1)%w][min(y+1,h-1)]) block = ( not(neighbors[0] and neighbors[2] and diags[0]), not(neighbors[1] and neighbors[2] and diags[1]), not(neighbors[0] and neighbors[3] and diags[2]), not(neighbors[1] and neighbors[3] and diags[3])) c = blockgraphics.blocks[block] elif(self.style == 'Dirt'): grass = clamp(max([0]+[y-yi for yi in range(0, y) if self.ground[x][yi]]), 0, 4) c = ['█', '▓', '▒', '░', ' '][grass] elif(self.style == 'Candy'): block = (waves[0][(x*2 +2*y)%10], waves[0][(x*2+1+2*y)%10], waves[1][(x*2 +2*y)%10], waves[1][(x*2+1+2*y)%10]) c = blockgraphics.blocks[block] elif(self.style == 'Pipes'): neighbors = (self.ground[x][y-1] or y % 4 == 0, self.ground[x-1][y] or y % 4 == 0, self.ground[(x+1)%w][y] or x % 4 == 0, self.ground[x][(y+1)%h] or x % 4 == 0) c = blockgraphics.pipes[neighbors] self.groundchars[x][y] = c
def selectToolMouseMove(self, modifiers, idx): """ Given a new index (pre-validated as different from the prev index), calculate the new x coordinate for self, move there, and notify the parent strandItem to redraw its horizontal line. """ idx = util.clamp(idx, self._lowDragBound, self._highDragBound)
def mutatedCopy(self): copy_genes = [] for i in range(self.rod_count): copy_genes.append( clamp(self.genes[4 * i + 0] + uniform(-1, 1), 1, 160)) copy_genes.append( clamp(self.genes[4 * i + 1] + uniform(-1, 1), 0, 160)) copy_genes.append( clamp(self.genes[4 * i + 2] + uniform(-1, 1), 0, 40)) copy_genes.append( clamp(self.genes[4 * i + 3] + uniform(-0.0001, 0.0001), 0, 1)) copy = Dna(self.rod_count) copy.genes = copy_genes return copy
def attemptToCreateStrand(self, virtualHelixItem, strandSet, idx): self._tempStrandItem.hideIt() sIdx = self._startIdx if abs(sIdx-idx) > 1: idx = util.clamp(idx, self._lowDragBound, self._highDragBound) idxs = (idx, sIdx) if self.isDragLow(idx) else (sIdx, idx) self._startStrandSet.createStrand(*idxs)
def attemptToCreateStrand(self, virtualHelixItem, strandSet, idx): self._tempStrandItem.hideIt() sIdx = self._startIdx if abs(sIdx - idx) > 1: idx = util.clamp(idx, self._lowDragBound, self._highDragBound) idxs = (idx, sIdx) if self.isDragLow(idx) else (sIdx, idx) self._startStrandSet.createStrand(*idxs)
def pos2linecol(self, ctrl, x, y): lineh = self.getLineHeight(ctrl) ls = ctrl.sp.lines sel = None for t in self.getScreen(ctrl, False)[0]: if t.line == -1: continue # above or to the left if (x < t.x) or (y < t.y): continue # below if y > (t.y + lineh - 1): continue # to the right w = t.fi.fx * (len(ls[t.line].text) + 1) if x > (t.x + w - 1): continue sel = t break if sel == None: return (None, None) line = sel.line l = ls[line] column = util.clamp(int((x - sel.x) / sel.fi.fx), 0, len(l.text)) return (line, column)
def _draw_agents(self): """ Draw all Agent objects to the screen """ blue = pygame.Color(100,100,200) black = pygame.Color(0,0,0) green = pygame.Color(0,255,0) red = pygame.Color(255,0,0) for agent in self.model.agents: health = agent.health / 100.0 health = util.clamp(health, 0, 1) pos = util.int_tuple(agent.get_pos()) radians = agent.radians radius = agent.radius # Draw a black line showing current heading line_p0 = agent.get_pos() line_r = radius * 1.5 line_p1 = (line_p0[0] + math.cos(radians)*line_r, line_p0[1] + math.sin(radians)*line_r) pygame.draw.line(self.buffer, black, line_p0, line_p1, 2) # Draw a circle for the body. Blue for normal, red for attacking col = blue if agent.interact_attacked: col = red pygame.draw.circle(self.buffer, col, pos, radius, 0) pygame.draw.circle(self.buffer, black, pos, radius, 1) # Draw a green health bar rect = (int(agent.x)-20, int(agent.y)-30, 40, 3) pygame.draw.rect(self.buffer, red, rect) rect = (int(agent.x)-20, int(agent.y)-30, int(40*health), 3) pygame.draw.rect(self.buffer, green, rect)
def paint_foreground_cb(self, cr, wd, ht): b = int(self.BORDER_WIDTH) col = self.get_managed_color() amt = self.get_bar_amount_for_color(col) amt = float(clamp(amt, 0, 1)) bar_size = int((self.vertical and ht or wd) - 1 - 2 * b) if self.vertical: amt = 1.0 - amt x1 = b + 0.5 x2 = wd - x1 y1 = y2 = int(amt * bar_size) + b + 0.5 else: x1 = x2 = int(amt * bar_size) + b + 0.5 y1 = b + 0.5 y2 = ht - y1 cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.set_line_width(5) cr.move_to(x1, y1) cr.line_to(x2, y2) cr.set_source_rgb(0, 0, 0) cr.stroke_preserve() cr.set_source_rgb(1, 1, 1) cr.set_line_width(3.5) cr.stroke_preserve() cr.set_source_rgb(*col.get_rgb()) cr.set_line_width(0.25) cr.stroke()
def _draw_agents(self): """ Draw all Agent objects to the screen """ blue = pygame.Color(100, 100, 200) black = pygame.Color(0, 0, 0) green = pygame.Color(0, 255, 0) red = pygame.Color(255, 0, 0) for agent in self.model.agents: health = agent.health / 100.0 health = util.clamp(health, 0, 1) pos = util.int_tuple(agent.get_pos()) radians = agent.radians radius = agent.radius # Draw a black line showing current heading line_p0 = agent.get_pos() line_r = radius * 1.5 line_p1 = (line_p0[0] + math.cos(radians) * line_r, line_p0[1] + math.sin(radians) * line_r) pygame.draw.line(self.buffer, black, line_p0, line_p1, 2) # Draw a circle for the body. Blue for normal, red for attacking col = blue if agent.interact_attacked: col = red pygame.draw.circle(self.buffer, col, pos, radius, 0) pygame.draw.circle(self.buffer, black, pos, radius, 1) # Draw a green health bar rect = (int(agent.x) - 20, int(agent.y) - 30, 40, 3) pygame.draw.rect(self.buffer, red, rect) rect = (int(agent.x) - 20, int(agent.y) - 30, int(40 * health), 3) pygame.draw.rect(self.buffer, green, rect)
def quote_context(): if channel is None: self.send_message(reply_target, "command only available in channel :(") return if len(args) < 1: self.send_message(reply_target, "missing sequence id :(") return try: seq_id = int(args[0]) except ValueError: self.send_message(reply_target, "bad sequence id :(") return lines = 20 if len(args) > 1: try: lines = clamp(0, int(args[1]), 100) except ValueError: pass context = self.database.quote_context(reply_target, seq_id, lines) if len(context) == 0: self.send_message(reply_target, "no context found :(") return link = link_generator.make_pastebin("\r\n".join(context), self.pastebin_api_key) self.send_message(reply_target, link if link is not None else "couldn't upload to pastebin :(")
def testClamp(self): self.assEqual(util.clamp(-.3), 0.0) self.assEqual(util.clamp(0.0), 0.0) self.assEqual(util.clamp(.2), .2) self.assEqual(util.clamp(.9), .9) self.assEqual(util.clamp(1.0), 1.0) self.assEqual(util.clamp(1.6), 1.0) self.assEqual(util.clamp(1.6,1.2,1.9), 1.6) self.assEqual(util.clamp(1.6,2.8,8.9), 2.8)
def _draw_cb(self, widget, cr): if self._palette is None: return alloc = widget.get_allocation() w, h = alloc.width, alloc.height s_max = 16 # min(w, h) s_min = 4 ncolumns = self._palette.get_columns() ncolors = len(self._palette) if ncolors == 0: return if not ncolumns == 0: s = w / ncolumns s = clamp(s, s_min, s_max) s = int(s) if s * ncolumns > w: ncolumns = 0 if ncolumns == 0: s = math.sqrt(float(w * h) / ncolors) s = clamp(s, s_min, s_max) s = int(s) ncolumns = max(1, int(w / s)) nrows = int(ncolors // ncolumns) if ncolors % ncolumns != 0: nrows += 1 nrows = max(1, nrows) dx, dy = 0, 0 if nrows * s < h: dy = int(h - nrows * s) / 2 if ncolumns * s < w: dx = int(w - ncolumns * s) / 2 state = self.get_state_flags() style = self.get_style_context() bg_rgba = style.get_background_color(state) bg_color = RGBColor.new_from_gdk_rgba(bg_rgba) _palette_render(self._palette, cr, rows=nrows, columns=ncolumns, swatch_size=s, bg_color=bg_color, offset_x=dx, offset_y=dy, rtl=False)
def measure_slit(scidata, contour_level, slitxpos, slitypos): # cut out the slit data pixel_buffer = 50 xmin, xmax = clamp(scidata, slitxpos, pixel_buffer, 1) # cut a strip along the y-axis, small strips are better at avoiding bright objects pixel_buffer = STRIP_SIZE[1] / 2 ymin, ymax = clamp(scidata, slitypos, pixel_buffer, 0) slitdata = scidata[ymin:ymax,xmin:xmax] contours = measure.find_contours(slitdata, contour_level) contours.sort(cmp=compare_contours, reverse=True) if len(contours) < 2: raise MeasurementFailed("Only one contour found at the level of %f, try somewhere else without a bright object" % contour_level) # the first two largest contours should be the borders of the slit borders = [] for contour in contours[:2]: x = contour[:, 1] y = contour[:, 0] y_length = get_contour_length(y) limit = (STRIP_SIZE[1] / 2.0) if y_length < limit: raise MeasurementFailed("One of the edge contours is less than half the height of the strip being searched") # for vertical slits, swap the inputs, linregress works better x, y = y, x slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) # adjust for the slicing done borders.append(SlitBorder(y_length, slope, intercept, r_value, p_value, std_err)) borders.sort(cmp=compare_slit_borders) slit = SlitMeasurement(slitdata, contours, contour_level, xmin, ymin, slitxpos, slitypos, *borders) return slit
def _hsv_alloc_cb(self, hsv, alloc): # When extra space is given, grow the HSV wheel. old_radius, ring_width = hsv.get_metrics() new_radius = min(alloc.width, alloc.height) new_radius = clamp(new_radius, 50, 200) new_radius -= ring_width if new_radius != old_radius: hsv.set_metrics(new_radius, ring_width) hsv.queue_draw()
def train(ratings, U, V, lrate=0.001, lamb=0.02): for i, j, truth in ratings: pred = clamp(U[i].dot(V[:, j]), 1, 5) err = truth - pred U[i] += lrate * (err * V[:, j] - lamb * U[i]) V[:, j] += lrate * (err * U[i] - lamb * V[:, j]) return U, V
def seek(self, step): ''' :parameter step: the time, in nanoseconds, to move in the currently playing track. Negative values seek backwards. ''' seek_to_pos = self.get_position() + step seek_to_pos = clamp(seek_to_pos, 0, self.get_duration()) self.pipeline.seek_simple( gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH, seek_to_pos)
def organize(self): # Try to use sane values for padding pad = util.clamp(conf.stack_padding, 0, 100) for i, win in enumerate(self.windows): win.x = self.x + pad win.y = self.y + pad win.w = self.w - pad - pad win.h = self.h - pad - pad
def makeSelectedTabVisible(self): maxTab = self.getLastVisibleTab() # if already visible, no need to do anything if (self.selected >= self.firstTab) and (self.selected <= maxTab): return # otherwise, position the selected tab as far right as possible self.firstTab = util.clamp(self.selected - self.calcMaxVisibleTabs() + 1, 0)
def new_from_gdk_rgba(gdk_rgba): """Construct a new `UIColor` from a `Gdk.RGBA` (omitting alpha) >>> UIColor.new_from_gdk_rgba(Gdk.RGBA(0.5, 0.8, 0.2, 1)) <RGBColor r=0.5000, g=0.8000, b=0.2000> """ rgbflt = (gdk_rgba.red, gdk_rgba.green, gdk_rgba.blue) return RGBColor(*[clamp(c, 0., 1.) for c in rgbflt])
def _update_swatch_size(self): # Recalculates the best swatch size for the current palette. We try to # fit all the colours into the area available. assert self._sizes is not None assert len(self._sizes) > 0 alloc = self.get_allocation() ncolumns = self._palette.get_columns() ncolors = len(self._palette) if ncolors == 0: self._swatch_size = self._SWATCH_SIZE_NOMINAL return self._swatch_size # Attempt to show the palette within this area... width = min([w for w,h in self._sizes]) height = max([h for w,h in self._sizes]) if self._parent_size is not None: pw, ph = self._parent_size height = min(ph, height) if ncolumns == 0: # Try to fit everything in s = math.sqrt(float(width * height) / ncolors) s = clamp(s, self._SWATCH_SIZE_MIN, self._SWATCH_SIZE_MAX) ncolumns = max(1, int(width/s)) # Calculate the number of rows nrows = int(ncolors // ncolumns) if ncolors % ncolumns != 0: nrows += 1 nrows = max(1, nrows) # Calculate swatch size s1 = float(width) / ncolumns s2 = float(height) / nrows s = min(s1, s2) s = int(s) s = clamp(s, self._SWATCH_SIZE_MIN, self._SWATCH_SIZE_MAX) # Restrict to multiples of 2 for patterns, plus one for the border if s % 2 == 0: s -= 1 self._swatch_size = int(s)
def makeSelectedTabVisible(self): maxTab = self.getLastVisibleTab() # if already visible, no need to do anything if (self.selected >= self.firstTab) and (self.selected <= maxTab): return # otherwise, position the selected tab as far right as possible self.firstTab = util.clamp( self.selected - self.calcMaxVisibleTabs() + 1, 0)
def _updateActiveSlice(self, baseIndex): """The slot that receives active slice changed notifications from the part and changes the receiver to reflect the part""" bi = util.clamp(int(baseIndex), 0, self.part().numBases()-1) self.setPos(bi * self._baseWidth, -styles.PATH_HELIX_PADDING) self._activeSlice = bi if self._label: self._label.setText("%d" % bi) self._label.setX((self._baseWidth -\ self._label.boundingRect().width()) / 2)
def __scroll_cb(self, widget, event): d = self.SCROLL_DELTA if event.direction in (gdk.SCROLL_DOWN, gdk.SCROLL_LEFT): d *= -1 col = HSVColor(color=self.get_managed_color()) v = clamp(col.v + d, 0.0, 1.0) if col.v != v: col.v = v self.set_managed_color(col) return True
def __scroll_cb(self, widget, event): d = self.SCROLL_DELTA if event.direction in (gdk.SCROLL_DOWN, gdk.SCROLL_LEFT): d *= -1 col = HSVColor(color=self.get_managed_color()) v = clamp(col.v+d, 0.0, 1.0) if col.v != v: col.v = v self.set_managed_color(col) return True