Beispiel #1
0
def run_FreeCAD_Polygon(self):

    # recursion stopper
    if self.Called:
        return
    #sayl()
    # mit zeitstemple aktivieren
    #self.Called=True

    pts = self.points.getData()
    #say(pts)
    if pts[0].__class__.__name__ == 'list':
        pts = pts[0]
    say("--")
    if len(pts) < 2:
        sayW("zu wenig points")
    else:
        try:
            shape = Part.makePolygon(pts)
        except:
            return

    self.setPinObject("Shape_out", shape)

    if self._preview:
        self.preview()
Beispiel #2
0
def getInstance():

    try:
        return FreeCAD.PF
    except:
        pass
    try:
        INITIALIZE()
    except:
        pass

    if 0:
        from PyFlow.App import PyFlow
        instance = PyFlow.instance(None, "standalone")
    else:
        from nodeeditor.freecad_pyflowapp import FreeCADPyFlow
        sayl("---------get FreeCADPyFlow-------------------")
        instance = FreeCADPyFlow.instance(None, "standalone")
        say(instance)

    t = instance.windowTitle()
    if not t.startswith("FreeCAD NodeEditor"):
        instance.setWindowTitle("FreeCAD NodeEditor v0.35 @ " +
                                instance.windowTitle())
        #instance.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

    FreeCAD.PF = instance

    from PyFlow import (INITIALIZE, GET_PACKAGES)

    from PyFlow.Core import (GraphBase, PinBase, NodeBase, GraphManager)
    sayl("create instance")
    return instance
Beispiel #3
0
def params2obj(idd, data):

    vals = Config()
    pclass = None  # data[0]

    params = data[1]

    if data[0] == 'B_SPLINE_CURVE_WITH_KNOTS':

        pclass = data[0].lower()

        dat = {
            "descript": STRING,
            "deg": INT,
            "poles": REFLIST,
            '_3': NON,
            '_4': NON,
            '_5': NON,
            "mults": INTLIST,
            "knots": FLOATLIST,
        }

        for i, k in enumerate(dat):
            vals[k] = dat[k](params[i])
            # poles=[pol for pol in params[2]]

        for k in dat:
            say(k, vals[k])

        say(vals.descript)

    return pclass, vals
Beispiel #4
0
    def run_Cypher_LoadCSV(self):

        driver=self.getPinObject('driver')
        cmd=self.getData('command')
        filename=self.getData('filename')
        #filename="https://neo4j.com/docs/cypher-manual/4.0/csv/artists.csv"
        
        ft=self.getData('fieldTerminator')
        if self.getData('withHeaders'):
            cmdall="LOAD CSV WITH HEADERS FROM '{}' AS line FIELDTERMINATOR '{}' ".format(filename,ft)
        else:
            cmdall="LOAD CSV FROM '{}' AS line FIELDTERMINATOR '{}' ".format(filename,ft)
        cmdall += " " + cmd
        say(cmdall)
        
        
        with driver.session() as session:
             rc = session.run(cmdall)

                
        rst=''
        ids=[]
        for d in rc.data():
            say(d)
            ids += [d['id']]
            rst += "\n"+str(d)
        self.setData('ids',ids)
Beispiel #5
0
def PyFlowRef(name="Ref2", ):

    obj = FreeCAD.ActiveDocument.getObject(name)
    if 1 or obj == None:
        obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name)
        #obj=FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython",name)
        obj.addProperty("App::PropertyString", "refname", "Data",
                        "name of the node in pyflow")
        obj.addProperty(
            "App::PropertyLinkList",
            "sources",
            "Data",
        )
        obj.addProperty("App::PropertyInteger", "pauseAfter", "_aux",
                        "minimum time between consecutive recomputes")
        obj.pauseAfter = 1000

        _PyFlowRef(obj)
        _PyFlowRefViewProvider(
            obj.ViewObject,
            '/home/thomas/.FreeCAD/Mod.PyFlow/NodeEditor/icons/BB.svg')
    say(obj)

    #obj.myExecute()
    return obj
Beispiel #6
0
 def max(x=('Float', [0,0.5,1.,1.5],{PinSpecifires.ENABLED_OPTIONS: PinOptions.ArraySupported})) :
     """
     maximum value in list x
     """  
     say("maximum of list")
     say(max(x)) 
     return max(x)
Beispiel #7
0
 def rotMultiply(a=('RotationPin', [1, 0, 0]), b=('RotationPin', [0, 1,
                                                                  0])):
     '''concatenate Rotation a and b'''
     say("rot mult a", a)
     say("rot mult b", b)
     return list(
         FreeCAD.Rotation(*a).multiply(FreeCAD.Rotation(*b)).toEuler())
Beispiel #8
0
def run_FreeCAD_Geom2DCircle(self, *args, **kwargs):

    face = self.getPinObject("Shape")
    if face == None:
        return

    umin, umax, vmin, vmax = face.ParameterRange
    sf = face.Surface

    u = self.getData("u") * 0.1
    v = self.getData("v") * 0.1
    r = self.getData("radius") * 0.1

    u = umin + u * (umax - umin)
    v = vmin + v * (vmax - vmin)
    r = r * (umax - umin)

    a = FreeCAD.Base.Vector2d(u, v)

    line = Part.Geom2d.Circle2d(a, r)
    say(line)

    ee = line.toShape(sf)

    self.setPinObject("geometry", line)
    self.setPinObject("Shape_out", ee)
def run_FreeCAD_Compound(self, *args, **kwargs):

    #+# todo ShapesList implementieren
    #        try:
    #            subshapes=self.getPinObjects("Shapes")
    #        except:
    #            subshapes=[]
    #        try:
    #            subshapes += self.getPinObjects("ShapeList")
    #        except:
    #            pass

    # get list of nodes
    outArray = []
    ySortedPins = sorted(self.shapes.affected_by,
                         key=lambda pin: pin.owningNode().y)

    for i in ySortedPins:
        outArray.append(i.owningNode().getPinObject(i.name))


#-----------------

    say("Compound Shapes:", outArray)
    shape = Part.Compound(outArray)

    self.setPinObject("Shape_out", shape)
Beispiel #10
0
def run_FreeCAD_InterpolateBSpline(self):
    points = self.getData("points")
    say("interpolate for {} points".format(len(points)))
    if len(points) < 2: return

    shin = self.getPinObject("Shape_in")
    if shin is None:
        bs2d = Part.BSplineCurve()
        tol = max(self.getData("tolerance"), 1.)
        #+# todo: problem with tolerance parameter - how to use it ?

        bs2d.interpolate(points, PeriodicFlag=False)
        self.setPinObject("Shape_out", bs2d.toShape())

        return

    shin = shin.toNurbs().Face1
    sf = shin.Surface

    uvs = []
    pts2da = [sf.parameter(p) for p in points]
    pts2d = []
    for i, p in enumerate(pts2da):
        pts2d += [FreeCAD.Base.Vector2d(p[0], p[1])]

    bs2d = Part.Geom2d.BSplineCurve2d()

    tol = max(self.getData("tolerance"), 1.)
    #+# todo: problem with tolerance parameter - how to use it ?

    bs2d.interpolate(pts2d, PeriodicFlag=False)
    self.setPinObject("Shape_out", bs2d.toShape(sf))
Beispiel #11
0
    def workspace(
            name=('String', "workspace"),
            temp=('BoolPin', True),
    ):

        say("workspace called")
        return (name)
Beispiel #12
0
def run_FreeCAD_Plot(self, *args, **kwargs):

    sayl("huhuhu44")

    mode = self.getData("Figure")
    say("mode", mode)

    if mode == "Figure1":
        fig = plt.figure(1)

    elif mode == "Figure2":
        fig = plt.figure(2)

    elif mode == "Figure3":
        fig = plt.figure(3)

    else:
        fig = plt.figure(4)

    #plt.close()
    plt.clf()
    plt.title(self.getName())

    x = self.xpin.getData()
    y = self.ypin.getData()

    say(x)
    say(y)
    say(len(x), len(y))

    #x=[1,2,3]
    #y=[1,5,3]

    if len(y) != 0:
        N = len(y)
        if len(x) != len(y):
            x = np.linspace(0, len(y), N, endpoint=True)
        else:
            x = np.array(x)

        y = np.array(y)

        if not mode == "Figure3":
            plt.plot(x, y, 'b-')

    x2 = self.xpin2.getData()
    y2 = self.ypin2.getData()
    say(len(x2), len(y2))
    if x2 != None and y2 != None:
        x2 = np.array(x2)
        y2 = np.array(y2)
        if not mode == "Figure3":
            plt.plot(x2, y2, 'r-')
        else:
            plt.plot(x2, y2, 'ro')

    plt.show()

    fig.canvas.draw()
Beispiel #13
0
    def linSpace(start=('FloatPin', 0.),
                 stop=('FloatPin', 10),
                 num=('IntPin', 50)):
        """create a linear Space"""

        x1 = np.linspace(start, stop, num, endpoint=True)
        say("linspace", x1)
        return x1.tolist()
Beispiel #14
0
 def do(self):
     nodes = FreeCAD.PF.graphManager.get().getAllNodes()
     nodes2 = sorted(nodes, key=lambda node: node.x)
     say("selected Nodes ...")
     for n in nodes2:
         if n.getWrapper().isSelected():
             say(n, n.x)
             n.compute()
Beispiel #15
0
def run_FreeCAD_Zip(self):
    x = self.getData("x")
    y = self.getData("y")
    z = self.getData("z")

    zz = [FreeCAD.Vector(x, y, z) for x, y, z in zip(x, y, z)]
    say("len", len(zz))
    self.setData("vectors_out", zz)
Beispiel #16
0
def run_FreeCAD_Expression2Function(self):

    s=self.getData('expression')
    if s != '':
        cmd="lambda a,b,c:{}".format(s)
        say(cmd)
        cmd2=eval(cmd)
        self.setPinObject('function_out',cmd2)
Beispiel #17
0
 def do(self):
     nodes = FreeCAD.PF.graphManager.get().getAllNodes()
     say("selected Nodes ...")
     for n in nodes:
         if n.getWrapper().isSelected():
             say(n)
             n._preview = not n._preview
             n.preview()
Beispiel #18
0
	def list(self):
		try:
			FreeCAD.STORE
		except:
			FreeCAD.STORE={}
		say("store object list ...")
		for k in FreeCAD.STORE.keys():
			say(k,FreeCAD.STORE[k])
Beispiel #19
0
def setDataG(self, data):
    say("setDataG", self.name)
    super(self.__class__, self).setData(data)
    try:
        if self.direction == PinDirection.Input and not self.hasConnections():
            self.owningNode().compute()
    except:
        pass
Beispiel #20
0
def run_FreeCAD_ImageT(self):

    from scipy import ndimage
    fn = self.getData('image')
    import matplotlib.image as mpimg

    img = mpimg.imread(fn)
    (sa, sb, sc) = img.shape
    red = 0.005 * (self.getData("red") + 100)
    green = 0.005 * (self.getData("green") + 100)
    blue = 0.005 * (self.getData("blue") + 100)
    #blue=0
    say("rgb", red, green, blue)

    # andere filtre
    #img = ndimage.sobel(img)
    #img = ndimage.laplace(img)

    im2 = img[:, :, 0] * red + img[:, :, 1] * green + img[:, :, 2] * blue
    im2 = np.round(im2)

    if self.getData('invert'):
        im2 = 1 - im2

    #im2 = ndimage.sobel(im2)

    ss = int((self.getData('maskSize') + 100) / 20)
    say("ss", ss)
    if ss != 0:
        mode = self.getData('mode')
        say("mode", mode)
        if mode == 'closing':
            im2 = ndimage.grey_closing(im2, size=(ss, ss))
        elif mode == 'opening':
            im2 = ndimage.grey_opening(im2, size=(ss, ss))
        elif mode == 'erosion':
            im2 = ndimage.grey_erosion(im2, size=(ss, ss))
        elif mode == 'dilitation':
            im2 = ndimage.grey_dilation(im2, footprint=np.ones((ss, ss)))
        else:
            say("NO MODE")

    nonzes = np.where(im2 == 0)
    pts = [
        FreeCAD.Vector(sb + -x, sa - y)
        for y, x in np.array(nonzes).swapaxes(0, 1)
    ]

    h = 10
    pts = [
        FreeCAD.Vector(
            sb + -x, sa - y,
            (red * img[y, x, 0] + green * img[y, x, 1] + blue * img[y, x, 2]) *
            h) for y, x in np.array(nonzes).swapaxes(0, 1)
    ]
    colors = [img[y, x] for y, x in np.array(nonzes).swapaxes(0, 1)]
    say("len pts", len(pts))
    self.setData("Points_out", pts)
Beispiel #21
0
def createElevationGrid(pts,mode='thin_plate',rbfmode=True,source=None,gridCount=20,zfactor=1,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)
    }


    k=0.0001
    k=0
    pts2=[p+FreeCAD.Vector(random.random(),random.random(),random.random())*k for p in pts]
    pts=pts2

    #say("points",pts)
    x=np.array(pts)[:,0]
    y=np.array(pts)[:,1]
    z=np.array(pts)[:,2]
    say(x)
    say(y)
    say(z)
    say("----------")
    
    #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=[10,-10,10,-10]
    ye=[10,-9,10,-10]
    ze=[0,0,0,0]


    #rbf2,xi2,yi2,zi2 = interpolate(xe,ye,ze, gridsize,mode,rbfmode,zi1.shape)
    rbf2=0
    #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)

    points=showFace(rbf,rbf2,x,y,gridsize,color,bound)
    say("XXXX points",points)

 
    return points
Beispiel #22
0
 def recompute(self):
     obj = self.Object
     say("Recompute ", obj.Label)
     instance = pfwrap.getInstance()
     instance.graphManager.get().clear()
     a = PyFlowGraph()
     data = eval(a.graph)
     instance.loadFromData(data)
     pfwrap.getInstance().show()
Beispiel #23
0
def run_FreeCAD_Toy3(self):
    say(noto)
    d = [[1, 2, 3], [4, 5, 6, 6, 7, 8]]
    #d=[1,2,3,4,5,6]
    #d=[1,2,3]
    rc = noto.data2vecs(d)
    say(rc)
    bs = noto.createBSplineSurface()
    self.setPinObject("Shape1", bs.toShape())
Beispiel #24
0
def run_FreeCAD_MoreThan(self):
    values = self.getData("values")
    threshold = self.getData("threshold")
    rc = []
    for v in values:
        say(v, v > threshold)
        rc += [v > threshold]
    self.setData("moreThan", rc)
    self.setColor(b=0, a=0.4)
Beispiel #25
0
def run_FreeCAD_Equal(self):
    values = self.getData("values")
    threshold = self.getData("value")
    rc = []
    for v in values:
        say(v, v == threshold)
        rc += [v == threshold]
    self.setData("equal", rc)
    self.setColor(b=0, a=0.4)
Beispiel #26
0
def run_FreeCAD_ListOfVectorlist(self):

    ySortedPins = sorted(self.pas.affected_by,
                         key=lambda pin: pin.owningNode().y)
    col = []
    for i in ySortedPins:
        vv = i.owningNode().getData(i.name)
        col += [vv]
    say("shape result", np.array(col).shape)
    self.setData('vectorarray', col)
Beispiel #27
0
def run_FreeCAD_Toy(self):
    self.setNodename("HU"+str(time.time()))
    self.setImage("freecad_cone")

    pml=[1,2,3,4,5,6,7,8,10,11,12,12,14,15,16,]
    tt=FreeCAD.Placement(FreeCAD.Matrix(*pml))
    pm2=self.getPinPlacement("PlacementPin_in")
    say("got",pm2)

    self.setPinPlacement("PlacementPin_out",tt.multiply(pm2))
Beispiel #28
0
    def run(pts, k=1):

        l = len(pts)

        if mode == 'constant':
            pts2 = [pts[0]] + [(pts[i - 1] + 2 * pts[i] + pts[i + 1]) / 4
                               for i in range(1, l - 1)] + [pts[-1]]
            pts2 = [pts[0]] + [(pts[i - 1] + w * pts[i] + pts[i + 1]) / (2 + w)
                               for i in range(1, l - 1)] + [pts[-1]]
        else:
            pts2 = [pts[0]]
            for i in range(1, l - 1):
                al = (pts[i - 1] - pts[i]).Length
                el = (pts[i + 1] - pts[i]).Length
                say(i, al, el)
                f = 10.
                if al != 0:
                    al = min(1, 1 / al * (w + 1))
                else:
                    al = 1
                if el != 0:
                    el = min(1, 1 / el * (w + 1))
                else:
                    el = 1

                say(i, al, el)

                pts2 += [(al * pts[i - 1] + pts[i] + el * pts[i + 1]) /
                         (1 + al + el)]

            pts2 += [pts[-1]]

        dd = [FreeCAD.Vector()] + [
            (pts[i] - pts2[i]).normalize() * k for i in range(1, l - 1)
        ] + [FreeCAD.Vector()]
        pts3 = [p + q for p, q in zip(pts2, dd)]

        if 0:
            for i in range(1, l - 3):

                if (pts3[i] - pts3[i + 1]).Length > (pts3[i] -
                                                     pts3[i + 3]).Length:
                    pts3 = pts3[:i + 1] + [
                        pts3[i + 3], pts3[i + 2], pts3[i + 1]
                    ] + pts3[i + 4:]

            for i in range(1, l - 2):
                if (pts3[i] - pts3[i + 1]).Length > (pts3[i] -
                                                     pts3[i + 2]).Length:
                    pts3 = pts3[:i + 1] + [pts3[i + 2], pts3[i + 1]
                                           ] + pts3[i + 3:]

        c = Part.BSplineCurve(pts3)
        return pts3, c.toShape()
Beispiel #29
0
	def dela(self,key):
		try:
			FreeCAD.STORE
		except:
			FreeCAD.STORE={}
		self.list()
		say("delete",key)
		try:
			del(FreeCAD.STORE[str(key)])
		except:
			pass
Beispiel #30
0
    def run_Cypher_ResultToy(self):
        sayl()

        result=self.getPinObject('bolTResult')        
        a=result.summary()
        say(a.statement)
        say(a.server.address)
        data=result.data()

        self.setData('outString',str(data))
        return