def initial_points(n,k): pos_dict = {} point_list = [] for idx in xrange(n): if idx >= 0: x_tmp = random.randrange(200) y_tmp = random.randrange(200) s_tmp = str(x_tmp)+'-'+str(y_tmp) while s_tmp in pos_dict: x_tmp = random.randrange(200) y_tmp = random.randrange(200) s_tmp = str(x_tmp)+'-'+str(y_tmp) pos_dict[s_tmp] = 1 point_list.append(point(idx,x_tmp,y_tmp,random.randrange(k))) else: x_tmp = random.randrange(200) y_tmp = random.randrange(200) s_tmp = str(x_tmp)+'-'+str(y_tmp) while s_tmp in pos_dict: x_tmp = random.randrange(200) y_tmp = random.randrange(200) s_tmp = str(x_tmp)+'-'+str(y_tmp) pos_dict[s_tmp] = 1 point_list.append(point(idx,x_tmp,y_tmp,idx)) return point_list
def bipartition(ab,direct,opposite,F): a_i,b_i=ab p_a=direct[a_i].pt() p_b=direct[b_i].pt() A_direct=[direct[a_i]] B_direct=[direct[b_i]] for d in direct: p_d=d.pt() if np.linalg.norm(p_d-p_a)<np.linalg.norm(p_d-p_b): A_direct.append(d) else: B_direct.append(d) epl_a=epiline(p_a,F) epl_b=epiline(p_b,F) A_opposite=[] B_opposite=[] for o in opposite: oh=np.array(o.pt().tolist()+[1.]) if np.dot(oh,epl_a)<np.dot(oh,epl_b): A_opposite.append(o) else: B_opposite.append(o) A=point(0,A_direct+A_opposite) B=point(0,B_direct+B_opposite) return A,B
def synthPoints(leader,followers): new_points=[] new_leader=point(0,leader.allViews()) for p_old in followers: p=point(0,p_old.allViews()) new_leader=hard_merge(new_leader,p) new_points.append(new_leader) #dubbio: è dimostrabile l' unicità delle viste dentro new_points? return new_points
def __init__(self, kind='tri', a=point(),b=point(),c=point(),d=point(), input_b=0, input_g=255, input_r=0): self.surface_type = kind self.b = input_b self.g = input_g self.r = input_r if kind=='rect': self.createRect(a,b,c,d) elif kind=='tri': self.createTri(a,b,c)
def track(p, raspi): global cam_center_angle global cam_pan_cur, cam_tilt_cur # Correct relative to center of image # ----------------------------------- diff = p - capsize / 2 # Convert to percentage offset # ---------------------------- diff.toFloat() if feedback: print('diff = (%f, %f)' % (diff.x, diff.y)) # in pixels turn = point(diff.x / capsize.x, diff.y / capsize.y) # in % ## servo seems to react with excessively large movement to tilt commands, so ## divide turn.y by 8 instead of by 2 turn = point(turn.x / 2.0, turn.y / 8) if feedback: print('turn = (%f, %f)' % (turn.x, turn.y)) # Scale offset to degrees # ----------------------- turn.x = turn.x * fov.x turn.y = turn.y * fov.y # print('turn = (%f, %f)' % (turn.x, turn.y)) cam_pan = -turn.x cam_tilt = cam_center_angle + turn.y # Update the robot # ---------------- if feedback: print('pan = %f, tilt = %f ' % (cam_pan, cam_tilt)) if use_servo: cam_pan_cur += cam_pan cam_tilt_cur += cam_tilt if feedback: print('pan_cur = %f, tilt_cur = %f ' % (cam_pan_cur, cam_tilt_cur)) # Clamp Pan/Tilt to 0 to 180 degrees # ---------------------------------- cam_tilt_cur = max(0, min(130, cam_tilt_cur)) pan(cam_pan_cur) tilt(cam_tilt_cur) else: if int(cam_pan) == 0: raspi.putNumber('shoot', 1) else: raspi.putNumber('shoot', 0) raspi.putNumber('pan', int(cam_pan)) raspi.putNumber('tilt', int(cam_tilt))
def get_location_geoclue(self): self.geoclue = Geoclue.DiscoverLocation() self.geoclue.init() self.geoclue.set_position_provider("hostip") coordinates = self.geoclue.get_location_info() self.geoclue.position.connect_to_signal("PositionChanged", self.location_changed_geoclue) try: self.location = point.point(coordinates['latitude'], coordinates['longitude']) self.log_location_change() except KeyError, e: #TODO: Define exception for no location self.location = point.point()
def robustSynthPoints(leader,followers,gEpG,radius): new_points=[] new_leader=point(0,leader.allViews()) for p_old in followers: p=point(0,p_old.allViews()) validation_report=validation(new_leader,p,gEpG,radius) if validation_report.merge: new_leader=merge(validation_report,new_leader,p,radius=radius,permissiveLimit=4) else: new_leader,q=split(validation_report,new_leader,p) new_points.append(q) new_points.append(new_leader) #dubbio: è dimostrabile l' unicità delle viste dentro new_points? return new_points
def findFace(frame): global faceCascade gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist( gray ) faces = faceCascade.detectMultiScale(gray, 1.1, 3, 0, (10, 10)) if show_image: for (x, y, w, h) in faces: cv2.rectangle(gray, (x, y), (x+w, y+h), (0, 255, 0), 2) # Draw a green rectangle around the face for (x, y, w, h) in faces: return (gray, point(x, y) + (point(w, h) / 2)) # and return the center of the first one found return (gray, None)
def __init__(self,p1,p2): if type(p1) is point: self.p1 = p1 elif type(p1) is tuple: self.p1 = point(p1) else: raise TypeError("oops") if type(p2) is point: self.p2 = p2 elif type(p2) is tuple: self.p2 = point(p2) else: raise TypeError("oops")
def get_location_geoclue(self): self.geoclue = Geoclue.DiscoverLocation() self.geoclue.init() providers = self.geoclue.get_available_providers() selected_provider = None lat_accuracy = 0 for provider in providers: if not provider['position']: continue if provider['service'] == 'org.freedesktop.Geoclue.Providers.Example': continue self.geoclue.set_position_provider(provider['name']) coordinates = self.geoclue.get_location_info() # Ugly hack for determining most accurate provider as python-geoclue doesn't pass this info lat_accuracy_provider = len(str(coordinates['latitude'])) if lat_accuracy_provider > lat_accuracy: lat_accuracy = lat_accuracy_provider selected_provider = provider['name'] self.geoclue.set_position_provider(selected_provider) self.geoclue.position.connect_to_signal("PositionChanged", self.location_changed_geoclue) try: self.set_location(point.point(coordinates['latitude'], coordinates['longitude'])) except KeyError, e: #TODO: Define exception for no location pass
def merge(vr,p,q,radius=4.,permissiveLimit=4): PuQ=point(0,[]) inserted=set() for im_id in vr.R: permissive=False samples=0 pt=vr.R[im_id] if im_id in p.views: for v in p.views[im_id]: key=v.key() dist=np.linalg.norm(vr.R[im_id]-v.pt()) if (dist<radius or permissive) and not key in inserted: inserted.add(v.key()) PuQ.add_view(v) if im_id in q.views: for v in q.views[im_id]: key=v.key() dist=np.linalg.norm(vr.R[im_id]-v.pt()) if (dist<radius or permissive) and not key in inserted: inserted.add(v.key()) PuQ.add_view(v) if not PuQ.not_empty(): print 'empty point from merge' #ipdb.set_trace() return PuQ
def get_location(self): if Geoclue: self.get_location_geoclue() elif location: self.get_location_liblocation() else: self.location = point.point()
def __init__(self, nickname, login = False): gobject.GObject.__init__(self) if login is True: self.init_midgard_session(nickname) # Every adventurer has a ttoa_user record, check if it already exists qb = midgard.query_builder('ttoa_user') qb.add_constraint('username', '=', nickname) if qb.count() is 0: # No user yet in database, create it self.user = midgard.mgdschema.ttoa_user() self.user.username = nickname self.user.create() # Default colour for new adventurers self.set_colour('grey') else: users = qb.execute() for user in users: self.user = user self.colour = self.user.get_parameter('adventuretablet', 'colour') if self.colour is None: self.set_colour('grey') if login is True: self.apikey = self.user.get_parameter('adventuretablet', 'apikey') self.nick = nickname self.location = point.point(self.user.latitude, self.user.longitude)
def get_location_liblocation(self): self.control = location.GPSDControl.get_default() self.device = location.GPSDevice() self.control.set_properties(preferred_method=location.METHOD_USER_SELECTED, preferred_interval=location.INTERVAL_10S) # We don't have a location yet, return blank point self.location = point.point() self.control.connect("error-verbose", self.location_error_liblocation, None) self.device.connect("changed", self.location_changed_liblocation, self.control) self.control.start() if self.device.fix: if self.device.fix[1] & location.GPS_DEVICE_LATLONG_SET: # We have a "hot" fix self.location = point.point(self.device.fix[4], self.device.fix[5]) self.log_location_change()
def hard_merge(p,q): PuQ=point(0,[]) inserted=set() for v in (p.allViews()+q.allViews()): if not v.key() in inserted: inserted.add(v.key()) PuQ.add_view(v) return PuQ
def location_changed_liblocation(self, device, control): if not self.device: return if self.device.fix: if self.device.fix[1] & location.GPS_DEVICE_LATLONG_SET: self.location = point.point(self.device.fix[4], self.device.fix[5]) self.log_location_change() self.emit('location-changed', self.location, '', '', False)
def parse_partition(pb_blob): pb_part = closure_pb2.Partition() pb_part.ParseFromString(pb_blob) partition = transitiveclosure() for pb_t in tqdm(pb_part.tracks,"reading partition"): V=[pbView(pb_v) for pb_v in pb_t.views] t= point(0,V) partition._insertPoint(t) return partition
def doAttribute(self): layer = self.iface.mainWindow().activeLayer() selection = layer.selectedFeatures() if len(selection) == 1: row = selection[0].attributes() # Атрибуты земельного участка if layer.name() == gln['ln_uchastok']: d = uchAttributes(self.iface) d.idParcel = int(selection[0].id()) d.geom = QgsGeometry(selection[0].geometry()) d.sumArea = 0 if paramByName([['interface/isEditMultiContour', 'bool']])[0]: listParentId = attributesBySearchCondition('pb_parcel_parcel', '\"id_children\"=' + str(d.idParcel), ['id_parent']) if len(listParentId) == 1: d.idParent = int(listParentId[0]['id_parent']) if (d.idParent > 0): d.layerUc.removeSelection() d.layerUc.select(d.idParent) selection = d.layerUc.selectedFeatures() d.idParcel = d.idParent d.geom = QgsGeometry() d.sumArea = calculatedArea(d.idParent) d.dlgFill() d.layerUc.removeSelection() elif layer.name() == gln['ln_kvartal']: d = kvrAttributes(self.iface) elif layer.name() == gln['ln_tochka']: d = point(self.iface) d.idPoint = int(row[layer.fieldNameIndex('id')]) d.idParcel = row[layer.fieldNameIndex('id_uchastok')] d.action = 'edit' d.dlgFill() elif layer.name() == gln['ln_granica']: d = border(self.iface) d.idBorder = int(row[layer.fieldNameIndex('id')]) d.dlgFill() else: QMessageBox.warning(self.iface.mainWindow(), u"Ошибка выбора данных", u'Необходимо выбрать объект на одном из перечисленных слоёв: \"Точка\", \"Граница\", \"Участок\", \"Квартал\"') return d.exec_() del d self.canvas.refresh() else: QMessageBox.warning(self.iface.mainWindow(), u"Ошибка выбора данных", u'Необходимо выбрать только один объект для работы с атрибутами.')
def __init__(self, input_dir=0): # Coordinates of player self.position = point() # Angle of view from Y axis in horizontal plane in degrees self.direction = input_dir # Horizontal field of view in degrees self.xFOV = 90 # Vertical field of view in degrees self.xFOV = 90 # Picture plane distance self.ppdist = 350
def create_graphic(panel, function): graphic = [] for i in range(-250 * PRECISION, 250 * PRECISION + 1): j = i / PRECISION try: p = point(j * SCALE, -func(j, function) * SCALE) graphic.append(p) except ZeroDivisionError: continue draw_graphic(graphic, panel)
def get_location_liblocation(self): self.control = location.GPSDControl.get_default() self.device = location.GPSDevice() self.control.set_properties(preferred_method=location.METHOD_USER_SELECTED, preferred_interval=location.INTERVAL_10S) self.device.connect("changed", self.location_changed_liblocation, self.control) self.control.start() if self.device.fix: if self.device.fix[1] & location.GPS_DEVICE_LATLONG_SET: # We have a "hot" fix self.set_location(point.point(self.device.fix[4], self.device.fix[5]))
def parse_kml(self, kmlxml): kml = ET.fromstring(kmlxml) buses = [] for document in kml: for folder in document: if folder.tag == '{http://www.opengis.net/kml/2.2}Folder': for placemark in folder: if placemark.tag != '{http://www.opengis.net/kml/2.2}Placemark': continue bus = {} bus['id'] = placemark.get('id') numberelement = placemark.find('{http://www.opengis.net/kml/2.2}name') bus['number'] = numberelement.text pointelement = placemark.find('{http://www.opengis.net/kml/2.2}Point').find('{http://www.opengis.net/kml/2.2}coordinates') locationstring = pointelement.text.split(',') bus['location'] = point.point(locationstring[1], locationstring[0]) bus['styleid'] = placemark.find('{http://www.opengis.net/kml/2.2}styleUrl').text[1:] buses.append(bus) elif folder.tag == '{http://www.opengis.net/kml/2.2}Style': style = folder styleid = style.get('id') iconurl = style.find('{http://www.opengis.net/kml/2.2}IconStyle').find('{http://www.opengis.net/kml/2.2}Icon').find('{http://www.opengis.net/kml/2.2}href').text iconname = os.path.basename(iconurl) iconpath = self.icondir + '/' + iconname if iconurl not in self.downloads: if not os.path.exists(iconpath): print "Downloading " + iconurl web = urllib.urlopen(iconurl) local = open(iconpath, 'w') local.write(web.read()) web.close() local.close() self.downloads[iconurl] = iconpath self.icons[styleid] = iconpath for bus in buses: self.update_bus(bus)
def adventure_from_mission(self, mission, player): target = point.point(mission.latitude, mission.longitude) mission_adventure = adventure.adventure(target, mission.text, mission) # Check for adventurers adventurers = [] qb = midgard.query_builder('ttoa_log') qb.add_constraint('mission', '=', mission.id) logs = qb.execute() for log in logs: if log.author not in adventurers: adventurers.append(log.author) for participant in adventurers: user = midgard.mgdschema.ttoa_user() user.get_by_id(participant) if user.username == player.nick: # We don't add the current player to adventures, they do so manually continue else: mission_adventure.add_adventurer(adventurer.adventurer(user.username), True) return mission_adventure
todo = True dx = numpy.square(lplacedcx - cx) dy = numpy.square(lplacedcy - cy) dz = numpy.square(lplacedcz - cz) dists = numpy.sqrt(dx + dy + dz) selectedidx = numpy.argwhere(dists <= 3 * r) lplacedcx.append(cx) lplacedcy.append(cy) lplacedcz.append(cz) counter = 0 mintetha = 0.0 minp2 = point.point(0.0, 0.0, 0.0) mindval = 10000.0 p1 = point.point(cx, cy, cz) while todo: counter = counter + 1 # ruota la nanoparticella random p2x = random.uniform(botx, topx) p2y = random.uniform(boty, topy) p2z = random.uniform(botz, topz) p2 = point.point(p2x, p2y, p2z) tetha = random.uniform(0.0, 2.0 * math.pi)
def kd_tree(): try: from kdtree import kdtree from kdnode import kdnode print("Create Kd tree") global xs global ys global points points = [] for i in range(len(xs)): newpoint = point(xs[i], ys[i]) points.append(newpoint) maxbinsz = int(input("Enter max bin size (integer): ")) emax = 100 tree = kdtree(maxbinsz, emax) tree.timer = 0.05 ## Plotting ## minx, miny, maxx, maxy = -2, -2, 12, 12 ## -------- ## root = tree.makeTree(points, minx, miny, maxx, maxy) print("finished") ch = 0 prev = 0 rectangles = 0 while True: print("1. for nearest neighbor") print("0. Exit") try: ch = int(input()) except ValueError: print("That's not an int!") continue if ch == 1: print("Enter: x y NN") i = input() i = i.split(' ') try: query = [float(i[0]), float(i[1])] except ValueError: print("Could not convert string to float") continue if (prev != 0): ## Plotting ## prev.set_color('gray') prev.set_alpha(0.4) for rect in rectangles: rect.set_color('black') rect.set_alpha(0.05) ## -------- ## prev, rectangles = tree.queuryNNwrap(query, int(i[2])) print("finished") elif ch == 0: plt.ioff() points = [] break except: plt.ioff() plt.close("all")
topRight = y hull = [] hull.append(leftHull[topLeft]) hull.append(rightHull[topRight]) current = topRight while current is not botRight: hull.append(rightHull[current]) curent += 1 if current + 1 < len(rightHull) else 0 hull.append(rightHull[botRight]) current = botLeft while current is not topLeft: hull.append(leftHull[current]) current += 1 if current + 1 < len(leftHull) else 0 return hull # While the line x-y is not tangent to both hulls (on the bottom) do { # While x-y is not tangent to the left hull, let x be the next clockwise point in the left hull. # While x-y is not tangent to the right hull, let y be the next counterclockwise point in the right hull. # } # When this loop is finished, x will be Bottom_left and y will be Bottom_right. A similar method can be used to determine Top_left and Top_right. ps = [point("A", 0, 0), point("B", -5, -2), point("C", -2, -1), point("D", -6, 0), point("E", -3.5, 1), point("F", -4.5, 1.5), point("G", -2.5, -5), point("H", 1, -2.5), point("I", 2.5, .5), point("J", -2.2, 2.2)] print(recursiveHull(ps))
def __init__(self, p1_=point(), p2_=point()): self.p1 = p1_ self.p2 = p2_ self.r = self.p2 - self.p1
def createTri(self, x1=point(), x2=point(), x3=point()): self.p1=x1 self.p2=x2 self.p3=x3
import sys sys.path.append("../modules") import plane import point import math p1 = point.point(0.060167, -0.267595, -0.094069) p2 = point.point(-0.029163, -0.510884, 1.967362) p3 = point.point(-1.836883, 0.380311, 0.286389) pA = plane.plane(p1, p2, p3) p4 = point.point(0.060167, -0.267595, -0.094069) p5 = point.point(2.036123, -0.514122, 0.052635) p6 = point.point(-0.129902, -0.189737, -1.927521) pB = plane.plane(p4, p5, p6) angle = pA.return_angle(pB) print angle, "rad ", 360.0 * (angle / math.pi), " grad"
def draw(self, canvas): #//public virtual void draw(Graphics G) self.updateinoutpointlocations() #//Draw main tank #GraphicsPath tankmain #Pen plotPen #float width = 1 #tankmain = new GraphicsPath() #plotPen = new Pen(Color.Black, width) point0 = point( globe.OriginX + int(globe.GScale * (self.location.x - globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y + 0.5 * globe.TankHeightDraw))) point1 = point( globe.OriginX + int(globe.GScale * (self.location.x - globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y - 0.5 * globe.TankHeightDraw))) point2 = point( globe.OriginX + int(globe.GScale * (self.location.x + globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y - 0.5 * globe.TankHeightDraw))) point3 = point( globe.OriginX + int(globe.GScale * (self.location.x + globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y + 0.5 * globe.TankHeightDraw))) polygon = canvas.create_polygon(point0.x, point0.y, point1.x, point1.y, point2.x, point2.y, point3.x, point3.y) #Point[] myArray = new Point[] #{new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x - global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y + 0.5*global.TankHeightDraw))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x - global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y - 0.5*global.TankHeightDraw))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x + global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y - 0.5*global.TankHeightDraw))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x + global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y + 0.5*global.TankHeightDraw)))} #tankmain.AddPolygon(myArray) if (self.highlighted == True): canvas.itemconfig(polygon, fill='red') elif self.detailtrended: canvas.itemconfig(polygon, fill=globe.DetailTrendHighlightColour) else: canvas.itemconfig(polygon, fill='grey') #plotPen.Color = Color.Black #SolidBrush brush = new SolidBrush(Color.White) #brush.Color = (highlighted) ? Color.Orange : Color.White #G.FillPath(brush, tankmain) #G.DrawPath(plotPen, tankmain) #//Draw level in the tank (might later be changed for an embedded trend) #GraphicsPath tanklevel #tanklevel = new GraphicsPath() levelpoint0 = point( globe.OriginX + int(globe.GScale * (self.location.x - globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y + 0.5 * globe.TankHeightDraw))) levelpoint1 = point( globe.OriginX + int(globe.GScale * (self.location.x - globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y + 0.5 * globe.TankHeightDraw - self.fracinventory.v * globe.TankHeightDraw))) levelpoint2 = point( globe.OriginX + int(globe.GScale * (self.location.x + globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y + 0.5 * globe.TankHeightDraw - self.fracinventory.v * globe.TankHeightDraw))) levelpoint3 = point( globe.OriginX + int(globe.GScale * (self.location.x + globe.TankRadiusDraw)), globe.OriginY + int(globe.GScale * (self.location.y + 0.5 * globe.TankHeightDraw))) tanklevel = canvas.create_polygon(levelpoint0.x, levelpoint0.y, levelpoint1.x, levelpoint1.y, levelpoint2.x, levelpoint2.y, levelpoint3.x, levelpoint3.y) #Point[] tanklevelarray = new Point[] #{new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x - global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y + 0.5*global.TankHeightDraw))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x - global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y + 0.5*global.TankHeightDraw - fracinventory.v*global.TankHeightDraw))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x + global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y + 0.5*global.TankHeightDraw - fracinventory.v*global.TankHeightDraw))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(location.x + global.TankRadiusDraw)), # global.OriginY + Convert.ToInt32(global.GScale*(location.y + 0.5*global.TankHeightDraw)))} #tanklevel.AddPolygon(tanklevelarray) #plotPen.Color = Color.Black #brush.Color = (highlighted) ? Color.Blue : Color.Green #G.FillPath(brush, tanklevel) #G.DrawPath(plotPen, tanklevel) if (self.highlighted == True): canvas.itemconfig(tanklevel, fill='red') elif self.detailtrended: canvas.itemconfig(tanklevel, fill=globe.DetailTrendHighlightColour) else: canvas.itemconfig(tanklevel, fill='sky blue') #//Draw inpoint super(tank, self).draw(canvas)
def location_changed_liblocation(self, device, control): if not self.device: return if self.device.fix: if self.device.fix[1] & location.GPS_DEVICE_LATLONG_SET: self.set_location(point.point(self.device.fix[4], self.device.fix[5]))
self.comp_dphi(targ) if ((self.p - targ).length2() > 100): self.phi += self.dphi * 0.07 self.v = point(cos(self.phi), sin(self.phi)) DR = demoRobot() x_ = np.array([100, 200, 300, 400, 500, 550, 560]) #y_=np.array([100,200,100,100,100,100,100]) y_ = np.array([100, 110, 80, 120, 140, 180, 200]) pioneerPath = path(x_, y_) pioneerPath.comp_n() targ = point(10, 10) def max(a, b): if a > b: return a else: return b def min(a, b): if a < b: return a else: return b
pcx, pcy, pcz, (2.0 * nanop.get_max_sphere())) print "Selected ", len(neardst), " nanoparticles " max_numt = 1000 min_nanop = nanop superfract = compute_superfract(nanop, nearnanop) tetha = nanop.get_theta() p2 = nanop.get_p2() min_superfract = superfract i = 0 while superfract > 0.01: p2x = random.uniform(botx, topx) p2y = random.uniform(boty, topy) p2z = random.uniform(botz, topz) p2 = point.point(float(p2x), float(p2y), float(p2z)) tetha = random.uniform(0.0, 2.0 * math.pi) nanop = rotate_nanop(nanop, tetha, p2) superfract = compute_superfract(nanop, nearnanop) if (superfract < min_superfract): min_nanop = nanop min_superfract = superfract i = i + 1 if (i > max_numt): break if i > max_numt:
if (maxbox_x < (cx + dm)): maxbox_x = (cx + dm) if (maxbox_y < (cy + dm)): maxbox_y = (cy + dm) if (maxbox_z < (cz + dm)): maxbox_z = (cz + dm) if (minbox_x > (cx - dm)): minbox_x = (cx - dm) if (minbox_y > (cy - dm)): minbox_y = (cy - dm) if (minbox_z > (cz - dm)): minbox_z = (cz - dm) print "Volume: ", nanop.get_volume() print "Volume of sphere: ", sphere.sphere(point.point(), \ nanop.get_max_sphere()).get_volume() renderer.AddActor(nanop.get_vtk_actor((distance[i] != 0.0))) i += 1 # adesso creo una griglia e determino i punti sovrapposti # ma lo faccio usando come box il paralleloepipedo che inscrive la # nanorpaticella centrale nanop = selected[0] cx, cy, cz = nanop.get_center() A, B, H = nanop.get_dimensions() dm = max(B, A, H) / 2.0
from lightSource import lightSource from transform import transform from graphicsWindow import graphicsWindow from myRayTracer import cameraMatrix from implicitSphere import implicitSphere from myRayTracer import shader NP = 1.0 FP = 25.0 WIDTH = 512 HEIGHT = 512 THETA = 45.0 P = vector(0.0, 0.0, 1.0) #Up vector E = point(5.0, 5.0, 5.0) #Camera position G = point(0.0, 0.0, 0.0) #Gaze point L = point(5.0, 0.0, 3.0) #Set light position C = (1.0, 1.0, 1.0) #Light color I = (1.0, 1.0, 1.0) #Light intensity light = lightSource(L, C, I) window = graphicsWindow(WIDTH, HEIGHT) camera = cameraMatrix(window, P, E, G, NP, FP, THETA) #Creating a scene with three spheres objectList = [] objectList.append( implicitSphere(color=(255, 0, 255), T=transform().translate(),
import point dirs_matrices = { 'up': point.point(0, -1), 'down': point.point(0, 1), 'left': point.point(-1, 0), 'right': point.point(1, 0) } basic_dirs = ['up', 'down', 'left', 'right']
def generate_point_inside_poly(p1, p2, p3, p4, step, psurface_list, label): polypoint = [] polypoint.append(p1) polypoint.append(p2) polypoint.append(p3) polypoint.append(p4) # i 4 punti devono essere ordinati oraio o antiorario e' indifferente # calcolo il lato piu' lungo d = [] d.append(p1.get_distance_from(p2)) d.append(p2.get_distance_from(p3)) d.append(p3.get_distance_from(p4)) d.append(p4.get_distance_from(p1)) idx = 0 for i in range(1,4): if (d[i] > d[i-1]): idx = i #print "Max: ", d[idx] # forse meglio indicare lo step cosi' da avere uniformita' di punti numofp = int(d[idx] / step) if (numofp == 0): print("Step too big ", d[idx] , " and ", step, file=sys.stderr) return B = point.point() C = point.point() l = line.line3d() if idx == 0: l.set_two_point(p1, p2) B.set_coordinates(p2.get_x(), p2.get_y(), p2.get_z()) C.set_coordinates(p3.get_x(), p3.get_y(), p3.get_z()) elif idx == 1: l.set_two_point(p2, p3) B.set_coordinates(p3.get_x(), p3.get_y(), p3.get_z()) C.set_coordinates(p4.get_x(), p4.get_y(), p4.get_z()) elif idx == 2: l.set_two_point(p3, p4) B.set_coordinates(p4.get_x(), p4.get_y(), p4.get_z()) C.set_coordinates(p1.get_x(), p1.get_y(), p1.get_z()) elif idx == 3: l.set_two_point(p4, p1) B.set_coordinates(p1.get_x(), p1.get_y(), p1.get_z()) C.set_coordinates(p2.get_x(), p2.get_y(), p2.get_z()) # questi punti li genero lungo il lato piu' lungo plist = l.generate_equi_point(numofp) """ provo a non aggiungere i punti del lato che comunque non sono bene indetificabili come apparteneti ad una superficie o all'altra """ for p in plist: p.set_label(label) psurface_list.append(p) #print psurface_list[-1].get_label() # http://www.youtube.com/watch?v=HmMJGcHV9Oc # equazione vettoriale del piano # # -- -- -- -- # OP = OA + a * AB + b * BC # # dove O origine P punto che voglio e A B C li definisco # a seconda del segmento che ho preso sopra # # A---------------------B # | # | # | # C # mi muovo lungo BC step by step # posso usare sempre le rette cambio nella line3d il valore di a # e di b quindi A diventa ogni volta il punto in plist, e b diventa # il vettore paralleloa BC, dovrebbe bastare appunto BC. lBC = line.line3d() lBC.set_b(C-B) for p in plist: lBC.set_a(p) plistBC = lBC.generate_equi_point(numofp) for pBC in plistBC: diff = math.fabs(angle_sum_poly(polypoint, pBC) - TWOPI) if (diff < 1e-10): pBC.set_label(label) psurface_list.append(pBC) #print psurface_list[-1].get_label() return
Ts.append(T3) Ts.append(T4) Ts.append(T5) Ts.append(T6) ''' addComponent(60, 68, 5, 13, ' o', Map) addComponent(45, 51, 10, 20, ' o', Map) addComponent(35, 48, 27, 33, ' o', Map) addComponent(7, 13, 18, 27, ' o', Map) addComponent(47, 60, 40, 47, ' o', Map) printMap(Map) #Start Points Isaac's Schematic S1 = point(14, 20) S2 = point(14, 25) S3 = point(49, 27) S4 = point(49, 29) S5 = point(49, 31) S6 = point(49, 33) S7 = point(52, 12) S8 = point(59, 7) S9 = point(59, 5) #End Points Isaac T1 = point(34, 29) T2 = point(34, 31) T3 = point(52, 14) T4 = point(52, 16) T5 = point(58, 39)
tocluster = [] clusterpair = [] minidists = [] print "Start pair selection ..." for id1 in range(len(nanoparticles)): nanop1 = nanoparticles[id1] p1cx, p1cy, p1cz = nanop1.get_center() sumr = 2.25 * nanop1.get_max_sphere() indices, d = nanoparticle.get_near_nanoparticle_indexs(nanoparticles, \ p1cx, p1cy, p1cz, sumr) theta = nanop1.get_theta() p2 = nanop1.get_p2() p1 = point.point(p1cx, p1cy, p1cz) xlist1, ylist1, zlist1 = xyznanop.return_rototransl_xyz(p1, p2, theta, \ xlist, ylist, zlist) n1 = numpy.column_stack((xlist1, ylist1, zlist1)) for i in range(len(indices)): id2 = indices[i] pair = str(id1) + "_" + str(id2) if (id1 != id2) and (pair not in pairs): pairs.append(str(id1) + "_" + str(id2)) pairs.append(str(id2) + "_" + str(id1)) nanop2 = nanoparticles[id2]
def mapIterator(i, goal, dir, Map): X, Y = getNextPos(dir, mtPoint[0], Map) current = point(X, Y) start = current curSym = Map[current.X][current.Y] print(curSym) print(goal) print(len(Map)) if goal == "T": change = "t" else: change = "s" temp = [] temp.append(current) path = [] first = 0 i = 0 while goal not in curSym: #and i < 29: #just add a counter for first time: in first time i only check one direction whatever dir is #if curSym == " +": # return None print("Current Symbol: " + curSym) print(goal) nextX, nextY = getNextPos(dir, current, Map) if nextX == -1 and first == 0: #means we are on first line and reached the limit; meaning this line goes nowhere print("HERE1") return [] if nextX == -1: print("HERE2") current = start temp = [] temp.append(current) curSym = Map[current.X][current.Y] dir = (dir + 2) % 4 continue nextSym = Map[nextX][nextY] if nextSym[0] in curSym or nextSym[0] in change: current = point(nextX, nextY) temp.append(current) else: path = path + temp current = point(nextX, nextY) start = current temp = [] first = 1 temp.append(current) dir = (dir + 1) % 4 curSym = Map[current.X][current.Y] i += 1 print("Current Symbol: " + curSym) path.append(current) return path
def queuryNN(self, queury, n, root): self.stepmode = True distances = []; NNs = []; plotted = []; for i in range(n): distances.append(9999999999); # nearest neighbor distances initialized to infinity NNs.append((-1, -1)); # nearest neighbor indices initialized to -1 plotted.append(point(-100, -100)); ordering = []; dx = max(root.minx - queury[0], 0, queury[0] - root.minx-root.width); dy = max(root.miny - queury[1], 0, queury[1] - root.miny-root.height); root.dist = dx*dx + dy*dy; heapq.heappush( ordering, root ); count = 0; rectangles = []; while (len(ordering) != 0 and count < self.emax): dCur = heapq.heappop(ordering); while (dCur.dim != -1): dx = max(dCur.greaterChild.minx - queury[0], 0, queury[0] - dCur.greaterChild.minx-dCur.greaterChild.width); dy = max(dCur.greaterChild.miny - queury[1], 0, queury[1] - dCur.greaterChild.miny-dCur.greaterChild.height); dCur.greaterChild.dist = dx*dx + dy*dy; dx = max(dCur.lessChild.minx - queury[0], 0, queury[0] - dCur.lessChild.minx-dCur.lessChild.width); dy = max(dCur.lessChild.miny - queury[1], 0, queury[1] - dCur.lessChild.miny-dCur.lessChild.height); dCur.lessChild.dist = dx*dx + dy*dy; heapq.heappush( ordering, dCur.greaterChild ); heapq.heappush( ordering, dCur.lessChild ); dCur = heapq.heappop(ordering); if (dCur.dist < distances[0]): ## Plotting ## rect = self.currentAxis.add_patch( Rectangle( (dCur.minx, dCur.miny), dCur.width, dCur.height, alpha=0.3, color=numpy.random.rand(3,1) ) ); rectangles.append(rect); ## -------- ## for i in range( dCur.st, dCur.end ): ## Plotting ## prev = plt.scatter([p.x for p in plotted], [p.y for p in plotted], color='red', marker=u's'); cur = plt.scatter( self.pts[i][0], self.pts[i][1], color='black', s = 50); self.fig.canvas.draw(); self.fig.canvas.flush_events(); plt.show(); if self.stepmode: a = input("Press Enter to step or c to continue:") if a == 'c': self.stepmode = False print("finishing...") else: time.sleep(self.timer); cur.remove(); prev.remove(); ## -------- ## dist = sqedEucDist(self.pts[i], queury); if (dist < distances[0]): distances[0] = dist; NNs[0] = self.pts[i]; plotted[0] = self.pts[i]; ii = 0; while (ii < n-1 and distances[ii] < distances[ii+1]): distances[ii] = distances[ii+1]; distances[ii+1] = dist; NNs[ii] = NNs[ii+1]; NNs[ii+1] = self.pts[i]; plotted[ii] = plotted[ii+1]; plotted[ii+1] = self.pts[i]; ii += 1; count += 1; else: break; ## Plotting ## prev = plt.scatter([p.x for p in plotted], [p.y for p in plotted], color='red', s = 50); ## -------- ## return prev, rectangles;
if (dist <= radius[idx]): if (nanoparticles[idx].is_point_inside([x, y, zplane])): is_inside = True break if not is_inside: count_point_not_inside += 1 if (count_point_not_inside >= MAX_POINT_TODO): print >> sys.stderr, "Max point reached " sys.stdout.flush() sys.stderr.flush() exit(1) p = point.point(x, y, zplane) # q lo genro fuori dalla box perche' cosi' sono certo attraversera # tutte le nanoparticelle point_circle = circle.circle(x, y, 2.0 * max(Dx, Dy, Dz)) second_points = point_circle.generate_circle_points(\ util_for_tr.NUMOFCIRCLEPOINTS) poly_data_points = [] for sp in second_points: q = point.point(sp[0], sp[1], zplane) selected_point = [] min_d = float("inf") for idx in interior_indices:
return (type_path, route_path) if __name__ == "__main__": parser = optparse.OptionParser("buscatcher OPTIONS") parser.add_option("--update-interval", type="int", default=3000) parser.add_option("--initial-lat", type="float", default=60.170424) parser.add_option("--initial-lon", type="float", default=24.94070) parser.add_option("--initial-zoom", type="int", default=15) parser.add_option("--repo-uri", type="str",default="http://tile.openstreetmap.org/#Z/#X/#Y.png") parser.add_option("--no-update-position", action="store_true", default=True) (options, args) = parser.parse_args() if conic: # Request Maemo to start an internet connection, as buscatcher doesn't really make sense without one connection = conic.Connection() u = buscatcher(options.repo_uri, options.initial_zoom) initial_location = point.point(options.initial_lat, options.initial_lon) u.set_location(initial_location) u.show_all() if osso: import devicemonitor osso_c = osso.Context("buscatcher", "0.0.1", False) device_monitor = devicemonitor.device_monitor(osso_c) device_monitor.set_display_off_cb(u.tracking_stop) device_monitor.set_display_on_cb(u.tracking_start) gtk.main()
def __init__(self, x=40,y=20,z=5, b=255,g=255,r=255): self.pos = point(x,y,z) self.b = b self.g = g self.r = r
#=============================================================================== # Map is (x,y) x wide and y high Map = numpy.empty((40, 30), dtype=numpy.object) Map.fill(' -') addComponent(16, 23, 3, 12, ' o', Map) addComponent(11, 15, 16, 29, ' o', Map) #addComponent(22, 30, 19, 26, ' o', Map) MapOriginal = copyMap(Map) #addComponent(16, 16, 10, 17, ' o') #addComponent S1 = point(5, 4) T1 = point(34, 9) Map[5][4] = 'S1' Map[34][9] = 'T1' Map[5][10] = "S2" Map[27][7] = "T2" printMap(Map) s = Route(S1, T1, Map) for each in s: MapOriginal[each.X][each.Y] = 'c1' printMap(MapOriginal) S2 = point(5, 10) T2 = point(27, 7)
def rectangle(canvas, top_left_x, top_left_y, bottom_right_x, bottom_right_y, border=DEFAULT_COLOUR, fill=False, fill_colour=DEFAULT_EMPTY): """ Creates a rectangle given its top-left and bottom-right co-ordinates :param canvas: canvas to manipulate :param top_left_x: x co-ordinate of top-left :param top_left_y: y co-ordinate of top-left :param bottom_right_x: x co-ordinate of bottom-right :param bottom_right_y: y co-ordinate of bottom-right :param border: colour to set at :param fill: boolean flag indicating if the rectangle is to be filled :param fill_colour: colour to fill the inside of the rectangle :return: None :raises RectangleTypeError: when 'bottom-right' is not really below and to the right of 'top-left' :Example: rectangle(canvas(5,5), 2, 2, 4, 4) == [[' ', ' ', ' ', ' ', ' '], [' ', 'x', 'x', 'x', ' '], [' ', 'x', ' ', 'x', ' '], [' ', 'x', 'x', 'x', ' '], [' ', ' ', ' ', ' ', ' ']] """ # function expects top left and bottom right co-ordinates try: assert top_left_x <= bottom_right_x and top_left_y <= bottom_right_y except AssertionError: raise RectangleTypeError( "Co-ordinates top-left {},{} are not above " "and to the left of co-ordinates bottom-right {},{}".format( top_left_x, top_left_y, bottom_right_x, bottom_right_y)) # draw lines upper left - upper right, upper right - bottom right, bottom right - bottom left, # and finally, bottom left - upper left upper_left = (top_left_x, top_left_y) upper_right = (bottom_right_x, top_left_y) bottom_right = (bottom_right_x, bottom_right_y) bottom_left = (top_left_x, bottom_right_y) def rect_border_line(start_x, start_y, end_x, end_y): # closure of canvas and border line(canvas, start_x, start_y, end_x, end_y, border) rect_border_line(*(upper_left + upper_right)) rect_border_line(*(upper_right + bottom_right)) rect_border_line(*(bottom_right + bottom_left)) rect_border_line(*(bottom_left + upper_left)) if fill: # set points inside the rectangle borders for x in contain_x_range_to_canvas(canvas, top_left_x, bottom_right_x): for y in contain_y_range_to_canvas(canvas, top_left_y, bottom_right_y): # exclude borders if x not in (top_left_x, bottom_right_x) and y not in (top_left_y, bottom_right_y): point(canvas, x, y, fill_colour)
def location_changed_geoclue(self, fields, timestamp, latitude, longitude, altitude, accuracy): self.set_location(point.point(latitude, longitude))
def __init__(self): self.dphi = 0 self.v = point(1, 0) self.p = point(40, 40) self.phi = 0
def newPoint(self,views): pointId=0 p=point(pointId,views) self._insertPoint(p) return p
def draw(self, canvas): self.updateinoutpointlocations() #GraphicsPath plot1 #Pen plotPen #float width = 1 #plot1 = new GraphicsPath() #plotPen = new Pen(Color.Black, width) point0 = point( globe.OriginX + int(globe.GScale * (self.inpoint[0].x)), globe.OriginY + int(globe.GScale * (self.inpoint[0].y - globe.TeeBranchThickness / 2))) point1 = point( globe.OriginX + int(globe.GScale * (self.inpoint[0].x - globe.TeeLength / 2)), globe.OriginY + int(globe.GScale * (self.inpoint[0].y - globe.TeeBranchThickness / 2))) point2 = point( globe.OriginX + int(globe.GScale * (self.inpoint[0].x - globe.TeeLength / 2)), globe.OriginY + int(globe.GScale * (self.inpoint[0].y + globe.TeeBranchThickness / 2))) point3 = point( globe.OriginX + int(globe.GScale * (self.inpoint[0].x)), globe.OriginY + int(globe.GScale * (self.inpoint[0].y + globe.TeeBranchThickness / 2))) maininput = canvas.create_polygon(point0.x, point0.y, point1.x, point1.y, point2.x, point2.y, point3.x, point3.y) #Point[] input = new Point[] #{new Point(global.OriginX + Convert.ToInt32(global.GScale*(inpoint[0].x)), # global.OriginY + Convert.ToInt32(global.GScale*(inpoint[0].y - global.TeeBranchThickness/2))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(inpoint[0].x - global.TeeLength/2)), # global.OriginY + Convert.ToInt32(global.GScale*(inpoint[0].y - global.TeeBranchThickness/2))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(inpoint[0].x - global.TeeLength/2)), # global.OriginY + Convert.ToInt32(global.GScale*(inpoint[0].y + global.TeeBranchThickness/2))), #new Point(global.OriginX + Convert.ToInt32(global.GScale*(inpoint[0].x)), # global.OriginY + Convert.ToInt32(global.GScale*(inpoint[0].y + global.TeeBranchThickness/2)))} #plot1.AddPolygon(input) x0 = globe.OriginX + int( globe.GScale * (self.location.x - globe.TeeBranchThickness / 2)) y0 = globe.OriginY + int(globe.GScale * (self.location.y - (self.nout - 1) / 2.0 * \ globe.TeeDistanceBetweenBranches)) x1 = x0 + int(globe.GScale * (globe.TeeBranchThickness)) y1 = y0 + int(globe.GScale * ((self.nout - 1) * globe.TeeDistanceBetweenBranches)) upright = canvas.create_rectangle(x0, y0, x1, y1) if self.highlighted: canvas.itemconfig(upright, fill='red') else: canvas.itemconfig(upright, fill='black') #Rectangle upright = new Rectangle( # global.OriginX + Convert.ToInt32(global.GScale * (location.x - global.TeeBranchThickness / 2)), # global.OriginY + Convert.ToInt32(global.GScale * (location.y - (nout - 1) / 2.0 * global.TeeDistanceBetweenBranches)), # Convert.ToInt32(global.GScale * (global.TeeBranchThickness)), # Convert.ToInt32(global.GScale * ((nout - 1) * global.TeeDistanceBetweenBranches))) #plot1.AddRectangle(upright) branches = list() #list of Rectangles #Rectangle[] branches = new Rectangle[nout] for i in range(self.nout): x0 = globe.OriginX + int(globe.GScale * (self.location.x - globe.TeeLength / 2)) y0 = globe.OriginY + int(globe.GScale * (self.location.y - (self.nout - 1) / 2.0 * \ globe.TeeDistanceBetweenBranches + i * globe.TeeDistanceBetweenBranches)) x1 = x0 + int(globe.GScale * (globe.TeeLength / 2)) y1 = y0 + int(globe.GScale * (globe.TeeBranchThickness)) #branches[i] = new Rectangle( # global.OriginX + Convert.ToInt32(global.GScale * (location.x - global.TeeLength / 2)), # global.OriginY + Convert.ToInt32(global.GScale * (location.y - (nout - 1) / 2.0 * global.TeeDistanceBetweenBranches + # i * global.TeeDistanceBetweenBranches)), # Convert.ToInt32(global.GScale * (global.TeeLength / 2)), # Convert.ToInt32(global.GScale * (global.TeeBranchThickness))) rect = canvas.create_rectangle(x0, y0, x1, y1) branches.append(rect) #plot1.AddRectangle(branches[i]) #plotPen.Color = Color.Black #SolidBrush brush = new SolidBrush(Color.Black) #if (highlighted) { brush.Color = Color.Orange; } #G.FillPath(brush, plot1) #G.DrawPath(plotPen, plot1) super(tee, self).draw(canvas)
def createRect(self, x1=point(), x2=point(), x3=point(), x4=point()): self.p1=x1 self.p2=x2 self.p3=x3 self.p4=x4
def make_plot(prefix='tb', show_plot=True, caR=15.0, caL=15.0, saL=12.0, saR=15.0, u=1.0, N=15, curve_fun=ptb_straightline, kite=0, cutProtoconch=True, addAngle=0.0): figure, ax = plt.subplots() name = '{}_cal{}_car{}_sal{}_sar{}_N{}_add{}'.format( prefix, int(caL), int(caR), int(saL), int(saR), N, int(100 * addAngle)) print(name) # angles from known angBR = 90 + (caR) angBL = 90 + (caL) angCL = 180 - angBL - saL angCR = 180 - angBR - saR # known length BL_BR = u # initial protoconch triangle pointA = point(0, 0) A_BL = law_sines(BL_BR, caL + caR, 90 - caR) A_BR = law_sines(BL_BR, caL + caR, 90 - caL) pointBR = pointA.pointFrom(A_BR, caR) pointBL = pointA.pointFrom(A_BL, -caL) if cutProtoconch: outerPolyVertices = [pointBR.pts(), pointBL.pts()] else: outerPolyVertices = [pointBR.pts(), pointA.pts(), pointBL.pts()] prevA = pointA paths = [] for i in range(N + 1): angCL = 180 - angBL - saL # recalculate as it depends on saL which can change angCR = 180 - angBR - saR # recalculate as it depends on saR which can change # this is a magical incantation supported by the unholy art of geometry saSinRatio = sin(radians(saR)) / sin(radians(saL)) numerator = BL_BR * sin(radians(angBL)) * sin(radians(angBR)) denom_A = saSinRatio * sin(radians(angCL)) * sin(radians(angBR)) denom_B = sin(radians(angCR)) * sin(radians(angBL)) A_CR = numerator / (denom_A + denom_B) A_CL = law_sines(A_CR, saL, saR) A_BL = law_sines(A_CL, angBL, angCL) A_BR = law_sines(A_CR, angBR, angCR) pointA = pointBL.pointFrom(A_BL, 90.0) pointBR = pointA.pointFrom(A_BR, 90.0) pointCR = pointA.pointFrom(A_CR, 90 - saR) pointCL = pointA.pointFrom(A_CL, -(90 - saL)) if i != N: # last pass is for the outer cut if curve_fun == ptb_straightline: add_plot(paths, pointBL, pointBR, color='r', curve_fun=curve_fun) else: add_plot(paths, pointA, pointBR, color='r', curve_fun=curve_fun) add_plot(paths, pointA, pointBL, color='r', curve_fun=curve_fun) add_plot(paths, pointA, pointCL, color='b', curve_fun=curve_fun) add_plot(paths, pointA, pointCR, color='b', curve_fun=curve_fun) if i == (N - kite): kiteBL = pointBL kiteBR = pointBR if cutProtoconch == False and i == 0: add_plot(paths, prevA, pointA, color='g', curve_fun=ptb_straightline) pointBL = pointCL pointBR = pointCR BL_BR = pointCL.lengthTo(pointCR) prevA = pointA saL += saL * addAngle saR += saR * addAngle if kite == 0: outerPolyVertices.extend([pointCL.pts(), pointCR.pts()]) else: # cut off kite and also modify the lines halfC = pointCL.lengthTo(pointCR) / 2.0 outerPolyVertices.extend( [kiteBL.pts(), pointCL.pointFrom(halfC, 90).pts(), kiteBR.pts()]) left = [kiteBL.pts(), pointCL.pointFrom(halfC, 90).pts()] right = [pointCL.pointFrom(halfC, 90).pts(), kiteBR.pts()] Npaths = len(paths) curves_per_whorl = 4 for i in range(Npaths - (kite * curves_per_whorl), Npaths): curve, color = paths[i] curve = cutAtIntersection(curve, left) curve = cutAtIntersection(curve, right) paths[i] = (curve, color) for curve, color in paths: ax.plot(curve[:, 0], curve[:, 1], color) poly = Polygon(outerPolyVertices, facecolor='1.0', edgecolor='k') p = ax.add_patch(poly) plt.axis('off') plt.box(False) ax.set_aspect(1), ax.autoscale() plt.savefig(name + ".svg") if show_plot: plt.title(name), plt.show()
filename = "pore_radius_list_nano.txt" filenamenanop = "final_config_nanoparticle.txt" if (len(sys.argv)) == 3: filename = sys.argv[1] filenamenanop = sys.argv[2] file = open(filename, "r") pores = [] for sp in file: x, y, z, cx, cy, cz, r = sp.split(" ") center = point.point(float(cx), float(cy), float(cz)) s = sphere.sphere(center, float(r)) pores.append(s) file.close() nanoparticles = [] botx, topx, boty, topy, botz, topz = \ nanoparticle.file_to_nanoparticle_list(filenamenanop, nanoparticles) nanopscx, nanopscy, nanopscz = \ nanoparticle.nanoparticle_to_arrays (nanoparticles) for pore in pores: pcenter = pore.get_center()
def ptb_sumxdiv090_avey(pt1, pt2): divisor = 2.0 * 0.90 xb = (pt1.x + pt2.x) / divisor yb = (pt1.y + pt2.y) / divisor return point(xb, yb)
#cv2.imshow("skel",skel) #D* Lite Method --------------------------------------------- newHeight = int(height * 0.1) newWidth = int(width * 0.1) dliteimage = cv2.resize(agvcmap.getImage(), (newWidth, newHeight)) cv2.imwrite('AGVCmap2.bmp', dliteimage) robot = Robot(TEG.x, TEG.y, TEG.radius * 2) imageMap = ImageReader() imageMap.loadFile("AGVCmap2.bmp") mapper.initalize(imageMap, robot) moveGrid = imageMap.convertToGrid().copy() ##goal = point(3,17) testdivider = 1 goal = point(int(newHeight / testdivider * 0.8), int(newWidth / testdivider * 0.8)) #cv2.waitKey(0) ##mapper.printMoveGrid() print "STARTIN LOOP" moveId = 0 Xlength = mapper.grid.shape[0] / testdivider Ylength = mapper.grid.shape[1] / testdivider #dstar = dstar3.DStar(Xlength,Ylength,goal) dstar = dlite.Dlite(Xlength, Ylength, goal, robot) print "Entering Loop" testvar = 0 while (robot.y != goal.y or robot.x != goal.x): if testvar % 10 == 0:
nanoparticle.POINTINSURFACESTEP = float('inf') nearnanop, neardst = nanoparticle.get_near_nanoparticle (nanoparticles, \ pcx, pcy, pcz, (2.0 * nanop.get_max_sphere())) print "Selected ", len(neardst), " nanoparticles " maxdiff = 1.0 # anche 2 vale la pena provare fino a 1000 ho visto casi in # cui si arriva ad una diff di 2 e poco piu' # genera la spfera su cui poi generare i p2 ncx, ncy, ncz = nanop.get_center() p2sphere = sphere.sphere(point.point(ncx, ncy, ncz), nanop.get_max_sphere()) p2list = p2sphere.generate_surface_points(180) min_nanop = nanop to_rotate_nanop = nanop superfract_ratio = compute_superfract_ratio(min_nanop, nearnanop) tetha = 0.0 p2 = point.point(float(pcx), float(pcy), float(pcz)) min_superfract_ratio = superfract_ratio i = 0 for p2 in p2list: tetha = 1.0 while tetha < 2.0 * math.pi: to_rotate_nanop = rotate_nanop(to_rotate_nanop, tetha, p2) superfract_ratio = compute_superfract_ratio(
# ------------------------------------------------------------------------ import cv2, sys, time, os, math, logging from point import point from networktables import NetworkTable from threading import Thread # ------------------------------------------------------------------------ # config # ------------------------------------------------------------------------ if sys.platform == 'win32': method = 0 # 0 = face tracking, 1 = SURF feedback = True camera = "c905" use_servo = False # when False, use networktables show_image = True # display grabbed image capsize = point(640, 480) cam_center_angle = 0.0 else: method = 0 # 0 = face tracking, 1 = SURF feedback = False camera = "pi" use_servo = True # when False, use networktables show_image = True # display grabbed image capsize = point(640, 480) cam_center_angle = 0.0 print("using %s camera" % camera) if camera == "pi": fov = point(53.5, 41.4) # see https://www.raspberrypi.org/documentation/hardware/camera.md elif camera == "c905": fov = point(64.0, 48.0) # est. Logitech c905 webcam
xs = np.zeros(numPoints) ys = np.zeros(numPoints) # populate initial sample for i in range(numPoints): state = np.zeros(numInputs) for j in range(numInputs): state[j] = random.random()*10.0 x,y = calculation.func(state) xs[i] = x ys[i] = y xmin = min(x,xmin) ymin = min(y,ymin) xmax = max(x,xmax) ymax = max(y,ymax) pos = vector2(x,y) points.append(point(i,pos,state)) # construct neighbor sets for i in range(numPoints): thisPoint = points[i] thisPoint.updateNeighbors(points,nNeighbor) thisPoint.weight = thisPoint.volume # calculate the 0th order corrections if do_Corrections: for i in range(numPoints): thisPoint = points[i] thisPoint.calcCorrection(points) plt.scatter(xs,ys,c='black',marker='+') if do_Map: sSize = 50
def click_and_crop(event, x, y, flags, DR): if (event == cv2.EVENT_LBUTTONDOWN): p = point(x, y) global targ targ = p
def doAttribute(self): layer = self.iface.mainWindow().activeLayer() selection = layer.selectedFeatures() if len(selection) == 1: row = selection[0].attributes() # Атрибуты земельного участка if layer.name() == gln['ln_uchastok']: d = uchAttributes(self.iface) d.idParcel = int(selection[0].id()) d.geom = QgsGeometry(selection[0].geometry()) d.sumArea = 0 if paramByName([['interface/isEditMultiContour', 'bool']])[0]: listParentId = attributesBySearchCondition( 'pb_parcel_parcel', '\"id_children\"=' + str(d.idParcel), ['id_parent']) if len(listParentId) == 1: d.idParent = int(listParentId[0]['id_parent']) if (d.idParent > 0): d.layerUc.removeSelection() d.layerUc.select(d.idParent) selection = d.layerUc.selectedFeatures() d.idParcel = d.idParent d.geom = QgsGeometry() d.sumArea = calculatedArea(d.idParent) d.dlgFill() d.layerUc.removeSelection() elif layer.name() == gln['ln_kvartal']: d = kvrAttributes(self.iface) elif layer.name() == gln['ln_tochka']: d = point(self.iface) d.idPoint = int(row[layer.fieldNameIndex('id')]) d.idParcel = row[layer.fieldNameIndex('id_uchastok')] d.action = 'edit' d.dlgFill() elif layer.name() == gln['ln_granica']: d = border(self.iface) d.idBorder = int(row[layer.fieldNameIndex('id')]) d.dlgFill() else: QMessageBox.warning( self.iface.mainWindow(), u"Ошибка выбора данных", u'Необходимо выбрать объект на одном из перечисленных слоёв: \"Точка\", \"Граница\", \"Участок\", \"Квартал\"' ) return d.exec_() del d self.canvas.refresh() else: QMessageBox.warning( self.iface.mainWindow(), u"Ошибка выбора данных", u'Необходимо выбрать только один объект для работы с атрибутами.' )