def testSpatialDistortion(self): strRefX = "spline-3-18x.edf" strRefY = "spline-3-18y.edf" self.loadTestImage([strRefX, strRefY]) edPluginSPD = self.createPlugin() strXMLInput = EDUtilsFile.readFileAndParseVariables(self.strReferenceInputFileName) xsDataInputSPDCake = XSDataInputSPDCake.parseString(strXMLInput) edPluginSPD.setDataInput(xsDataInputSPDCake) edPluginSPD.configure() edPluginSPD.getInputParameter() ######################################################################## # Enforce some values ######################################################################## edPluginSPD.dictGeometry["SpatialDistortionFile"] = os.path.join(self.getTestsDataImagesHome(), "frelon_spline_file_to_correct_SPD.spline") edPluginSPD.dictGeometry["TiltRotation"] = 18 edPluginSPD.dictGeometry["AngleOfTilt"] = 3 spline = Spline() spline.read(edPluginSPD.dictGeometry["SpatialDistortionFile"]) edPluginSPD.dictGeometry["PixelSizeX"], edPluginSPD.dictGeometry["PixelSizeY"] = spline.getPixelSize() edPluginSPD.createDisplacementMatrix(spline) edPluginSPD.cleanDispMat(edPluginSPD.getWorkingDirectory()) refX = fabio.openimage.openimage(os.path.join(self.getTestsDataImagesHome(), strRefX)).data obtX = fabio.openimage.openimage(os.path.join(edPluginSPD.getWorkingDirectory(), "frelon_spline_file_to_correct_SPD-tilted-x.edf")).data refY = fabio.openimage.openimage(os.path.join(self.getTestsDataImagesHome(), strRefY)).data obtY = fabio.openimage.openimage(os.path.join(edPluginSPD.getWorkingDirectory(), "frelon_spline_file_to_correct_SPD-tilted-y.edf")).data # print edPluginSPD.dictGeometry EDAssert.arraySimilar(obtX, refX , _fAbsMaxDelta=0.1, _strComment="X displacement Matrix is the same") EDAssert.arraySimilar(obtY, refY , _fAbsMaxDelta=0.1, _strComment="Y displacement Matrix is the same")
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() mc = self.canvas self.tool = None self.connectedLayer = None # Create actions self.action_spline = QAction( QIcon(":/plugins/spline/icon.png"), QCoreApplication.translate("spline", "Digitize Spline Curves"), self.iface.mainWindow()) self.action_spline.setObjectName("actionSpline") self.action_spline.setEnabled(False) self.action_spline.setCheckable(True) # Get the tool self.tool = Spline(self.iface) # Connect to signals for button behaviour self.action_spline.triggered.connect(self.digitize) self.iface.currentLayerChanged.connect(self.layerChanged) self.layerChanged() # to enable when plugin is loaded mc.mapToolSet.connect(self.deactivate) # Add actions to the toolbar self.iface.addToolBarIcon(self.action_spline)
def update_active_spline(self): coordinates = list() if self.active_spline is None: width = self.default_spline_width else: width = self.active_spline.width n_point_handles = len(self.point_handles) if n_point_handles == 1: self.canvas.delete(self.active_spline.handle) if n_point_handles >= 2: self.delete_active_spline() for handle in self.point_handles: x1, y1, x2, y2 = self.canvas.bbox(handle) x = (x1 + x2) / 2 y = (y1 + y2) / 2 coordinates.append([x, y]) new_spline = Spline(coordinates, width=width) new_spline.handle = self.canvas.create_spline(coordinates, width=width, stipple="gray50") self.canvas.tag_lower(new_spline.handle) self.canvas.tag_lower(self.image_handle) self.splines.append(new_spline)
def left2right_motion(robot, left_point, center, right_point, multiplier): # Move left and then move back with multiplier 2 robot.add_goal(cb2_robot.Goal(left_point, True, 'linear', radius=0.0)) while not robot.goals.empty(): robot.move_on_stop() print("moved left!") robot.add_goal(cb2_robot.Goal(center, True, 'linear', radius=0.0)) spliner = Spline(order=2) path = spliner.get_path(left_point[:3], center[:3], right_point[:3], n=100, bezier=False) #print(path) new = center new[2] = new[2] + 0.1 robot.add_goal(cb2_robot.Goal(new, True, 'linear', radius=0.0)) while not robot.goals.empty(): robot.move_on_error(multiplier=multiplier) print("moved to the right with spline")
def circuit(robot, start): spliner = Spline(order=2) # A point little to the right of the start point1 = list(start) point1[0] += 0.2 # a point above the previous point. # Should form curve path to this using previous point as a control point point2 = list(point1) point2[2] = point1[2] + 0.1 path = spliner.get_path(start[:3], point1[:3], point2[:3], n=50, bezier=True) for p in path: robot.add_goal(cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # Continue moving slightly up point3 = list(point2) point3[2] += 0.01 robot.add_goal(cb2_robot.Goal([point3[0], point3[1], point3[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # A little more up from point3 point4 = list(point2) point4[2] += 0.05 # A point to the left of point 4. # Should have a curve path from 3 to 5 via control point 4 point5 = list(point4) point5[0] -= 0.2 path = spliner.get_path(point3[:3], point4[:3], point5[:3], n=50, bezier=True) for p in path: robot.add_goal(cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # Point more to the left of point 5 and slightly below point6 = list(point5) point6[0] -= 0.3 point6[2] -= 0.1 # point down to point 6 #point7 = list(point6) #point7[2] -= 0.1 # move back to the start point in a curve path = spliner.get_path(point5[:3], point6[:3], start[:3], n=50, bezier=True) for p in path[:-5]: robot.add_goal(cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) while not robot.goals.empty(): robot.move_on_error(multiplier=2.0) robot.add_goal(cb2_robot.Goal([path[-1][0], path[-1][1], path[-1][2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) while not robot.goals.empty(): robot.move_on_error(multiplier=1.0) time.sleep(2)
def curve_motion(robot, current, goal, new): spliner = Spline(order=2) path = spliner.get_path(current[:3], goal[:3], new[:3], n=30, bezier=True) print(path) for p in path: robot.add_goal(cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process')) while not robot.goals.empty(): robot.move_on_error(multiplier=2.5)
def externalEnergy(self, controlpoints): """ Returns the external energy of the snake. The external energy is computed via the provided ExternalEnergy subclass object. The external energy is the sum of the external energies at each control point which get multiplied by the inverse of the number of control points. """ # compute the factor the energy of each control points get's weighed with external = 0.0 if len(self.controlpoints) > 0: factor = float(1)/len(self.controlpoints) else: factor = 1 # check if the given controlpoints are equal to the current ones if np.equal(controlpoints, self.controlpoints).all(): # take the current normals normals = self.normals else: # otherwise calculate the according normals spline = Spline() spline.addControlPoints(*controlpoints) normals = spline.normals # ACHTUNG! hier müssen die Normalen zur Berechnung gedreht werden, # falls flip es vorgibt if self.flip: normals = map(lambda n: rotateVector(n, angle=pi), normals) # only remember each external control point energy if the given control points are # the snakes current control points memorize_energies = np.equal(controlpoints, self.controlpoints).all() # reset the controlpointenergy list if necessary if memorize_energies: self.ext_energies = [] # sum up the energies at the single control points multiplied by the inverse # of the number of control points for i in range(len(controlpoints)): point = controlpoints[i] # if len(normals) > 0: # normal = normals[i] # else: # normal = None normal = normals[i] pointenergy = self.ExternalEnergy.getEnergy(point, iteration=self.iteration, normal=normal) # check wether to save the point energy if memorize_energies: #self.ext_energies.append(self.ExternalEnergy.getEnergy(point)) self.ext_energies.append(pointenergy) external += pointenergy * factor return external
def setUp(self): """ Creates a spline with uniform grid. :return: -- """ "" n = 10 # number of points x = np.linspace(0, 2 * np.pi, n) #test with sine-curve y = np.sin(x) self.u = np.arange(len(x) - 2) coord = np.array([x, y]) self.sp = Spline(coord, self.u, True) # define from interpolation
def curve_motion(robot, current, goal, new): spliner = Spline(order=2) path = spliner.get_path(current[:3], goal[:3], new[:3], n=30, bezier=True) print(path) for p in path: robot.add_goal( cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process')) while not robot.goals.empty(): robot.move_on_error(multiplier=2.5)
def __init__(self, iface, toolBar): # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() self.layer = self.iface.activeLayer() self.mc = self.canvas self.tool = None # Create actions self.action_spline = QAction( QIcon(":/plugins/cadtools/icons/spline.png"), QCoreApplication.translate("ctools", "Create Spline Lines/Polygons"), self.iface.mainWindow()) self.action_spline.setCheckable(True) try: if self.layer.isEditable(): self.action_spline.setEnabled(True) self.layer.editingStopped.connect(self.toggle) except: pass else: self.action_spline.setEnabled(False) self.layer.editingStarted.connect(self.toggle) # Connect to signals for button behaviour self.count = 0 self.count += 1 if self.count == 1: self.action_spline.triggered.connect(self.digitize) self.count -= 1 if self.count == 0: self.canvas.mapToolSet.connect(self.deactivate) self.count += 1 # self.iface.currentLayerChanged.connect(self.toggle) # Add actions to the toolbar toolBar.addSeparator() toolBar.addAction(self.action_spline) # Get the tool self.tool = Spline(self.iface)
def semi_track(robot, current): """ Start at the center and do a complete circuit motion Args: robot: current: Returns: """ spliner = Spline(order=2) # A point little to the right of the center point1 = list(current) point1[0] = current[0] + 0.2 # a point above the previous point. # Should form curve path to this using previous point as a control point point2 = list(point1) point2[2] = point1[2] + 0.1 path = spliner.get_path(current[:3], point1[:3], point2[:3], n=30, bezier=True) #print(path) for p in path: robot.add_goal(cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # Continue moving slightly up point3 = list(point2) point3[2] += 0.01 robot.add_goal(cb2_robot.Goal([point3[0], point3[1], point3[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # A little more up from point2 point4 = list(point2) point4[2] += 0.05 # A point to the left of point 4. # Should have a curve path from 3 to 5 via control point 4 point5 = list(point4) point5[0] -= 0.2 path = spliner.get_path(point3[:3], point4[:3], point5[:3], n=30, bezier=True) #print(path) for p in path: robot.add_goal(cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) while not robot.goals.empty(): robot.move_on_error(multiplier=2.5)
def testSpatialDistortion(self): strRefX = "spline-3-18x.edf" strRefY = "spline-3-18y.edf" self.loadTestImage([strRefX, strRefY]) edPluginSPD = self.createPlugin() strXMLInput = EDUtilsFile.readFileAndParseVariables( self.strReferenceInputFileName) xsDataInputSPDCake = XSDataInputSPDCake.parseString(strXMLInput) edPluginSPD.setDataInput(xsDataInputSPDCake) edPluginSPD.configure() edPluginSPD.getInputParameter() ######################################################################## # Enforce some values ######################################################################## edPluginSPD.dictGeometry["SpatialDistortionFile"] = os.path.join( self.getTestsDataImagesHome(), "frelon_spline_file_to_correct_SPD.spline") edPluginSPD.dictGeometry["TiltRotation"] = 18 edPluginSPD.dictGeometry["AngleOfTilt"] = 3 spline = Spline() spline.read(edPluginSPD.dictGeometry["SpatialDistortionFile"]) edPluginSPD.dictGeometry["PixelSizeX"], edPluginSPD.dictGeometry[ "PixelSizeY"] = spline.getPixelSize() edPluginSPD.createDisplacementMatrix(spline) edPluginSPD.cleanDispMat(edPluginSPD.getWorkingDirectory()) refX = fabio.openimage.openimage( os.path.join(self.getTestsDataImagesHome(), strRefX)).data obtX = fabio.openimage.openimage( os.path.join( edPluginSPD.getWorkingDirectory(), "frelon_spline_file_to_correct_SPD-tilted-x.edf")).data refY = fabio.openimage.openimage( os.path.join(self.getTestsDataImagesHome(), strRefY)).data obtY = fabio.openimage.openimage( os.path.join( edPluginSPD.getWorkingDirectory(), "frelon_spline_file_to_correct_SPD-tilted-y.edf")).data # print edPluginSPD.dictGeometry EDAssert.arraySimilar(obtX, refX, _fAbsMaxDelta=0.1, _strComment="X displacement Matrix is the same") EDAssert.arraySimilar(obtY, refY, _fAbsMaxDelta=0.1, _strComment="Y displacement Matrix is the same")
def suctionside(inputData): turbine, conditions = Turbine.by_conditions(*inputData, lambd=3.5) newconditions = np.array([ conditions[0], np.array([0.22, 0.94]), np.array([0.5, .97]), np.array([0.77, .7]), conditions[6] ]) # plt.plot(newconditions[:,0], newconditions[:,1]) # plt.show() tvals = util.spacing(newconditions, (0, 1), 'uniform') knots = np.array([0, 0, 0, 0, 1 / 3. * sum(tvals[1:4]), 1, 1, 1, 1]) basis = util.basisarray(3, knots) der0 = basis[-1] rang = 5 probmatrix = np.array([ [der0[i](tvals[0]) for i in range(rang)], [der0[i](tvals[1]) for i in range(rang)], [der0[i](tvals[2]) for i in range(rang)], [der0[i](tvals[3]) for i in range(rang)], [der0[i](tvals[4]) for i in range(rang)], ]) xpts = np.linalg.solve(probmatrix, newconditions[:, 0]) ypts = np.linalg.solve(probmatrix, newconditions[:, 1]) return Spline(np.array([xpts, ypts]), knots)
def create_new_spline(self): if self.active_spline is None: width = self.default_spline_width else: width = self.active_spline.width self.splines.append(Spline(width=width))
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() mc = self.canvas self.tool = None self.connectedLayer = None # Create actions self.action_spline = QAction(QIcon(":/plugins/spline/icon.png"), QCoreApplication.translate("spline", "Digitize Spline Curves"), self.iface.mainWindow()) self.action_spline.setObjectName("actionSpline") self.action_spline.setEnabled(False) self.action_spline.setCheckable(True) # Get the tool self.tool = Spline(self.iface) # Connect to signals for button behaviour self.action_spline.triggered.connect(self.digitize) self.iface.currentLayerChanged.connect(self.layerChanged) self.layerChanged() # to enable when plugin is loaded mc.mapToolSet.connect(self.deactivate) # Add actions to the toolbar self.iface.addToolBarIcon(self.action_spline)
def get_boson_splines(length, amplitude, n_waves, power, amp): N = n_waves * 2 wavelength = length / N cntrl_strength = wavelength # OLD TUNING PARAMETER # scaling envelope divisor = N - 1 if power: # TUNING PARAMETER envelope = [1 - abs(2 * i / divisor - 1)**power for i in range(N)] else: envelope = [1 for i in range(N)] # x offsets of points: px = [0.0] + [wavelength * (0.5 + i) for i in range(N)] px.append(px[-1] + wavelength / 2) # y offsets of points: py = [0.0] + [amplitude * envelope[i] for i in range(N)] + [0.0] splines = [] sgn = 1 for i in range(1, N + 2): # STYLE HALF OPEN PHOTONS: Was N+2 op = Point2D(px[i - 1], -sgn * py[i - 1]) cp1 = Point2D(px[i - 1], -sgn * py[i - 1]) cp2 = Point2D(px[i], sgn * py[i]) dp = Point2D(px[i], sgn * py[i]) if i == 1: cp1 = op elif i == N + 1: cp2 = dp splines.append(Spline(op, cp1, cp2, dp)) sgn = -sgn return SplineLine(splines)
def get_gluon_splines(length, amplitude, n_waves, amp): loopyness = 0.75 # TUNING PARAMETER init_length = 2 # TUNING PARAMETER N = n_waves * 2 + 1 wavelength = length / (N - 1 + 2 * init_length) cntrl_strength = wavelength * loopyness # x offsets of points: px = [0.0] + [wavelength * (init_length + i) for i in range(N)] px.append(px[-1] + init_length * wavelength) # y offsets of points: py = [0.0] + [amplitude for i in range(N)] + [0.0] splines = [] sgn = 1 for i in range(1, N + 2): op = Point2D(px[i - 1], -sgn * py[i - 1]) cp1 = Point2D(px[i - 1] - sgn * (2 - sgn) * cntrl_strength, -sgn * py[i - 1]) cp2 = Point2D(px[i] - sgn * (2 + sgn) * cntrl_strength, sgn * py[i]) dp = Point2D(px[i], sgn * py[i]) if i == 1: cp1 = op elif i == N + 1: cp2 = dp splines.append(Spline(op, cp1, cp2, dp)) sgn = -sgn return SplineLine(splines)
def arc(pt1, pt2, pt3, pt4, alpha): length = np.linalg.norm(pt2 - pt3) / alpha v1 = (pt2 - pt1) / np.linalg.norm(pt2 - pt1) v2 = (pt3 - pt4) / np.linalg.norm(pt3 - pt4) newpt1 = pt2 + v1 * length newpt2 = pt3 + v2 * length ary = np.array([pt2, newpt1, newpt2, pt3]).T return Spline(ary, np.array([0, 0, 0, 0, 1, 1, 1, 1]))
def main(): spline = Spline('dots.txt') print(spline.dots, spline.dots_count) spline.get_polynomials() x = [] y = [] for dot in spline.dots: x.append(dot[0]) y.append(dot[1]) f = interpolate.interp1d(x, y, kind='cubic') xnew = np.arange(min(spline.dots)[0], max(spline.dots)[0], 0.01) ynew = f(xnew) plt.plot(x, y, 'ro', xnew, ynew) plt.grid(True) plt.show()
def draw_outlines(svg, outlines): # We need to sort outlines, because one outline can cover other outline outlines = sorted(outlines, key=lambda elem: min(elem['outline_points'])) for outline_obj in outlines: outline_points = outline_obj['outline_points'] if len(outline_points) < 4: svg.add_poly_element(outline_points, outline_obj['fill']) else: outline_on_img = Spline.get_cubic_b_spline_points(np.array(outline_points)) svg.add_spline_element(outline_on_img, outline_obj['fill']) svg.save_as_svg('vot-eto-da-both.svg')
def update(self): """ Recomputes energies and the contour, e.g. after a control point has been added. """ # compute the contour and normals spline = Spline() spline.addControlPoints(*self.controlpoints) lencontrolpoints = len(self.controlpoints) self.contour = spline.interpolation self.normals = spline.normals # the following is not needed anymore #if self.flip: # self.normals = map(lambda n: rotateVector(n, angle=pi), self.normals) # compute the energies self.spacing = self.spacingEnergy(self.controlpoints) self.curvature = self.curvatureEnergy(self.controlpoints) self.external = self.externalEnergy(self.controlpoints) self.energy = self.totalEnergy(self.controlpoints) # compute the contour gradient for displaying the curvature energies self.contour_gradient = contourCurvatureGradient(self.contour, self.controlpoints, self.crv_energies) # check for saneness if lencontrolpoints == 1 or lencontrolpoints == 0: assert self.contour == [] assert self.spacing == 0.0 assert self.curvature == 0.0 elif lencontrolpoints == 0: assert self.external == 0.0 assert len(self.normals) == [] elif lencontrolpoints > 1: assert len(self.contour) > 0 assert lencontrolpoints == len(self.normals) assert lencontrolpoints == len(self.ext_energies), '%s != %s' % (len(self.controlpoints), len(self.ext_energies))
def preProcess(self, _edObject=None): """ Preprocess methods for the EDPluginSPDCorrectv10 : - Reads input parameters - Creates the displacement matrix if the the detector is tilted - create the configuration for SPD - selects the worker (SPD program under control) """ EDPluginExecProcess.preProcess(self) self.DEBUG("EDPluginSPDCorrectv10.preProcess") # Check that the input data and correction images are present self.getInputParameter() if "SpatialDistortionFile" in self.dictGeometry: splineDM = Spline() splineDM.read(self.dictGeometry["SpatialDistortionFile"]) self.dictGeometry["PixelSizeX"], self.dictGeometry[ "PixelSizeY"] = splineDM.getPixelSize() else: splineDM = None if self.dictGeometry["AngleOfTilt"] != 0: EDPluginSPDCorrectv10.__lockTilt.acquire() if splineDM == None: edfFile = fabio.open(self.pathToInputFile) data = edfFile.data size = data.shape splineDM = splineDM.zeros(xmin=0.0, ymin=0.0, xmax=size[0], ymax=size[1]) if ("PixelSizeX" in self.dictGeometry) and ("PixelSizeY" in self.dictGeometry): splineDM.setPixelSize = (self.dictGeometry["PixelSizeX"], self.dictGeometry["PixelSizeY"]) strtmp = os.path.join( self.getSPDCommonDirectory(), os.path.basename( os.path.splitext( self.dictGeometry["SpatialDistortionFile"])[0])) if not (os.path.isfile(strtmp + "-tilted-x.edf") and os.path.isfile(strtmp + "-tilted-y.edf")): # self.DEBUG("preProcess: \t EDPluginSPDCorrectv10.__lock.acquire(), currently: %i" % EDPluginSPDCorrectv10.__lock._Semaphore__value) if not (os.path.isfile(strtmp + "-tilted-x.edf") and os.path.isfile(strtmp + "-tilted-y.edf")): #The second test is just here to gain some time as the global semaphore could be in use elsewhere self.createDisplacementMatrix(splineDM) self.dictGeometry["DistortionFileX"] = strtmp + "-tilted-x.edf" self.dictGeometry["DistortionFileY"] = strtmp + "-tilted-y.edf" EDPluginSPDCorrectv10.__lockTilt.release() self.generateSPDCommand()
def main() -> None: f = argv[1] points = read_points(f) print("Table of points\n") print_points(points) print('\nEntry X for interpolate:\n') x = float(input()) spline_res = Spline(points).solve(x) newton_res = NewtonPolynom(points).solve(x) print_res(spline_res, newton_res)
def get_segment_splines(length, n_segments, n, offset): N = n_segments * 2 - 1 wavelength = length / N # x offsets of points: px_start = wavelength * n px_mid = wavelength * (n + 0.5) px_end = wavelength * (n + 1) if px_start: py_start = offset * px_start else: py_start = 0 splines = [ Spline(Point2D(px_start, py_start), Point2D(px_mid, offset * px_mid), Point2D(px_mid, offset * px_mid), Point2D(px_end, offset * px_end)) ] return SplineLine(splines)
def get_shape_by_name(shape_name, priors): import re if shape_name == 'sigmoid': from sigmoid import Sigmoid return Sigmoid(priors) if shape_name == 'sigslope': from sigslope import Sigslope return Sigslope(priors) elif shape_name.startswith('poly'): m = re.match('poly(\d)', shape_name) assert m, 'Illegal polynomial shape name' degree = int(m.group(1)) from poly import Poly return Poly(degree, priors) elif shape_name == 'spline': from spline import Spline return Spline() else: raise AssertionError('Unknown shape: {}'.format(shape_name))
def pressureside(inputData): beta1, beta2, GAMMA, tau, betag, gamma, Bx, R1, R2, dbeta1, dbeta2 = inputData beta1 = radians(beta1) beta2 = radians(beta2) dbeta1 = radians(dbeta1) dbeta2 = radians(dbeta2) betag = radians(betag) gamma = radians(gamma) GAMMA = radians(GAMMA) chord = (Bx - R1 * (1 - np.cos(beta1)) - R2 * (1 - np.cos(beta2))) / np.cos(gamma) height = chord * np.sin(gamma) + R1 * np.sin(beta1) - R2 * np.sin(beta2) p1 = (R1 * (1 + np.sin(beta1 - dbeta1 / 2.)), height - R1 * np.cos(beta1 - dbeta1 / 2.)) p4 = (Bx - R2 * (1 + np.sin(beta2 - dbeta2 / 2.)), -R2 * np.cos(beta2 - dbeta2 / 2.)) newconditions = np.array( [p1, np.array([0.3, 0.57]), np.array([0.61, 0.48]), p4]) tvals = util.spacing(newconditions, (0, 1), 'uniform') knots = np.array([0, 0, 0, 0, 1, 1, 1, 1]) basis = util.basisarray(3, knots) der0 = basis[-1] rang = 4 probmatrix = np.array([ [der0[i](tvals[0]) for i in range(rang)], [der0[i](tvals[1]) for i in range(rang)], [der0[i](tvals[2]) for i in range(rang)], [der0[i](tvals[3]) for i in range(rang)], ]) xpts = np.linalg.solve(probmatrix, newconditions[:, 0]) ypts = np.linalg.solve(probmatrix, newconditions[:, 1]) return Spline(np.array([xpts, ypts]), knots)
def main(): spline = Spline('dots.txt') print(spline.dots, spline.dots_count) spline.get_polynomials() try: file = open('result.txt', 'w', encoding='utf-8') except FileNotFoundError: print('Result file is nor founded') exit(2) for i in range(len(spline.polynomials)): print('F' + str(i+1) + '(x) = ' + str(spline.polynomials[i])) file.write('F' + str(i+1) + '(x) = ' + str(spline.polynomials[i]) + '\n') file.close() spline.get_plot()
def preProcess(self, _edObject=None): """ Preprocess methods for the EDPluginSPDCorrectv10 : - Reads input parameters - Creates the displacement matrix if the the detector is tilted - create the configuration for SPD - selects the worker (SPD program under control) """ EDPluginExecProcess.preProcess(self) self.DEBUG("EDPluginSPDCorrectv10.preProcess") # Check that the input data and correction images are present self.getInputParameter() if "SpatialDistortionFile" in self.dictGeometry: splineDM = Spline() splineDM.read(self.dictGeometry["SpatialDistortionFile"]) self.dictGeometry["PixelSizeX"], self.dictGeometry["PixelSizeY"] = splineDM.getPixelSize() else: splineDM = None if self.dictGeometry["AngleOfTilt"] != 0: EDPluginSPDCorrectv10.__lockTilt.acquire() if splineDM == None: edfFile = fabio.open(self.pathToInputFile) data = edfFile.data size = data.shape splineDM = splineDM.zeros(xmin=0.0, ymin=0.0, xmax=size[0], ymax=size[1]) if ("PixelSizeX" in self.dictGeometry) and ("PixelSizeY" in self.dictGeometry): splineDM.setPixelSize = (self.dictGeometry["PixelSizeX"], self.dictGeometry["PixelSizeY"]) strtmp = os.path.join( self.getSPDCommonDirectory(), os.path.basename(os.path.splitext(self.dictGeometry["SpatialDistortionFile"])[0]), ) if not (os.path.isfile(strtmp + "-tilted-x.edf") and os.path.isfile(strtmp + "-tilted-y.edf")): # self.DEBUG("preProcess: \t EDPluginSPDCorrectv10.__lock.acquire(), currently: %i" % EDPluginSPDCorrectv10.__lock._Semaphore__value) if not (os.path.isfile(strtmp + "-tilted-x.edf") and os.path.isfile(strtmp + "-tilted-y.edf")): # The second test is just here to gain some time as the global semaphore could be in use elsewhere self.createDisplacementMatrix(splineDM) self.dictGeometry["DistortionFileX"] = strtmp + "-tilted-x.edf" self.dictGeometry["DistortionFileY"] = strtmp + "-tilted-y.edf" EDPluginSPDCorrectv10.__lockTilt.release() self.generateSPDCommand()
def circuit(robot, start): spliner = Spline(order=2) # A point little to the right of the start point1 = list(start) point1[0] += 0.2 # a point above the previous point. # Should form curve path to this using previous point as a control point point2 = list(point1) point2[2] = point1[2] + 0.1 path = spliner.get_path(start[:3], point1[:3], point2[:3], n=50, bezier=True) for p in path: robot.add_goal( cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # Continue moving slightly up point3 = list(point2) point3[2] += 0.01 robot.add_goal( cb2_robot.Goal([point3[0], point3[1], point3[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # A little more up from point3 point4 = list(point2) point4[2] += 0.05 # A point to the left of point 4. # Should have a curve path from 3 to 5 via control point 4 point5 = list(point4) point5[0] -= 0.2 path = spliner.get_path(point3[:3], point4[:3], point5[:3], n=50, bezier=True) for p in path: robot.add_goal( cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # Point more to the left of point 5 and slightly below point6 = list(point5) point6[0] -= 0.3 point6[2] -= 0.1 # point down to point 6 #point7 = list(point6) #point7[2] -= 0.1 # move back to the start point in a curve path = spliner.get_path(point5[:3], point6[:3], start[:3], n=50, bezier=True) for p in path[:-5]: robot.add_goal( cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) while not robot.goals.empty(): robot.move_on_error(multiplier=2.0) robot.add_goal( cb2_robot.Goal([path[-1][0], path[-1][1], path[-1][2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) while not robot.goals.empty(): robot.move_on_error(multiplier=1.0) time.sleep(2)
def main(): print MENU choose = get_int_or_empty_input() while choose != 0: if choose == 1 or choose == 2: if choose == 1: range_start = get_int_or_empty_input( "Enter range start [%d by default]: " % DEFAULT_RANGE_START) if range_start == "": range_start = DEFAULT_RANGE_START range_end = get_int_or_empty_input( "Enter range end[%d by default]: " % DEFAULT_RANGE_END) if range_end == "": range_end = DEFAULT_RANGE_END range_splits = RANGE_SPLITS function = FUNCTION else: range_start = 0 range_end = 5 range_splits = 5 function = BINARY_TASK_FUNCTION spline = Spline(range_start, range_end, range_splits, function) print "Maple functions:" print "s := spline(%s, %s, x, cubic)" % (str(spline.x), str(spline.y)) print "plot(s, x=%d..%d, thickness = 2)" % (range_start, range_end) print print "POINTS:" print "X: " print spline.x print "Y: " print spline.y print print "Coefficients:" print spline.n for i in xrange(spline.n - 1): print "e[%(i)d]= %(e).5f \tG[%(i)d]= %(G).5f \tH[%(i)d]= %(H).5f" % { "i": i, "e": spline.E(i), "G": spline.G(i), "H": spline.H(i), } print file_name = raw_input( "Enter file name for plot image [enter to show on screen]: ") if file_name: try: spline.plot_to_file(file_name) except IOError: print "Wrong path." else: spline.plot_on_screen() point = get_float_or_empty_input("Enter x value: ") while isinstance(point, float): if point in spline.ranges: print "X: %.3f, Y: %.3f" % (point, spline.f(point)) else: print "Number %.3f not in range. Enter number again." % point point = get_float_or_empty_input("Enter x value: ") elif choose == 3: file_name = raw_input( "Enter file name for matrix [data/1.matrix by default]: ") or "data/1.matrix" matrix_type = raw_input( "Enter f - if matrix full, c - if matrix compact [full by default]: ") try: parser = TridiagonalMatrixParser() if matrix_type.startswith("c"): matrix = parser.parse_from_tridiagonal_matrix(file_name) else: matrix = parser.parse_from_full_matrix(file_name) if matrix.validate(): for i, res in enumerate(matrix.solve()): print "X%d= %f" % (i + 1, res) else: print "Matrix not valid." except IOError: print "File does not exsist." else: print "Bad choise." print MENU choose = get_int_or_empty_input()
class SplineTool(): def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() mc = self.canvas self.tool = None self.connectedLayer = None # Create actions self.action_spline = QAction( QIcon(":/plugins/spline/icon.png"), QCoreApplication.translate("spline", "Digitize Spline Curves"), self.iface.mainWindow()) self.action_spline.setObjectName("actionSpline") self.action_spline.setEnabled(False) self.action_spline.setCheckable(True) # Get the tool self.tool = Spline(self.iface) # Connect to signals for button behaviour self.action_spline.triggered.connect(self.digitize) self.iface.currentLayerChanged.connect(self.layerChanged) self.layerChanged() # to enable when plugin is loaded mc.mapToolSet.connect(self.deactivate) # Add actions to the toolbar self.iface.addToolBarIcon(self.action_spline) def __del__(self): self.disconnectLayer() self.iface.removeToolBarIcon(self.action_spline) def digitize(self): mc = self.canvas layer = mc.currentLayer() mc.setMapTool(self.tool) self.action_spline.setChecked(True) # get current layer if it is line or polygon, otherwise None def getLayer(self): layer = self.canvas.currentLayer() if layer is None: return None if layer.type() != QgsMapLayer.VectorLayer: return None if not layer.geometryType() in [QGis.Line, QGis.Polygon]: return None return layer def enableAction(self): self.action_spline.setEnabled(False) layer = self.getLayer() if layer: self.action_spline.setEnabled(layer.isEditable()) def layerChanged(self): self.tool.deactivate() self.enableAction() self.disconnectLayer() self.connectLayer(self.getLayer()) def connectLayer(self, layer): if layer is None: return self.connectedLayer = layer layer.editingStopped.connect(self.enableAction) layer.editingStarted.connect(self.enableAction) def disconnectLayer(self): if self.connectedLayer is None: return self.connectedLayer.editingStopped.disconnect(self.enableAction) self.connectedLayer.editingStarted.disconnect(self.enableAction) self.connectedLayer = None def deactivate(self): self.action_spline.setChecked(False) def settingsChanged(self): self.tool.refresh()
import numpy as np import scipy.linalg as sl import matplotlib.pyplot as plt from spline import Spline #from spline import eval_basis #runfile('./spline.py') #%% grid = np.linspace(0,10,10) # K = 9 #control_points = np.array([[3,4.5,5,6,7,8,8.6,9],[4,5,6,8,4,6,7.2,6]])# L = K - 2 = 7 control_points = np.array([[2.3,2.1,4,6,7,8,5.5,6.3],[7,5.5,4.3,4.5,4,5.56,7.2,6]])# L = K - 2 = 7 #%% s = Spline(grid, control_points) # initialize the spline #%% s._find_interval(3) #%% t = s._find_control_points(7) #%% #s._alpha(3.5) #%% s._blossom(3.5) #%% #t = eval_basis(s.grid, 3) #%% s.plot(100) #%% control_points = np.zeros((7,2)) control_points[5] = 1 #%% #s(2) # this is not an valid input since 2 in [u_1 u_2] #%%
class TestSpline(unittest.TestCase): def setUp(self): """ Creates a spline with uniform grid. :return: -- """ "" n = 10 # number of points x = np.linspace(0, 2 * np.pi, n) #test with sine-curve y = np.sin(x) self.u = np.arange(len(x) - 2) coord = np.array([x, y]) self.sp = Spline(coord, self.u, True) # define from interpolation def tearDown(self): pass def test_normalized(self): """ Test that asserts sum(Ni(u)) = 1 for any u in [u_2, u_{K-2}] :return: -- """ "" t = self.u[0] + (self.u[-1] - self.u[0]) * np.random.rand( 1000) #randomized values over interval np.append(t, self.u[-1]) #include final value for i in range(t.shape[0]): N = np.array( [self.sp.basis(t[i], j) for j in range(self.u.shape[0] + 2)]) self.assertAlmostEqual(1., np.sum(N)) def test_byInterpolation(self): """ Test how well sine-function can be reproduced using spline interpolation. :return: -- """ "" spline_vec = self.sp.spline() np.testing.assert_almost_equal(spline_vec[1, :], np.sin(spline_vec[0, :]), 1) def test_blossom(self): """ Test that spline calculation using basis interpolation and Blossom algorithm gives the same result, s(u) = sum(d*N). :return: -- """ "" s_vec_blossom = self.sp.spline() s_vec_intpol = self.sp.splineInterpol() np.testing.assert_almost_equal(s_vec_blossom, s_vec_intpol) def test_runtimes(self): """ Check runtimes of blossom algorithm vs basis interpolation. :return: -- """ "" tmin_intpol = 100 tmin_blossom = 100 for i in range(10): start = timer() s_vec_intpol = self.sp.splineInterpol() end = timer() if (end - start < tmin_intpol): tmin_intpol = end - start start = timer() s_vec_blossom = self.sp.spline() end = timer() if (end - start < tmin_intpol): tmin_blossom = end - start print('Runtime basis interpolation: ', tmin_intpol) print('Runtime blossom algorithm: ', tmin_blossom) def test_uremark(self): """ Test that contribution from basis function N_0^2 that is multiplied with u[-1]-term is always zero. :return: -- """ "" t = self.u[0] + (self.u[-1] - self.u[0]) * np.random.rand( 100) # randomized values over interval np.append(t, self.u[-1]) # include final value N = self.sp.makeBasisFunc(0, 2) # create function N_0^2 Nvec = np.array([N(t[i]) for i in range(t.shape[0])]) self.assertAlmostEqual(0, np.linalg.norm(Nvec))
def test(): from spline import Spline, SplineLine, Line spline1 = Spline((5.0, -10), (20.000, -10), (15.0, 30.000), (40.0, 10.000)) spline2 = Spline((40, 10), (65, -10), (60, 30), (80, 20)) spline = SplineLine((spline1, spline2)) line = Line((0, 0), (spline.length, 0)) doc = svgxml.createElement("svg") doc.setAttribute("xmlns", "http://www.w3.org/2000/svg") doc.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink") doc.setAttribute("viewBox", "0 0 1000 1000") spath = svgxml.createElement("path") spath.setAttribute("d", spline.svg_path_data) spath.setAttribute("transform", "translate(%i,%i)" % (10, 10)) spath.setAttribute("fill", "none") spath.setAttribute("stroke", "red") doc.appendChild(spath) args = {"fill": "none", "stroke": "blue", "scale": 5} fargs = {"fill": "blue", "stroke": "blue", "scale": 5} mgargs = {"color": "blue", "anticolor": "red", "scale": 5} n = 10 for i in range(n + 1): x = 10 y = 40 + i * 25 e = i / n doc.appendChild( photon(e, line, transform="translate(%i,%i)" % (x, y), **args)).toprettyxml() doc.appendChild( photon(e, spline, transform="translate(%i,%i)" % (x + 100, y), **args)).toprettyxml() doc.appendChild( gluon(e, line, transform="translate(%i,%i)" % (x + 200, y), **args)).toprettyxml() doc.appendChild( gluon(e, spline, transform="translate(%i,%i)" % (x + 300, y), **args)).toprettyxml() doc.appendChild( boson(e, line, transform="translate(%i,%i)" % (x + 400, y), **args)).toprettyxml() doc.appendChild( boson(e, spline, transform="translate(%i,%i)" % (x + 500, y), **args)).toprettyxml() doc.appendChild( fermion(e, line, transform="translate(%i,%i)" % (x + 600, y), **fargs)).toprettyxml() doc.appendChild( fermion(e, spline, transform="translate(%i,%i)" % (x + 700, y), **fargs)).toprettyxml() doc.appendChild( multigluon(e, spline, transform="translate(%i,%i)" % (x + 800, y), **mgargs)).toprettyxml() for i in range(n + 1): x = 10 y = 400 + i * 25 e = 0.6 l = Line((0, 0), ((i + 0.5) / n * 180, 10)) doc.appendChild( photon(e, l, transform="translate(%i,%i)" % (x, y), **args)).toprettyxml() doc.appendChild( gluon(e, l, transform="translate(%i,%i)" % (x + 250, y), **args)).toprettyxml() doc.appendChild( boson(e, l, transform="translate(%i,%i)" % (x + 500, y), **args)).toprettyxml() doc.appendChild( fermion(e, l, transform="translate(%i,%i)" % (x + 750, y), **fargs)).toprettyxml() #s.append('<path transform="translate(10,10)" fill="none" stroke="red" id="u" d="%s" />\n' % (gluon(0.5, 200))) f = file("feynman_shapes.svg", "w") f.write(doc.toprettyxml()) f.close() print "Written feynman_shapes.svg."
def OnLine(self,id,event=None): """when mouse is online creates oval and displays its value""" c = self.canvas #del old pn = c.find_withtag("point_online") if pn!=[]: for i in pn: c.delete(i) tx = c.find_withtag("text_online") if tx!=[]: for i in tx: c.delete(i) x = event.x y = event.y self.canvas.create_oval(x-2,y-2,x+2,y+2,fill="white",tags=("point_online",)) val = self.getValueforCoords((x,y)) self.canvas.create_text((x+10,y+10),text=val,tags= ("text_online",)) if __name__ == "__main__": ########### import Tkinter sp = Spline([(0.0,0.0),(1.0,1.0)],[ (None, (1,-1)), ((1,1), None) ] ) canvas = Tkinter.Canvas(width = 700, height = 700) canvas.pack() #canvas.configure(cursor="cross") canvas.create_rectangle([100,600,600,100]) anim = AnimatorSpline(sp, canvas, (100, 600, 500, 500), 'abc') slopes = [ (None, (1,1)), ((1,1), None) ] anim.doit(50,80,5,100,slopes)
# Line d = np.array([[0, 1, 2, 3, 1, 0], [3, 3, 3, 3, 3, 3]]) u = np.array([0, 1, 2]) # Polygon 1 d = np.array([[0, 1, 2, 3, 1, 0], [2, 3, 4, 3, 2, 0]]) u = np.array([0, 1, 2, 3]) # 0 0 0 1 2 3 3 3 # Polygon 2 - ser lite skum ut d = np.array([[0, 1, 2, 3, 1, 0, -1, -2], [2, 3, 4, 3, 2, 0, -1, -2]]) u = np.array([0, 1, 2, 3, 4, 5]) # 0 0 0 1 2 3 3 3 s = Spline(d,u) s(d,u) s.plotSpline() x = 2 i = 3 N = s.basis(x,i) x = np.linspace(0, 10) plt.plot(x, np.sin(x), '--', linewidth=2)
objPC.Error(F3, X)""" print("* * * * * * * * * * * * * * * * * * * *") # S P L I N E # orden = 8 # grado nudos = 15 # numero de nudos for i in range(0, len(files)): start = time.time() print("------------------------------------------") print("Runing Sample M" +str(i+1) + "...") objS = Spline() F4 = objS.RegresionSpline(X[i], Y[i], orden, nudos) #print("Function " + str(i) + ": " + str(F4)) objS.Error(X[i], Y[i], F4) print("Generation graph...") # graph function objG.addScatter(X[i], Y[i], "green") objG.addLineFunction(F4, min(X[i]), max(X[i])) objG.displayPlot(("Regresión Spline " + str(i+1)) , "x", "y") print("Sample M" + str(i + 1) + " Generated correctly!") print("------------------------------------------") end = time.time() print("Elapsed time: " + str((end -start) / 60) + " minutes" )
if __name__ == "__main__": a = 0 b = 4 approximated = g verbose = True n = int(input("Введите степень полинома: ")) # trigonometric = QuadraticApproximation(a, b, approximated, fs.TrigonometricSystem()) exponential = QuadraticApproximation(a, b, approximated, fs.ExponentialSystem()) # polynomial = QuadraticApproximation(a, b, approximated, fs.PolynomialSystem()) legandre = LegendreApproximation(a, b, approximated) discrete = DiscreteApproximation(a, b, approximated) spline = Spline(a, b, approximated, rho=100) # Qn_trig = trigonometric.get_mean_quadratic_approximation(n, verbose=verbose) # title = "Trigonometric continuous approximation" # util.plot_approximation(a, b, title, f=approximated, phi=Qn_trig) # # print() # Qn_exp = exponential.get_mean_quadratic_approximation(n, verbose=verbose) title = "Exponential continuous approximation" util.plot_approximation(a, b, title, f=approximated, phi=Qn_exp) print() # # Qn_polynomial = polynomial.get_mean_quadratic_approximation(n, verbose=verbose) # title = "Polynomial continuous approximation"
class SplineTool(): def __init__(self, iface, toolBar): # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() self.layer = self.iface.activeLayer() self.mc = self.canvas self.tool = None # Create actions self.action_spline = QAction( QIcon(":/plugins/cadtools/icons/spline.png"), QCoreApplication.translate("ctools", "Create Spline Lines/Polygons"), self.iface.mainWindow()) self.action_spline.setCheckable(True) try: if self.layer.isEditable(): self.action_spline.setEnabled(True) self.layer.editingStopped.connect(self.toggle) except: pass else: self.action_spline.setEnabled(False) self.layer.editingStarted.connect(self.toggle) # Connect to signals for button behaviour self.count = 0 self.count += 1 if self.count == 1: self.action_spline.triggered.connect(self.digitize) self.count -= 1 if self.count == 0: self.canvas.mapToolSet.connect(self.deactivate) self.count += 1 # self.iface.currentLayerChanged.connect(self.toggle) # Add actions to the toolbar toolBar.addSeparator() toolBar.addAction(self.action_spline) # Get the tool self.tool = Spline(self.iface) def digitize(self): layer = self.mc.currentLayer() self.action_spline.setChecked(True) if self.action_spline.isChecked(): self.mc.setMapTool(self.tool) print 'call' self.count -= 1 def deactivate(self): if self.count == 0: self.action_spline.setChecked(False) self.mc.unsetMapTool(self.tool) print 'tool' else: self.count = 1 pass def toggle(self): if self.layer: # disconnect all previously connect signals in current layer try: self.layer.editingStarted.disconnect(self.toggle) except: pass try: self.layer.editingStopped.disconnect(self.toggle) except: pass # check if current layer is editable and has selected features # and decide whether the plugin button should be enable or disable if self.layer.isEditable(): self.action_spline.setEnabled(True) # self.action_spline.setChecked(True) self.layer.editingStopped.connect(self.toggle) # layer is not editable else: self.action_spline.setEnabled(False) # self.action_spline.setChecked(False) self.layer.editingStarted.connect(self.toggle) # self.mc.mapToolSet.connect(self.deactivate) else: self.action_spline.setEnabled(False) # self.mc.mapToolSet.connect(self.deactivate) # self.action_spline.setChecked(True) def settingsChanged(self): self.tool.refresh()
def semi_track(robot, current): """ Start at the center and do a complete circuit motion Args: robot: current: Returns: """ spliner = Spline(order=2) # A point little to the right of the center point1 = list(current) point1[0] = current[0] + 0.2 # a point above the previous point. # Should form curve path to this using previous point as a control point point2 = list(point1) point2[2] = point1[2] + 0.1 path = spliner.get_path(current[:3], point1[:3], point2[:3], n=30, bezier=True) #print(path) for p in path: robot.add_goal( cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # Continue moving slightly up point3 = list(point2) point3[2] += 0.01 robot.add_goal( cb2_robot.Goal([point3[0], point3[1], point3[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) # A little more up from point2 point4 = list(point2) point4[2] += 0.05 # A point to the left of point 4. # Should have a curve path from 3 to 5 via control point 4 point5 = list(point4) point5[0] -= 0.2 path = spliner.get_path(point3[:3], point4[:3], point5[:3], n=30, bezier=True) #print(path) for p in path: robot.add_goal( cb2_robot.Goal([p[0], p[1], p[2], 1.2, -1.2, 1.2], True, 'process', radius=0.001)) while not robot.goals.empty(): robot.move_on_error(multiplier=2.5)
class SplineTool(): def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() mc = self.canvas self.tool = None self.connectedLayer = None # Create actions self.action_spline = QAction(QIcon(":/plugins/spline/icon.png"), QCoreApplication.translate("spline", "Digitize Spline Curves"), self.iface.mainWindow()) self.action_spline.setObjectName("actionSpline") self.action_spline.setEnabled(False) self.action_spline.setCheckable(True) # Get the tool self.tool = Spline(self.iface) # Connect to signals for button behaviour self.action_spline.triggered.connect(self.digitize) self.iface.currentLayerChanged.connect(self.layerChanged) self.layerChanged() # to enable when plugin is loaded mc.mapToolSet.connect(self.deactivate) # Add actions to the toolbar self.iface.addToolBarIcon(self.action_spline) def __del__(self): self.disconnectLayer() self.iface.removeToolBarIcon(self.action_spline) def digitize(self): mc = self.canvas layer = mc.currentLayer() mc.setMapTool(self.tool) self.action_spline.setChecked(True) # get current layer if it is line or polygon, otherwise None def getLayer(self): layer = self.canvas.currentLayer() if layer is None: return None if layer.type() != QgsMapLayer.VectorLayer: return None if not layer.geometryType() in [ QGis.Line, QGis.Polygon ]: return None return layer def enableAction(self): self.action_spline.setEnabled(False) layer = self.getLayer() if layer: self.action_spline.setEnabled( layer.isEditable() ) def layerChanged(self): self.tool.deactivate() self.enableAction() self.disconnectLayer() self.connectLayer( self.getLayer() ) def connectLayer(self, layer): if layer is None: return self.connectedLayer = layer layer.editingStopped.connect(self.enableAction) layer.editingStarted.connect(self.enableAction) def disconnectLayer(self): if self.connectedLayer is None: return self.connectedLayer.editingStopped.disconnect(self.enableAction) self.connectedLayer.editingStarted.disconnect(self.enableAction) self.connectedLayer = None def deactivate(self): self.action_spline.setChecked(False) def settingsChanged(self): self.tool.refresh()