예제 #1
0
def Load_STEP_File(doc_status, material):
    import tkFileDialog
    import FreeCAD
    import Import
    import FreeCADGui
    import Draft
    import Part
    #prepares and opens STEP file with FreeCADs
    path_to_file = tkFileDialog.askopenfilename()
    if (path_to_file[-5:] == ".STEP" or path_to_file[-5:] == ".step"
            or path_to_file[-4:] == ".stp"):
        if (
                doc_status
        ):  #If a file was already open the document associated with it must be closed
            FreeCAD.closeDocument("Unnamed")
            print "Previous document closed"
        FreeCAD.newDocument("Unnamed")
        FreeCAD.setActiveDocument("Unnamed")
        try:
            Import.insert(
                path_to_file, "Unnamed"
            )  #FreeCAD attempts to open file - If the format is wrong it will be detected
            print "File read successfuly"
            list_of_objects = []
            for obj in FreeCAD.ActiveDocument.Objects:
                list_of_objects.append(Volumes.Volume(obj, material, 0.1, 1))
            return list_of_objects
        except:
            print "Error reading file. Format might be incorrect."
            return 0
    else:
        print "Error with file extension"
        return 0
예제 #2
0
def reorient_object(input_file_name, output_file_name, refinement_level):
	__objToExport__ = FreeCAD.getDocument("tmp").findObjects()

	# get the original file
	Import.insert(input_file_name, "tmp")

	# get bounding box
	bB = FreeCAD.getDocument("tmp").Objects[-1].Shape.BoundBox

	# create rotation parameters
	displacement = FreeCAD.Vector(2.0, 0.0, 0.0)
	centerRot = FreeCAD.Vector(bB.XMin, 0.5*(bB.YMin+bB.YMax), bB.ZMin)
	axisRot1 = FreeCAD.Vector(0.0, 0.0, 1.0)
	axisRot2 = FreeCAD.Vector(0.0, 1.0, 0.0)
	angleRot1 = 180.0
	angleRot2 = 90.0

	# import the draft module
	import Draft
	Draft.move(FreeCAD.getDocument("tmp").Objects[0], displacement, copy=False) # perform move
	Draft.rotate(FreeCAD.getDocument("tmp").Objects[0], angleRot1, centerRot,axis=axisRot1,copy=False) # perform first rotation
	Draft.rotate(FreeCAD.getDocument("tmp").Objects[0], angleRot2, centerRot,axis=axisRot2,copy=False) # perform second rotation

	# remove originalGeom
	originalGeom = FreeCAD.getDocument("tmp").Objects[-1].Name
	FreeCAD.getDocument("tmp").removeObject(originalGeom)

	print "Exporting RAW file..."
	Part.export(__objToExport__, output_file_name+".step")
	print "Output file " + output_file_name+".step" + " exported."
예제 #3
0
def process_nonchanging_domains(nonchanging_file_name, output_file_name):
    if len(nonchanging_file_name) != 0:

        __objs_original__ = FreeCAD.getDocument("tmp").findObjects()
        len_original = len(__objs_original__)
        print "Loading non-changing component..."
        Import.insert(nonchanging_file_name, "tmp")

        # get objects
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        # create fusion object
        FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

        # add objs to FusionTool
        FreeCAD.getDocument(
            "tmp").FusionTool.Shapes = __objs__[0:len(__objs__)]

        # compute
        FreeCAD.getDocument("tmp").recompute()

        # make one solid
        Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # remove all except the last
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        for i in range(0, len(__objs__) - 1):
            FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        print "Exporting BOOLEANED file..."
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        Part.export(__objs__, output_file_name + "_BOOLEANED.step")
        print "Output file " + output_file_name + "_BOOLEANED.step" + " exported."
def process_nonchanging_domains(nonchanging_file_name, output_file_name):
	if len(nonchanging_file_name) != 0:

		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()
		len_original =len(__objs_original__)
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
def process_nonchanging_domains(nonchanging_file_name, output_file_name, refinement_level):
	if len(nonchanging_file_name) != 0:
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")
		
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
예제 #6
0
def setup_example_ada(T):
    """Sets the global variable up to work with the example data from Import.py"""
    global attributes, labels, example_weights, train_data, test_data
    attributes = Import.example_attributes
    labels = Import.bank_labels
    m = 14
    example_weights = np.tile(np.repeat(1.0 / m, m), (T, 1))
    train_data = Import.get_example_data()
    test_data = Import.get_example_data()
예제 #7
0
def process_allowed_domains(allowed_domains_file_name, output_file_name, refinement_level):
	if len(allowed_domains_file_name) != 0:
		print "Checking allowed domains..."
		# take the intersection of allowed domains
		# read in step file for allowed domains
		Import.insert(allowed_domains_file_name, "tmp")
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# get bounding box of the allowed domains
		# NOTE: ASSUMING ALLOWED DOMAINS ARE ALL FUSED IN ONE OBJECT.
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# create mega BB object
		create_mega_bounding_box_object()

		# cut out allowed domains from mega BB object
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
		FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument("tmp").Objects[-3]
		FreeCAD.getDocument("tmp").recompute()
		#Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# cut out not-allowed parts
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
		FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument("tmp").Objects[0]
		FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").recompute()
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove everything except the last cut-object
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		print __objs__

		if len(__objs__) > 1:
			# create a fuse object and union all "Common"s
			FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
			FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1: len(__objs__)]
			print FreeCAD.getDocument("tmp").Fuse.Shapes
			FreeCAD.getDocument("tmp").recompute()

			# remove "Commons"s
			for i in range(0, len(__objs__)):
				FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
예제 #8
0
def process_allowed_domains(allowed_domains_file_name, output_file_name):
    if len(allowed_domains_file_name) != 0:
        print "Checking allowed domains..."
        # take the intersection of allowed domains
        # read in step file for allowed domains

        __objs_original__ = FreeCAD.getDocument("tmp").findObjects()

        Import.insert(allowed_domains_file_name, "tmp")
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        # create mega BB object
        create_mega_bounding_box_object()

        # cut out allowed domains from mega BB object
        FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
        FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument(
            "tmp").Objects[-2]
        FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument(
            "tmp").Objects[-3]
        FreeCAD.getDocument("tmp").recompute()
        #Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # cut out not-allowed parts
        FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
        FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument(
            "tmp").Objects[0]
        FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument(
            "tmp").Objects[-2]
        FreeCAD.getDocument("tmp").recompute()
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # remove everything except the last cut-object
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        for i in range(0, len(__objs__) - 1):
            FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        # update __objs__
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        if len(__objs__) > 1:
            # create a fuse object and union all "Common"s
            FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
            FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1:len(__objs__)]
            print FreeCAD.getDocument("tmp").Fuse.Shapes
            FreeCAD.getDocument("tmp").recompute()

            # remove "Commons"s
            for i in range(0, len(__objs__)):
                FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        # update __objs__
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
    def __init__(self, log):
        fecha = str(datetime.today().strftime('%Y%m%d'))
        ruta = "../ProxiesList/" + fecha
        ruta_proxies = ruta + "/" + fecha + "_listaProxies"
        ruta_paginas = ruta + "/" + fecha + "_paginasProxies"
        #0.Declaracion de variables
        extension = "csv"

        #1.Importamos el DataFrame de proxies
        if os.path.exists(ruta) == False:
            log.info(
                "Proceso: ProxyProvider init||Mensaje: inicializando lista proxies"
            )
            self.proxyDf = pd.DataFrame(
                columns=['CADENA', 'ESTADO', 'SITUACION'])
            self.paginasDf = pd.DataFrame(columns=['PAGINA'])
            self.importar(ruta, ruta_proxies, ruta_paginas, log)
            log.info(
                "Proceso: ProxyProvider init||Mensaje: Lista proxies inicializada"
            )
        else:
            log.info(
                "Proceso: Proxies init||Mensaje: inicializando lista proxies")
            self.proxyDf = Import.fichero(ruta_proxies, extension, log)
            self.paginasDf = Import.fichero(ruta_paginas, extension, log)
            log.info(
                "Proceso: ProxyProvider init||Mensaje: Lista proxies inicializada"
            )

#2.Inicializacion del socket
        self.socketInitialize(log)

        #3.Conexion al puerto
        self.connect(log)

        #4.Listening
        self.listen(1, log)  #una conexion de momento
        while True:
            #Wait for a connection
            connection, client_address = self.sock.accept()
            try:
                data = self.receive(connection)
                p = self.unpickleObject(data, log)
                if p.cadena == "":
                    proxy = None
                else:
                    proxy = p
                proxy = self.darProxy(ruta, ruta_proxies, ruta_paginas, log,
                                      proxy)
                data = self.pickleObject(proxy, log)
                self.send(connection, data, log)
            finally:
                self.disconnect(connection, log)
예제 #10
0
	def export_file(self):
		# Read database:
		if self.file_type == 'FCStd':
			self.doc.recompute()  # Alway recomputer before save file
			self.doc.saveAs(u"{}Mold_{}.FCStd".format(self.save_path, self.order_number))
		else:
			self.doc.recompute()
			select = []
			for obj in self.doc.Objects:
				if obj.Name[:5] in ['Trans', 'Fixed']:
					select.append(obj)
			self.doc.recompute()
			Import.export(select, "{}Mold_{}.{}".format(self.save_path, self.order_number, self.file_type))
예제 #11
0
def process_allowed_domains(allowed_domains_file_name, output_file_name):
	if len(allowed_domains_file_name) != 0:
		print "Checking allowed domains..."
		# take the intersection of allowed domains
		# read in step file for allowed domains
		
		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()

		Import.insert(allowed_domains_file_name, "tmp")
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create mega BB object
		create_mega_bounding_box_object()

		# cut out allowed domains from mega BB object
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
		FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument("tmp").Objects[-3]
		FreeCAD.getDocument("tmp").recompute()
		#Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# cut out not-allowed parts
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
		FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument("tmp").Objects[0]
		FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").recompute()
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove everything except the last cut-object
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		if len(__objs__) > 1:
			# create a fuse object and union all "Common"s
			FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
			FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1: len(__objs__)]
			print FreeCAD.getDocument("tmp").Fuse.Shapes
			FreeCAD.getDocument("tmp").recompute()

			# remove "Commons"s
			for i in range(0, len(__objs__)):
				FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
예제 #12
0
    def stripSTPfile(self, partfile, rawSTP, outfile=None, partsOnly=True):
        """
        Strips an stpfile down to the parts defined in the parts csv input file
        STPfile is the output file defined in input file to HEAT, and is included
        in self variable.  rawSTP is the input CAD file that we want to strip.

        If partsOnly is True then we only copy parts (not assemblies), which
        technically means only objects with type=Part.Feature
        """
        print('Stripping STP file')
        t0 = time.time()
        with open(partfile) as f:
            part_list = f.read().splitlines()
        print("Read parts list...")
        print(part_list)

        #Input / Output STEP files
        infile = rawSTP
        if outfile is None:
            outfile = self.STPfile

        #If a shape has a label in part_list, keep it
        CAD = Import.open(infile)
        newobj = []
        count = 0
        for i, obj in enumerate(FreeCAD.ActiveDocument.Objects):
            if any(substring in obj.Label for substring in part_list):
                #conditional to check if item is part (Part.Feature) or
                # assembly (App.Part).
                # This could be adapted in future to exclude objects containing
                # specific string (like "_ASM") in Label that CAD engineer uses
                # for assemblies
                if partsOnly == True:
                    if type(obj) == Part.Feature:
                        count += 1
                        newobj.append(obj)
                        newobj[-1].Placement = obj.getGlobalPlacement()
                else:
                    count += 1
                    newobj.append(obj)
                    newobj[-1].Placement = obj.getGlobalPlacement()

        #Export to a new step file
        Import.export(newobj, outfile)
        print("Step file export complete.")
        print("Exported {:d} part objects".format(count))
        print("Execution took {:f} seconds".format(time.time() - t0))
        return
예제 #13
0
        def start_convert():
            var1 = var_input_path.get()
            var2 = var_target_file_path.get()
            var3 = var_target_lan.get()
            var4 = var_target_dir_path.get()

            importUtils = Import.ImportUtils()

            isDir = callRB()  # 导出是文件导出还是目录导出

            if isDir:
                error = importUtils.xls2xml(var1, None, None,
                                            var4)  # type: Constant.Error
            else:
                error = importUtils.xls2xml(var1, var2, var3,
                                            None)  # type: Constant.Error

            if error is not None:
                if error.isError():
                    tkinter.messagebox.showerror(title='Error',
                                                 message=error.get_desc(),
                                                 parent=window)
                else:
                    tkinter.messagebox.showinfo(title='congratulation',
                                                message=error.get_desc(),
                                                parent=window)
예제 #14
0
def setup_data(m=4999, iters=1):
    """
    Sets attributes, labels, example_weights train_data, and test_data based on the data_type
    :param m: number of examples ID3 will run on
    :param iters: number of iterations ID3 will be run
    """
    global attributes, labels, example_weights, train_data, test_data
    if data_type == "car":
        attributes = Import.car_attributes
        labels = Import.car_labels
        m = 1000

    else:
        attributes = Import.bank_attributes
        labels = Import.bank_labels
    example_weights = np.tile(np.repeat(1.0 / m, m), (iters, 1))
    train_data = Import.import_data(data_type, True, True)
    test_data = Import.import_data(data_type, False, True)
예제 #15
0
def loadAssemblyFromFile(file):
    """loadAssemblyFromFile

    Open a 3D CAD assembly file, return the document object and [list of all the parts]
    """
    if file.__contains__(".FCStd"):

        FreeCAD.open(file)
        doc = App.activeDocument()
        doc = FreeCAD.ActiveDocument
        objs = FreeCAD.ActiveDocument.Objects
        return doc, objs

    if file.__contains__(".STEP") or file.__contains__(".step"):
        Import.open(file)
        doc = App.activeDocument()
        doc = FreeCAD.ActiveDocument
        objs = FreeCAD.ActiveDocument.Objects
        return doc, objs
예제 #16
0
def reorient_object(input_file_name, output_file_name):
    __objToExport__ = FreeCAD.getDocument("tmp").findObjects()

    # get the original file
    Import.insert(input_file_name, "tmp")

    # get bounding box
    bB = FreeCAD.getDocument("tmp").Objects[-1].Shape.BoundBox

    # create rotation parameters
    #print "XMin:", bB.XMin, "XMax:", bB.XMax, "YMin:", bB.YMin, "YMax:", bB.YMax, "ZMin:", bB.ZMin, "ZMax:", bB.ZMax
    displacement = FreeCAD.Vector(-bB.ZMin, bB.YMin, -bB.XMin)
    centerRot = FreeCAD.Vector(bB.XMin, 0.5 * (bB.YMin + bB.YMax), bB.ZMin)
    axisRot1 = FreeCAD.Vector(0.0, 0.0, 1.0)
    axisRot2 = FreeCAD.Vector(0.0, 1.0, 0.0)
    angleRot1 = 180.0
    angleRot2 = 90.0

    # import the draft module
    import Draft
    Draft.move(FreeCAD.getDocument("tmp").Objects[0], displacement,
               copy=False)  # perform move
    Draft.rotate(FreeCAD.getDocument("tmp").Objects[0],
                 angleRot1,
                 centerRot,
                 axis=axisRot1,
                 copy=False)  # perform first rotation
    Draft.rotate(FreeCAD.getDocument("tmp").Objects[0],
                 angleRot2,
                 centerRot,
                 axis=axisRot2,
                 copy=False)  # perform second rotation

    # remove originalGeom
    originalGeom = FreeCAD.getDocument("tmp").Objects[-1].Name
    FreeCAD.getDocument("tmp").removeObject(originalGeom)

    print "Exporting RAW file..."
    Part.export(__objToExport__, output_file_name + ".step")
    print "Output file " + output_file_name + ".step" + " exported."

    return bB.YMax
예제 #17
0
    def importCAD(self, filename):
        self._status = {
            'status': 'error',
            'fuuid': self._fuuid,
            'obs': []
        }
        try:

            infos = []
            self._source_filename = filename

            if filename.endswith('.fcstd'):

                FreeCAD.open(filename)
            else:
                Import.open(filename)

            self._doc = App.ActiveDocument
            self._objects = self._doc.Objects
            self._json_data = []
            n_ok = 0
            self._doc.Id = self._fuuid
            for i in self._objects:
                uid = uuid.uuid4().hex
                label = secure_filename(i.Label)
                i.Label = uid

                if self.tessellate(i, uid):
                    info = {'uuid': uid, 'label': label}
                    infos.append(info)
                    n_ok += 1

            self._status['status'] = 'ready'
            self._status['n'] = n_ok
            self._status['obs'] = infos
            self.dump()
        except:
            pass

        json_response = json.dumps(self._status)
        self.dumpStatus(json_response)
        return json_response
예제 #18
0
def loadApiClass(self, api):
    if api.projectName not in self.globals.apiNameList:
        self.globals.makeApiAvaliable(api.projectName)
    try:
        with open(self.importApplicationScriptPath,
                  self.globals.OVERRIDE,
                  encoding=self.globals.ENCODING) as scriptFile:
            scriptFile.write(''.join(api.importScript))
        import Import
        apiClass = Import.getApiClass()
        return apiClass
    except Exception as exception:
        self.globals.error(f'Not possible to reach {api.key} due command line',
                           exception)
예제 #19
0
def main():
    """
  Convert all parts in a STEP file to many STL files plus TXT offset files.
  """
    Import.open(sys.argv[1])
    doc = FreeCAD.activeDocument()
    i = 0
    for obj in doc.Objects:
        obj_export = []
        obj_export.append(obj)
        a = obj.Name
        b = obj.Label
        filename = a + '_' + "".join(
            x for x in b if (x.isalnum() or x in "._- ")) + str(i).zfill(4)
        f = open(sys.argv[2] + filename + '.txt', 'w')
        f.write(a + ' -> ' + b + '\n')
        f.write(str(obj.Placement) + '\n')
        f.write(str(obj.Shape.Placement) + '\n')
        f.write(str(obj.Shape.BoundBox) + '\n')
        #f.write(str(obj.Shape.CenterOfMass)+'\n')
        f.close()
        Mesh.export(obj_export, sys.argv[2] + filename + ".stl")
        i = i + 1
예제 #20
0
파일: LoadOP.py 프로젝트: achim1/GUIMesh3
def Load_STEP_File(doc_status,material):
    from GUIMeshLibs import Volumes
    import tkinter.filedialog
    import FreeCAD
    import Import
    import FreeCADGui
    import Draft
    import Part
    #prepares and opens STEP file with FreeCADs
    path_to_file = tkinter.filedialog.askopenfilename()
    if( path_to_file[-5:]==".STEP" or path_to_file[-5:]==".step"or path_to_file[-4:]==".stp"):
        if (doc_status):    #If a file was already open the document associated with it must be closed
            FreeCAD.closeDocument("Unnamed")
            print("Previous document closed")
        FreeCAD.newDocument("Unnamed")
        FreeCAD.setActiveDocument("Unnamed")
        try: 
            Import.insert(path_to_file,"Unnamed") #FreeCAD attempts to open file - If the format is wrong it will be detected
            print("File read successfuly")
            list_of_objects=[]
            for obj in FreeCAD.ActiveDocument.Objects:
                try:
                        if(obj.TypeId=="Part::Feature"):
                                obj.Label=obj.Label.replace(" ","_")
                                obj.Label=obj.Label.replace(".","_")
                                obj.Label=obj.Label.replace("---","_")
                                list_of_objects.append(Volumes.Volume(obj,material,0.1,1))
                except:
                        continue
            return list_of_objects
        except:
            print("Error reading file. Format might be incorrect.")
            return 0
    else:
        print("Error with file extension")
        return 0
예제 #21
0
파일: Main.py 프로젝트: 0vishal/MYSQL
def Main():
    """
    Description:
    Function : To get input from user and call the required function
    """
    option = int(input("Enter the option 1.Import Data  2. Export data "))
    try:
        if option == 1:
            import_data = ie.Import()
            import_data.import_csv()
            #import_data.get_import_data()
        elif option == 2:
            export_data = ex.Export()
            export_data.export_data()
    except (ValueError, KeyboardInterrupt) as e:
        print(e)
예제 #22
0
    def loadSTEP(self):
        """
        Loads CAD STEP (ISO 10303-21) file into object
        """
        print("Loading STEP file...")
        log.info("Loading STEP file...")
        self.CAD = Import.open(self.STPfile)
        self.CADdoc = FreeCAD.ActiveDocument
        #Coordinate permutation if necessary
        if self.permute_mask == 'True' or self.permute_mask == True:
            self.permuteSTEP()
            #self.permuteSTEPAssy()
            self.permute_mask = False

        #Save all parts/objects
        self.CADobjs = self.CADdoc.Objects
        self.CADparts = []
        for obj in self.CADobjs:
            if type(obj) == Part.Feature:
                self.CADparts.append(obj)

        print("Loaded STEP file: " + self.STPfile)
        log.info("Loaded STEP file: " + self.STPfile)
        return
예제 #23
0
파일: GUI.py 프로젝트: danagain/egh455
    def __init__(self, master):
        master.title("Surf Safe Detection")
        master.geometry('901x531')
        master.resizable(0, 0)  #Don't allow resizing in the x or y direction
        self.master = master

        # TODO: surfer, dolphin and animal totals
        # restart video when it comes to the end

        ################################## GUI Frames ##################################
        windowColour = "white"
        animalTotalFrame = tkinter.Frame(self.master,
                                         bg=windowColour,
                                         width=580,
                                         height=200,
                                         highlightthickness=1,
                                         highlightbackground="black")
        leftFrame = tkinter.Frame(self.master,
                                  bg=windowColour,
                                  width=320,
                                  height=550,
                                  highlightthickness=1,
                                  highlightbackground="black")
        videoFrame = tkinter.Frame(self.master,
                                   bg=windowColour,
                                   width=579,
                                   height=550,
                                   highlightthickness=1,
                                   highlightbackground="black")
        statusFrame = tkinter.Frame(self.master,
                                    bg=windowColour,
                                    width=899,
                                    height=20,
                                    highlightthickness=1,
                                    highlightbackground="black")
        videoSelectionFrame = tkinter.Frame(self.master,
                                            bg=windowColour,
                                            width=200,
                                            height=100,
                                            highlightthickness=1,
                                            highlightbackground="white")
        videoStatFrame = tkinter.Frame(leftFrame,
                                       bg=windowColour,
                                       width=350,
                                       height=300,
                                       pady=3)

        animalTotalFrame.place(x=320, y=485)
        videoStatFrame.place(x=10, y=280)
        videoSelectionFrame.place(y=90, x=10)
        statusFrame.place(x=1, y=510)
        leftFrame.place(x=1, y=1)
        videoFrame.place(x=320, y=1)

        ############################### Object Creation #####################################
        statusMessage = Status.StatusMessage(statusFrame)
        dataStructure = SSDdataStructure.DataStructure(videoSelectionFrame)
        videoStatistics = UpdateStatistics.UpdateStatistics(
            animalTotalFrame, videoStatFrame, dataStructure)
        VideoPlayer = videoClass.VideoPlayer(
            videoFrame, dataStructure, videoStatistics, statusMessage,
            self.master, project_root + "/455SSDWelcomeMessage.jpg")
        processVideo = Process.Process(leftFrame, dataStructure, self.master,
                                       statusMessage)
        importVideoCSV = Import.Import(leftFrame, dataStructure, self.master,
                                       statusMessage)
        exportVideoCSV = Export.Export(leftFrame, dataStructure, self.master,
                                       statusMessage)

        ########################## Window Top Menu #########################################
        # a root menu to insert all the sub menus
        root_menu = tkinter.Menu(self.master)
        self.master.config(menu=root_menu)

        # file sub menu
        file_menu = tkinter.Menu(root_menu)
        root_menu.add_cascade(label="File", menu=file_menu)
        file_menu.add_command(label="Import Video",
                              command=importVideoCSV.importVideo)
        file_menu.add_command(label="Import Image",
                              command=importVideoCSV.importVideo)
        file_menu.add_command(label="Import CSV",
                              command=importVideoCSV.importCSV)
        file_menu.add_separator()
        file_menu.add_command(label="Export CSV",
                              command=exportVideoCSV.exportCSV)
        file_menu.add_command(label="Save Video",
                              command=exportVideoCSV.exportVideo)
        file_menu.add_command(label="Save Image",
                              command=exportVideoCSV.exportVideo)
        file_menu.add_separator()
        file_menu.add_command(label="Quit", command=self.quit)

        # help sub menu
        help_menu = tkinter.Menu(root_menu)
        root_menu.add_cascade(label="Help", menu=help_menu)
        help_menu.add_command(label="Help", command=self.helpMenu)

        #shortcut functionalty
        self.master.bind("<Control-q>", self.quit)
        self.master.bind("<h>", self.helpMenu)
        self.master.bind("<p>", processVideo.processVideo)
        self.master.bind('n', importVideoCSV.importVideo)
        self.master.bind("<Control-n>", importVideoCSV.importCSV)
        self.master.bind('s', exportVideoCSV.exportVideo)
        self.master.bind("<Control-s>", exportVideoCSV.exportCSV)
        self.master.bind("<space>", VideoPlayer.playPause)
        self.master.bind("<Left>", VideoPlayer.lastFrame)
        self.master.bind("<Right>", VideoPlayer.nextFrame)
App.getDocument('Unnamed').recompute()

f = FreeCAD.getDocument('Unnamed').addObject('Part::Extrusion', 'Extrude')
f = App.getDocument('Unnamed').getObject('Extrude')
f.Base = App.getDocument('Unnamed').getObject('Sketch')
f.DirMode = "Custom"
f.Dir = App.Vector(0.000000000000000, 0.000000000000000, 1.000000000000000)
f.DirLink = None
f.LengthFwd = 1.000000000000000  # длина выдавливания
f.LengthRev = 0.000000000000000
f.Solid = True
f.Reversed = False
f.Symmetric = False
f.TaperAngle = 0.000000000000000
f.TaperAngleRev = 0.000000000000000
# Gui.ActiveDocument.Extrude.ShapeColor=Gui.ActiveDocument.Sketch.ShapeColor
# Gui.ActiveDocument.Extrude.LineColor=Gui.ActiveDocument.Sketch.LineColor
# Gui.ActiveDocument.Extrude.PointColor=Gui.ActiveDocument.Sketch.PointColor
# f.Base.ViewObject.hide()
App.ActiveDocument.recompute()

__objs__ = []
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("Extrude"))
import Import
Import.export(
    __objs__,
    u"C:/Users/asea2/Desktop/PycharmProjects/Prikolno/freecadfiles/model.step")

del __objs__
예제 #25
0
from NB.NaiveBayes import GaussianNB, CategoricalNB, EqualWidthPartitioning, EqualDepthPartitioning, KMeansPartitioning
import Import as imp
import numpy as np
from Validation.ConfusionMatrix import ConfusionMatrixStatistic, Measure
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

from Validation.CrossValidation import KFold, split_list

data = ['seeds']  #, 'wine', 'glass', 'pima']
dataset_name = data[0]

raw_data = imp.loadCSV("data/" + dataset_name + ".data")

#sns.pairplot(pd.DataFrame(raw_data, columns=['sepal lenght', 'sepal width', 'petal length', 'petal width', 'class']), hue="class")
#plt.show()
from sklearn.cluster import KMeans

#classifiers = [GaussianNB, CategoricalNB]
dicretizations = [
    KMeansPartitioning, EqualWidthPartitioning, EqualDepthPartitioning
]

measurment = []
## GaussianNB
classifier = GaussianNB
k_folds = [2, 5, 10]

for k_fold in k_folds:
    for strat in [True, False]:
예제 #26
0
        else:
            log.error(
                "Proceso: Orquestador||Mensaje: La web indicada no existe||Error: "
                + str(e))
            sys.exit()

        #2.1 Nombramiento de fichero de entrada y salida
        if item == 'Arbol':
            fichero_input = path_entrada + "/" + web + transaccion + tipologia
            fichero_output = path_resultados + "/" + fecha + "_Resultados_" + web + "_" + transaccion + "_" + tipologia + "_" + item
        elif item == 'Inmuebles':
            fichero_input = path_entrada + "/" + fecha + "_arbol_" + web + "_" + transaccion + "_" + tipologia
            fichero_output = path_resultados + "/" + fecha + "_Resultados_" + web + "_" + transaccion + "_" + tipologia + "_" + item
        elif item == 'Bancos':
            fichero_input = path_entrada + "/" + fecha + "arbol_" + web + "_" + transaccion + "_" + tipologia + "_bancos"
            fichero_output = path_resultados + "/" + fecha + "_Resultados_" + web + "_" + transaccion + "_" + tipologia + "_" + item
        else:
            log.error(
                "Proceso: Orquestador||Mensaje: El item seleccionado no existe.Por favor selecciono entre [Arbol,Inmuebles,Bancos]"
            )
            sys.exit()

        #2.2 Creacion de lista a partir del fichero importado y creacion de lista de salida
        lista_input = Import.fichero(fichero_input, "csv", log)
        lista_input = manager.list(lista_input)
        resultados = manager.list(resultados)

        #2.3 Lanzamiento multiproceso en funcion del item seleccionado
        lanzarScraper(web, item, url_base, diccionario, lista_input,
                      resultados, lock)
예제 #27
0
                        required=False)
    parser.add_argument("-g",
                        "--use-design-global-origin",
                        help="Flag to use global origin.",
                        required=False,
                        action="store_true")
    parser.add_argument("-v",
                        "--verbose",
                        help="Print meshlabscript outputs.",
                        required=False,
                        action="store_true")
    args = parser.parse_args()
    # Open file
    doc = FreeCAD.newDocument("temp")
    FreeCAD.setActiveDocument("temp")
    freecadimport.insert(args.cadfile, "temp")

    # Gather the unique shapes, and clone parts
    unique_objs = []
    parts = {}
    num_objs = 0
    for obj in doc.Objects:
        new_shape = True
        if obj.TypeId == "Part::Feature":
            num_objs += 1
            for uobj in unique_objs:
                if uobj.Shape.isPartner(obj.Shape):
                    new_shape = False
                    parts[uobj.Label]["placements"] += [[
                        obj.Label, obj.Placement
                    ]]
예제 #28
0
App.getDocument('Unnamed').recompute()

f = FreeCAD.getDocument('Unnamed').addObject('Part::Extrusion', 'Extrude')
f = App.getDocument('Unnamed').getObject('Extrude')
f.Base = App.getDocument('Unnamed').getObject('Sketch')
f.DirMode = "Custom"
f.Dir = App.Vector(0.000000000000000, 0.000000000000000, 1.000000000000000)
f.DirLink = None
f.LengthFwd = 4.500000000000000
f.LengthRev = 0.000000000000000
f.Solid = True
f.Reversed = False
f.Symmetric = False
f.TaperAngle = 0.000000000000000
f.TaperAngleRev = 0.000000000000000
# Gui.ActiveDocument.Extrude.ShapeColor=Gui.ActiveDocument.Sketch.ShapeColor
# Gui.ActiveDocument.Extrude.LineColor=Gui.ActiveDocument.Sketch.LineColor
# Gui.ActiveDocument.Extrude.PointColor=Gui.ActiveDocument.Sketch.PointColor
# f.Base.ViewObject.hide()

doc.recompute()

__objs__=[]
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("Extrude"))
import Import
Import.export(__objs__, u"C:/Users/asea2/Desktop/"
                           u"PycharmProjects/Prikolno/freecadfiles/imyafila.step")

del __objs__

예제 #29
0
    return vertices


def generate_quad(vertices):
    edges = 4 * [None]
    for i in range(4):
        edges[i] = Part.makeLine(tuple(vertices[i]),tuple(vertices[(i+1)%4]))

    wires = 4 * [None]
    wires[0] = Part.Wire([edges[0],edges[3]])
    wires[1] = Part.Wire([edges[2],edges[1]])
    wires[2] = Part.Wire([wires[0],wires[1]])
    Part.show(wires[2])

doc = FreeCAD.newDocument("tmp")
print "Document created"

pts, quads = parse_all_from_folder('./PetersSchemeInput/cantilever')
print "Stuff parsed"

for quad in quads:
    vertices = get_vertices(quad, pts)
    generate_quad(vertices)

print "points plotted"

__objs__ = FreeCAD.getDocument("tmp").findObjects()

Import.export(__objs__, "./torus_mesh.step")
print ".step exported"
App.activeDocument().addObject("Part::Cut", "TibiaCutted")
App.activeDocument().TibiaCutted.Base = Tibia
App.activeDocument().TibiaCutted.Tool = CutProth

App.activeDocument().addObject("Part::MultiCommon", "TibialCut")
App.activeDocument().TibialCut.Shapes = [
    Tibia2,
    CutProth2,
]

doc.recompute()

__objs__ = []
__objs__.append(FreeCAD.getDocument("Noname").getObject("TibiaCutted"))
Import.export(__objs__, u"CWD\Output\NAME\Tibia_NAME_cutted_aALPHA.step")
del __objs__

__objs__ = []
__objs__.append(FreeCAD.getDocument("Noname").getObject("TibialCut"))
Import.export(__objs__, u"CWD\Output\NAME\Tibia_NAME_cut_aALPHA.step")
del __objs__

__objs__ = []
__objs__.append(FreeCAD.getDocument("Noname").getObject("Proth"))
Import.export(__objs__, u"CWD\Output\NAME\Implant_SIZE_WLS_NAME_aALPHA.step")
del __objs__

__objs__ = []
__objs__.append(FreeCAD.getDocument("Noname").getObject("Cement"))
Import.export(__objs__, u"CWD\Output\NAME\C_SIZE_WLS_NAME_aALPHA.step")
예제 #31
0
def main(path=None):
    Import.import_path = path

    # if date is None:
    #     date = dt.date.today()
    #
    # if long:
    #     Import.import_dates = pd.date_range(end=date, periods=30)
    # else:
    #Import.import_dates = [date]

    dfs, prices = Import.import_files()

    if (len(dfs) == 0) or (prices is None):
        return

    df3 = None
    if 'SEM03' in dfs.keys():
        df = dfs['SEM03']
        if df.shape[0] > 0:
            filterr = df.TradeType.apply(
                lambda trade_type: trade_type not in repo_trade_types)
            df.TradeTime = pd.to_datetime(
                df.apply(lambda x: str(x.TradeDate) + ' ' + str(x.TradeTime),
                         axis=1)).dt.tz_localize(None)
            df = process_trades_and_bids(df, prices, filterr)
            df = populate_trades_intervals(df)
            df3 = df

    df2 = None
    if 'SEM02' in dfs.keys():
        df = dfs['SEM02']
        df = Criteria.process_fr(df, Criteria.limit_type_codes, ['R', 'FR'])
        df = Criteria.process_fr(df, Criteria.market_type_codes, ['P', 'PR'])
        # filterr = df.BoardName.apply(lambda name: not name.startswith('РЕПО'))
        # df = process_trades_and_bids(df, prices, 'EntryTime')
        df2 = df

    if 'SEM21' in dfs.keys():
        df21 = dfs['SEM21']
        df21['Volume'] = df21['Volume'].astype(float)
        if df3 is not None:
            df3 = check_volume_breaches(df3, df21)
            df3_dates = df3.TradeDate.unique()
            try:
                coeffs = Import.import_coeffs(df3_dates)
                if coeffs is not None:
                    df3 = df3.merge(coeffs,
                                    on=['TradeDate', 'SecurityId'],
                                    how='left')
            except:
                print('Couldn\'t import coeffs')

            df3 = Criteria.calculate_criteria(df3, df21, True)

            try:
                if_messages = Import.import_if(df3_dates)
                df3 = check_if(df3, if_messages, [])
            except Exception as e:
                print(f'Couldn\'t check interfax: {e}')

            df3.to_excel('SEM03_result.xlsx', index=False, encoding='utf-8')

        if df2 is not None:
            df2 = df2.merge(df21,
                            on=['BoardId', 'SecurityId', 'TradeDate'],
                            how='left')
            df2.to_excel('SEM02_result.xlsx', index=False, encoding='utf-8')
            if df3 is not None:
                df3 = df3.merge(df2[['OrderNo', 'R', 'FR', 'P', 'PR']],
                                on='OrderNo',
                                how='left')
                df3.to_excel('SEM03_result.xlsx',
                             index=False,
                             encoding='utf-8')
예제 #32
0
파일: Network.py 프로젝트: sybila/BCSgen
	def createNetwork(self, bcsModelFile):
		rules, state = Import.import_model(bcsModelFile)
		for rule in rules:
			self.addEdge(rule.getLeftHandSide(), rule.getRightHandSide(), rule)
		self.introduceNewAgents(state)
		return state
예제 #33
0
    else:
        grey = False

    if args.recursive is not None:
        rec = True
    else:
        rec = False

    if grey:
        IMAGE = cv2.imread(args.input, 0)
    else:
        IMAGE = cv2.imread(args.input, 1)

        # Play with these arguments:
    window_size = 4
    gallery_im_siz = 32

    gallery = Import.Importer(args.gallery, './output/', recursion=rec, im_size=gallery_im_siz, Gray=grey,
                              verbose=verbose)

    ws = window_size
    ncluster = min(len(gallery), (IMAGE.shape[0] * IMAGE.shape[1]) // ((ws + 1) ** 2))
    C = Core.Core(IMAGE, window_size, n_cluster=ncluster)

    # out, esum = C.build(gallery, target_pixel_size=args.scale // window_size)
    out = C.build_cosine(gallery)
    esum = 0
    out = np.uint8(out)
    print('Error = {}'.format(esum))
    cv2.imwrite(args.output, out)
예제 #34
0
    pts = parse_csv_into_matrix(folder_path+'/verts_fine.csv',float)

    return pts


def generate_point(vertex):
    free_cad_vect = FreeCAD.Vector(vertex[0],vertex[1],vertex[2])
    Part.show(Part.Vertex(free_cad_vect))


doc = FreeCAD.newDocument("tmp")
print "Document created"

pts = parse_all_from_folder('./PetersSchemeInput/torus')
print "Stuff parsed"

i=0
for vertex in pts:
    i+=1
    if i % 1000 == 0:
        print i
    generate_point(vertex)

print "points plotted"

__objs__ = FreeCAD.getDocument("tmp").findObjects()

Import.export(__objs__, "./torus_pointcloud.step")
print ".step exported"
def create_grating(slit_l,slit_h,slit_p,strut_w,num_col,num_row,fillet,col_or_ash):
    # Input Dimensions #
    strut_h = slit_h
    film_mrgn = strut_w*10
    film_w = (slit_l + strut_w)*num_col-strut_w+2*film_mrgn
    film_h = (slit_h + slit_p)*num_row-strut_h+2*film_mrgn
    
    # Create new document #
    doc = FreeCAD.newDocument("myDoc")
    
    # Create Film #
    film = Draft.makeRectangle(film_w,film_h)
    film.Label = 'myFilm'
    move_film = FreeCAD.Vector(-film_mrgn,-film_mrgn,0)
    Draft.move(film,move_film)
    
    # Create single slit #
    slit = Draft.makeRectangle(slit_l,slit_h)
    slit.Label = 'mySlit'
    long_slit = (slit_l+strut_w)*num_col-strut_w
    
    # Fillet #
    slit.FilletRadius = slit_h/2.01*fillet
        
    if col_or_ash == 1:
        '''COLUMNAR FORM'''
        # Slit Matrix #
        array = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                FreeCAD.Vector(0,slit_h+slit_p,0),num_col,num_row)
        grating = cut_soowon(film,array)
        
    elif col_or_ash == 2:
        '''ASHLAR FORM'''
        # Slit Matrix #
        row_arr1 = int(math.ceil(num_row/2.))
        row_arr2 = int(math.floor(num_row/2.))
        
        array1 = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                 FreeCAD.Vector(0,2*(slit_h+slit_p),0),num_col,row_arr1)
        array2 = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                 FreeCAD.Vector(0,2*(slit_h+slit_p),0),num_col-1,row_arr2)
        #edge_l = (slit_l-strut_w)/2
        #edge = Draft.makeRectangle(edge_l,slit_h)
        #edge.FilletRadius = slit_h/2.01*fillet
        #edge_array = Draft.makeArray(edge,FreeCAD.Vector(long_slit-edge_l,0,0),\
        #                             FreeCAD.Vector(0,2*(slit_h+slit_p),0),2,row_arr2)
        
        move_array2 = FreeCAD.Vector((slit_l+strut_w)/2,slit_h+slit_p,0)
        #move_edge_array = FreeCAD.Vector(0,slit_h+slit_p,0)
        Draft.move(array2,move_array2)
        #Draft.move(edge_array,move_edge_array)

        step1 = cut_soowon(film,array1)
        grating = cut_soowon(step1,array2)
        #step2 = cut_soowon(step1,array2)
        #grating = cut_soowon(step2,edge_array)

    elif col_or_ash == 3:
        num_strut = num_col - 1
        grating = film
        for x in xrange(1,num_row+1):
            
            pseudo_strut = random.randint(num_strut-int(math.ceil(num_strut/2.)),\
                                          num_strut+int(math.ceil(num_strut/2.)))
            new_slit_l = (long_slit- pseudo_strut*strut_w)/(pseudo_strut+1)
            new_slit = Draft.makeRectangle(new_slit_l,slit_h)
            new_slit.FilletRadius = slit_h/2.01*fillet

            move_new_slit = FreeCAD.Vector(0,(x-1)*(slit_h+slit_p),0)
            Draft.move(new_slit,move_new_slit)
            array = Draft.makeArray(new_slit,FreeCAD.Vector(new_slit_l+strut_w,0,0), \
                                             FreeCAD.Vector(0,slit_h+slit_p,0),(pseudo_strut+1),1)
            grating = cut_soowon(grating,array)

    elif col_or_ash == 4:
        '''This function randomize the starting point of the strut on columnar form but maintaining
        strut density'''
        sigma = 0.01 #Standard Deviation: 10 nm #
        for x in xrange(1,num_row+1):
            first_slit_l = random.gauss(slit_l, sigma)
            if first_slit_l < slit_l:
                last_slit_l = slit_l - first_slit_l
            else:
                last_slit_l = 2*slit_l - first_slit_l
                first_slit_l = first_slit_l - slit_l

            first_slit = Draft.makeRectangle(first_slit_l,slit_h)

            move_first = FreeCAD.Vector(0, (x-1)*(slit_h+slit_p) ,0)

            Draft.move(first_slit,move_first)
            
            middle_array = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                 FreeCAD.Vector(0,1,0),num_col-1,1)

            move_middle = FreeCAD.Vector(first_slit_l+strut_w,(x-1)*(slit_h+slit_p),0)

            Draft.move(middle_array,move_middle)

            last_slit = Draft.makeRectangle(last_slit_l,slit_h)

            move_last = FreeCAD.Vector(first_slit_l+(strut_w+slit_l)*(num_col-1)+strut_w,\
                                       (x-1)*(slit_h+slit_p),0)

            Draft.move(last_slit,move_last)
            film = cut_soowon(film,first_slit)
            film = cut_soowon(film,middle_array)
            film = cut_soowon(film,last_slit)
        grating = film

    elif col_or_ash == 5:
        '''RANDOMIZED ASHLAR'''
        sigma = 0.01 #Standard Deviation: 10 nm #
        num_arr1 = int(math.ceil(num_row/2.))
        num_arr2 = num_row - num_arr1

        for x in xrange(1,num_arr1+1):
#            first_slit_l = random.uniform(slit_l-2*strut_w , slit_l+2*strut_w)
#            (long_slit - first_slit_l)
#            if first_slit_l < slit_l:
#                last_slit_l = slit_l - first_slit_l
#            else:
#                last_slit_l = 2*slit_l - first_slit_l
#                first_slit_l = first_slit_l - slit_l

#            first_slit = Draft.makeRectangle(first_slit_l,slit_h)

#            move_first = FreeCAD.Vector(0, (x-1)*2*(slit_h+slit_p) ,0)

#            Draft.move(first_slit,move_first)


            rand_start = random.uniform(-strut_w , strut_w)
            
            array = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                FreeCAD.Vector(0,1,0),num_col,1)
            move_array = FreeCAD.Vector(rand_start,(x-1)*2*(slit_h+slit_p),0)
            Draft.move(array,move_array)
            film = cut_soowon(film,array)
            
#            middle_array = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
#                                 FreeCAD.Vector(0,1,0),num_col-1,1)

#            middle = FreeCAD.Vector(0,(x-1)*2*(slit_h+slit_p),0)
#            move_middle = FreeCAD.Vector(first_slit_l+strut_w,(x-1)*2*(slit_h+slit_p),0)

#            Draft.move(middle_array,move_middle)

#            last_slit = Draft.makeRectangle(last_slit_l,slit_h)

#            move_last = FreeCAD.Vector(first_slit_l+(strut_w+slit_l)*(num_col-1)+strut_w,\
#                                       (x-1)*2*(slit_h+slit_p),0)

#            Draft.move(last_slit,move_last)
#            film = cut_soowon(film,first_slit)
#            film = cut_soowon(film,middle_array)
#            film = cut_soowon(film,last_slit)
            
            
        for x in xrange(1,num_arr2+1):
            '''edge_l = (slit_l-strut_w)/2
            
            first_slit_l = random.uniform(edge_l-2*strut_w, edge_l+2*strut_w)
            first_slit = Draft.makeRectangle(first_slit_l,slit_h)
            move_first = FreeCAD.Vector(0, (2*x-1)*(slit_h+slit_p) ,0) # move slit to the 2nd layer. Then, move up to every other layer.
            Draft.move(first_slit,move_first)
            
            middle_array = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                 FreeCAD.Vector(0,1,0),num_col-1,1) # Number of slit is going to be one less then the number of column.
            move_middle = FreeCAD.Vector(first_slit_l+strut_w,(2*x-1)*(slit_h+slit_p),0)
            Draft.move(middle_array,move_middle)

            last_slit_l = slit_l - strut_w - first_slit_l
            last_slit = Draft.makeRectangle(last_slit_l,slit_h)
            move_last = FreeCAD.Vector(first_slit_l+(strut_w+slit_l)*(num_col-1)+strut_w,\
                                       (2*x-1)*(slit_h+slit_p),0)
            Draft.move(last_slit,move_last)
            film = cut_soowon(film,first_slit)
            film = cut_soowon(film,middle_array)
            film = cut_soowon(film,last_slit)'''
            rand_start = random.uniform(-strut_w , strut_w)
            
            array = Draft.makeArray(slit,FreeCAD.Vector(slit_l+strut_w,0,0),\
                                FreeCAD.Vector(0,1,0),num_col-1,1)
            move_array = FreeCAD.Vector(rand_start+(slit_l+strut_w)/2,(2*x-1)*(slit_h+slit_p),0)
            Draft.move(array,move_array)
            film = cut_soowon(film,array)
        grating = film

    # Generate geometry #
    FreeCAD.ActiveDocument.recompute()
    
    # Export #
    __objs__=[]
    __objs__.append(grating)
    Import.export(__objs__,"C:/Users/Soowon Kim/Desktop/grating.step")
    del __objs__
예제 #36
0
import numpy as np
import Analysis
import Import
import BP

print("正在训练神经网络")
# 训练数据输入
TrainSet_x = Import.read_case('DataFile/StatusAndResult.xls', 'Sheet1_x')
TrainSet_y = Import.read_case('DataFile/StatusAndResult.xls', 'Sheet2_y')
# 训练神经网络
nt = BP.training(TrainSet_x, TrainSet_y)
# 训练结果保存
Import.write_syn('DataFile/Syn.xls', nt.weights)
# 测试数据输入
Test_input = np.array(Import.read_case('DataFile/Test.xls', 'Sheet1_x'))
Test_output = Import.read_case('DataFile/Test.xls', 'Sheet2_y')
# 测试数据输出
result = BP.forward(Test_input, nt)[nt.num_layers - 1]
# 测试结果整理
result_sort = Analysis.sort(result)
print("\n整理后的测试结果\n", result_sort)
# 正确率计算
rate = Analysis.rate(result, Test_output)
print("\n测试正确率为:\n", rate)
예제 #37
0
    cutobject.Tool = toolobject

    # Keep the reference to the subsequent cut
    cut_master = cutobject

doc.recompute()

doc.saveCopy("extrude_test_with_outline_with_cuts" + ".FCStd")

# doc.activeDocument().addObject("Part::Cut","Cut")
# doc.activeDocument().Cut.Base = doc.activeDocument().SVGExtrudeOutline
# doc.activeDocument().Cut.Tool = doc.activeDocument().SVGExtrude

# Save as step

Import.export([doc.getObject(cut_master.Name)], "final_export.step")

exit(0)
# # # Iteratively join all the objects together
# # reduce_join(joined_objects, doc)
# # print(joined_objects)

# doc.recompute()
# doc.saveCopy("join_test_final_step" + ".FCStd")

# # Now that all the joins are done, refine the shape by removing splinters
# for i in range(len(joined_objects)):
#     feature = doc.getObject(joined_objects[i])
#     refined_shape = doc.addObject("Part::Feature", "RefinedShape")
#     refined_shape.Shape = feature.Shape.removeSplitter()
예제 #38
0
if len(sys.argv)<3:
  print ("Usage: sys.argv[0] <in_file> <out_file>")
  sys.exit(1)

iname=sys.argv[1]
oname=sys.argv[2]

print('Importing : '+iname)
FreeCAD.loadFile(iname)

# iterate through all objects
for o in App.ActiveDocument.Objects:
  # find root object and export the shape
  #print(dir(o))
  #print(o.Name)
  if o.TypeId == 'App::Part' :
     #print(o.TypeId) 
     print('Exporting STEP file : '+oname)
     print('This can be a very slow process')
     print('for large files Please be patient')
     #Import.export([o],"/tmp/test4.step")
     Import.export([o],oname)
     sys.exit(0)

sys.exit(0)

print ("Error: can't find any object")
sys.exit(1)

예제 #39
0
            #Part.show(Part.Vertex(control_point))

    Part.show(patch.toShape())


doc = FreeCAD.newDocument("tmp")
print "Document created"

bq_idx, bq_pts, bc_idx, bc_pts = parse_all_from_folder('./TorusFairBezier')
print "Stuff parsed"

deg = 2
for patch in bq_idx:
    vertices = get_vertices(patch, bq_pts)
    generate_bezier_patch(deg, vertices)

print "biquadratic patches plotted"

deg = 3
patch=bc_idx
for patch in bc_idx:
    vertices = get_vertices(patch, bc_pts)
    generate_bezier_patch(deg, vertices)

print "bicubic patches plotted"

__objs__ = FreeCAD.getDocument("tmp").findObjects()

Import.export(__objs__, "./FairTorus.step")
print ".step exported"