def shell(shellCount,extrusionWidth,layer): #This also needs to be made smarter. It can't handle intersections that change the order of the loop yet. ''' This function takes a layer which has been through straighten and order, and forms the perimeter lines which will actually be extruded from the loops. Stores perimeter lines in layer.shells as a list of shell groups. Each shell group is a list of shells with varying insets. Shells are ordered lists of edges similar to loops. ''' insets = [n*extrusionWidth+extrusionWidth/2.0 for n in range(shellCount)] shellGroups = [] for loop in layer.loops: shells = [] for inset in insets: shell = [] for edge in loop: left = sp.cross(sp.array([0,0,1]),edge.dir[0]) shell.append(Basics.edge(edge.a+left*inset,edge.b+left*inset)) for index in range(len(shell)-1): activeEdge = shell[index] nextEdge = shell[index+1] if activeEdge.check2dintersect(nextEdge): intersect = activeEdge.point2dIntersect(nextEdge) shell[index]=Basics.edge(activeEdge.a,intersect) shell[index+1]=Basics.edge(intersect,nextEdge.b) activeEdge = shell[-1] nextEdge = shell[0] if activeEdge.check2dintersect(nextEdge): intersect = activeEdge.point2dIntersect(nextEdge) shell[-1]=Basics.edge(activeEdge.a,intersect) shell[0]=Basics.edge(intersect,nextEdge.b) shells.append(shell) shellGroups.append(shells) layer.shells = shellGroups
def addConstraints(self, Solver): if self.label in ConjLabelEval: parameters = [p for pair in self.pairs for p in pair] for pair in self.pairs: func = self.pair_func(pair, self.op_conj) Solver.add( CPS.FunctionConstraint(Basics.FuncWrapper(func, pair)), pair) if self.label in DisjLabelEval: parameters = [p for pair in self.pairs for p in pair] Solver.add( CPS.FunctionConstraint( Basics.FuncWrapper(self.DisjEval, parameters)), parameters)
def objectRemoval(image, remove_mask=None, preserve_mask=None, nn=0, nm=0, rmask=False, pmask=False): img = image.copy() n,m = image.shape[:2] if rmask: nn, nm = Basics.maskSize(remove_mask) if nn < nm: #Eliminamos las filas print("\nNumero de seams horizontales a eliminar: ", nn) #Rotamos img = np.rot90(img, k=-1, axes=(0, 1)) if rmask: remove_mask = np.rot90(remove_mask, k=-1, axes=(0, 1)) if pmask: preserve_mask = np.rot90(preserve_mask, k=-1, axes=(0, 1)) #Eliminamos las horizontales que sobren for i in range(abs(nn)): print("Eliminamos ", i) a, b, path = Basics.verticalSeam(img, energias.forwardEnergy, remove_mask, preserve_mask, rmask, pmask) img = Basics.removeSeam(img, path) if rmask: remove_mask = Basics.removeSeam(remove_mask, path) if pmask: preserve_mask = Basics.removeSeam(preserve_mask, path) #Rotamos return np.rot90(img, k=1, axes=(0, 1)) # return img else: print("\nNumero de seams verticales a eliminar: ", abs(nm)) #Eliminamos las verticales que sobren for i in range(abs(nm)): print("Eliminamos", i) a, b, path = Basics.verticalSeam(img, energias.forwardEnergy, remove_mask, preserve_mask, rmask, pmask) img = Basics.removeSeam(img, path) if rmask: remove_mask = Basics.removeSeam(remove_mask, path) if pmask: preserve_mask = Basics.removeSeam(preserve_mask, path) return img
def edgeWrap(self, e, n, up=True): """ Similar to edgeShift, but with edge broken up into n segments of equal XY length to fit the function better. """ points = [e.a + m * e.dir[0] * e.length / n for m in range(n)] + [e.b] shiftPoints = [self.pointShift(p, up) for p in points] return [Basics.edge(shiftPoints[k], shiftPoints[k + 1]) for k in range(n)]
def triShift(self, t, u=1): """ Returns tri t with its vertices shifted vertically by their functional values. No interpolation is performed by this function. """ return Basics.tri( [self.pointShift(t.points[0], u), self.pointShift(t.points[1], u), self.pointShift(t.points[2], u)] )
def main(run=RUN, load=LOAD, verbose=VERBOSE): # Initialize Log File print("\nRepeatedMergers.py\n") start_time = datetime.now() # Set basic Parameters print(" - Loading Basics") start = datetime.now() base = Basics.Basics(run) stop = datetime.now() print((" - - Loaded after {:s}".format(str(stop - start)))) # Load Repeated Mergers # repeats = getRepeats(run, base, load=False, verbose=verbose) # Process Repeat Data # lowerInter, numPast, numFuture = analyzeRepeats(interval, next, last, base) return interval, lowerInter, numPast, numFuture # Plot Repeat Data # gwplot.plotFig4_RepeatedMergers(interval, lowerInter, numFuture) end_time = datetime.now() durat = end_time - start_time print(("Done after {:s}\n\n".format(str(durat)))) return
def stl_import(fileName): # Imports an ASCII stl file coontaining ONE solid model. output = None # Holding variable for the output mesh object currentTris = [] # list of tris which have been created but not yet included into a solid. currentPoints = [] # list of points which have been created but not yet included in a tri # Support for arbitrary normals from file removed for now # currentNormal=None #Holding variable for one normal vector which has not yet been included in a tri. inMesh = None # Boolean flag to ensure currentTris isn't populated outside a mesh. inTri = False # Boolean flag to ensure currentPoints isn't populated outside a tri stl = open(fileName, "r") for line in stl: # Terminating a tri resets currentPoints, and stores the tri in currentTris lineList = line.split() if lineList[0] == "outer": continue # I don't understand why loops exist. if lineList[0] == "endloop": continue # I don't understand why loops exist. if lineList[0] == "endfacet": if not inTri: print "Error: endfacet found outside of tri." return currentTris.append(Basics.tri(currentPoints)) currentPoints = [] # Support for arbitrary normals from file removed for now # currentNormal=[] inTri = False continue # Initiating a new mesh if lineList[0] == "solid": if inMesh: print "Error: solid initiated inside another solid." return inMesh = True continue # Ending a mesh if lineList[0] == "endsolid": if not inMesh: print "Error: endsolid found outside of mesh." return inMesh = False output = mesh.mesh(currentTris) continue # Initiating a new triangle wipes all old points. if lineList[0] == "facet": if inTri: print "Error: facet initiated inside another facet." return inTri = True # Support for arbitrary normals from file removed for now # currentNormal=sp.array([[float(lineList[2]),float(lineList[3]),float(lineList[4])],[0,0,0]]) continue # Put vertices into currentPoints list if lineList[0] == "vertex": if len(currentPoints) > 2: print "Error, nontriangle facet in file." return currentPoints.append(sp.array([float(lineList[1]), float(lineList[2]), float(lineList[3])])) continue if output != None: return output else: print "Error: endsolid not found!" return
def dDeriv(self, v, p): """ Returns the directional derivative of f along v at p as a scalar. """ v[0][2] = 0 # Flattening v if it wasn't already. uv = Basics.unit(v)[0] uv = sp.array([uv[0], uv[1]]) # Turning uv 2D so that the dot product works return sp.dot(self.grad(p), uv)
def triShift(self, t, u=1): ''' Returns tri t with its vertices shifted vertically by their functional values. No interpolation is performed by this function. ''' return Basics.tri([ self.pointShift(t.points[0], u), self.pointShift(t.points[1], u), self.pointShift(t.points[2], u) ])
def dDeriv(self, v, p): ''' Returns the directional derivative of f along v at p as a scalar. ''' v[0][2] = 0 #Flattening v if it wasn't already. uv = Basics.unit(v)[0] uv = sp.array([uv[0], uv[1]]) #Turning uv 2D so that the dot product works return sp.dot(self.grad(p), uv)
def edgeWrap(self, e, n, up=True): ''' Similar to edgeShift, but with edge broken up into n segments of equal XY length to fit the function better. ''' points = [e.a + m * e.dir[0] * e.length / n for m in range(n)] + [e.b] shiftPoints = [self.pointShift(p, up) for p in points] return [ Basics.edge(shiftPoints[k], shiftPoints[k + 1]) for k in range(n) ]
def initialize(self, Model): self.regulator = self.regulator.initialize(Model) self.target = self.target.initialize(Model) accepted = False for comp, thrs in self.regulator.targets: if comp == self.target: if self.thr in thrs: accepted = True break if not accepted: raise Exception( 'Non-existing threshold %i for interaction %s->%s' % (self.thr, self.regulator, self.target)) ParsLHS = [ p for p in self.target.parameters if self.thr in p.context[self.regulator] ] ParsRHS = [ p for p in self.target.parameters if self.thr - 1 in p.context[self.regulator] ] if self.formula: self.formula.initialize(Model) prob = CPS.Problem() pairs = [] for p1, p2 in zip(ParsLHS, ParsRHS): for comp in Model.components: domain = list(p1.context.get(comp, range(comp.max + 1))) prob.addVariable(comp.index, domain) prob.addConstraint( CPS.FunctionConstraint( Basics.FuncWrapper(self.formula, Model.components)), Model.components) if prob.getSolution(): pairs.append((p1, p2)) prob.reset() self.pairs = pairs else: self.pairs = zip(ParsLHS, ParsRHS) self.requirements = [] if self.label in ConjLabelEval: self.op_conj = ConjLabelEval[self.label] self.requirements.append(self.ConjEval) if self.label in DisjLabelEval: self.op_disj = DisjLabelEval[self.label] self.requirements.append(self.DisjEval)
def chop(self,layerHeight): #This is chunky and bad. Needs to be done much more intelligently for anything beyond proof of concept. The number of layers calculation sucks. #Returns an ordered list of layers. Each layer consists of a list of edges which represent the intersection of self with the plane z=(layer #-1/2) * layerHeight. The first item in each layer is a point inside the mesh. height = self.region[0][2]-self.region[1][2] layers= [] for layer in range(int(sp.floor(height/layerHeight))): #Adding 0.5*layerHeight to height of cutting plane so that the plane will be as representative as possible of the general layer volume. cuttingPlane = Basics.plane(sp.array([0,0,(layer+0.5)*layerHeight]),sp.array([[0,0,1],[0,0,0]])) edges = [] for triangle in self.tris: intersect = triangle.plane_intersect(cuttingPlane) if intersect[1]==2: edges.append(intersect[0]) layers.append(layerClass.layer(edges,layerHeight,self)) return layers
def clean(loop): ''' Takes a straightened, ordered loop and cleans it up by removing any colinear edges with shared endpoints which can be represented as single edges. Returns a straight ordered loop with such substitions made. NOTE FOR NEXT WORK: This appproach makes the handling of the first/last edge interface ugly. Rewrite to save chains as pairs of start and end indices, and not combine anything until all edges have been checked and no chains can be further extended. ''' chain = False startChain = None cleanLoop = [] nextIndex = range(len(loop))[1:]+[0] for i in range(len(loop)): #Look at edge i and edge i+1 act = loop[i] nex = loop[nextIndex[i]] if sp.allclose(act.dir[0],nex.dir[0]): #As this is an ordered loop, we know they share endpoints. Thus if they share dirs these two edges can be replaced by a single one. if not chain: #chain flag remembers whether act can form a single edge with one or more edges before it in the loop. #If chain is false, we're starting a new chain of replaceable edges and need to remember where it starts. startChain = act chain = True elif chain: #If act and nex can't chain together, we've reached the end of any chain we may be in, and should add it to the output. chain = False cleanLoop.append(Basics.edge(startChain.a,act.b)) else: #If we don't have an active chain going, we need to put act into the output as is, since it can't chain with either of its neighbors. cleanLoop.append(act) #handle the hanging stuff from the end of the loop if chain: #If at the end of the for loop the chain flag is still raised, the first edge in loop can be combined with the last edge, and potentially more before it. #Also, the first edge in cleanLoop is guaranteed to have the same dir and startpoint as the first edge in loop. Therefore, if chain, we should combine the first edge in cleanLoop with the active chain. cleanLoop.append(Basics.edge(startChain.a,cleanLoop[0].b)) cleanLoop = cleanLoop[1:] return cleanLoop
def gcode_Export(path,e): #Converts a list of vectors to a gcode file for the path. e is the scalar relating E coordinates to distance moved. #Outputs gcode to the file output.gcode, with the file start.gcode at the beginning and end.gcode at the end. output = open('output.gcode','w') start = open('start.gcode','r') end = open('end.gcode','r') for line in start: output.write(line) output.write(G1([path[0][1][0],path[0][1][1],path[0][1][2],0]) + '\n') ePos = 0 for v in path: ePos +=e*Basics.vlength(v[0]) output.write(G1(v[0]+v[1],ePos) + '\n') for line in end: output.write(line)
def gcode_Export(path, e): #Converts a list of vectors to a gcode file for the path. e is the scalar relating E coordinates to distance moved. #Outputs gcode to the file output.gcode, with the file start.gcode at the beginning and end.gcode at the end. output = open('output.gcode', 'w') start = open('start.gcode', 'r') end = open('end.gcode', 'r') for line in start: output.write(line) output.write(G1([path[0][1][0], path[0][1][1], path[0][1][2], 0]) + '\n') ePos = 0 for v in path: ePos += e * Basics.vlength(v[0]) output.write(G1(v[0] + v[1], ePos) + '\n') for line in end: output.write(line)
def straighten(layer): #Changes all the edges in layer so that if the vector from a to b is regarded as forward, the inside of mesh is always to the left. #layer is a list of edges outputted by mesh.chop. It is NOT a layer. newEdges = [] startLen = len(layer.borders) for edge in layer.borders: right = sp.cross(edge.dir[0],sp.array([0,0,1])) testPoint = edge.midpoint() - 0.0001 * right #A testpoint which is a miniscule distance to the left of the line. if layer.mesh.contains(testPoint): newEdges.append(edge) #print "Did not flip" else: #print "Flipped" newEdges.append(Basics.edge(edge.b,edge.a)) if startLen!=len(newEdges): print "straighten procedure has lost edges." layer.borders = newEdges
def chop(self, layerHeight): #This is chunky and bad. Needs to be done much more intelligently for anything beyond proof of concept. The number of layers calculation sucks. #Returns an ordered list of layers. Each layer consists of a list of edges which represent the intersection of self with the plane z=(layer #-1/2) * layerHeight. The first item in each layer is a point inside the mesh. height = self.region[0][2] - self.region[1][2] layers = [] for layer in range(int(sp.floor(height / layerHeight))): #Adding 0.5*layerHeight to height of cutting plane so that the plane will be as representative as possible of the general layer volume. cuttingPlane = Basics.plane( sp.array([0, 0, (layer + 0.5) * layerHeight]), sp.array([[0, 0, 1], [0, 0, 0]])) edges = [] for triangle in self.tris: intersect = triangle.plane_intersect(cuttingPlane) if intersect[1] == 2: edges.append(intersect[0]) layers.append(layerClass.layer(edges, layerHeight, self)) return layers
def initialize(self, Model): self.formula.initialize(Model) self.comp = self.comp.initialize(Model) prob = CPS.Problem() self.ones = [] self.zeros = [] for p in self.comp.parameters: for comp in Model.components: domain = list(p.context.get(comp, range(comp.max + 1))) prob.addVariable(comp, domain) prob.addConstraint( CPS.FunctionConstraint( Basics.FuncWrapper(self.formula, Model.components)), Model.components) if prob.getSolution(): self.ones.append(p) else: self.zeros.append(p) prob.reset()
def initialize(self, Model): for f in self.formulas: f.initialize(Model) self.comp = self.comp.initialize(Model) prob = CPS.Problem() classes = {} for p in self.comp.parameters: Id = [] for func in self.formulas: for comp in Model.components: domain = list(p.context.get(comp, range(comp.max + 1))) prob.addVariable(comp, domain) prob.addConstraint( CPS.FunctionConstraint( Basics.FuncWrapper(func, Model.components)), Model.components) if prob.getSolution(): Id.append(True) else: Id.append(False) prob.reset() Id = tuple(Id) if Id in classes: classes[Id].append(p) else: classes[Id] = [p] self.classes = [tuple(c) for c in classes.values() if len(c) > 1] if not self.classes: raise Exception("'%s' defines only empty classes, please remove." % self.s) self.parameters = set([p for c in classes.values() for p in c])
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegressionCV from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import GradientBoostingClassifier from sklearn.linear_model import SGDClassifier ################################################## data = pd.read_csv("data6.txt") x = data.iloc[:, :-1].values y = data.iloc[:, -1].values ''' import matplotlib.pyplot as plt plt.scatter(x , y) plt.show(') ''' y = lp.LABLEENCODER(y, 2) ''' from sklearn.preprocessing import StandardScaler scale = StandardScaler() x2 = scale.fit_transform(x) ''' ################################################## def TRAIN_TEST_SPLIT(X_var, Y_var, TEST_SIZE=None, RAND_STATE=None): if TEST_SIZE == None: TEST_SIZE = randint(1, 3) * 10 try: from sklearn.cross_validation import train_test_split except DeprecationWarning as e: print(e, "NEED TO BE CHECKED !")
""" Created on Sat Jan 18 13:38:44 2020 @author: Paula """ import cv2 import Basics import SeamsCarving import energias ''' Leemos las imágenes de prueba ''' #Imágenes para comprobación de energía playa = Basics.readImage("imagenes/playa.jpg", 1) #Imágenes para content aware resizing campo = Basics.readImage("imagenes/campo.jpg", 1) arbol1 = Basics.readImage("imagenes/arbol1.jpg", 1) arco1 = Basics.readImage("imagenes/arco.jpg", 1) arco2 = Basics.readImage("imagenes/arco2.jpg", 1) hombre = Basics.readImage("imagenes/hombre.jpg", 1) roca = Basics.readImage("imagenes/roca.jpg", 1) banco = Basics.readImage("imagenes/banco.jpg", 1)
'final': { 'func_name': 'fully_connected', 'input_arg': 'inputs', 'layer_para': { 'inputs': None, 'num_outputs': n_action, 'biases_initializer': None, 'activation_fn': tf.nn.relu, 'weights_initializer': tf.ones_initializer() } } } state_in = tf.placeholder(shape=[1], dtype=tf.int32) N = basics.Network(state_in) N.build_layers(one_hot) N.add_layer_duplicates(output_layer, 1) # Create learning object and perform training RL_Train = RL.ContextualBandit(N, config_train, EG_Train) sess = tf.Session() RL_Train.process(sess, save=False, restore=False) # Extract training results action = RL_Train.recorder.record['NETWORK_ACTION'] reward = RL_Train.recorder.record['ENGINE_REWARD'] print(np.mean(reward)) df1 = pd.DataFrame()
def edgeShift(self, e, u=1): """ Returns edge e with its endpoints shifted vertically by their functional values*u. This does not interpolate at all, so large edges will have problems. """ return Basics.edge(self.pointShift(e.a, u), self.pointShift(e.b, u))
def box(mins,maxes): #defines a box mesh by its minimum and maximum values. a=sp.array([mins[0],mins[1],mins[2]]) b=sp.array([mins[0],maxes[1],mins[2]]) c=sp.array([maxes[0],maxes[1],mins[2]]) d=sp.array([maxes[0],mins[1],mins[2]]) e=sp.array([mins[0],mins[1],maxes[2]]) f=sp.array([mins[0],maxes[1],maxes[2]]) g=sp.array([maxes[0],maxes[1],maxes[2]]) h=sp.array([maxes[0],mins[1],maxes[2]]) return surfaces.closedMesh([ #Bottom Basics.tri([a,b,c]), Basics.tri([a,d,c]), #Top Basics.tri([e,f,g]), Basics.tri([e,h,g]), #Front Left Basics.tri([d,c,g]), Basics.tri([d,h,g]), #Front Right Basics.tri([b,c,g]), Basics.tri([b,f,g]), #Back Left Basics.tri([a,d,h]), Basics.tri([a,e,h]), #Back Right Basics.tri([a,b,f]), Basics.tri([a,e,f])])
def edgeShift(self, e, u=1): ''' Returns edge e with its endpoints shifted vertically by their functional values*u. This does not interpolate at all, so large edges will have problems. ''' return Basics.edge(self.pointShift(e.a, u), self.pointShift(e.b, u))
def testBasics(): assertEqual(Basics.toFloat(5), 5.0) assertEqual(Basics.round(8.2), 8) assertEqual(Basics.round(8.8), 9) assertEqual(Basics.round(-8.8), -9) assertEqual(Basics.floor(8.8), 8) assertEqual(Basics.floor(-8.8), -9) assertEqual(Basics.ceiling(8.8), 9) assertEqual(Basics.ceiling(-8.8), -8) assertEqual(Basics.truncate(8.8), 8) assertEqual(Basics.truncate(-8.8), -8) assertEqual(Basics.min(5, 3), 3) assertEqual(Basics.max(5, 3), 5) assertEqual( Basics.compare(4, 3), Order.GT ) assertEqual( Basics.compare(4, 4), Order.EQ ) assertEqual( Basics.compare(4, 8), Order.LT ) assertEqual(Basics.xor(True, False), True) assertEqual(Basics.xor(False, True), True) assertEqual(Basics.xor(True, True), False) assertEqual(Basics.xor(False, False), False) assertEqual(Basics.modBy(3, 0), 0) assertEqual(Basics.modBy(3, 6), 0) assertEqual(Basics.modBy(3, 7), 1) assertEqual(Basics.modBy(3, -8), 1) assertEqual(Basics.modBy(3, -7), 2) assertEqual(Basics.modBy(3, -6), 0) assertEqual(Basics.modBy(-3, 7), -2) assertEqual(Basics.remainderBy(3, 0), 0) assertEqual(Basics.remainderBy(3, 3), 0) assertEqual(Basics.remainderBy(3, 6), 0) assertEqual(Basics.remainderBy(3, 7), 1) assertEqual(Basics.remainderBy(3, -6), 0) assertEqual(Basics.remainderBy(3, -7), -1) assertEqual(Basics.remainderBy(3, -8), -2) assertEqual(Basics.remainderBy(-3, -7), -1) assertEqual(Basics.remainderBy(-3, 7), 1) assertEqual(Basics.negate(5), -5) assertEqual(Basics.negate(-5), 5) assertEqual(Basics.abs(5), 5) assertEqual(Basics.abs(-5), 5) assertEqual(Basics.clamp(100, 200, 80), 100) assertEqual(Basics.clamp(100, 200, 150), 150) assertEqual(Basics.clamp(100, 200, 220), 200) assertEqual(Basics.sqrt(81), 9) assertFloat(Basics.logBase(10, 100), 2) assertFloat(Basics.logBase(10, 1000), 3) assertFloat(Basics.logBase(2, 256), 8) assertFloat(Basics.e, 2.718281828459045) assertFloat(Basics.pi, 3.141592653589793) pi = Basics.pi assertFloat(Basics.degrees(180), pi) assertFloat(Basics.radians(2), 2) assertFloat(Basics.turns(1/2), pi) assertFloat(Basics.cos(pi/3), 0.5) assertFloat(Basics.sin(pi/6), 0.5) assertFloat(Basics.tan(pi/4), 1) assertFloat(Basics.acos(0.5), pi/3) assertFloat(Basics.asin(0.5), pi/6) assertFloat(Basics.atan(1), pi/4) assertFloat(Basics.atan(-1), -1 * pi/4) assertFloat(Basics.atan2(1, 1), pi/4) assertFloat(Basics.atan2(1, -1), 3 * pi/4) assertFloat(Basics.atan2(-1, -1), -3 * pi/4) assertFloat(Basics.atan2(-1, 1), -1 * pi/4) assertFloat(Basics.toPolar((3, 4)), ( 5, 0.9272952180016122)) assertFloat(Basics.toPolar((5,12)), (13, 1.1760052070951352)) assertFloat(Basics.fromPolar(Basics.toPolar((-3, -4))), (-3, -4)) assertFloat(Basics.div(7, 2), 3.5) assertTrue(Basics.isNaN(Basics.sqrt(-1))) assertTrue(Basics.isNaN(Basics.div(0, 0))) assertFalse(Basics.isNaN(Basics.div(1, 0))) assertFalse(Basics.isNaN(42)) assertFalse(Basics.isInfinite(Basics.div(0, 0))) assertFalse(Basics.isInfinite(Basics.sqrt(-1))) assertTrue(Basics.isInfinite(Basics.div(1, 0))) assertFalse(Basics.isInfinite(42)) assertEqual(Basics.identity(42), 42) assertEqual(Basics.always(42, 99), 42) assertTrue(hasattr(Basics, 'never')) # The following are << and >> in Basics.elm, but we put them # in Elm.py. assertEqual(Elm.lcompose(Basics.sqrt, double)(50), 10) assertEqual(Elm.rcompose(Basics.sqrt, double)(49), 14)
def stl_import(fileName): #Imports an ASCII stl file containing ONE solid model. output = None #Holding variable for the output mesh object currentTris = [ ] #list of tris which have been created but not yet included into a solid. currentPoints = [ ] #list of points which have been created but not yet included in a tri #Support for arbitrary normals from file removed for now # currentNormal=None #Holding variable for one normal vector which has not yet been included in a tri. inMesh = None #Boolean flag to ensure currentTris isn't populated outside a mesh. inTri = False #Boolean flag to ensure currentPoints isn't populated outside a tri stl = open(fileName, 'r') for line in stl: #Terminating a tri resets currentPoints, and stores the tri in currentTris lineList = line.split() if lineList[0] == 'outer': continue #I don't understand why loops exist. if lineList[0] == 'endloop': continue #I don't understand why loops exist. if lineList[0] == 'endfacet': if not inTri: print "Error: endfacet found outside of tri." return currentTris.append(Basics.tri(currentPoints)) currentPoints = [] #Support for arbitrary normals from file removed for now # currentNormal=[] inTri = False continue #Initiating a new mesh if lineList[0] == 'solid': if inMesh: print "Error: solid initiated inside another solid." return inMesh = True continue #Ending a mesh if lineList[0] == 'endsolid': if not inMesh: print "Error: endsolid found outside of mesh." return inMesh = False output = mesh.mesh(currentTris) continue #Initiating a new triangle wipes all old points. if lineList[0] == 'facet': if inTri: print "Error: facet initiated inside another facet." return inTri = True #Support for arbitrary normals from file removed for now # currentNormal=sp.array([[float(lineList[2]),float(lineList[3]),float(lineList[4])],[0,0,0]]) continue #Put vertices into currentPoints list if lineList[0] == 'vertex': if len(currentPoints) > 2: print "Error, nontriangle facet in file." return currentPoints.append( sp.array([ float(lineList[1]), float(lineList[2]), float(lineList[3]) ])) continue if output != None: return output else: print "Error: endsolid not found!" return
import Basics Basics.atomicDictionary()
def addConstraints(self, Solver): if self.parameters: Solver.add( CPS.FunctionConstraint( Basics.FuncWrapper(self.__call__, self.parameters)), self.parameters)