def _get_curve_disp(self): x_y = self.driver.sc.fetch() meta = dict() meta["name"] = "na_curve" meta["curve_type"] = "NaCurve" meta["averaging"] = self.averaging_factor*self.averaging meta["center_freq"] = self.frequency_center meta["start_freq"] = self.frequency_start meta["stop_freq"] = self.frequency_stop meta["span"] = self.span meta["bandwidth"] = self.if_bandwidth meta["sweep_time"] = self.sweep_time meta["output_port"] = self.output_port meta["input_port"] = self.input_port meta["format"] = self.formats[self.format] meta["measurement"] = self.measurement_idxs[self.measurement_idx] meta["channel"] = self.channel_idxs[self.channel_idx] meta["instrument_type"] = "NA" meta["instrument_logical_name"] = self.logical_name curve = Curve() curve.set_data(pandas.Series(x_y[1], index = x_y[0])) curve.set_params(**meta) return curve
def _guesslorentzSB(self): from curve import Curve cu = Curve() cu.set_data(self.data) res, lor = cu.fit('lorentz') magdata = lor.data.abs() scale = numpy.sign(lor.params['scale'])*(magdata.max() - abs(lor.params['y0'])) res, lor = cu.fit('lorentz', fixed_params={'x0':lor.params['x0'], 'bandwidth':0.7*lor.params['bandwidth'], 'scale':scale}) diff = numpy.sign(lor.params['scale'])*(cu.data - lor.data)*self.lorentz(-1.0, lor.params['x0'], 1.0, lor.params['bandwidth']) upper_half = diff[lor.params['x0']:] index_up = upper_half.argmax() scale_up = upper_half[index_up] x_up = upper_half.index[index_up] lower_half = diff[:lor.params['x0']] index_lo = lower_half.argmax() scale_lo = lower_half[index_lo] x_lo = lower_half.index[index_lo] # replacement = {'bandwidth': fit_params['bandwidth']/2.0,\ # 'SBwidth': fit_params['bandwidth']*1.1, 'SBscale' : 0.3} return {'scale' : lor.params['scale'], 'x0' : lor.params['x0'], 'y0' : lor.params['y0'], 'bandwidth' : lor.params['bandwidth'], 'SBwidth' : (x_up - x_lo)/2, 'SBscale' : 1./lor.params['scale']*(scale_up + scale_lo)/2}
def setUp(self): self.pos = [ [0, 0], [3, 4] ] self.vel = [ [cos(radians(90)), sin(radians(90))], [cos(radians(0)), sin(radians(0))] ] self.acc = [ [-sin(radians(90)), cos(radians(90))], [-sin(radians(0)), cos(radians(0))] ] quintic_data = nparray([ self.pos[0], self.vel[0], self.acc[0], self.pos[1], self.vel[1], self.acc[1] ]) self.quintic_hermite = Curve(SplineType.QUINTIC_HERMITE, quintic_data) cubic_data = nparray([ self.pos[0], self.pos[1], self.vel[0], self.vel[1] ]) self.cubic_hermite = Curve(SplineType.CUBIC_HERMITE, cubic_data)
def generate_graph(): # pygame.draw.lines(window, Color['black'], False, generate_pixels(), 1) first_curve = Curve(lambda x: x, Color['black'], 1) second_curve = Curve(lambda x: x**2, Color['red'], 1) third_curve = Curve(lambda x: 4 * (x**3) + 3 * (x**2) + 2 * x + 1, Color['green'], 1) window.draw_curve(first_curve) window.draw_curve(second_curve) window.draw_curve(third_curve)
def run_starboy_batch(curves_directory, out_directory="test_dir"): ''' Function that runs our starboys algorithm over folder specified in 'curves_directory' string. It reads and classifies curves in real time, may take some time on large data set. Starboy algorithm is described in Predictor class. ''' dir = f"std{Predictor.std_threshold}_n{Predictor.width}_count{Predictor.count_threshold}" if out_directory != "test_dir": dir = out_directory if dir not in os.listdir("visualization"): os.mkdir(f"visualization/{dir}") if dir not in os.listdir("curves"): os.mkdir(f"curves/{dir}") parser = Parser("test") for filename in os.listdir(curves_directory): data = parser.read_one_curve(curves_directory + filename) curve = Curve(data, filename[5:-4:], Predictor.error_threshold) if Predictor.starboy(curve): curve.plot( t_mean=curve.time_mean ) # plots curve, saves to file in visualization/dir/ pl.savefig(f"visualization/{dir}/{curve.name}.png") pl.clf() print(curve)
def __new__(self, shape): if shape == "Chart": return Chart() if shape == "Image": return Image() if shape == "Table": return Table() if shape == "BarCode": return BarCode() if shape == "Text": return Text() if shape == "Rounded": return Rounded() if shape == "Box": return Box() if shape == "Connector": return Connector() if shape == "Curve": return Curve() if shape == "Line": return Line() if shape == "Arc": return Arc() return None
def get_trace(self, label='A', name=None): tr = self._trace_(label) trData = tr.MeasurementData X = list(tr.DoubleData(TraceDataSelect.X,True)) Y = list(tr.DoubleData(TraceDataSelect.Y,True)) if name == None: name = tr.DataName res = Series(Y, index=X) meas = self.app.Measurements[tr.MeasurementIndex] curve = Curve() curve.set_params(**self.params_from_meas(meas)) y_unit=tr.YAxisUnit if y_unit=="dBm": res = 1000*(10**(res/10))/curve.params['bandwidth'] y_unit='J' curve.set_data(res) curve.set_params(y_unit=y_unit, x_unit=tr.XAxisUnit) curve.set_params(trace_label=label) curve.set_params(current_average=self.current_average(label)) curve.set_params(data_name=tr.DataName) return curve
def _get_curve(self): x_y = self.driver.sc.fetch() meta = dict() meta["name"] = "specan_curve" meta["curve_type"] = 'SpecAnCurve' meta["trace_type"] = self.tr_types[self.tr_type] meta["averaging"] = self.number_of_sweeps meta["center_freq"] = self.frequency_center meta["start_freq"] = self.frequency_start meta["stop_freq"] = self.frequency_stop meta["span"] = self.span meta["bandwidth"] = self.resolution_bandwidth meta["sweep_time"] = self.sweep_time meta["detector_type"] = self.detector_types[self.detector_type] meta["trace"] = self.trace_idxs[self.trace_idx] meta["instrument_type"] = "SpecAn" meta["instrument_logical_name"] = self.logical_name #curve = Curve(pandas.Series(x_y[1], index = x_y[0]), meta = meta) curve = Curve() curve.set_data(pandas.Series(x_y[1], index = x_y[0])) curve.set_params(**meta) return curve
def redraw_curve(self, evt=None): r1 = self.radius1.get() r2 = self.radius2.get() w1 = self.omega1.get() w2 = self.omega2.get() p = self.phi.get() points = self.points.get() try: points = int(points) except ValueError: return curve = Curve(r1, r2, w1, w2, p, points) self.canvas.delete("all") for i in range(0, points - 1): coord0 = curve.coordinates[i] x0, y0 = coord0 coord1 = curve.coordinates[i + 1] x1, y1 = coord1 # Ligger 250 til for at centrerer det i billedet self.canvas.create_line(x0 + 250, y0 + 250, x1 + 250, y1 + 250, fill="blue")
def main(): # 1st part: drawing curve and manipulate image color input_image = Image.open('zzz.jpg') pp0 = Pixel(30, 30) pp1 = Pixel(330, 30) C = Curve(input_image) cc = C.curve_draw(pp0, pp1, [(.2, 90), (.4, 350), (.6, 100), (.8, 80)]) # cc = C.curve_draw(pp0, pp1, [(.2,90), (.4, 150), (.6, 100), (.8, 80)]) # cc = C.curve_draw(pp0, pp1, [(.2,70), (.4, 100), (.6, 120), (.8, 80)]) # cc = C.curve_draw(pp0, pp1, [(.2,90), (.4, 120), (.6, 100), (.8, 80)]) C.image.show() print(cc) a, b, c = C.calc_parabola_vertex(int(cc[1][0]), int(cc[1][1]), int(cc[2][0]), int(cc[2][1]), int(cc[3][0]), int(cc[3][1])) C.color_map(a, b, c) C.image.show() print(a, b, c) # 2nd part: hue switching image_manipulation('zzz.jpg', 'Second_Image.png', save_name='hue_modification.png') image_manipulation('zzz.jpg', 'Second_Image_1.png', save_name='hue_modification_1.png') image_manipulation('zzz.jpg', 'Second_Image_2.png', save_name='hue_modification_2.png')
def apply_curve(image, curve_file): img_curve = Curve(curve_file, 'crgb') image_array = numpy.array(image) curve_manager = CurveManager() curve_manager.add_curve(img_curve) curve_array = curve_manager.apply_curve('crgb', image_array) return Image.fromarray(curve_array)
def plot_all_curves(): ''' Simple function that plots all curves located in 'data/' folder ''' dir = f"batch_alg_std{Predictor.std_threshold}_count{Predictor.count_threshold}" if dir not in os.listdir("visualization"): os.mkdir(f"visualization/{dir}") if dir not in os.listdir("curves"): os.mkdir(f"curves/{dir}") for filename in os.listdir('data/'): parser = Parser("test") data = parser.read_one_curve("data/" + filename) curve = Curve(data, filename[5:-4:], Predictor.error_threshold) if Predictor.predict_test(curve, Predictor.std_threshold, Predictor.count_threshold): params = f"{curve.some_value:.0}|{curve.time_mean:.1f}|{curve.time_std:.1f}|{curve.discarded_count}|{filename[:-4:]}" curve.plot( t_mean=curve.time_mean ) # plots whole curve, saves to file in visualization/dir/ pl.savefig(f"visualization/{dir}/{filename[:-4:]}.png") pl.clf() curve.plot(t_min = curve.time_mean - curve.time_std/2, \ t_max = curve.time_mean + curve.time_std/2, t_mean = curve.time_mean) # plots only interesting are, saves to file in curves/dir pl.savefig(f"curves/{dir}/{filename[:-4:]}_{params}.png") pl.clf() #print(curve.time_mean, curve.time_std, curve.discarded_count, curve.some_value) # prints parameters print(params)
def distance(self, concat: bool = True): """ Calculates the distance passed by the middle of the robot through the curve. :return: The distance passed through the curve """ cp = self.control_points() curves = [ Curve(control_points=points, spline_type=SplineType.QUINTIC_HERMITE) for points in cp ] seg_lengths = [ length_integral( 0, 1, lambda u: curves[i].calculate(u, CurveType.VELOCITY), Trajectory.L_SAMPLE_SIZE) for i in range(self.num_of_segments) ] sums = [ sum([seg_lengths[j] for j in range(i)]) if i > 0 else 0 for i in range(self.num_of_segments) ] lengths = [[[ i + j / Trajectory.SAMPLE_SIZE, length_integral( 0, j / Trajectory.SAMPLE_SIZE, lambda u: curves[i].calculate(u, CurveType.VELOCITY), Trajectory.L_SAMPLE_SIZE) + sums[i] ] for j in range(Trajectory.SAMPLE_SIZE + 1)] for i in range(self.num_of_segments)] return npconcat(lengths) if concat else lengths
def suzuki(q0): ''' TODO: add reference ''' data = {} data['q0'] = q0 data['family'] = 'suzuki' data['q'] = q = 2 * q0**2 data['m'] = m = q + 2 * q0 + 1 data['g'] = g = q0 * (q - 1) #generating values for d(i) where i is taken mod m dlist = [] for a in range(-q0, q0 + 1): for b in range(-q0 + abs(a), q0 - abs(a) + 1): dlist.append([(a * (q0 + 1) + b * q0 - q0 * (q0 + 1)) % m, (q0 - a) * (q - 1)]) dlist.sort() data['dvalp'] = data['dvalq'] = [i[1] for i in dlist] data['kq'] = 0 data['n'] = q + 1 + 2 * g * q0 data['curve_eq_latex'] = 'y^%(q)s + y = x^%(q0)s (x^%(q)s + x)' % data data['curve_eq_code'] = 'y^%(q)s + y - x^%(q0)s * (x^%(q)s + x)' % data data['P'] = '[0 , 0 , 1]' data['Q'] = '[1 , 0 , 0]' data['ddeg'] = q**2 - 1 data['dq'] = -1 c = Curve() c._data = data return c
def robot_curve(self, curve_type: CurveType, side: RobotSide): """ Calculates the given curve for the given side of the robot. :param curve_type: The type of the curve to calculate :param side: The side to use in the calculation :return: The points of the calculated curve """ coeff = (self.robot.robot_info[3] / 2) * (1 if side == RobotSide.LEFT else -1) cp = self.control_points() t = linspace(0, 1, samples=Trajectory.SAMPLE_SIZE + 1) curves = [ Curve(control_points=points, spline_type=SplineType.QUINTIC_HERMITE) for points in cp ] dx, dy = npconcat([c.calculate(t, CurveType.VELOCITY) for c in curves]).T theta = nprads(angle_from_slope(dx, dy)) points = npconcat([c.calculate(t, curve_type) for c in curves]) normals = coeff * nparray([-npsin(theta), npcos(theta)]).T return points + normals
def hermitian(q0): ''' TODO: add reference to Stichtenoth paper ''' data = {} data['q0'] = q0 data['family'] = 'hermitian' data['q'] = q = q0**2 data['m'] = m = q0 + 1 data['g'] = g = q0 * (q0 - 1) / 2 #generating values for d(i) where i is taken mod m dlist = [] for d in range(m): dlist.append([(-d) % m, d * (q0 - 1)]) dlist.sort() data['dvalp'] = data['dvalq'] = [i[1] for i in dlist] data['kq'] = 0 data['n'] = q + 1 + 2 * g * q0 data['curve_eq_latex'] = 'y^{q + 1} = x^q + x' data['curve_eq'] = 'y^(%(q0)s + 1) - x^%(q0)s - x' % data data['P'] = '[0 , 0 , 1]' data['Q'] = '[1 , 0 , 0]' data['ddeg'] = q0**3 - 1 data['dq'] = -1 c = Curve() c._data = data return c
def __init__(self, jointsName, curve, spans=10, horizontalSpine=0): """ :param jointsName: :param curve: :param spans: :param horizontalSpine: """ jointsName = jointsName + "_jnt_" curveName = jointsName + "baseCrv" #Position of the Joints self._jointsPos = [] # Curve Node creation self._curve = Curve(curveName, curve) self._curve.rebuildCurve(spans) self._startJoint = None self._endJoint = None #get cv positions for to create a joint chain self._horizontalSpine = horizontalSpine self._frontAxis = None self._zeroJoint = None self._zeroPos = None self._get_curve_points() super(SpineJoints, self).__init__(jointsName, self._jointsPos) self.set_zero_joint()
def read_input_as_curve(json_path): # read file with open(json_path, 'r') as j: data = j.read() # parse file points = json.loads(data) return Curve(points)
def start_curve(self): if self.parentWidget().present_next_num < self.parentWidget().allowed_next_num: start_point = self.get_mid_pos() curve = Curve(self.parentWidget().parentWidget(), function_widget=self.parentWidget()) curve.move(self.parentWidget().parentWidget().mapFromGlobal(start_point)) curve.raise_() self.curves.append(curve)
def test_addition(self): curve = Curve(1, 1, 31) p1 = Point(0, 1, 1, curve) p2 = Point(0, 1, 1, curve) expected = Point(8, 26, 1, curve) actual = p1 + p2 actual.convert_to_affine() self.assertEqual(actual, expected)
def main(): # a, b, c, d = [float(x) for x in input('Enter a b c d: ').strip().split(' ')] # A, B, C, D, E, F = [a, -1 / 2, 0, b / 2, -d / 2, c] x = Curve(3, -0.5, 0, 0.0, 0.0, 10000) # x = Curve(3, -0.5, 0, 6.5, -0.5, 9) # методичка app = QtGui.QApplication(sys.argv) ex = Carcass(HyperbolaDrawer(x)) sys.exit(app.exec_())
def addCurve(self, ctype, cname=''): if cname == '': cname = "Curve {}".format(len(self.curves) + 1) self.curves[cname] = Curve(ctype=ctype) self.c.addCurve.emit(cname) self.selectCurve(cname) self.c.selectedCurveName.emit(cname) self.update()
def processCurve(self, macro): begin = float(macro.split(' ')[0]) end = float(macro.split(' ').pop()) change = float(end - begin) duration = change * (1 / self.step_size) if self.step_size is not None else change curve = Curve(begin, end, duration) if hasattr(curve, self.curve_type): return curve.render(self.curve_type) raise Exception('curve doex not exist with type: ' + self.curve_type)
def DisplayAndQuit(self, display, size): image = Image.open(os.path.expanduser(self.InputVar.get())) rows = self.RowsVar.get() columns = self.ColumnsVar.get() curve = Curve(display, image) curve.scale = (self.ScaleVar.get(), self.ScaleVar.get()) curve.is_inverted = self.InvertedVar.get() curve.calculate_levels(5, 0, 0, columns * size, rows * size) self.display_nxm_with_border(rows, columns, size, display, curve) display.close() self.WriteConfig() self.quit()
def matching_problem(p0) : "Energy minimized in the variable 'p0'." [c, info] = Cost(q0, p0, Xt_x, Xt_mu) matching_problem.Info = info if (matching_problem.it % 20 == 0):# and (c.data.cpu().numpy()[0] < matching_problem.bestc): matching_problem.bestc = c.data.cpu().numpy()[0] q1,p1,g1 = ShootingVisualization(q0, p0, g0) q1 = q1.data.cpu().numpy() p1 = p1.data.cpu().numpy() g1 = g1.data.cpu().numpy() Q1 = Curve(q1, connec) ; G1 = Curve(g1, cgrid ) DisplayShoot( Q0, G0, p0.data.cpu().numpy(), Q1, G1, Xt, info.data.cpu().numpy(), matching_problem.it, scale_momentum, scale_attach) print('Iteration : ', matching_problem.it, ', cost : ', c.data.cpu().numpy(), ' info : ', info.data.cpu().numpy().shape) matching_problem.it += 1 return c
def generate_random_curve(number_of_points=360, gear_diff_val=1, stick_diff_val=1, position_diff_val=1): random_assembly_a = create_assemblyA(gear_diff_val=gear_diff_val, stick_diff_val=stick_diff_val, \ position_diff_val=position_diff_val) assembly_curve = get_assembly_curve_parallel( random_assembly_a, number_of_points=number_of_points) assembly_curve = normalize_curve2(assembly_curve.points) c = Curve(assembly_curve) # output curve to stdout for the C# to read print(c.to_json())
def run(): curve = Curve( CURVE ) # Generate private/public key pairs print "Generating %d key pairs..." % KEY_COUNT t = time.time() key_gen_time = keys = map( lambda _: KeyPair( curve ), range( KEY_COUNT ) ) print "Generating %d key pairs took %.3f seconds" % ( KEY_COUNT, time.time() - t ) results = [] for i in [ 2, 3, 5, 10, 20, 30, 50, 100, 200, 300, 500, 1000, 2000, 3000, 5000, 10000]: results.append( run_multiple_tests( curve, keys[0:i], tests=10 ) ) print repr( results )
def load(inputfile): incurve = Curve() incurve.load(inputfile) incurve.wrap_tables() # put curve data into global namespace global codes codes = Coding(incurve) globals().update(incurve._data) globals().update(incurve.__dict__) globals().update(codes.__dict__) global curve, c c = curve = incurve global best best = BestCodes(codes) best.load_best_codes()
def double(P): curve = Curve() inf = float('inf') a = curve.a R = Point() if (P.y == 0): R.x = inf R.y = inf return R gradien = ((3 * (P.x**2) + a) * inverse_mod(2 * P.y, curve.p)) % curve.p R.x = (gradien**2 - 2 * P.x) % curve.p R.y = (gradien * (P.x - R.x) - P.y) % curve.p return R
def load_file(): text.delete(1.0, END) statebox.delete(0, END) curves.clear() text_file = open("results/" + filebox.get(filebox.curselection()), "r") lines = [l.strip().split("\t") for l in text_file.readlines()] names = lines[0] r = np.array([float(lines[i][0]) for i in range(2, len(lines))]) for i in range(len(lines[0]) - 1): omega = np.array( [float(lines[j][i + 1]) for j in range(2, len(lines))]) curves.append( Curve(r, omega, float(lines[1][i + 1]) * 1e-36, names[i + 1])) for curve in curves: statebox.insert(END, curve.name)