def actionToPoint(goalPoint, robotPose, forwardGain, rotationGain, maxVel, angleEps): """ Internal procedure that returns an action to take to drive toward a specified goal point. """ rvel = 0 fvel = 0 robotPoint = robotPose.point() # Compute the angle between the robot and the goal point headingTheta = robotPoint.angleTo(goalPoint) # Difference between the way the robot is currently heading and # the angle to the goal. This is an angular error relative to the # robot's current heading, in the range +pi to -pi. headingError = util.fixAnglePlusMinusPi(headingTheta - robotPose.theta) if util.nearAngle(robotPose.theta, headingTheta, angleEps): # The robot is pointing toward the goal, so it's okay to move # forward. Note that we are actually doing two proportional # controllers simultaneously: one to reduce angular error # and one to reduce distance error. distToGoal = robotPoint.distance(goalPoint) fvel = distToGoal * forwardGain rvel = headingError * rotationGain else: # The robot is not pointing close enough to the goal, so don't # start moving foward yet. This is a proportional controller # to reduce angular error. rvel = headingError * rotationGain return io.Action(fvel = util.clip(fvel, -maxVel, maxVel), rvel = util.clip(rvel, -maxVel, maxVel))
def actionToPoint(goalPoint, robotPose, forwardGain, rotationGain, maxVel, angleEps): """ Internal procedure that returns an action to take to drive toward a specified goal point. """ rvel = 0 fvel = 0 robotPoint = robotPose.point() # Compute the angle between the robot and the goal point headingTheta = robotPoint.angleTo(goalPoint) # Difference between the way the robot is currently heading and # the angle to the goal. This is an angular error relative to the # robot's current heading, in the range +pi to -pi. headingError = util.fixAnglePlusMinusPi(headingTheta - robotPose.theta) if util.nearAngle(robotPose.theta, headingTheta, angleEps): # The robot is pointing toward the goal, so it's okay to move # forward. Note that we are actually doing two proportional # controllers simultaneously: one to reduce angular error # and one to reduce distance error. distToGoal = robotPoint.distance(goalPoint) fvel = distToGoal * forwardGain rvel = headingError * rotationGain else: # The robot is not pointing close enough to the goal, so don't # start moving foward yet. This is a proportional controller # to reduce angular error. rvel = headingError * rotationGain return io.Action(fvel=util.clip(fvel, -maxVel, maxVel), rvel=util.clip(rvel, -maxVel, maxVel))
def getNextValues(self, state, inp): (goalPoint, sensors) = inp robotPose = sensors.odometry robotPoint = robotPose.point() robotTheta = robotPose.theta nearGoal = robotPoint.isNear(goalPoint, self.distEps) headingTheta = robotPoint.angleTo(goalPoint) r = robotPoint.distance(goalPoint) if nearGoal: # At the right place, so do nothing a = io.Action() elif util.nearAngle(robotTheta, headingTheta, self.angleEps): # Pointing in the right direction, so move forward a = io.Action( fvel=util.clip(r * self.forwardGain, -self.maxFVel, self.maxFVel)) else: # Rotate to point toward goal headingError = util.fixAnglePlusMinusPi(headingTheta - robotTheta) a = io.Action( rvel=util.clip(headingError * self.rotationGain, -self.maxRVel, self.maxRVel)) return (nearGoal, a)
def nextState(self, state, action): (board, (x, y)) = state (dx, dy) = action newSpaceLoc = (util.clip(x + dx, 0, 2), util.clip(y + dy, 0, 2)) newBoard = swap(board, (x, y), newSpaceLoc) return (newBoard, newSpaceLoc)
def step(self, err, derr, dt): self.sum += err self.sum = clip(self.sum, -self.icap / dt, self.icap / dt) if self.outputcap is None: return self.p * err + self.i * self.sum * dt + self.d * derr else: return clip(self.p * err + self.i * self.sum * dt + self.d * derr, -self.outputcap, self.outputcap)
def drawStatusBars(self): bottomStatusBarLocation = Location(self.location.x, int(self.location.y - 1.5 * self.size)) graphics.drawStatusBar(bottomStatusBarLocation, int(2.0 * self.size), clip((self.timeToStarvation - self.timeSinceLastEaten) / (self.timeToStarvation - self.timeToHunger), 0.0, 1.0)) graphics.drawStatusBar(Location(bottomStatusBarLocation.x, int(bottomStatusBarLocation.y - 1.2 * graphics.STATUS_BAR_HEIGHT)), int(2.0 * self.size), clip((self.timeToHunger - self.timeSinceLastEaten) / self.timeToHunger, 0.0, 1.0))
def create_input_files(tile_id): print "Getting extent of", tile_id xmin, ymin, xmax, ymax = uu.coords(tile_id) # # Soil tiles are already processed, so there's no need to include them here. # # Below is the old code for tile-izing the histosole soil raster. # # Leaving this in case I ever add in soil processing again. # print "clip soil" # extra_param = ['-tr', '.00025', '.00025', '-dstnodata', '0'] # clip_soil_tile = util.clip('hwsd_oc_final.tif', '{}_soil.tif'.format(tile_id), xmin, ymin, xmax, ymax, extra_param) # # print "removing no data flag from soil" # cmd = ['gdal_edit.py', '-unsetnodata', clip_soil_tile] # subprocess.check_call(cmd) # # print "uploading soil tile to s3" # util.upload(clip_soil_tile, cn.soil_C_processed_dir) print "Rasterizing ecozone" rasterized_eco_zone_tile = util.rasterize( 'fao_ecozones_bor_tem_tro.shp', "{}_fao_ecozones_bor_tem_tro.tif".format(tile_id), xmin, ymin, xmax, ymax, '.008', 'Byte', 'recode', '0') print "Resampling eco zone" resampled_ecozone = util.resample( rasterized_eco_zone_tile, "{0}_{1}.tif".format(tile_id, cn.pattern_fao_ecozone_processed)) print "Uploading processed ecozone" util.upload(resampled_ecozone, cn.fao_ecozone_processed_dir) print "Clipping srtm" tile_srtm = util.clip('srtm.vrt', '{}_srtm.tif'.format(tile_id), xmin, ymin, xmax, ymax) print "Resampling srtm" tile_res_srtm = util.resample( tile_srtm, '{0}_{1}.tif'.format(tile_id, cn.pattern_srtm)) print "Uploading processed srtm" util.upload(tile_res_srtm, cn.srtm_processed_dir) print "Clipping precipitation" clipped_precip_tile = util.clip('add_30s_precip.tif', '{}_clip_precip.tif'.format(tile_id), xmin, ymin, xmax, ymax) print "Resampling precipitation" resample_precip_tile = util.resample( clipped_precip_tile, '{0}_{1}.tif'.format(tile_id, cn.pattern_precip)) print "Uploading processed precipitation" util.upload(resample_precip_tile, cn.precip_processed_dir)
def probToMapColor(p, hue = yellowHue): """ :param p: probability value :returns: a Python color that's good for mapmaking. It's yellow when p = 0.5, black when p = 1, white when p = 1. """ m = 0.51 x = p - 0.5 v = util.clip(2*(m - x), 0, 1) s = util.clip(2*(m + x), 0, 1) return RGBToPyColor(HSVtoRGB(hue, s, v))
def squareColor(self, indices): """ :param documentme """ (xIndex, yIndex) = indices maxValue = 10 storedValue = util.clip(self.grid[xIndex][yIndex], -maxValue, maxValue) v = util.clip((maxValue - storedValue) / maxValue, 0, 1) s = util.clip((storedValue + maxValue) / maxValue, 0, 1) if self.robotCanOccupy(indices): hue = colors.greenHue else: hue = colors.redHue return colors.RGBToPyColor(colors.HSVtoRGB(hue, 0.2 + 0.8 * s, v))
def squareColor(self, indices): """ @param documentme """ (xIndex, yIndex) = indices maxValue = 10 storedValue = util.clip(self.grid[xIndex][yIndex], -maxValue, maxValue) v = util.clip((maxValue - storedValue) / maxValue, 0, 1) s = util.clip((storedValue + maxValue) / maxValue, 0, 1) if self.robotCanOccupy(indices): hue = colors.greenHue else: hue = colors.redHue return colors.RGBToPyColor(colors.HSVtoRGB(hue, 0.2 + 0.8 * s, v))
def getNextValues(self, state, inp): # output is average probability mass in range of true loc (cheat, b) = inp (overallTotal, count) = state trueState = xToState(cheat.odometry.x) lo = xToState(cheat.odometry.x - probRange) hi = xToState(cheat.odometry.x + probRange) total = 0 for i in range(util.clip(lo, 0, numStates-1), util.clip(hi, 1, numStates)): total += b.prob(i) # print 'score', total, (overallTotal + total) / (count + 1.0) return ((overallTotal + total, count + 1), (overallTotal + total) / (count + 1.0))
def getNextValues(self, state, inp): # output is average probability mass in range of true loc (cheat, b) = inp (overallTotal, count) = state trueState = xToState(cheat.odometry.x) lo = xToState(cheat.odometry.x - probRange) hi = xToState(cheat.odometry.x + probRange) total = 0 for i in range(util.clip(lo, 0, numStates - 1), util.clip(hi, 1, numStates)): total += b.prob(i) # print 'score', total, (overallTotal + total) / (count + 1.0) return ((overallTotal + total, count + 1), (overallTotal + total) / (count + 1.0))
def newDynamics(vm0, vm1, state): if modelinductance: (vel, pos,curr) = state else: (vel, pos) = state if clipmotorvoltages: # limit outputs from opamp vm0 = util.clip(vm0, 0, sourceVoltage) vm1 = util.clip(vm1, 0, sourceVoltage) voltage = (vm0 - vm1) - vel * KB # subtract back EMF if modelinductance: newCurr = (voltage + Lm/Tsim*curr) / (Rm+Lm/Tsim) else: newCurr = voltage / Rm if clipmotorcurrent: # KA344 opamp limitation newCurr = util.clip(newCurr,-1.0,+1.0) # check whether stationary and current too small if modelfriction and vel == 0 and abs(newCurr) < istiction: newPos = pos newVel = 0 # stalled else: # calculate current needed to support friction if modelfriction: if vel == 0: sgn = signum(newCurr) else: sgn = signum(vel) ifric = sgn * ifricstatic + ifricslope * vel else: ifric = 0 newVel = vel + KM * (newCurr - ifric) * Tsim if vel * newVel > 0 or vel == newVel: # normal case newPos = pos + Tsim * (vel + newVel) / 2 else: # velocity changes sign # at zero velocity now, determine whether stalled... if modelfriction and abs(newCurr) < istiction: kTsim = vel / (vel - newVel) * Tsim # time of zero crossing newPos = pos + kTsim * vel / 2 newVel = 0 # stalled else: # there is enough current to keep going newPos = pos + Tsim * (vel + newVel) / 2 if (newPos >= potAngle and newVel >= 0) or (newPos <= 0 and newVel <= 0): # crashed into the pot limits newPos = util.clip(newPos, 0.0, potAngle) newVel = 0 if modelinductance: return (newVel, newPos, newCurr) else: return (newVel, newPos)
def leftSlipTransNoiseModel(nominalLoc, hallwayLength): """ @param nominalLoc: location that the robot would have ended up given perfect dynamics @param hallwayLength: length of the hallway @returns: distribution over resulting locations, modeling noisy execution of commands; in this case, the robot goes to the nominal location with probability 0.9, and goes one step too far left with probability 0.1. If any of these locations are out of bounds, then the associated probability mass stays at C{nominalLoc}. """ d = {} dist.incrDictEntry(d, util.clip(loc-1, 0, n-1), 0.1) dist.incrDictEntry(d, util.clip(loc, 0, n-1), 0.9) return dist.DDist(d)
def leftSlipTransNoiseModel(nominalLoc, hallwayLength): """ @param nominalLoc: location that the robot would have ended up given perfect dynamics @param hallwayLength: length of the hallway @returns: distribution over resulting locations, modeling noisy execution of commands; in this case, the robot goes to the nominal location with probability 0.9, and goes one step too far left with probability 0.1. If any of these locations are out of bounds, then the associated probability mass stays at C{nominalLoc}. """ d = {} dist.incrDictEntry(d, util.clip(loc - 1, 0, n - 1), 0.1) dist.incrDictEntry(d, util.clip(loc, 0, n - 1), 0.9) return dist.DDist(d)
def boost(self, nodes): # TODO type annotation for node in as_iter(nodes): a = self.nodes[node]['a'] #incr = max(min(1.0, a), 2.0) incr = clip(0.5, 1.0, a) self.nodes[node]['a'] += incr print('BOOST', node, 'TO', self.a(node)) #DIAG
def _scrape(self, country): self.logger.info(f"Scraping news for {country}...") url = self._construct_url(country) rss = feedparser.parse(url) # get the top Google news entries from the RSS feed idx, feed = 0, [] while idx < 100 and idx < len(rss.entries): try: entry = rss.entries[idx] link, published, title = entry.link, entry.published, entry.title self.logger.debug(f"Processing {link}...") response = (request.urlopen( link, timeout=self.timeout).read().decode("utf-8", "ignore")) soup = BeautifulSoup(response, "html.parser") description = clip(self._get_metatag(soup, name="description")) image = self._get_metatag(soup, name="image") feed.append({ "description": description, "link": link, "image": image, "published": published, "title": title, }) except ( request_err.HTTPError, request_err.URLError, HTTPException, timeout, ) as e: self.logger.debug(f"{str(e)} - {link}") feed.append({ "description": None, "link": link, "image": None, "published": published, "title": title, }) continue except AttributeError as e: self.logger.error(str(e)) continue finally: idx += 1 self.cache[country] = {"news": feed, "updated": get_utc_time()} self.logger.info( f"Finished scraping news for {country} - collected {len(feed)} stories!" )
def transitionGivenState(s): # A uniform distribution we mix in to handle teleportation transUniform = dist.UniformDist(range(numStates)) return dist.MixtureDist(dist.triangleDist(\ util.clip(s+a, 0, numStates-1), transDiscTriangleWidth, 0, numStates-1), transUniform, 1 - teleportProb)
def boost(self, node: Node, amt: Optional[Activation] = None): '''Boosts the activation of 'node' by 'amt'. If 'node' does not exist, has no effect.''' if not self.has_node(node): return if amt is None: amt = clip(0.5, 1.0, self.a(node)) self.activations[node] += amt
def yToIndex(self, y): """ @param y: real world y coordinate @return: y grid index it maps into """ shiftedY = y - self.yStep/2.0 return util.clip(int(round((shiftedY-self.yMin)/self.yStep)), 0, self.yN-1)
def xToIndex(self, x): """ @param x: real world x coordinate @return: x grid index it maps into """ shiftedX = x - self.xStep/2.0 return util.clip(int(round((shiftedX-self.xMin)/self.xStep)), 0, self.xN-1)
def noisyTransNoiseModel(nominalLoc, hallwayLength): """ @param nominalLoc: location that the robot would have ended up given perfect dynamics @param hallwayLength: length of the hallway @returns: distribution over resulting locations, modeling noisy execution of commands; in this case, the robot goes to the nominal location with probability 0.8, goes one step too far left with probability 0.1, and goes one step too far right with probability 0.1. If any of these locations are out of bounds, then the associated probability mass goes is assigned to the boundary location (either 0 or C{hallwayLength-1}). """ d = {} dist.incrDictEntry(d, util.clip(nominalLoc - 1, 0, hallwayLength - 1), 0.1) dist.incrDictEntry(d, util.clip(nominalLoc, 0, hallwayLength - 1), 0.8) dist.incrDictEntry(d, util.clip(nominalLoc + 1, 0, hallwayLength - 1), 0.1) return dist.DDist(d)
def noisyTransNoiseModel(nominalLoc, hallwayLength): """ @param nominalLoc: location that the robot would have ended up given perfect dynamics @param hallwayLength: length of the hallway @returns: distribution over resulting locations, modeling noisy execution of commands; in this case, the robot goes to the nominal location with probability 0.8, goes one step too far left with probability 0.1, and goes one step too far right with probability 0.1. If any of these locations are out of bounds, then the associated probability mass goes is assigned to the boundary location (either 0 or C{hallwayLength-1}). """ d = {} dist.incrDictEntry(d, util.clip(nominalLoc-1, 0, hallwayLength-1), 0.1) dist.incrDictEntry(d, util.clip(nominalLoc, 0, hallwayLength-1), 0.8) dist.incrDictEntry(d, util.clip(nominalLoc+1, 0, hallwayLength-1), 0.1) return dist.DDist(d)
def standardDynamics(loc, act, hallwayLength): """ @param loc: current loc (integer index) of the robot @param act: a positive or negative integer (or 0) indicating the nominal number of squares moved @param hallwayLength: number of cells in the hallway @returns: new loc of the robot assuming perfect execution. If the action would take it out of bounds, the robot stays where it is. """ return util.clip(loc + act, 0, hallwayLength-1)
def standardDynamics(loc, act, hallwayLength): """ @param loc: current loc (integer index) of the robot @param act: a positive or negative integer (or 0) indicating the nominal number of squares moved @param hallwayLength: number of cells in the hallway @returns: new loc of the robot assuming perfect execution. If the action would take it out of bounds, the robot stays where it is. """ return util.clip(loc + act, 0, hallwayLength - 1)
def getBounds(self, data, bounds): if bounds == 'auto': upper = max(data) lower = min(data) if util.within(upper, lower, 0.0001): upper = 2*lower + 0.0001 boundMargin = util.clip((upper - lower) * 0.1, 1, 100) return ((lower - boundMargin) , (upper + boundMargin)) else: return bounds
def getBounds(self, data, bounds): if bounds == 'auto': upper = max(data) lower = min(data) if util.within(upper, lower, 0.0001): upper = 2 * lower + 0.0001 boundMargin = util.clip((upper - lower) * 0.1, 1, 100) return ((lower - boundMargin), (upper + boundMargin)) else: return bounds
def triangleDist(peak, halfWidth, lo = None, hi = None): """ Construct and return a DDist over integers. The distribution will have its peak at index ``peak`` and fall off linearly from there, reaching 0 at an index ``halfWidth`` on either side of ``peak``. Any probability mass that would be below ``lo`` or above ``hi`` is assigned to ``lo`` or ``hi`` """ d = {} d[util.clip(peak, lo, hi)] = 1 total = 1 fhw = float(halfWidth) for offset in range(1, halfWidth): p = (halfWidth - offset) / fhw incrDictEntry(d, util.clip(peak + offset, lo, hi), p) incrDictEntry(d, util.clip(peak - offset, lo, hi), p) total += 2 * p for (elt, value) in d.items(): d[elt] = value / total return DDist(d)
def go(self, g, actor, env): nodes = self.get(g, actor, env, 'nodes') a = g.activation(actor) if a is None: a = 1.0 #boost_amount = max(a * 10.0, 0.2) boost_amount = clip(0.2, 10.0, a * 10.0) for node in as_iter(nodes): #print('BOOST', node) # TODO Make the boost_amount a function of actor's activation g.boost_activation(node, boost_amount)
def max_y_for_zoom(scale_brackets, zoom, max_zoom): """return the minimum and maximum y-tiles at the given zoom level for which the effective scale will not exceed the maximum zoom level""" zdiff = max_zoom - zoom if zdiff < 0: mid = 2**(zoom - 1) return (mid, mid - 1) max_merc_y = scale_brackets[zdiff] if zdiff < len(scale_brackets) else math.pi ybounds = [xy_to_tile(mercator_to_xy((0, s * max_merc_y)), zoom)[1] for s in (1, -1)] return tuple(u.clip(y, 0, 2**zoom - 1) for y in ybounds) #needed to fix y=-pi, but also a sanity check
def go(self, g, actor): # Find the target number in regard to which we are going to assess # a Proposal. want = g.neighbor(actor, 'behalf_of') target = g.neighbor(want, 'taggees') target_value = g.value_of(target) if target_value is None: raise Fizzle # TODO Is fizzling right? Something is wrong if we can't find # the target_value for our assessment. g.sleep(actor) # Look up the proposal proposal = g.look_for(Proposal, focal_point=g.ws) # TODO Require that proposal's proposed_operands be Avail if not proposal: raise Fizzle # TODO Indicate why we fizzled proposal = g.as_node(proposal) if g.has_tag(proposal, Done): g.cut_off_support(actor, proposal) return operator = g.neighbor(proposal, 'proposed_operator') if not operator: raise Fizzle # TODO Indicate why we fizzled operands = g.neighbors(proposal, 'proposed_operands') if not operands: raise Fizzle # TODO Indicate why we fizzled operand_values = list(map(g.value_of, operands)) result = g.neighbor(operator, 'result') result_value = g.value_of(result) if result_value is None: # HACK: Should put pressure on something else to estimate the # result, not calculate it ourselves. But as of 28-Jan-2021, # this gets the atests to pass. operator_class = g.class_of(operator) result_value = operator_class.result_value(proposal) # Assess whether we think the Proposal makes progress #print('ASSESS', operator, result, result_value, operands) result_dist = abs(target_value - result_value) if result_dist == 0: g.add_support(actor, proposal, 5.0) g.set_activation_from_to(actor, proposal) # Is the expected result closer to the target than any of the operands? elif any(abs(v - target) < result_dist for v in operand_values): # Yes: give both activation and support #weight = clip(0.0, 1.0, exp(-(result_dist - 1) / 20)) weight = clip(0.0, 3.0, 3 * exp(-(result_dist - 1) / 20)) # TODO Scale according to the sizes of the Target and Bricks g.set_support_from_to(actor, proposal, weight) g.set_activation_from_to(actor, proposal, 1.0) else: # No: give opposition g.oppose(actor, proposal)
def triangleDist(peak, halfWidth, lo=None, hi=None): """ Construct and return a DDist over integers. The distribution will have its peak at index C{peak} and fall off linearly from there, reaching 0 at an index C{halfWidth} on either side of C{peak}. Any probability mass that would be below C{lo} or above C{hi} is assigned to C{lo} or C{hi} """ d = {} d[util.clip(peak, lo, hi)] = 1 total = 1 fhw = float(halfWidth) for offset in range(1, halfWidth): p = (halfWidth - offset) / fhw incrDictEntry(d, util.clip(peak + offset, lo, hi), p) incrDictEntry(d, util.clip(peak - offset, lo, hi), p) total += 2 * p for (elt, value) in d.items(): d[elt] = value / total return DDist(d)
def oldDynamics(vm0, vm1, state): (vel, pos) = state current = (vm0 - vm1) / 5 # voltage/5 is input current if abs(current) < mincurrent and abs(vel) < minvelocity: return (0, pos) # stalled else: newPos = pos+T*vel newVel = B*(vel+KM*current*Tsim) if (newPos >= potAngle and newVel >= 0) or (newPos <= 0 and newVel <= 0): newPos = util.clip(newPos, 0.0, potAngle) newVel = 0 return (newVel, newPos)
def set_value(self, value, force=False): """ Try to set the control to the provided value. Due to the configuration of the Control it might assume a different value. The assumed value is returned to the caller. force should circumvent any stateful logic the control have and put it right into the correct state for that value. This does not mean ignoring minval and maxval though. """ self._value = clip(self.minval, self.maxval, value) return self._value
def squareDist(lo, hi, loLimit = None, hiLimit = None): """ Construct and return a DDist over integers. The distribution will have a uniform distribution on integers from lo to hi-1 (inclusive). Any probability mass that would be below ``lo`` or above ``hi`` is assigned to ``lo`` or ``hi``. """ d = {} p = 1.0 / (hi - lo) for i in range(lo, hi): incrDictEntry(d, util.clip(i, loLimit, hiLimit), p) return DDist(d)
def squareDist(lo, hi, loLimit=None, hiLimit=None): """ Construct and return a DDist over integers. The distribution will have a uniform distribution on integers from lo to hi-1 (inclusive). Any probability mass that would be below C{lo} or above C{hi} is assigned to C{lo} or C{hi}. """ d = {} p = 1.0 / (hi - lo) for i in range(lo, hi): incrDictEntry(d, util.clip(i, loLimit, hiLimit), p) return DDist(d)
def log_cost(X, y, w, C, order, reg=0): """ Args: X: np.array shape (n,d) float - Features y: np.array shape (n,) int - Labels w: np.array shape (d,) float - Initial parameter vector reg: scalar - regularization parameter Returns: cost: scalar the cross entropy cost of logistic regression with data X,y using regularization parameter reg grad: np.arrray shape(n,d) gradient of cost at w with regularization value reg """ gradients = None grad_reg = reg * w grad_reg[0] = 0 for i, data in enumerate(X): grad = -(data * (y[i] - logistic(np.dot(data, w)))) gradients = util.clip( C, grad, order) if gradients is None else gradients + util.clip( C, grad, order) gradients = gradients + grad_reg assert gradients.shape == w.shape return gradients
def getNextValues(self, state, inp): (goalPoint, sensors) = inp robotPose = sensors.odometry robotPoint = robotPose.point() robotTheta = robotPose.theta nearGoal = robotPoint.isNear(goalPoint, self.distEps) headingTheta = robotPoint.angleTo(goalPoint) r = robotPoint.distance(goalPoint) if nearGoal: # At the right place, so do nothing a = io.Action() elif util.nearAngle(robotTheta, headingTheta, self.angleEps): # Pointing in the right direction, so move forward a = io.Action(fvel = util.clip(r * self.forwardGain, -self.maxFVel, self.maxFVel)) else: # Rotate to point toward goal headingError = util.fixAnglePlusMinusPi(headingTheta - robotTheta) a = io.Action(rvel = util.clip(headingError * self.rotationGain, -self.maxRVel, self.maxRVel)) return (nearGoal, a)
def getNextValues(self, state, inp): # State is: starting pose currentPos = inp.odometry.point() if state == 'start': print "Starting forward", self.deltaDesired startPos = currentPos else: (startPos, lastPos) = state newState = (startPos, currentPos) # Drive straight at a speed proportional to remaining distance to # be traveled. No attempt to correct for angular deviations. error = self.deltaDesired - startPos.distance(currentPos) action = io.Action(fvel=util.clip(self.forwardGain * error, -self.maxVel, self.maxVel)) return (newState, action)
def getNextValues(self, state, inp): # State is: starting pose currentPos = inp.odometry.point() if state == 'start': print "Starting forward", self.deltaDesired startPos = currentPos else: (startPos, lastPos) = state newState = (startPos, currentPos) # Drive straight at a speed proportional to remaining distance to # be traveled. No attempt to correct for angular deviations. error = self.deltaDesired - startPos.distance(currentPos) action = io.Action(fvel = util.clip(self.forwardGain * error, -self.maxVel, self.maxVel)) return (newState, action)
def max_y_for_zoom(scale_brackets, zoom, max_zoom): """return the minimum and maximum y-tiles at the given zoom level for which the effective scale will not exceed the maximum zoom level""" zdiff = max_zoom - zoom if zdiff < 0: mid = 2**(zoom - 1) return (mid, mid - 1) max_merc_y = scale_brackets[zdiff] if zdiff < len( scale_brackets) else math.pi ybounds = [ xy_to_tile(mercator_to_xy((0, s * max_merc_y)), zoom)[1] for s in (1, -1) ] return tuple( u.clip(y, 0, 2**zoom - 1) for y in ybounds) #needed to fix y=-pi, but also a sanity check
def getNextValues(self, state, inp): currentTheta = inp.odometry.theta if state == 'start': print "Starting to rotate", self.headingDelta # Compute a desired absolute heading by adding the desired # delta to our current heading thetaDesired = \ util.fixAnglePlusMinusPi(currentTheta + self.headingDelta) else: (thetaDesired, thetaLast) = state newState = (thetaDesired, currentTheta) # Rotate at a velocity proportional to angular error # This sets the 'rvel' field in the action specification, and # leaves the other fields at their default values action = io.Action(rvel = util.clip(self.rotationalGain * \ util.fixAnglePlusMinusPi(thetaDesired - currentTheta), -self.maxVel, self.maxVel)) return (newState, action)
def angle_with(self, v, in_degrees=False): """Returns angle between v and self. Args: v: vector to compute angle with. in_degrees: specify return radians or degrees True -> degrees False -> radians (default) Returns: in_degrees == True -> angle in degrees in_degrees == False -> angle in radians Raises: Exception: if catch Exception with msg 'Cannot normalize the zero vector' Throws with msg 'Cannot compute angle with zero vector' else Throws caught Exception """ try: u1 = self.normalized() u2 = v.normalized() angle_in_radians = Decimal(acos(clip(u1.dot(u2), 1.0, -1.0))) if in_degrees: degrees_per_radian = Decimal('180.0') / Decimal(pi) return angle_in_radians * degrees_per_radian else: return angle_in_radians except Exception as e: if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG: raise Exception(self.CANNOT_COMPUTE_ANGLE_WITH_ZERO_VECTOR_MSG) else: raise e
if sys.argv[1] == '-cc': cc1 = read_cc(open(sys.argv[2], 'r')) sys.argv = sys.argv[2:] if sys.argv[1] == '-cc2': cc2 = read_cc(open(sys.argv[2], 'r')) sys.argv = sys.argv[2:] blur = True comparing = len(sys.argv) > 3 colorize = False show_affinity = True arr = np.load(sys.argv[1]) chr1 = sys.argv[1].split('/')[-1].split('.')[0].split('_')[0] if blur: arr = clip_and_blur(arr) else: arr = clip(arr) if comparing: arr = np.triu(arr) doms = read_domains(open(sys.argv[2], 'r')) result = colored_with_affinity(arr, doms, chr=chr1, cc=cc1) if comparing: arr2 = np.load(sys.argv[3]) chr2 = sys.argv[3].split('/')[-1].split('.')[0].split('_')[0] doms2 = read_domains(open(sys.argv[4], 'r')) if blur: arr2 = clip_and_blur(arr2) else: arr2 = clip(arr2) arr2 = np.triu(arr2, 1) result2 = colored_with_affinity(arr2, doms2, chr=chr2, cc=cc2) result += np.transpose(result2, (1, 0, 2))
def makePot(alpha, nodes, value = 5000): alpha = util.clip(alpha, 0.01, 0.99) return [cc.Resistor(value*alpha, nodes[0], nodes[1]), cc.Resistor(value*(1-alpha), nodes[1], nodes[2])]
changed = self.grid[xIndex][yIndex] == True self.grid[xIndex][yIndex] = False if changed: self.drawSquare((xIndex, yIndex)) def robotCanOccupy(self, (xIndex, yIndex)): """ Returns ``True`` if the robot's center can be at any location within the cell specified by ``(xIndex, yIndex)`` and not cause a collision. This implementation is very slow: it considers a range of boxes around the spcified box, and ensures that none of them is ``self.occupied``. """ for dx in range(0, self.growRadiusInCells + 1): for dy in range(0, self.growRadiusInCells + 1): xPlus = util.clip(xIndex+dx, 0, self.xN-1) xMinus = util.clip(xIndex-dx, 0, self.xN-1) yPlus = util.clip(yIndex+dy, 0, self.yN-1) yMinus = util.clip(yIndex-dy, 0, self.yN-1) if self.occupied((xPlus, yPlus)) or \ self.occupied((xPlus,yMinus)) or \ self.occupied((xMinus, yPlus)) or \ self.occupied((xMinus, yMinus)): return False return True def occupied(self, (xIndex, yIndex)): """ Returns ``True`` if there is an obstacle in any part of this cell. Note that it can be the case that a cell is not occupied, but the robot cannot occupy it (because if the
def motorAngleAlpha(angle): return util.clip(angle/potAngle, 0, 1)
# From defective clusters have color WHITE, not clustered have GREY. for dom in domains: #dom.color = 'GREY' dom.color = -1 for i, dom in enumerate(non_empty_domains): #if clusters[i] in non_empty_clusters: # colorConverter.to_rgba #dom.color = ( # COLORS[ # np.where(non_empty_clusters == clusters[i])[0][0] + 1 # ]) dom.color = np.where(non_empty_clusters == clusters[i])[0][0] #else: #dom.color = COLORS[0] #print 'wrong' #Tracer()() if __name__ == '__main__': if len(sys.argv) < 3: print 'arr doms' sys.exit(1) blur = True arr = np.load(sys.argv[1]) if blur: arr = clip_and_blur(arr) else: arr = clip(arr) doms = topify(read_domains(open(sys.argv[2], 'r'))) colorize_doms(arr, doms) print_domains(doms)
def xToState(x): return util.clip(int(round(numStates * (x - xMin) / (xMax - xMin))), 0, numStates-1)