def transformPointCloud2(cmd,string,extend,showmatplot=False):

	pout=createPointset(cmd.T,extend)
	Points.show(pout)

	result=App.ActiveDocument.ActiveObject
	result.ViewObject.hide()

	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	App.ActiveDocument.ActiveObject.Label=string

	if showmatplot:
		plt.imshow(cmd, origin='lower')
		plt.title('data for ' + string)
		plt.gca().get_xaxis().set_visible(False)
		plt.gca().get_yaxis().set_visible(False)
		plt.colorbar()
		plt.show()

	s=[]
	for  p in pout.Points:
		shape = Part.Vertex(p)
		s.append(shape)

	comp=Part.makeCompound(s)

	result2=comp
	return result,result2
Beispiel #2
0
def reducepoints(k=40):

	sels=Gui.Selection.getSelection()
	if len(sels)<>1: print("Du musst Pointset auswaehlen" )
	pts=np.array(sels[0].Points.Points)

	print ("len start",len(pts))
	pts=np.array(pts)

	ptsm=pts

	if k<>0:
#		ptsm[:]  += [100,300,500]
		ptsm /=k 
		pts2=ptsm.round()
		pts2 *=k
	else:
		pts2=ptsm

	data=pts2
	ncols = data.shape[1]
	dtype = data.dtype.descr * ncols
	struct = data.view(dtype)

	uniq = np.unique(struct)
	uniq = uniq.view(data.dtype).reshape(-1, ncols)

	pts3= uniq
	print len(uniq)

	pts3v=[FreeCAD.Vector(p) for p in pts3]
	pcl=Points.Points(pts3v)
	Points.show(pcl)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	App.ActiveDocument.ActiveObject.Label="Reduce " +str(k) + " " +sels[0].Label +" "
Beispiel #3
0
def loadobj():

	fn='/home/thomas/Dokumente/freecad_buch/b231_kscan/body-v2-obj/body-v2.obj'
	fn='/home/thomas/Dokumente/freecad_buch/b231_kscan/model.obj'
	fn='/home/thomas/Dokumente/freecad_buch/b232_blender_banana/banana.obj'
#	fn='/home/thomas/Downloads/CUP_GOM_06.02.2017.stl'
#	fn='/home/thomas/Downloads/gh.stl'

	print "read ",fn
	with open(fn) as f:
		content = f.readlines()

	pts=[]
	for i,l in enumerate(content):
		if l.startswith('v '):
			print l
			[a,x,y,z]=l.split(' ')
			
			p=FreeCAD.Vector(float(x),float(z),-float(y))

			p=FreeCAD.Vector(float(x)-float(y),-float(z),float(x)+float(y))

			pts.append(p)

	t=Points.Points(pts)
	Points.show(t)
Beispiel #4
0
    def test_fifteens(self):
        fifteens_points = Points.Points([
            Card.Card(0, 1),
            Card.Card(0, 5),
            Card.Card(0, 5),
            Card.Card(0, 10)
        ], Card.Card(0, 10))
        fifteens_points.fifteens(0, 0)
        self.assertTrue(fifteens_points.points == 8)

        fifteens_points = Points.Points([
            Card.Card(0, 11),
            Card.Card(0, 12),
            Card.Card(0, 13),
            Card.Card(0, 5)
        ], Card.Card(0, 10))
        fifteens_points.fifteens(0, 0)
        self.assertTrue(fifteens_points.points == 8)

        fifteens_points = Points.Points([
            Card.Card(0, 8),
            Card.Card(0, 7),
            Card.Card(0, 9),
            Card.Card(0, 6)
        ], Card.Card(0, 10))
        fifteens_points.fifteens(0, 0)
        self.assertTrue(fifteens_points.points == 4)
def pcl(pts=None):
    '''create a point cloud of points pts'''
    if pts == None:
        pts = pointlist()
    pcl = Points.Points(pts)
    Points.show(pcl)
    return App.ActiveDocument.ActiveObject
Beispiel #6
0
    def setUp(self):
        self.C0 = circles.Circle()
        self.C0prim = circles.Circle()
        self.C112 = circles.Circle(1, 1, 2)

        self.p00 = Points.Point(0, 0)
        self.p11 = Points.Point(1, 1)
def transformPointCloud2(cmd, string, extend, showmatplot=False):

    pout = createPointset(cmd.T, extend)
    Points.show(pout)

    result = App.ActiveDocument.ActiveObject
    result.ViewObject.hide()

    App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (random.random(),
                                                             random.random(),
                                                             random.random())
    App.ActiveDocument.ActiveObject.Label = string

    if showmatplot:
        plt.imshow(cmd, origin='lower')
        plt.title('data for ' + string)
        plt.gca().get_xaxis().set_visible(False)
        plt.gca().get_yaxis().set_visible(False)
        plt.colorbar()
        plt.show()

    s = []
    for p in pout.Points:
        shape = Part.Vertex(p)
        s.append(shape)

    comp = Part.makeCompound(s)

    result2 = comp
    return result, result2
Beispiel #8
0
    def test_runs(self):
        run_points = Points.Points([
            Card.Card(0, 1),
            Card.Card(0, 1),
            Card.Card(0, 2),
            Card.Card(0, 3)
        ], Card.Card(0, 4))
        run_points.runs()
        self.assertTrue(run_points.points == 8)

        run_points = Points.Points([
            Card.Card(0, 9),
            Card.Card(0, 10),
            Card.Card(0, 10),
            Card.Card(0, 11)
        ], Card.Card(0, 3))
        run_points.runs()
        self.assertTrue(run_points.points == 6)

        run_points = Points.Points([
            Card.Card(0, 2),
            Card.Card(0, 3),
            Card.Card(0, 4),
            Card.Card(0, 5)
        ], Card.Card(0, 9))
        run_points.runs()
        self.assertTrue(run_points.points == 4)
Beispiel #9
0
 def readfloats(self, i, total):
     if not Points.numpyimported:
         Points.importnumpy()
     N = Points.N
     data = self.readstr(i)
     if hasattr(N, "ndarray") and isinstance(data, N.ndarray):
         return data
     fromstring = Points.fromstring
     if fromstring:
         fdata = []
         if "D".encode("ascii") not in data:
             fdata = fromstring(data, dtype=float, sep=' ')
         if fdata == [] or len(fdata) != total:
             fdata = N.array(map(parseB.AUTOatof, data.split()), 'd')
         else:
             #make sure the last element is correct
             #(fromstring may not do this correctly for a
             #string like -2.05071-106)
             fdata[-1] = parseB.AUTOatof(
                 data[data.rfind(" ".encode("ascii")) + 1:].strip())
     else:
         data = data.split()
         try:
             fdata = N.array(map(float, data), 'd')
         except ValueError:
             fdata = N.array(map(parseB.AUTOatof, data), 'd')
     if total != len(fdata):
         raise PrematureEndofData
     del self.solutions[i]['data']
     self.solutions[i]['data'] = fdata
     return fdata
Beispiel #10
0
def create_pcl(pu,color=(1.0,0.0,0.0)):
	say(len(pu))
	p=Points.Points(pu)
	Points.show(p)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=color
	App.ActiveDocument.points.addObject(App.ActiveDocument.ActiveObject)
	Gui.updateGui()
Beispiel #11
0
    def test_pairs(self):
        pairs_points = Points.Points([
            Card.Card(0, 1),
            Card.Card(0, 5),
            Card.Card(1, 5),
            Card.Card(0, 10)
        ], Card.Card(2, 10))
        pairs_points.pairs()
        self.assertTrue(pairs_points.points == 4)

        pairs_points = Points.Points([
            Card.Card(0, 13),
            Card.Card(0, 13),
            Card.Card(0, 13),
            Card.Card(0, 2)
        ], Card.Card(0, 10))
        pairs_points.pairs()
        self.assertTrue(pairs_points.points == 6)

        pairs_points = Points.Points([
            Card.Card(0, 10),
            Card.Card(0, 10),
            Card.Card(0, 10),
            Card.Card(0, 10)
        ], Card.Card(0, 1))
        pairs_points.pairs()
        self.assertTrue(pairs_points.points == 12)
Beispiel #12
0
    def test_nobs(self):
        nobs_points = Points.Points([
            Card.Card(0, 2),
            Card.Card(1, 11),
            Card.Card(0, 4),
            Card.Card(0, 5)
        ], Card.Card(1, 9))
        nobs_points.nobs()
        self.assertTrue(nobs_points.points == 1)

        nobs_points = Points.Points([
            Card.Card(0, 2),
            Card.Card(1, 11),
            Card.Card(0, 4),
            Card.Card(2, 11)
        ], Card.Card(2, 9))
        nobs_points.nobs()
        self.assertTrue(nobs_points.points == 1)

        nobs_points = Points.Points([
            Card.Card(0, 2),
            Card.Card(2, 11),
            Card.Card(0, 4),
            Card.Card(0, 5)
        ], Card.Card(2, 9))
        nobs_points.nobs()
        self.assertTrue(nobs_points.points == 1)
Beispiel #13
0
def randomcloud():
	r=1000.0
	pts=[FreeCAD.Vector(r*random.random(),r*random.random(),r*random.random()) for i in range(1000)]
	pcl=Points.Points(pts)
	Points.show(pcl)
	App.ActiveDocument.ActiveObject.Label="Random Cloud "
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
Beispiel #14
0
def run(mx, my, dx, dy):

    ys = my - dy
    yn = my + dy
    xw = mx - dx
    xe = mx + dx

    dats = []

    print(xw, ys, xe, yn)
    for ix in range(int(math.floor(xw)), int(math.floor(xe)) + 1):
        for iy in range(int(math.floor(ys)), int(math.floor(yn)) + 1):
            dat = "Lat" + str(iy) + "Lon" + str(ix) + "Lat" + str(
                iy + 1) + "Lon" + str(ix + 1)
            print(dat)
            dats.append(dat)

    directory = FreeCAD.ConfigGet("UserAppData") + "/geodat_SRTM/"

    if not os.path.isdir(directory):
        print("create " + directory)
        os.makedirs(directory)

    for dat in dats:
        getdata(directory, dat)
        fn = directory + "/" + dat + ".osm"
        pts = runfile(fn, xw, xe, ys, yn, mx, my)

        p = Points.Points(pts)
        Points.show(p)
        Gui.updateGui()
        Gui.SendMsgToActiveView("ViewFit")

    Gui.SendMsgToActiveView("ViewFit")
Beispiel #15
0
 def __parse(self):
     if self.__fullyParsed:
         return
     global N
     if not Points.numpyimported:
         Points.importnumpy()
     self.__fullyParsed = True
     fromstring = Points.fromstring
     N = Points.N
     datalist = self.__datalist
     del self.__datalist
     line0 = datalist[0].split()
     self.BR = int(line0[0])
     ncolumns = len(line0)
     nrows = len(datalist)
     datalist = "".join(datalist)
     if fromstring: #numpy
         data = []
         if "D" not in datalist:
             data = fromstring(datalist, dtype=float, sep=' ')
         if len(data) != nrows * ncolumns:
             data = N.array(map(AUTOatof,datalist.split()), 'd')
         else:
             #make sure the last element is correct
             #(fromstring may not do this correctly for a
             #string like -2.05071-106)
             data[-1] = AUTOatof(datalist[datalist.rfind(' ')+1:].strip())
     else: #numarray, Numeric, array
         datalist = datalist.split()
         try:
             data = N.array(map(float, datalist), 'd')
         except ValueError:
             data = N.array(map(AUTOatof, datalist), 'd')
     data.shape = (-1,ncolumns)
     coordarray = N.transpose(data[:,4:]).copy()
     points = data[:,1]
     if hasattr(N,"concatenate"):
         stability = self.__parsenumpy(points)
     else:
         stability = self.__parsearray(points)
     # add stability info labels
     branchtype = type_translation(self.TY)["short name"]
     for i in stability:
         if i < 0:
             stab = "S"
         else:
             stab = "U"
         self.labels.update(abs(i)-1, branchtype, {"stab": stab})
     # sometimes the columns names are the same: add spaces to those
     for i in range(len(self.coordnames)):
         name = self.coordnames[i]
         if self.coordnames.count(name) > 1:
             for j in range(i+1,len(self.coordnames)):
                 if self.coordnames[j] == name:
                     self.coordnames[j] = name + ' '
     Points.Pointset.__init__(self,{
         "coordarray": coordarray,
         "coordnames": self.coordnames,
         "labels": self.labels,
         })
Beispiel #16
0
def create_pcl(pu, color=(1.0, 0.0, 0.0)):
    '''create_pcl(pu,color=(1.0,0.0,0.0))'''

    say(len(pu))
    p = Points.Points(pu)
    Points.show(p)
    App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = color
    App.ActiveDocument.points.addObject(App.ActiveDocument.ActiveObject)
    Gui.updateGui()
Beispiel #17
0
def command_points(args, msg, event):
    if len(args) < 1:
        return "Not enough arguments."
    if args[0] == "give":
        return Points.give_points(args, msg, event)
    elif args[0] == "get":
        return Points.get_points(args, msg, event)
    elif args[0] == "admin":
        return Points.admin_points(args, msg, event)
Beispiel #18
0
def projectxy(d=2):
	sels=Gui.Selection.getSelection()
	if len(sels)<>1: print("Du musst Pointset auswaehlen" )
	pts=np.array(sels[0].Points.Points)
	pts[:,d]=0
	t=Points.Points([tuple(p) for p in pts])
	Points.show(t)
	proj=["yz","xz","xy"][d]
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	App.ActiveDocument.ActiveObject.Label=proj+"-Projection of " +sels[0].Label +" "
Beispiel #19
0
def fusionpoints():
	import Points

	sels=Gui.Selection.getSelection()
	pts=sels[0].Points.Points
	pts2=sels[1].Points.Points


	pcl=Points.Points(pts + pts2)
	Points.show(pcl)
Beispiel #20
0
def testD():
#	kku2=np.array(FreeCAD.kku).reshape(31,31,3)
#	kku=kku2[10:25,10:20].reshape(150,3)

	ptsu=[FreeCAD.Vector(tuple(i)) for i in kku]
	Draft.makeWire(ptsu)
	Points.show(Points.Points(ptsu))


	mode='thin_plate'
	xy2u = scipy.interpolate.Rbf(kku[:,0],kku[:,1],kku[:,2], function=mode)
Beispiel #21
0
def applyplacement():

	sels=Gui.Selection.getSelection()
	if len(sels)<>1: print("Du musst Pointset auswaehlen" )
	pts=sels[0].Points.Points
	p2=sels[0].Points.Placement

	pcl=Points.Points(pts)
	Points.show(pcl)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	App.ActiveDocument.ActiveObject.Label="Placed " + sels[0].Label +" "
Beispiel #22
0
    def __readAll(self):
        if self.__fullyParsed or self.__nodata():
            return
        if not Points.numpyimported:
            Points.importnumpy()
        fromstring = Points.fromstring
        N = Points.N
        self.__fullyParsed = True
        n = self.__numEntriesPerBlock
        nrows = self.__numSValues
        total = n * nrows + self.__numFreeParameters
        nlinessmall = (((n - 1) / 7 + 1) * nrows +
                       (self.__numFreeParameters + 6) / 7)
        if self["NTST"] != 0 and self.__numLinesPerEntry > nlinessmall:
            total += 2 * self.__numChangingParameters + (n - 1) * nrows
        fdata = self.__input.readfloats(self.__index, total)
        ups = N.reshape(fdata[:n * nrows], (nrows, n))
        self.indepvararray = ups[:, 0]
        self.coordarray = N.transpose(ups[:, 1:])
        j = n * nrows

        # Check if direction info is given
        if self["NTST"] != 0 and self.__numLinesPerEntry > nlinessmall:
            nfpr = self.__numChangingParameters
            self["Active ICP"] = list(map(int, fdata[j:j + nfpr]))
            j = j + nfpr
            self["rldot"] = fdata[j:j + nfpr]
            j = j + nfpr
            n = n - 1
            self["udotps"] = N.transpose(
                N.reshape(fdata[j:j + n * self.__numSValues], (-1, n)))
            udotnames = [
                "UDOT(%d)" % (i + 1)
                for i in range(self.__numEntriesPerBlock - 1)
            ]
            self["udotps"] = Points.Pointset({
                "coordarray": self["udotps"],
                "coordnames": udotnames,
                "name": self.name
            })
            self["udotps"]._dims = None
            j = j + n * nrows

        self.PAR = fdata[j:j + self.__numFreeParameters]
        Points.Pointset.__init__(
            self, {
                "indepvararray": self.indepvararray,
                "indepvarname": self.indepvarname,
                "coordarray": self.coordarray,
                "coordnames": self.coordnames,
                "name": self.name
            })
        self.update()
Beispiel #23
0
 def test_cards_only_rank(self):
     test_player1 = Player.Player("Player 1", False)
     test_player2 = Player.Player("Player 2", False)
     self.game = Game.Game(test_player1, test_player2)
     self.game.deal()
     self.game.top_card = self.game.deck.cut_deck()
     self.points1 = Points.Points(self.game.player1.hand.cards,
                                  self.game.top_card)
     self.points2 = Points.Points(self.game.player2.hand.cards,
                                  self.game.top_card)
     for card in self.points1.cards_only_rank:
         self.assertTrue(0 <= card <= 13)
     for card in self.points2.cards_only_rank:
         self.assertTrue(0 <= card <= 13)
Beispiel #24
0
def make_points_from_geometry(geometries, distance):
    for geom in geometries:
        global_plm = geom.getGlobalPlacement()
        local_plm = geom.Placement
        plm = global_plm * local_plm.inverse()

        prop = geom.getPropertyOfGeometry()
        if prop is None:
            continue

        points_and_normals = prop.getPoints(distance)
        if len(points_and_normals[0]) == 0:
            continue

        points = geom.Document.addObject("Points::Feature", "Points")

        kernel = Points.Points()
        kernel.addPoints(points_and_normals[0])

        points.Points = kernel
        points.Placement = plm

        if len(points_and_normals[1]) > 0 and len(
                points_and_normals[0]) == len(points_and_normals[1]):
            points.addProperty("Points::PropertyNormalList", "Normal")
            points.Normal = points_and_normals[1]

        points.purgeTouched()
Beispiel #25
0
def create_pcl(pu, color=(1.0, 0.0, 0.0)):
    '''create_pcl(pu,color=(1.0,0.0,0.0))'''

    say(len(pu))
    p = Points.Points(pu)
    Points.show(p)
    App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = color
    App.ActiveDocument.ActiveObject.ViewObject.PointSize = 3
    try:
        App.ActiveDocument.points
    except:
        points = App.ActiveDocument.addObject("App::DocumentObjectGroup",
                                              "points")

    App.ActiveDocument.points.addObject(App.ActiveDocument.ActiveObject)
    Gui.updateGui()
Beispiel #26
0
 def relabel(self,old_label=1,new_label=None):
     """Relabels the first solution with the given label"""
     if new_label is None:
         label = old_label
         new = self.__class__(self)
         labels = {}
         if not self.__fullyParsed:
             new.__datalist = self.__datalist[:]
         for index in self.labels.getIndices():
             labels[index] = self.labels[index].copy()
             ty_name,v = self._gettypelabel(index)
             if v.get("LAB",0) != 0:
                 labels[index][ty_name] = v.copy()
                 labels[index][ty_name]["LAB"] = label
                 if not self.__fullyParsed:
                     self.__patchline(new.__datalist,index,3,label)
                 label = label + 1
         new.labels = Points.PointInfo(labels)
         return new
     labels = self.labels
     if isinstance(old_label, int):
         old_label = [old_label]
         new_label = [new_label]
     for j in range(len(old_label)):
         for index in self.labels.getIndices():
             v = self._gettypelabel(index)[1]
             if "LAB" not in v:
                 continue
             if v["LAB"] == old_label[j]:
                 v["LAB"] = new_label[j]
                 if not self.__fullyParsed:
                     self.__patchline(self.__datalist,index,3,new_label[j])
Beispiel #27
0
 def deleteLabel(self,label=None,keepTY=0,keep=0,copy=0):
     """Removes solutions with the given labels or type names"""
     if label is None:
         label = [lab for lab in all_point_types if lab not in
                  ["No Label", "RG", "UZ"]]
     if isinstance(label, (str, int)):
         label = [label]
     if copy:
         new = self.__class__(self)
         new.labels = Points.PointInfo(self.labels.by_index.copy())
         if not self.__fullyParsed:
             new.__datalist = self.__datalist[:]
     else:
         new = self
     for idx in new.labels.getIndices():
         ty_name,v = new._gettypelabel(idx)
         if "LAB" not in v:
             continue
         if ((not keep and (v["LAB"] in label or ty_name in label)) or
            (keep and not v["LAB"] in label and not ty_name in label)):
             if copy:
                 new.labels[idx][ty_name] = v.copy()
             new.labels[idx][ty_name]["LAB"] = 0
             if not keepTY:
                 new.labels[idx][ty_name]["TY number"] = 0
             if not new.__fullyParsed:
                 new.__patchline(new.__datalist,idx,3,0)
                 if not keepTY:
                     new.__patchline(new.__datalist,idx,2,0)
             if v["TY number"] == 0:
                 new.labels.remove(idx)
     if copy:
         return new
Beispiel #28
0
def loadstl(): # stl !!

	fn='/home/thomas/Downloads/CUP_GOM_06.02.2017.stl'
	fn='/home/thomas/Downloads/gh.stl'

	print "read ",fn
	m = mesh.Mesh.from_file(fn)

	pts=[]
	for i,p in enumerate(m.points):
			[x,y,z]=p[0:3]
			p=FreeCAD.Vector(float(x),float(z),-float(y))
			pts.append(p)

	t=Points.Points(pts)
	Points.show(t)
Beispiel #29
0
    def makeRayBundle(self, raybundle, offset):
        raysorigin = raybundle.o
        nrays = np.shape(raysorigin)[1]

        pp = Points.Points()
        sectionpoints = []

        res = []

        for i in range(nrays):
            if abs(raybundle.t[i]) > 1e-6:
                x1 = raysorigin[0, i] + offset[0]
                y1 = raysorigin[1, i] + offset[1]
                z1 = raysorigin[2, i] + offset[2]

                x2 = x1 + raybundle.t[i] * raybundle.rayDir[0, i]
                y2 = y1 + raybundle.t[i] * raybundle.rayDir[1, i]
                z2 = z1 + raybundle.t[i] * raybundle.rayDir[2, i]

                res.append(Part.makeLine((x1, y1, z1),
                                         (x2, y2, z2)))  # draw ray
                sectionpoints.append((x2, y2, z2))
        pp.addPoints(sectionpoints)
        #Points.show(pp) # draw intersection points per raybundle per field point

        return (pp, res)
Beispiel #30
0
    def makeSurfaceFromSag(self,
                           surface,
                           startpoint=[0, 0, 0],
                           R=50.0,
                           rpoints=10,
                           phipoints=12):

        # TODO: sdia parameter not valid anymore, change behaviour here, too. depending on the type of aperture

        surPoints = []
        pts = Points.Points()
        pclpoints = []
        for r in np.linspace(0, R, rpoints):
            points = []
            for a in np.linspace(0.0, 360.0 - 360 / float(phipoints),
                                 phipoints):
                x = r * math.cos(a * math.pi / 180.0)  # + startpoint[0]
                y = r * math.sin(a * math.pi / 180.0)  # + startpoint[1]
                z = surface.shape.getSag(x, y)  # + startpoint[2]
                p = FreeCAD.Base.Vector(x, y, z)
                p2 = FreeCAD.Base.Vector(x + startpoint[0], y + startpoint[1],
                                         z + startpoint[2])
                points.append(p)
                pclpoints.append(p2)
            surPoints.append(points)
        pts.addPoints(pclpoints)
        sur = Part.BSplineSurface()
        sur.interpolate(surPoints)
        sur.setVPeriodic()
        surshape = sur.toShape()
        surshape.translate(tuple(startpoint))
        return (surshape, pts)
Beispiel #31
0
def createStepFC(self,i):
	ts=time.time()
	objs=pclgroup()
	(la,lb)=self.ptsl[i].shape
#	pts=[tuple(self.ptslix[self.ptsl[i][a][b]]) for a in range(la) for b in range(lb)]

	pts=[]
	for a in range(la):
		for b in range(lb):
			t=tuple(self.ptslix[self.ptsl[i][a][b]])
			if np.isnan(t[0]) or np.isnan(t[1]) or np.isnan(t[2]):
##debug				print "found error ", t
#				print (a,b)
				
				pass
# ignore zero points
			elif 	abs(t[0])<10 and  abs(t[1])<20:
##debug				print "ignore inner point ",t
				pass
			else:
				pts.append(t)

	pcl=Points.Points(pts)
	Points.show(pcl)

	App.activeDocument().recompute()
	if i%25==0: Gui.SendMsgToActiveView("ViewFit")

	obj=App.ActiveDocument.ActiveObject
	obj.ViewObject.ShapeColor=(random.random(),random.random(),random.random())


	if len(objs.OutList)==0:
		obj.Placement=self.obj2.startPosition
	else:
		#movePosition=FreeCAD.Placement()
		#movePosition.Rotation=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),10)
		movePosition=self.obj2.deltaPosition
		obj.Placement=objs.OutList[-1].Placement.multiply(movePosition)


	objs.addObject(obj)
	te=time.time()
	say(("createStepFC ",i,"timee",round(te-ts,3)))

	return obj
Beispiel #32
0
    def test_flush(self):
        flush_points = Points.Points([
            Card.Card(0, 2),
            Card.Card(0, 3),
            Card.Card(0, 4),
            Card.Card(0, 5)
        ], Card.Card(1, 9))
        flush_points.flush()
        self.assertTrue(flush_points.points == 4)

        flush_points = Points.Points([
            Card.Card(2, 2),
            Card.Card(2, 3),
            Card.Card(2, 4),
            Card.Card(2, 5)
        ], Card.Card(2, 9))
        flush_points.flush()
        self.assertTrue(flush_points.points == 5)
def displayQualityPoints():
    '''display the quality points as point clouds'''
    g = FreeCAD.g
    for q in range(1, 7):
        pts = []
        for v in g.nodes():
            #print g.node[v]['quality']
            if g.node[v]['quality'] == q: pts.append(g.node[v]['vector'])


#		print pts
        if pts <> []:
            Points.show(Points.Points(pts))
            App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (
                random.random(), random.random(), random.random())
            App.ActiveDocument.ActiveObject.ViewObject.PointSize = 10

            App.ActiveDocument.ActiveObject.Label = "Points Quality " + str(q)
Beispiel #34
0
def createStepFC(self,i):
	ts=time.time()
	objs=pclgroup()
	(la,lb)=self.ptsl[i].shape
#	pts=[tuple(self.ptslix[self.ptsl[i][a][b]]) for a in range(la) for b in range(lb)]

	pts=[]
	for a in range(la):
		for b in range(lb):
			t=tuple(self.ptslix[self.ptsl[i][a][b]])
			if np.isnan(t[0]) or np.isnan(t[1]) or np.isnan(t[2]):
				
				pass

			elif 	abs(t[0])<10 and  abs(t[1])<20:

				pass
			else:
				pts.append(t)

	pcl=Points.Points(pts)
	Points.show(pcl)

	App.activeDocument().recompute()
	if i%25==0: Gui.SendMsgToActiveView("ViewFit")

	obj=App.ActiveDocument.ActiveObject
	obj.ViewObject.ShapeColor=(random.random(),random.random(),random.random())


	if len(objs.OutList)==0:
		obj.Placement=self.obj2.startPosition
	else:
		#movePosition=FreeCAD.Placement()
		#movePosition.Rotation=FreeCAD.Rotation(FreeCAD.Vector(0,0,1),10)
		movePosition=self.obj2.deltaPosition
		obj.Placement=objs.OutList[-1].Placement.multiply(movePosition)


	objs.addObject(obj)
	te=time.time()
	say(("createStepFC ",i,"timee",round(te-ts,3)))

	return obj
Beispiel #35
0
def run():

    #default parameters
    p = {
        "count": [1000, 'Integer'],
        "radius": [400, 'Float'],
        "wave": [100, 'Float'],
        "debug": [False, 'Boolean'],
    }

    # parameter -----------------
    t = FreeCAD.ParamGet('User parameter:Plugins/nurbs/' + 'genrandomdat')
    l = t.GetContents()
    if l == None: l = []
    for k in l:
        p[k[1]] = k[2]
    for k in p:
        if p[k].__class__.__name__ == 'list':
            typ = p[k][1]
            if typ == 'Integer': t.SetInt(k, p[k][0])
            if typ == 'Boolean': t.SetBool(k, p[k][0])
            if typ == 'String': t.SetString(k, p[k][0])
            if typ == 'Float': t.SetFloat(k, p[k][0])
            p[k] = p[k][0]
    #--------------------

    count = p["count"]
    ri = p["wave"]
    rm = p["radius"]

    kaps = np.random.random(count) * 2 * np.pi
    mmaa = np.random.random(count) * ri * np.cos(kaps * 5) * np.cos(
        kaps * 1.3) + rm

    y = np.cos(kaps) * mmaa
    x = np.sin(kaps) * mmaa
    z = np.zeros(count)

    pps = np.array([x, y, z]).swapaxes(0, 1)
    goods = [FreeCAD.Vector(tuple(p)) for p in pps]

    Points.show(Points.Points(goods))
    App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (1.0, 0.0, 0.0)
    App.ActiveDocument.ActiveObject.ViewObject.PointSize = 10
Beispiel #36
0
def run():
	import Points
	try: pcl=FreeCADGui.Selection.getSelection()[0]
	except:
		self=None
		Gui.ActiveDocument=None
		App.newDocument("Unnamed")
		App.setActiveDocument("Unnamed")
		App.ActiveDocument=App.getDocument("Unnamed")
		Gui.ActiveDocument=Gui.getDocument("Unnamed")
		fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file with points','/home/thomas/freecad_buch/b234_heini_grid/')
		print(fname)
		Points.insert(fname,"Unnamed")
		t=App.ActiveDocument.ActiveObject.Label
		print(t)
		Gui.SendMsgToActiveView("ViewFit")
		pcl=App.ActiveDocument.ActiveObject

	dialog(pcl)
def run():
	import Points
	try: pcl=FreeCADGui.Selection.getSelection()[0]
	except Exception:
		self=None
		Gui.ActiveDocument=None
		App.newDocument("Unnamed")
		App.setActiveDocument("Unnamed")
		App.ActiveDocument=App.getDocument("Unnamed")
		Gui.ActiveDocument=Gui.getDocument("Unnamed")
		fn='/home/thomas/.FreeCAD/Mod/geodat/testdata/roo.asc'
		
		fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file with points',fn)
		say("Filename "+fname)
		Points.insert(fname,"Unnamed")
		Gui.SendMsgToActiveView("ViewFit")
		pcl=App.ActiveDocument.ActiveObject

	dialog(pcl)
def run():
	import Points
	try: pcl=FreeCADGui.Selection.getSelection()[0]
	except:
		self=None
		Gui.ActiveDocument=None
		App.newDocument("Unnamed")
		App.setActiveDocument("Unnamed")
		App.ActiveDocument=App.getDocument("Unnamed")
		Gui.ActiveDocument=Gui.getDocument("Unnamed")
		fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file with points','/home/thomas/freecad_buch/b234_heini_grid/')
		print fname
		Points.insert(fname,"Unnamed")
		t=App.ActiveDocument.ActiveObject.Label
		print t
		Gui.SendMsgToActiveView("ViewFit")
		pcl=App.ActiveDocument.ActiveObject

	dialog(pcl)
Beispiel #39
0
def modtest():
	'''update the points and the mesh example'''
	
	mm=App.ActiveDocument.getObject(pc.Name+'_M')
	pc=App.ActiveDocument.getObject(pc.Name)
	ptsk=mm.Mesh.Topology[0]
	faces=mm.Mesh.Topology[1]
	ptsk[128].z +=30
	pc.Points=Points.Points(ptsk)

	mm.Mesh=Mesh.Mesh((ptsk,faces))
Beispiel #40
0
 def __readarray(self, coordarray, indepvararray=None):
     #init from array
     if not Points.numpyimported:
         Points.importnumpy()
     N = Points.N
     if not hasattr(coordarray[0], '__len__'):
         # point
         indepvararray = [0.0]
         ncol = 0
         ntst = 1
         coordarray = [[d] for d in coordarray]
         pararray = []
     else:
         # time + solution
         if indepvararray is None:
             indepvararray = coordarray[0]
             coordarray = coordarray[1:]
         ncol = 1
         ntst = len(indepvararray) - 1
         t0 = indepvararray[0]
         period = indepvararray[-1] - t0
         if period != 1.0 or t0 != 0.0:
             #scale to [0,1]
             for i in range(len(indepvararray)):
                 indepvararray[i] = (indepvararray[i] - t0) / period
         # set PAR(11) to period
         pararray = 10 * [0.0] + [period]
     indepvarname = "t"
     ndim = len(coordarray)
     coordnames = ["U(%d)" % (i + 1) for i in range(ndim)]
     Points.Pointset.__init__(
         self, {
             "indepvararray": indepvararray,
             "indepvarname": indepvarname,
             "coordarray": coordarray,
             "coordnames": coordnames
         })
     self.__fullyParsed = True
     self.data.update({"NTST": ntst, "NCOL": ncol, "LAB": 1, "NDIM": ndim})
     self.__numChangingParameters = 1
     self.PAR = pararray
Beispiel #41
0
def transform():
	sels=Gui.Selection.getSelection()
	if len(sels)<>1: print("Du musst Pointset auswaehlen" )
	pts=np.array(sels[0].Points.Points)

	matrix=[float(f) for f in  '2 0  0 500 0 1 0 -500 0 0 0.5 130'.split()]
	matrix=np.array(matrix).reshape(3,4)
	print matrix


	[x,y,z]=np.array(pts).swapaxes(0,1)
	w=[1]*len(x)

	pts2=np.array([x,y,z,w])
	pts3=pts2.swapaxes(0,1)
	

	t=Points.Points([tuple(matrix.dot(p)) for p in pts3])
	Points.show(t)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	App.ActiveDocument.ActiveObject.Label="Transformed "  +sels[0].Label +" "
Beispiel #42
0
def center():

	sels=Gui.Selection.getSelection()
	if len(sels)<>1: print("Du musst Pointset auswaehlen" )
	pts=np.array(sels[0].Points.Points)


	x,y,z=pts.swapaxes(0,1)
	xm=x.mean()
	ym=y.mean()
	zm=z.mean()

	x -= xm
	y -= ym
	z -= zm

	pts3v=[FreeCAD.Vector(p) for p in np.array([x,y,z]).swapaxes(0,1)]
	pcl=Points.Points(pts3v)
	Points.show(pcl)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	App.ActiveDocument.ActiveObject.Label="Centered " + sels[0].Label +" "
Beispiel #43
0
def boundbox(inside=True) :
	sels=Gui.Selection.getSelection()
	if len(sels)<>2: print("Du musst 1. Volumen und 2. Points auswaehlen" )
	print sels[0]
	print sels[1]
	print sels[1].Points.Points
	print sels[0].Shape.BoundBox
	bb=sels[0].Shape.BoundBox
	pts=sels[1].Points.Points

	if inside:
		pts=[p for p in pts if bb.XMin<= p.x and p.x <=bb.XMax and bb.YMin<= p.y and p.y <=bb.YMax and bb.ZMin<= p.z and p.z <=bb.ZMax]
		rel=" inside "
	else:
		pts=[p for p in pts if not(bb.XMin<= p.x and p.x <=bb.XMax and bb.YMin<= p.y and p.y <=bb.YMax and bb.ZMin<= p.z and p.z <=bb.ZMax)]
		rel=" outside "

	t=Points.Points(pts)
	Points.show(t)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	
	App.ActiveDocument.ActiveObject.Label=sels[1].Label  + rel + sels[0].Label + " "
Beispiel #44
0
    def calculate_points_in_hand(self):

        if self.has_crib(self.get_turn()):
            current_player = self.get_turn()
            other_player = self.get_not_turn()
        else:
            other_player = self.get_turn()
            current_player = self.get_not_turn()
        crib = self.crib

        print "Calculating points for %s..." % other_player.name
        points = Points.Points(other_player.hand.cards, self.top_card)
        points.run_points()
        other_player.add_points(points.points)
        print "Calculating points for %s..." % current_player.name
        points = Points.Points(current_player.hand.cards, self.top_card)
        points.run_points()
        current_player.add_points(points.points)
        print "Calculating points for crib of %s..." % current_player.name
        points = Points.Points(crib.cards, self.top_card)
        points.run_points()
        current_player.add_points(points.points)
Beispiel #45
0
def run(pts, loop, d, dd, outliner=True):

    pts2 = np.array(pts)

    start = 0
    pts3 = []
    anzp = pts2.shape[0]

    for xp in range(120):  # gesamtpunktzahl
        yv = 0
        wv = 0
        for i in range(anzp):
            x, y, z = pts2[i]
            if x < xp - d:
                start = i
                continue
            if x > xp + d:
                end = i
                break
            fak = 1 - abs(xp - x) / d
            wv += fak
            yv += fak * y
        if wv <> 0:
            yn = yv / wv
        else:
            continue

        if outliner:
            yv = 0
            wv = 0
            for i in range(start, end + 1):
                x, y, z = pts2[i]

                if abs(y - yn) > dd:
                    print("outliner", loop, xp, i, y - yn)
                else:
                    fak = 1 - abs(xp - x) / d
                    wv += fak
                    yv += fak * y
        if wv <> 0:
            yn = yv / wv
            pts3 += [FreeCAD.Vector(xp, yn, 0)]

    Points.show(Points.Points(pts3))
    App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (
        0.5 + 0.5 * random.random(), 0.5 + 0.5 * random.random(),
        0.5 + 0.5 * random.random())

    pts4 = filter(lambda x: x[0] <= 100, pts3)
    ptsp = [
        FreeCAD.Vector(p.y * np.cos(p.x * np.pi * 0.02),
                       p.y * np.sin(p.x * np.pi * 0.02), 0) for p in pts4
    ]
    Points.show(Points.Points(ptsp))
    App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (
        0.5 + 0.5 * random.random(), 0.5 + 0.5 * random.random(),
        0.5 + 0.5 * random.random())

    return pts3, ptsp
Beispiel #46
0
def run(mx,my,dx,dy):

	ys=my-dy
	yn=my+dy
	xw=mx-dx
	xe=mx+dx
	
	dats=[]
	
	print (xw,ys,xe,yn)
	for ix in range(int(math.floor(xw)),int(math.floor(xe))+1):
		for iy in range(int(math.floor(ys)),int(math.floor(yn))+1):
			dat="Lat"+str(iy)+"Lon"+str(ix)+"Lat"+str(iy+1)+"Lon"+str(ix+1)
			print dat
			dats.append(dat)

	directory=FreeCAD.ConfigGet("UserAppData") + "/geodat_SRTM/"



	if not os.path.isdir(directory):
		print "create " + directory
		os.makedirs(directory)

	for dat in dats:
		getdata(directory,dat)
		fn=directory+"/"+dat+".osm"
		pts=runfile(fn,xw,xe,ys,yn,mx,my)

		p=Points.Points(pts)
		Points.show(p)
		Gui.updateGui()
		Gui.SendMsgToActiveView("ViewFit")


	Gui.SendMsgToActiveView("ViewFit")
filename_X = u"../out/channel_state.txt"
t_X, X = np.loadtxt(filename_X, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)

filename_dh = u"../out/CP_obs_0.txt"
t_dh, dh = np.loadtxt(filename_dh, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)
filename_dl = u"../out/CP_obs_1.txt"
t_dl, dl = np.loadtxt(filename_dl, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)

filename_co = u"../out/cont_obs.txt"
t_co, co = np.loadtxt(filename_co, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)


f = plt.figure(num=None, figsize=(20, 6), dpi=150, facecolor='w', edgecolor='k')

Xpoints = Points(t_X, X)
Xpoints.multiply()

filename = u"../out/filter_Dummy.txt"
# 0 t
# 1-4 pi (p0)
# 5 X
# 6-9 R
# 10-13 G
# 14-17 C0
# 18-21 C1
# 22 C0[X] - SimultJumpsRatesSum
# 23 C1[X] - SimultJumpsRatesSum
# 24-26 I0 SimultJumpsRates 0->3, 1->3, 1->2
# 27-29 I1 SimultJumpsRates 0->3, 1->3, 1->2
data = pd.read_csv(filename, delimiter = " ", header=None, usecols=(0, 6, 7, 8, 9, 10, 11, 12, 13), dtype=float, names = ["t", "R0", "R1", "R2", "R3", "G0", "G1", "G2", "G3"])
Beispiel #48
0
def scale():
	sels=Gui.Selection.getSelection()
	pts=sels[0].Points.Points
	pts2=[p*100 for p in pts]
	pcl=Points.Points(pts2)
	Points.show(pcl)
Beispiel #49
0
# pointexample.py
# Bill Kronholm
# 2015
#
# Basic usage of the Points.py class, methods, and functions.
#

import Points

P = Points.Point()
Q = Points.Point(2, 3)

print "P has coordinates (%g, %g)" %(P.x, P.y)
print "Q has coordinates (%g, %g)" %(Q.x, Q.y)

R = Points.Point(-4, 2)

d = Points.distance(Q,R)
print "Q and R are distance %g apart" % d

print "R has magnitude %g" % R.magnitude()

S = Points.add(Q,R)
print "Q+R = S = (%g, %g)" % (S.x, S.y)

print Points.subtract(Q, S)

filename = u"../out/" + subfolder + "control.txt"
t, u, ss, thresh, m, rtt = np.loadtxt(filename, delimiter = ' ', usecols=(0,1,2,3,4,5), unpack=True, dtype=float)

filename_X = u"../out/" + subfolder + "channel_state.txt"
t_X, X = np.loadtxt(filename_X, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)

filename_dh = u"../out/" + subfolder + "CP_obs_0.txt"
t_dh, dh = np.loadtxt(filename_dh, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)
filename_dl = u"../out/" + subfolder + "CP_obs_1.txt"
t_dl, dl = np.loadtxt(filename_dl, delimiter = ' ', usecols=(0,1), unpack=True, dtype=float)

f = plt.figure(num=None, figsize=(10, 6), dpi=150, facecolor='w', edgecolor='k')

Xpoints = Points(t_X, X)
Xpoints.multiply()


n = len(Xpoints.x)
o = np.zeros(n)
ones = np.ones(n)
levelzero = np.ones(n)*0.0
levelone = np.ones(n)*u.max()


dhpoints = Points(t_dh, dh)
dhpoints.toones()

dlpoints = Points(t_dl, dl)
dlpoints.toones()
def createElevationGrid(mode,rbfmode=True,source=None,gridCount=20,zfactor=20,bound=10**5,matplot=False):
	
	modeColor={
	'linear' : ( 1.0, 0.3, 0.0),
	'thin_plate' : (0.0, 1.0, 0.0),
	'cubic' : (0.0, 1.0, 1.0),
	'inverse' : (1.0, 1.0, 0.0),
	'multiquadric' : (1.0, .0, 1.0),
	'gaussian' : (1.0, 1.0, 1.0),
	'quintic' :(0.5,1.0, 0.0)
	}

	print ("Source",source,"mode",mode)
	if source<>None:

		if hasattr(source,"Shape"):
			# part object
			pts=[v.Point for v in  source.Shape.Vertexes]

			p=Points.Points(pts)
			Points.show(p)
			pob=App.ActiveDocument.ActiveObject
			pob.ViewObject.PointSize = 10.00
			pob.ViewObject.ShapeColor=(1.0,0.0,0.0)

		elif hasattr(source,"Points"):
			# point cloud

			pts=source.Points.Points

		elif source.__class__.__name__ == 'DocumentObjectGroup':
			hls=App.ActiveDocument.hoehenlinien
			apts=[]
			for l in hls.OutList:
				pts=[v.Point for v in  l.Shape.Vertexes]
				apts += pts

			pts=apts

		else:
			raise Exception("don't know to get points")

		x=[v[1] for v in pts]
		y=[v[0] for v in pts]
		z=[0.01*v[2] for v in pts]
		# staerker
		z=[zfactor*v[2] for v in pts]
		px= coordLists2points(x,y,z)
		Points.show(Points.Points(px))


	else:
		# testdata
		x,y,z= text2coordList(datatext)
		p= coordLists2points(x,y,z)

	x=np.array(x)
	y=np.array(y)
	z=np.array(z)

	gridsize=gridCount

	rbf,xi,yi,zi1 = interpolate(x,y,z, gridsize,mode,rbfmode)
	
	# hilfsebene
	xe=[100,-100,100,-100]
	ye=[100,100,-100,-100]
	ze=[20,10,20,5]

	rbf2,xi2,yi2,zi2 = interpolate(xe,ye,ze, gridsize,mode,rbfmode,zi1.shape)
	
	#print zi1.shape
	#print zi2.shape
	
	#zi=zi1-zi2
	zi=zi1

	try: color=modeColor[mode]
	except: color=(1.0,0.0,0.0)

	xmin=np.min(x)
	ymin=np.min(y)

	showFace(rbf,rbf2,x,y,gridsize,color,bound)
 
	App.ActiveDocument.ActiveObject.Label=mode + " ZFaktor " + str(zfactor) + " #"
	rc=App.ActiveDocument.ActiveObject


	if matplot: showHeightMap(x,y,z,zi)
	return rc

	# interpolation for image
	gridsize=400
	rbf,xi,yi,zi = interpolate(x,y,z, gridsize,mode,rbfmode)
	rbf2,xi2,yi2,zi2 = interpolate(xe,ye,ze, gridsize,mode,rbfmode,zi.shape)
	return [rbf,rbf2,x,y,z,zi,zi2]
Beispiel #52
0
# contains commands which do not depend on any variables in the WordAssociationChatbot class
import random
import sys
from datetime import datetime
import Points

Points.init()

def command_alive(args, msg, event):
    return "Yes, I'm alive."


def command_random(args, msg, event):
    return str(random.random())


def command_randomint(args, msg, event):
    if len(args) == 0:
        return str(random.randint(0, sys.maxint))
    if len(args) == 1:
        try:
            max_ = int(args[0])
        except ValueError:
            return "Invalid arguments."
        min_ = 0
        if min_ > max_:
            return "Min cannot be greater than max."
        return str(random.randint(min_, max_))
    if len(args) == 2:
        try:
            min_ = int(args[0])
Beispiel #53
0
			obj.Points=pts
			rc=App.activeDocument().recompute()
			_t=lls.append((B[0],B[1],0.1*obj.Shape.Edge1.Length))
			bsp2.append(FreeCAD.Vector(B[0],B[1],0.1*obj.Shape.Edge1.Length))
		except:
			print ("!",ix,iy)
			_t=lls.append((B[0],B[1],0))
	bsp3.append(bsp2)

obj.Points=ptsobj
rc=App.activeDocument().recompute()


if 0:
	import Points
	Points.show(Points.Points([FreeCAD.Vector(l) for l in lls]))


bs=Part.BSplineSurface()
bs.interpolate(bsp3)
bss=bs.toShape()

if 0:
	prof=FreeCAD.getDocument("Unnamed").addObject("Part::Feature","Length Profile")
	prof.Shape=bss



lls2=np.array(lls).swapaxes(0,1)
(y,x,z)=lls2
Beispiel #54
0
def run3(countbubbles=5000,radius=20,sizebox=1024,slize=None):
	cc=countbubbles

	if slize==None:
		circles=[[random.random(),random.random(),random.random(),random.random()] for i in range(cc)]
	else:
		circles=[[random.random(),random.random(),random.random(),1] for i in range(cc)]

#	for c in circles:
#		s=App.ActiveDocument.addObject("Part::Sphere","Sphere")
#		s.Radius=c[3]*radius
#		s.Placement.Base=FreeCAD.Vector(tuple(np.array(c[0:3])*sizebox))

	pts=[]
	ptsa=[]
	ct=0
	if slize<>None: slices=[slize]
	else: slices=range(sizebox)
	

	for z in slices:
	#for z in range(101):
		FreeCAD.Console.PrintMessage("--" +str(z) +"---\n")
		s=time.time()
		# Create a black image
		img = np.zeros((sizebox,sizebox), np.uint8)

		for i in range(cc):
			x=int(round(circles[i][0]*sizebox))
			y=int(round(circles[i][1]*sizebox))
			r2= int(round(circles[i][3]*radius))**2 - (int(round(circles[i][2]*sizebox))-z)**2
			if r2>0:
				r=int(round(np.sqrt(r2))) 
				cv2.circle(img,(x,y),r, 255, -1)

		# volumen points
		nzs=np.nonzero(img)
		nzs=np.array(nzs).swapaxes(0,1)

		ptsa += [FreeCAD.Vector(x,y,z)  for [x,y] in nzs]

		for [x,y] in nzs:
				img[x,y]=255 

		kernel = np.ones((5,5),np.uint8)
#		dilation = cv2.dilate(img,kernel,iterations = 1)
		erosion = cv2.erode(img,kernel,iterations = 1)
#		img=dilation
		img=erosion

		# border points
		edges = cv2.Canny(img,1,255)
#		edges2 = cv2.Laplacian(img,cv2.CV_64F)
#		edges += edges2


		nzs=np.nonzero(edges)
		nzs=np.array(nzs).swapaxes(0,1)


		pts += [FreeCAD.Vector(x,y,z)  for [x,y] in nzs]

		FreeCAD.Console.PrintMessage(str(round(time.time()-s,3)) + "\n")
		Gui.updateGui()

		if z % 10 == 0:
			Points.show(Points.Points(pts))
			App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
			App.ActiveDocument.ActiveObject.ViewObject.PointSize=5
			ct +=len(pts)
			FreeCAD.Console.PrintMessage("points added " + str(len(pts)) +"!! \n")
			pts=[]
			Gui.updateGui()
	if len(pts)>0:
		Points.show(Points.Points(pts))
		App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(random.random(),random.random(),random.random())

	Points.show(Points.Points(ptsa))
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(.0,.0,.0)
	App.ActiveDocument.ActiveObject.ViewObject.PointSize=1
	App.ActiveDocument.ActiveObject.ViewObject.hide()
	App.ActiveDocument.ActiveObject.Label="Volumen"
	return edges
Beispiel #55
0
def getAST(b=50.26, l=11.39):

    bs = np.floor(b)
    ls = np.floor(l)

    # the ast dataset
    ff = "N%02dE%03d" % (int(bs), int(ls))
    fn = FreeCAD.ConfigGet("UserAppData") + "/geodat/AST/ASTGTM2_" + ff + "_dem.tif"
    # print fn

    """
	fn='/home/microelly2/FCB/b217_heightmaps/tandemx_daten/Chile-Chuquicatmata.tif'
	b=-22.3054705
	l=-68.9259643
	bs=np.floor(b)
	ls=np.floor(l)
	print fn
	"""

    dataset = gdal.Open(fn, GA_ReadOnly)
    if dataset == None:
        msg = "\nProblem cannot open " + fn + "\n"
        FreeCAD.Console.PrintError(msg)
        errorDialog(msg)
        return

    cols = dataset.RasterXSize
    rows = dataset.RasterYSize

    geotransform = dataset.GetGeoTransform()
    originX = geotransform[0]
    originY = geotransform[3]
    pixelWidth = geotransform[1]
    pixelHeight = geotransform[5]

    band = dataset.GetRasterBand(1)
    data = band.ReadAsArray(0, 0, cols, rows)

    # data.shape -> 3601 x 3601 secs
    # erfurt 51,11
    # data[0,0]
    # zeitz  51,12
    # data[3600,0]
    # windischletten(zapfendorf) 50,11
    # data[0,3600]
    # troestau fichtelgebirge 50,12
    # data[3600,3600]

    px = int(round((bs + 1 - b) * 3600))
    py = int(round((l - ls) * 3600))

    pts = []
    d = 50

    tm = TransverseMercator()
    tm.lat = b
    tm.lon = l
    center = tm.fromGeographic(tm.lat, tm.lon)

    z0 = data[px, py]  # relative height to origin px,py

    for x in range(px - d, px + d):
        for y in range(py - d, py + d):
            ll = tm.fromGeographic(bs + 1 - 1.0 / 3600 * x, ls + 1.0 / 3600 * y)
            pt = FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 1000.0 * (data[x, y] - z0))
            pts.append(pt)

            # display the point cloud
    p = Points.Points(pts)
    Points.show(p)

    return pts
from Points import * 


subfolder = 'STATEBASED/'
interval = [0,200]

filename = u"../out/" + subfolder + "filter_DiscreteContinuousGaussian.txt"
data = pd.read_csv(filename, delimiter = " ", header=None, dtype=float, names = ["t", "p0", "p1", "p2", "p3", "dz", "R0", "R1", "R2", "R3", "G0", "G1", "G2", "G3"])
data = data.fillna(method='bfill')
#print(data[((data.t < 1.1) * (data.t > 0.9))])

filename = u"../out/" + subfolder + "channel_state.txt"
dataX = pd.read_csv(filename, delimiter = " ", header=None, usecols=(0,1), dtype=float, names = ["t", "X"])
X = dataX.as_matrix()

Xpoints = Points(X[:,0], X[:,1])
Xpoints.multiply()

n = len(Xpoints.x)
o = np.zeros(n)
ones = np.ones(n)


f = plt.figure(num=None, figsize=(10, 10), dpi=150, facecolor='w', edgecolor='k')
plt.subplots_adjust(left=0.06, bottom=0.07, right=0.95, top=0.95, wspace=0.1)
gs = gridspec.GridSpec(4, 1, height_ratios=[10, 10, 10, 10])     

ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
ax2 = plt.subplot(gs[2])
ax3 = plt.subplot(gs[3])
Beispiel #57
0
def createNurbsblock(filename=None,n=10,c=2,inverse=False,kx=10,ky=10,kz=60,gengrid=True,genblock=False,genpoles=False):

	if filename==None:
		filename='/home/microelly2/Schreibtisch/test_nurbs3.png'
	img = mpimg.imread(filename)

	ojn=os.path.basename(filename)

	# grey scaled image and color channel select
	if len(img.shape) == 2:
		lum_img = img
	else:
		lum_img = img[:,:,c]
		lum_img = 0.33*img[:,:,0]+0.33*img[:,:,1]+0.34*img[:,:,2]

	(lu,lv)=lum_img.shape

	##plt.imshow(lum_img)
	##plt.show()

	#create a n points border
	uu2=np.zeros((lu+2*n)*(lv+2*n))
	uu2=uu2.reshape(lu+2*n,lv+2*n)
	uu2[n:lu+n,n:lv+n]=lum_img
	lum_img=uu2

	(lu,lv)=lum_img.shape

	bz=kz+100
	if inverse: kz= -kz

	pts=[]
	uu=[]
	for u in range(lu):
		ul=[]
		for v in range(lv):
			# p=FreeCAD.Vector(ky*v,-kx*u,bz-kz*lum_img[u,v])
			r=0.001
			p=FreeCAD.Vector(ky*v+r*random.random(),-kx*u+r*random.random(),bz-kz*lum_img[u,v] +r*random.random())
			ul.append(p)
			pts.append(p)
		uu.append(ul)

	# show the points
	p=Points.Points(pts)
	Points.show(p)
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(1.0,.0,1.0)
	App.ActiveDocument.ActiveObject.Label="Points " + str(lv) +" " + str(lu) + " _"
	say ((("u, v, points"),u,v,len(pts)))
	Gui.updateGui()

	tt=Part.BSplineSurface()
	tt.interpolate(uu)

	#  flatten the border
	pols=tt.getPoles()
	pols2=np.array(pols)
	lup,lvp,la=pols2.shape
	zz=bz
	bord=n-2
	for u in range(lup):
		for v in range(bord):
			op=pols[u][v]
			nup=FreeCAD.Vector(op.x,op.y,zz)
			pols[u][v]=nup
			op=pols[u][-1-v]
			nup=FreeCAD.Vector(op.x,op.y,zz)
			pols[u][-1-v]=nup

	for u in range(bord):
		for v in range(lvp):
			op=pols[u][v]
			nup=FreeCAD.Vector(op.x,op.y,zz)
			pols[u][v]=nup
			op=pols[-1-u][v]
			nup=FreeCAD.Vector(op.x,op.y,zz)
			pols[-1-u][v]=nup

	bs=Part.BSplineSurface()
	knot_v2=tt.getVKnots()
	knot_u2=tt.getUKnots()
	mult_u=tt.getUMultiplicities()
	mult_v=tt.getVMultiplicities()
	ws=tt.getWeights()

	bs.buildFromPolesMultsKnots(pols,
			mult_u,
			mult_v,
			knot_u2,
			knot_v2,
			False,False,3,3,
			ws
		)

	sha=bs.toShape()

	# show the poles
	if genpoles:
		pols=bs.getPoles()
		ps=[]
		for l in pols:
			for po in l:
				ps.append(po)

		p=Points.Points(ps)
		Points.show(p)
		App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(1.0,1.0,.0)
		App.ActiveDocument.ActiveObject.Label='Poles '  + str(lv) +" " + str(lu) +" _"
		Gui.updateGui()


	# the nurbs grid
	if gengrid:
		jj=[]

		rr=lv
		for i in range(rr+1):
			v=bs.vIso((0.0+i)/rr).toShape()
			jj.append(v.Edge1)

		rr=lu
		for i in range(rr+1):
			v=bs.uIso((0.0+i)/rr).toShape()
			jj.append(v.Edge1)

		com=Part.makeCompound(jj)
		ttt=App.ActiveDocument.addObject('Part::Feature','Nurbsgrid ' + str(n) + ' ' + ojn)
		ttt.ViewObject.DisplayMode = "Wireframe"
#		ttt.ViewObject.hide()
		ttt.Shape=com
		ttt.Placement.Base.z=10
		Gui.updateGui()


	#create the solid
	a=FreeCAD.Vector(0,0,-bz)
	b=FreeCAD.Vector(0,-kx*(lu-1),-bz)
	c=FreeCAD.Vector(ky*(lv-1),-kx*(lu-1),-bz)
	d=FreeCAD.Vector(ky*(lv-1),0,-bz)

	ad=FreeCAD.Vector(0,0,bz)
	bd=FreeCAD.Vector(0,-kx*(lu-1),bz)
	cd=FreeCAD.Vector(ky*(lv-1),-kx*(lu-1),bz)
	dd=FreeCAD.Vector(ky*(lv-1),0,bz)


	# for nonlinear borders - experimental
	if 0:
		u0e=bs.uIso(0).toShape()
		p=Part.makePolygon([ad,a,d,dd],True)
		ll=p.Edges+[u0e.Edge1]
		f4=Part.makeFilledFace(Part.__sortEdges__(ll))
		Part.show(f4)

		v0e=bs.vIso(0).toShape()
		p=Part.makePolygon([bd,b,a,ad],True)
		ll=p.Edges+[v0e.Edge1]
		f1=Part.makeFilledFace(Part.__sortEdges__(ll))
		#Part.show(v0e)
		#Part.show(p)
		Part.show(f1)

		u1e=bs.uIso(1).toShape()
		p=Part.makePolygon([bd,b,c,cd],True)
		ll=p.Edges+[u1e.Edge1]
		f2=Part.makeFilledFace(Part.__sortEdges__(ll))
		# f2=Part.Face(Part.__sortEdges__(ll))
		#Part.show(u1e)
		#Part.show(p)
		Part.show(f2)

		v1e=bs.vIso(1).toShape()
		p=Part.makePolygon([dd,d,c,cd],True)
		ll=p.Edges+[v1e.Edge1]
		f3=Part.makeFilledFace(Part.__sortEdges__(ll))
		#Part.show(v1e)
		#Part.show(p)
		Part.show(f3)

		p=Part.makePolygon([a,b,c,d], True)
		f0=Part.makeFilledFace(p.Edges)
		Part.show(f0)

	if 1:
		Part.show(sha.Face1)
		App.ActiveDocument.ActiveObject.Label="Nurbs"

	if genblock:

		fln=sha.Face1

		f0=Part.Face(Part.makePolygon([a,b,c,d], True))
		f1=Part.Face(Part.makePolygon([ad,bd,b,a], True)) 
		f2=Part.Face(Part.makePolygon([b,bd,cd,c], True))
		f3=Part.Face(Part.makePolygon([cd,dd,d,c], True)) 
		f4=Part.Face(Part.makePolygon([ad,a,d,dd], True))

		fls=[f0,f1,f2,f3,f4,fln]
		sh=Part.Shell(fls)
		sol=Part.Solid(sh)

		ttt=App.ActiveDocument.addObject('Part::Feature','Nurbsblock ' + str(n) +   ' ' + ojn)
		ttt.Shape=sol
#		ttt.ViewObject.hide()

	print (lu,lv)
	return bs
Beispiel #58
0
def toppoints(mode=5):

	sels=Gui.Selection.getSelection()
	if len(sels)<>1: print("Du musst Pointset auswaehlen" )
	pts=np.array(sels[0].Points.Points)
#	pts=pts[:500]
	print ("pts shape",pts.shape, "mode",mode)
	#if len(pts)>6000:
	if len(pts)>17000:
		print "to much data, abort!"
		return

	x,y,z=pts.swapaxes(0,1)

	if mode in [0,1]:
		zu=np.unique(z)
		yu=np.unique(y)
		pts4=[]

		for iz in zu:
			for iy in yu:
				l=[p[0] for p in pts if p[2]==iz and p[1]==iy]
				if l<>[]:
					if mode==1: 
						pts4.append(FreeCAD.Vector(min(l),iy,iz))
						lab="X min"
					if mode==0: 
						pts4.append(FreeCAD.Vector(max(l),iy,iz))
						lab="X max"

	if mode in [2,3]:
		xu=np.unique(x)
		zu=np.unique(z)
		pts4=[]

		for ix in xu:
			for iz in zu:
				l=[p[1] for p in pts if p[0]==ix and p[2]==iz]
				if l<>[]:
					if mode==3: 
						pts4.append(FreeCAD.Vector(ix,min(l),iz))
						lab="Y min"
					if mode==2: 
						pts4.append(FreeCAD.Vector(ix,max(l),iz))
						lab="Y max"

	if mode in [4,5]:
		xu=np.unique(x)
		yu=np.unique(y)
		pts4=[]

		print xu
		print yu
		print len(xu)
		print len(yu)
		for ix in xu:
			for iy in yu:
				l=[p[2] for p in pts if p[0]==ix and p[1]==iy]
				if l<>[]:
					# print (ix,iy,min(l))
					if mode==5: 
						pts4.append(FreeCAD.Vector(ix,iy,min(l)))
						lab="Z min"
					if mode==4: 
						pts4.append(FreeCAD.Vector(ix,iy,max(l)))
						lab="Z max"



	print ("reduced points",len(pts4))

	pcl=Points.Points(pts4)
	Points.show(pcl)

	colormap=[ 
		(1.,0.,0.),(0.,1.,1.),
		(0.,1.,0.),(1.,0.,1.),
		(0.,0.,1.),(1.,1.,0.),
	]
	
	App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(colormap[mode])
	App.ActiveDocument.ActiveObject.ViewObject.PointSize=4
	App.ActiveDocument.ActiveObject.Label=lab+" "  +sels[0].Label +" "
Beispiel #59
0
def import_xyz(mode,filename="/tmp/test.xyz",label='',ku=20, kv=10,lu=0,lv=0):

	print "Import mode=",mode
	if mode:
		
		if lu>0 and lv>0:
			sayErr("read Points001")

		try:
			App.ActiveDocument.nurbs
		except:
			nurbs=App.ActiveDocument.addObject("App::DocumentObjectGroup","nurbs")
		try:
			App.ActiveDocument.grids
		except:
			grids=App.ActiveDocument.addObject("App::DocumentObjectGroup","grids")
		try:
			App.ActiveDocument.points
		except:
			points=nurbs=App.ActiveDocument.addObject("App::DocumentObjectGroup","points")

		objs=App.ActiveDocument.getObjectsByLabel(label)
		say(objs)
		#pts=App.ActiveDocument.Points001.Points.Points
		pts=objs[0].Points.Points
		say(("len pts, lu, lv, lu*lv",len(pts),lu,lv,lu*lv))
		assert(len(pts)==lu*lv)
		return pts



	say("iport")
	try:
		App.ActiveDocument.Points
		say("use Points")
		return App.ActiveDocument.Points.Points.Points
	except:
		try:
			App.ActiveDocument.nurbs
		except:
			nurbs=App.ActiveDocument.addObject("App::DocumentObjectGroup","nurbs")
		try:
			App.ActiveDocument.grids
		except:
			grids=App.ActiveDocument.addObject("App::DocumentObjectGroup","grids")
		try:
			App.ActiveDocument.points
		except:
			points=nurbs=App.ActiveDocument.addObject("App::DocumentObjectGroup","points")

#		filename='/home/microelly2/FCB/b202_gmx_tracks/dgm1/dgm1_32356_5638_2_nw.xyz'
		f=open(filename)
		lines=f.readlines()
		print len(lines)

		'''
		# utm coords 32356000.00 5638000.00

		# height scale factor
		hfac=3
		'''
		
		'''
		if lu>0 and lv>0:
			sayErr("read Points001")
			
			
			pts=App.ActiveDocument.Points001.Points.Points
			say(len(pts))
			assert(len(pts)==lu*lv)
			
			
			pts2=[]
			for i in range(lu):
				for j in range(lv):
					pts2.append(pts[i+j*lu])

			assert(len(pts)==len(pts2))
			# pts=pts2

		'''
		
		
		
		pts=[]
		sayW(len(lines))
		for l in lines:
			p=l.split()
			hfac=3
			pts.append(FreeCAD.Vector(float(p[0])-32356000.00,float(p[1])-5638000.00,hfac*float(p[2])))
		

		if ku>1 and kv>1:
			pts=reduceGrid(pts,ku,kv)

		p=Points.Points(pts)
		Points.show(p)
		App.ActiveDocument.ActiveObject.ViewObject.ShapeColor=(1.0,1.0,0.0)
		App.ActiveDocument.ActiveObject.ViewObject.PointSize=1.0
		Gui.updateGui()
		Gui.SendMsgToActiveView("ViewFit")
		App.ActiveDocument.ActiveObject.ViewObject.hide()
	print(len(pts))
	return pts
Beispiel #60
0
def main():
    
    #define new objects
    preprocess = Preprocess()
    process = Process()
    points = Points()
    postprocess = Postprocess()
    
    #declare and initialize variables
    search_string = ''
    option = 0
    count2 = 0      #delete this
    reordered_search_string = ''
    permutation_set = set()
    temp_permutation_set = set()
    permutation_list = []     #2D list
    blank_permutation_list = []
    filtered_content = []
    sorted_results = []
    final_results = []
    sorted_final_results = []
    

    #menu options
    print "\nSearch options:\n"
    print "1. Search for words" 
    print "2. Search for words starting with"
    print "3. Search for words ending with"
    print "4. Search for words containing"
    print "5. Search with blank tiles (use the underscore character to represent blanks)\n"
    #option = int(raw_input("Choose option:"))
    option = 1
    #search_string = raw_input('Please input tiles for search: ').lower()
    search_string = "andrew"
    
    #basic input check
    if (preprocess.checkInput(search_string)):
        reordered_search_string = preprocess.reorderString(search_string) #alphabetize tiles
    else:
        sys.exit()

    t1 = time.time()    #diagnostics
    #Input(search_string, option)    #turned into function for testing purposes
    if (option == 0):   #no option chosen
        print "ERROR: No option chosen, exiting."
        sys.exit()
    elif(option == 1):
        print "Searching for words...\n"
        permutation_list = process.stringPermutations(reordered_search_string)
        filtered_content = process.collectDictionarySegments(reordered_search_string)
        sorted_results = process.findWords(permutation_list, filtered_content)
        final_results = points.associatePointScore(sorted_results)
    elif(option == 2):
        print "Searching for words starting with: ", search_string, "\n"
        filtered_content = process.collectDictionarySegments(search_string[0])  #get first letter int he word being searched
        sorted_results = process.findWordsContaining(search_string, filtered_content, option)
        final_results = points.associatePointScore(sorted_results)
    elif(option == 3):
        print "Searching for words ending in: ", search_string, "\n"
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        filtered_content = process.collectDictionarySegments(alphabet)
        sorted_results = process.findWordsContaining(search_string, filtered_content, option)
        final_results = points.associatePointScore(sorted_results)
    elif(option == 4):
        print "Searching for words containing: ", search_string, "\n"
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        filtered_content = process.collectDictionarySegments(alphabet)
        sorted_results = process.findWordsContaining(search_string, filtered_content, option)
        final_results = points.associatePointScore(sorted_results)
    elif(option == 5):
        print "Searching with blank tiles...\n"
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        blank_permutation_list = process.blankTileProcessing(reordered_search_string)        
        filtered_content = process.collectDictionarySegments(alphabet)
        
        #TO DO: Creates a 2D list, gotta convert to 1D list - DONE
        #TO DO: find way to use union keyword to take out duplicates, it will take care of one nested for loop in findWords function - DONE
        #TO DO: Do another union - DONE
            # time vs duplication trade off. Takes longer to take out the duplicates with the union
        for blank_permutation_string in blank_permutation_list:
            #permutation_list.extend(process.stringPermutations(blank_permutation_string))
            temp_permutation_set = set(process.stringPermutations(blank_permutation_string))
            permutation_set = permutation_set.union(temp_permutation_set)
        permutation_list = list(permutation_set)
        
        sorted_results = process.findWords(permutation_list, filtered_content)
        final_results = points.associatePointScore(sorted_results)
    else:
        print "ERROR: Please choose an option between 1-5"
        sys.exit()
    t2 = time.time() - t1   #diagnostics
    
    sorted_option = 0
    print "Results found and processed. Sort results by...\n"
    print "1. Points - lowest to highest"
    print "2. Points - highest to lowest"
    print "3. Length - longest to shortest"
    print "4. Length - shortest to longest"
    sorted_option = int(raw_input("choose option: "))
    print "Option", sorted_option, "chosen"
    
    if (sorted_option == 1):
        print "Sorting results by points, highest to lowest\n"
        sorted_final_results = postprocess.resultsByPoints(final_results)
    elif (sorted_option == 2):
        print "Sorting results by points, lowest to highest\n"
        sorted_final_results = postprocess.resultsByPointsReverse(final_results)
    elif (sorted_option == 3):
        print "Sorting results by length, longest to shortest\n"
        sorted_final_results = postprocess.resultsByLength(final_results)
    elif (sorted_option == 4):
        print "Sorting results by length, shortest to longest\n"
        sorted_final_results = postprocess.resultsByLengthReverse(final_results)
    else:
        print "Option 1-4 not chosen, outputting results by default order"
        sorted_final_results = final_results
        
    Output(sorted_final_results, t2)