本文整理汇总了Python中util.clamp函数的典型用法代码示例。如果您正苦于以下问题:Python clamp函数的具体用法?Python clamp怎么用?Python clamp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clamp函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: baseAtLocation
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)
示例2: baseAtPoint
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)
示例3: baseAtPoint
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)
示例4: load
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()
示例5: calcBGOffset
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))
)
示例6: walkTo
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
示例7: load
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)
示例8: get_pos_for_color
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
示例9: paint
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
示例10: applyTool
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)
示例11: mutate_brain
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)
示例12: attemptToCreateStrand
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)
示例13: paint_foreground_cb
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()
示例14: predict
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)
示例15: _draw_agents
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)