Example #1
2
    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
Example #2
2
    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 update_all_files():
        res = QtGui.QMessageBox.question(QtGui.QWidget(),
                                           "are you sure",
                                           "It's strongly advised to backup the directory " \
                                           + MEDIA_ROOT \
                                           + " before updating the files. Proceed anyway ?",
                                           "Cancel",
                                           "OK")
        if res==0:
            return
        allcurves = models.CurveDB.objects.all()
        total = len(allcurves)
        n_done = 0
        for cur in allcurves:
            #cur.data
            
            cur.params
            file = cur.get_full_filename()
            directo = os.path.dirname(file)
            if not os.path.exists(directo):
                os.makedirs(directo)
            Curve.save(cur, file, with_data=False)
            n_done += 1
            print 'updated ' + str(n_done) + ' curves / ' + str(total) 
            #del cur._data
            #gc.collect()

        print "All "+str(len(allcurves))+" curve files are now up to date! "
Example #4
0
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
Example #5
0
def weil_pairing(P, Q, S, R, order):
    x1 = miller_loop(P, Curve.add(Q, S))
    x2 = miller_loop(P, S)
    x3 = miller_loop(Q, Curve.add(P, R))  # Curve.negate(S)))
    x4 = miller_loop(Q, R)  # Curve.negate(S))
    result = (x1 // x2) // (x3 // x4)
    return result
Example #6
0
    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()
Example #7
0
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
Example #8
0
    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)
Example #9
0
    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)
Example #10
0
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)
Example #11
0
    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)
Example #12
0
def miller_loop(P, XXX):
    T = P
    f = 1
    for i in [0, 1]:  # TODO: NEED ORDER HERE
        gtmp = g_pq(T, T, XXX)
        f = f * f * gtmp
        T = Curve.multiply(T, 2)
        if i == 1:
            g_tmp = g_pq(T, P, XXX)
            f = f * g_tmp  # g_pq(T, P, XXX)
            T = Curve.add(T, P)
    return f
Example #13
0
 def test_save_curve_only(self):
     from curve import Curve
     curve = CurveDB()
     curve.set_data(pandas.Series([1,4,6]))
     curve.save()
     print_and_log("================================")
     for i in range(3):
         for j in range(100):
             curve.params['coucou' + str(j)] = i*j
         tic = time.time()
         Curve.save(curve, curve.get_full_filename())
         print_and_log("time for saving 1 curve with 100 parameters in h5: " + str(time.time() - tic))
Example #14
0
 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()
Example #15
0
 def save(self):
     """
     Saves the curve in the database. If the curve is data_read_only 
     The actual datafile will be saved only on the first call of save().
     """
     tic = profile(PROFILE_SAVE, "start: ")
     
     self.set_default_params()
     tic = profile(PROFILE_SAVE, "set_defaults: ", tic)
     
     
     #models.Model.save(self) #this way, the id is correct
     
     tic = profile(PROFILE_SAVE, "other default assignements: ", tic)
     self.save_params() #this saves the curve with the correct id
     
     
     if not self.data_file:
         self.data_file = os.path.join( \
                 self.params["date"].strftime('%Y/%m/%d'), \
                 slugify(str(self.id) +"_"+ self.name) + '.h5')
         full_path = self.get_full_filename()
         dirname = os.path.dirname(full_path)
         
         tic = profile(PROFILE_SAVE, "format dirname: ", tic)
         
         if not os.path.exists(dirname):
             os.makedirs(dirname) 
         tic = profile(PROFILE_SAVE, "create dir: ", tic)
         full_path = default_storage.get_available_name(full_path)
         tic = profile(PROFILE_SAVE, "get_available_name: ", tic)
         self.data_file = os.path.relpath(full_path, MEDIA_ROOT)
         tic = profile(PROFILE_SAVE, "set datafile: ", tic)
     
     
     
     tic = profile(PROFILE_SAVE, "save_params: ", tic)
     if not self.params["data_read_only"]:
         Curve.save(self, self.get_full_filename())
         tic = profile(PROFILE_SAVE, "Curve.save(): ", tic)
     else:
         if not os.path.exists(self.get_full_filename()):
             Curve.save(self, self.get_full_filename())
             tic = profile(PROFILE_SAVE, "Curve.save(): ", tic)
     self.save_tags()
     tic = profile(PROFILE_SAVE, "save tags ", tic)
     #if self.saved_in_db==False:
     #    self.saved_in_db=True
     #    models.Model.save(self)
     models.Model.save(self)
     tic = profile(PROFILE_SAVE, "Model.save(): ", tic)
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 _backup_all_files(self):
     filename = str(QtGui.QFileDialog.getSaveFileName(parent=self))
     if not filename:
         return
     #with ZipFile(filename, 'w') as zpf:
     #    db_file = pyinstruments.datastore.settings.DATABASE_FILE
     #    zpf.write(db_file, os.path.split(db_file)[-1] + "_saved")
     for curve in models.CurveDB.objects.all():
         curve.data
         curve.params
         directo = os.path.dirname(os.path.join(filename, curve.data_file.name))
         if not os.path.exists(directo):
             os.makedirs(directo)
         Curve.save(curve, os.path.join(filename, curve.data_file.name))
         del cur._data
Example #18
0
    def train(self, features, grades):
        """Train a rank_svm on the specified features and grades.
        train_rank_svm(self, features, grades):
        
        features - numpy array/matrix with one row per essay
        grades - vector with one entry per essay
        """
        self.min_grade = min(grades)
        self.max_grade = max(grades)
        num_essays, num_features = features.shape
        
        # Convert data into svmlight format [(label, [(feature, value), ...], query_id), ...]
        training_data = []
        for essay_ind,grade in enumerate(grades):
            feature_list = [(feat_ind+1,feat_val) for feat_ind,feat_val in enumerate(features[essay_ind,:])]
            training_data.append((grade, feature_list, 1))

        self.model = svmlight.learn(training_data, type='ranking', verbosity=0, C=100)
        
        grade_counts = {}
        for grade in grades:
            if grade not in grade_counts:
                grade_counts[grade] = 0
            grade_counts[grade] += 1
        self.grade_probs = dict([(grade, count/float(num_essays)) for grade,count in grade_counts.iteritems()])
        scores = self.classify_rank_svm(features)
        self.curve = Curve(scores, probs=self.grade_probs)
Example #19
0
    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
Example #20
0
    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")
Example #21
0
    def train(self, features, grades):
        """Train a rank_svm on the specified features and grades.
        train_rank_svm(self, features, grades):
        
        features - numpy array/matrix with one row per essay
        grades - vector with one entry per essay
        """
        self.min_grade = min(grades)
        self.max_grade = max(grades)
        num_essays, num_features = features.shape

        f = open(SVM.data_file, "w")
        f.write("%d\t%d\n" % (num_essays, num_features))
        for essay_ind in range(num_essays):
            feature_str = "\t".join([str(feat) for feat in features[essay_ind, :]])
            f.write("%d\t%s\n" % (grades[essay_ind], feature_str))
        f.close()

        os.system("learn/rank_svm %s %s > /dev/null" % (SVM.data_file, SVM.model_file))

        # Set a curve based on the SVM ranking scores
        grade_counts = {}
        for grade in grades:
            if grade not in grade_counts:
                grade_counts[grade] = 0
            grade_counts[grade] += 1
        self.grade_probs = dict([(grade, count / float(num_essays)) for grade, count in grade_counts.iteritems()])
        scores = self.classify_rank_svm(features)
        self.curve = Curve(scores, probs=self.grade_probs)
Example #22
0
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 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)
Example #24
0
    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
Example #25
0
    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
Example #26
0
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_())
Example #27
0
 def _backup_all_files(self):
     filename = str(QtGui.QFileDialog.getSaveFileName(parent=self))
     if not filename:
         return
     #with ZipFile(filename, 'w') as zpf:
     #    db_file = pyinstruments.datastore.settings.DATABASE_FILE
     #    zpf.write(db_file, os.path.split(db_file)[-1] + "_saved")
     for curve in models.CurveDB.objects.all():
         curve.data
         curve.params
         directo = os.path.dirname(
             os.path.join(filename, curve.data_file.name))
         if not os.path.exists(directo):
             os.makedirs(directo)
         Curve.save(curve, os.path.join(filename, curve.data_file.name))
         del cur._data
         gc.collect()
Example #28
0
 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)
Example #29
0
 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()
Example #30
0
    def __init__(self):
        super(Window,self).__init__()
        self.set_size(1500,600)
       
        #These are the declarations of the circles to be put in series
        #for the fourier series representaion
        #Here i have them coded in by hand but i could change
        #the code to have a selected amount of circles
        #and pre-defined lengths,rates to create
        #certain curves
        self.pendulum = Pendulum((300,300),150,5,0)
        self.circle = Circle((300,300),100)
        
        self.pendulum2 = Pendulum((self.pendulum.end_diff_x + self.pendulum.pivot_x,
                                   self.pendulum.end_diff_y + self.pendulum.pivot_y),
                                    75,5,0)
        self.circle2 = Circle((self.pendulum2.pivot_x,
                              self.pendulum2.pivot_y),
                              self.pendulum2.length)
        
        self.pendulum3 = Pendulum((self.pendulum2.end_diff_x + self.pendulum2.pivot_x,
                                   self.pendulum2.end_diff_y + self.pendulum2.pivot_y),
                                    50,5,0)
        self.circle3 = Circle((self.pendulum3.pivot_x,
                              self.pendulum3.pivot_y),
                              self.pendulum3.length) 

        self.pendulum4 = Pendulum((self.pendulum3.end_diff_x + self.pendulum3.pivot_x,
                                   self.pendulum3.end_diff_y + self.pendulum3.pivot_y),
                                    25,5,0)
        self.circle4 = Circle((self.pendulum4.pivot_x,
                              self.pendulum4.pivot_y),
                              self.pendulum4.length) 

        self.pendulum5 = Pendulum((self.pendulum4.end_diff_x + self.pendulum4.pivot_x,
                                   self.pendulum4.end_diff_y + self.pendulum4.pivot_y),
                                    12,5,0)
        self.circle5 = Circle((self.pendulum5.pivot_x,
                              self.pendulum5.pivot_y),
                              self.pendulum5.length) 
        
        #the curve resulting from the series
        self.curve = Curve(200)

        pyglet.clock.schedule_interval(self.update,1.0/40)
Example #31
0
 def _get_curve(self):
     x_y = self.fetch()
     meta = dict()
     
     meta["name"] = "scope_curve"
     meta["acquisition_type"] = self.acquisition_type
     meta["averaging"] = self.number_of_averages
     meta["time_per_record"] = self.time_per_record
     meta["record_length"] = self.record_length
     meta["coupling"] = self.ch_coupling
     meta["full_range"] = self.ch_range
     meta["input_freq_max"] = self.ch_input_frequency_max
     meta["channel"] = "CH"+str(self.channel_idx)
     meta["curve_type"] = "ScopeCurve"
     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
Example #32
0
 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
Example #33
0
    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)
            name = filename.split(".")[-2].split("_")[-1]
            curve = Curve(data, name, Predictor.error_threshold)
            curve.cut_points([0, 2137], [2450, 2500])
        

            if Predictor.starboy(curve):
                
                p = curve.fit()

                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()

                curve.plot(t_mean = curve.time_mean, t_std=True, only_lens=True)                    # plots curve, saves to file in visualization/dir/
                x = np.arange(curve.times[0], curve.times[-1], 0.1)
                pl.plot(x, Curve.paczynski(x, p[0], p[1], p[2], p[3], p[4]), label="Fitted Paczyński's curve")
                pl.savefig(f"curves/{dir}/{curve.name}.png") 
                pl.clf()

                print(curve)
Example #34
0
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')
Example #35
0
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)
Example #36
0
	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
Example #37
0
 def _get_curve(self):
     x_y = self.driver.sc.fetch()
     meta = dict()
     
     meta["name"] = "scope_curve"
     meta["acquisition_type"] = self.acquisition_types[self.acquisition_type]
     meta["averaging"] = self.number_of_averages
     meta["start_time"] = self.start_time
     meta["record_length"] = self.record_length
     meta["sample_rate"] = self.sample_rate
     meta["coupling"] = self.ch_couplings[self.ch_coupling]
     meta["full_range"] = self.ch_range
     meta["offset"] = self.ch_offset
     meta["input_freq_max"] = self.ch_input_frequency_max
     meta["input_impedance"] = self.ch_input_impedance
     meta["channel"] = self.channel_idxs[self.channel_idx]
     meta["curve_type"] = "ScopeCurve"
     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
Example #38
0
class RankSVM:
    """Python interface to rank svm in svm_light."""
    
    def __init__(self, **kwargs):
        self.model = None
    def train(self, features, grades):
        """Train a rank_svm on the specified features and grades.
        train_rank_svm(self, features, grades):
        
        features - numpy array/matrix with one row per essay
        grades - vector with one entry per essay
        """
        self.min_grade = min(grades)
        self.max_grade = max(grades)
        num_essays, num_features = features.shape
        
        # Convert data into svmlight format [(label, [(feature, value), ...], query_id), ...]
        training_data = []
        for essay_ind,grade in enumerate(grades):
            feature_list = [(feat_ind+1,feat_val) for feat_ind,feat_val in enumerate(features[essay_ind,:])]
            training_data.append((grade, feature_list, 1))

        self.model = svmlight.learn(training_data, type='ranking', verbosity=0, C=100)
        
        grade_counts = {}
        for grade in grades:
            if grade not in grade_counts:
                grade_counts[grade] = 0
            grade_counts[grade] += 1
        self.grade_probs = dict([(grade, count/float(num_essays)) for grade,count in grade_counts.iteritems()])
        scores = self.classify_rank_svm(features)
        self.curve = Curve(scores, probs=self.grade_probs)
        
    def grade(self, features, options={}):
        scores = self.classify_rank_svm(features)
        return [self.curve.curve(score) for score in scores]
        
    def classify_rank_svm(self, features):
        """Run rank_svm to rank the specified essay features (numpy matrix/array).
        Returns a vector of scores of the specified essays."""
        assert self.model is not None

        # Convert data into svmlight format [(label, [(feature, value), ...], query_id), ...]
        test_data = []
        for essay_ind,feat_vec in enumerate(features):
            feature_list = [(feat_ind+1,feat_val) for feat_ind,feat_val in enumerate(feat_vec)]
            test_data.append((0, feature_list, 1))

        return svmlight.classify(self.model, test_data)
 def addCurve(self, label, type, ylabel, unit, tableName, keyword, combo, spinbox, cmb_unit):
     ax = self.getAxe(type)
     if ax is not None:
         if not spinbox:
             new_curve = Curve(self.parent, self, label, type, ylabel, unit, tableName, keyword, combo)
         else:
             new_curve = Derivate(self.parent, self, label, type, ylabel, unit, tableName, keyword, combo, spinbox,
                                  cmb_unit)
         if new_curve.last_id > 0:
             line, = ax.plot_date(new_curve.get_xdata(), new_curve.get_ydata(), '-', label=label)
             self.dictofline[line] = new_curve
             new_curve.setLine(line)
             self.figure.canvas.draw()
             return 1
         else:
             return 0
     else:
         return 0
Example #40
0
	def __init__( self ) :
		Curve.__init__(self)
Example #41
0
if graphics [0:3] == "Nar" :
    print "This is a test of the Python interface to the Limeil Lab graphics"
    print "package, Narcisse. You  need Narcisse to be running. Fire it up by"
    print "typing /dist/basis/Narcisse/bin/Narcisse."
elif graphics == "Gist" :
    print "This is a test of the Python interface to the Gist graphics package."

paws ()

vsf = 0.
c = 1
s = 1000.
kmax = 25
lmax = 35

c1 = Curve ( y = arange (1, kmax+1, dtype = Float) , color = "yellow" )
g2 = Graph2d ( c1 , titles = ["Bottom of the Barrel", "Top Dog",
                              "Leftist", "Reaganist"] )
g2.plot ( )
paws ( )
c2 = Curve ( y = sqrt (arange (1, kmax+1, dtype = Float)**3) ,
   color = "blue")
g2.add ( c2 )
g2.plot ( )
paws ( )
c1.set (marks = 1, marker = "A")
c2.set (marks = 1, marker = "B")
g2.plot ( )
paws ( )
c1.set (marks = 0)
c2.set (marks = 0)
Example #42
0
 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 = 1e3*(10**(res/10))/curve.params['bandwidth']
         y_unit='mJ'
     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
Example #43
0
class SVM:
    """Python interface to rank SVM c code."""

    tmp_path = "/tmp"
    data_file = os.path.join(tmp_path, "svm_rank_features.dat")
    model_file = os.path.join(tmp_path, "svm_rank_model.dat")
    test_file = os.path.join(tmp_path, "svm_rank_test.dat")
    predictions_file = os.path.join(tmp_path, "svm_rank_predictions")

    os.system("cd learn && make > /dev/null")

    def __init__(self, **kwargs):
        pass

    def train(self, features, grades):
        """Train a rank_svm on the specified features and grades.
        train_rank_svm(self, features, grades):
        
        features - numpy array/matrix with one row per essay
        grades - vector with one entry per essay
        """
        self.min_grade = min(grades)
        self.max_grade = max(grades)
        num_essays, num_features = features.shape

        f = open(SVM.data_file, "w")
        f.write("%d\t%d\n" % (num_essays, num_features))
        for essay_ind in range(num_essays):
            feature_str = "\t".join([str(feat) for feat in features[essay_ind, :]])
            f.write("%d\t%s\n" % (grades[essay_ind], feature_str))
        f.close()

        os.system("learn/rank_svm %s %s > /dev/null" % (SVM.data_file, SVM.model_file))

        # Set a curve based on the SVM ranking scores
        grade_counts = {}
        for grade in grades:
            if grade not in grade_counts:
                grade_counts[grade] = 0
            grade_counts[grade] += 1
        self.grade_probs = dict([(grade, count / float(num_essays)) for grade, count in grade_counts.iteritems()])
        scores = self.classify_rank_svm(features)
        self.curve = Curve(scores, probs=self.grade_probs)

    def grade(self, features, options={}):
        scores = self.classify_rank_svm(features)
        return [self.curve.curve(score) for score in scores]

    def classify_rank_svm(self, features):
        """Run rank_svm to rank the specified essay features (numpy matrix/array).
        Returns a vector of scores of the specified essays."""
        num_essays, num_features = features.shape

        f = open(SVM.test_file, "w")
        f.write("%d\t%d\n" % (num_essays, num_features))
        for essay_ind in range(num_essays):
            feature_str = "\t".join([str(feat) for feat in features[essay_ind, :]])
            f.write("0\t%s\n" % feature_str)
        f.close()

        os.system("learn/rank_svm %s %s %s > /dev/null" % (SVM.test_file, SVM.model_file, SVM.predictions_file))

        f = open(SVM.predictions_file)
        scores = [float(score) for score in f.readlines()]
        f.close()

        return scores
Example #44
0
def demo ( ) :
    c1 = Curve ( y = [0,1] , marks = 1 , marker = "A")
    pl = Plotter ( dpi = 75 )
    g1 = Graph2d ( c1, plotter = pl , titles = "Curve marked with A" ,
                title_colors = "blue")
    g1.plot ( )
    print "\nA small (75 dpi) window with line marked A from (0,0) to (1,1)."
    paws ( )
#  pl = Plotter ( dpi = 100 )
#  g1 = Graph2d ( c1, plotter = pl , titles = "Curve marked with A" ,
#              title_colors = "fg")
#  g1.plot ( )
#  print "\nA large (100 dpi) window with line marked A from (0,0) to (1,1)."
#  paws ( )
    c2 = Curve ( y = [1,0] , marks = 1 , marker = "B")
    g1.add (c2)
    g1.change (titles = "New curve marked B.")
    g1.plot ( )
    print "\nAdded line marked B from (0,1) to (1,0) in previous plot."
    paws ( )
    c1.set ( x = [1,2] )
    c2.set ( x = [1,2] )
    g1.change (axis_scales = "loglin", titles = "Same, x axis now logarithmic.")
    g1.plot ( )
    print "\nSame, x axis now logarithmic."
    paws ( )
    g1.change (x_axis_scale = "lin", titles = "x axis back to linear.")
    g1.plot ( )
    print "\nSame, x axis now linear again."
    paws ( )
    g1.change(axis_limits=[[1.2,1.8],[0.2,0.8]],
           titles="Limits now 1.2<x<1.8, 0.2<y<0.8.")
    g1.plot ( )
    print "\nLimits now 1.2<x<1.8, 0.2<y<0.8."
    paws ( )
#  g1.change(y_axis_limits=[0.4,0.6],
#         titles="Limits now 1.2<x<1.8, 0.4<y<0.6")
#  g1.plot ( )
#  print "\nLimits now 1.2<x<1.8, 0.4<y<0.6"
#  paws ( )
    g1.change(axis_limits="defaults",
           titles="Limits now back to extreme values.")
    g1.plot ( )
    print "\nLimits now back to extreme values."
    paws ( )
    x=10*pi*arange(200, dtype = Float)/199.0
    c1 = Curve ( x = x , y = sin(x),marks = 1, marker= "A")
    g1.delete (2)
    g1.delete (1)
    g1.add (c1)
    g1.change (titles = "Five cycles of a sine wave, marked A.")
    g1.plot ( )
    print "\nFive cycles of a sine wave."
    paws ( )
    c1.set(marks = 0, width = 6 , type = "dash")
    g1.change (titles = "A mark gone, bold dashed.")
    g1.plot ( )
    print "\nTurn off A marker, plot curve as bold dashed."
    paws ( )
    x=2*pi*arange(200, dtype = Float)/199.0
    crvs = []
    for i in range (1,7) :
        r = 0.5*i -(5-0.5*i)*cos(x)
        s = `i`
        crvs.append(Curve(y=r*sin(x),x=r*cos(x),marks=0, color=-4-i,label=s))
    g1=Graph2d(crvs,plotter = pl,titles="Nested cardioids in colors")
    g1.plot ( )
    print "\nNested cardioids in primary and secondary colors."
    paws()
    g1.change(titles = ["colors","cardioids","Nested","in many"],
           title_colors = ["red","yellow","magenta","blue"])
    g1.plot ( )
    print "\nThe same with four titles in many colors."
    paws()
    mks = ['.','+','*','o','x','A']
    for i in range (1,7) :
        crvs[i-1].set (color="fg", type = 0, marker = mks[i-1])
    g1.change (titles = "Marked curves", title_colors = "fg")
    g1.plot ( )
    print "\nChanges color to foreground, types to no lines."
    print "Markers are point, plus, asterisk, circle, cross, and A."
    paws()
    for i in range (1,6) :
        crvs[i-1].set (marks = 0, type = i-1)
    crvs[i].set (type = 1, width = 4)
    g1.change (titles = "Different curve types.")
    print "\nChanges line types to solid, dash, dot, dashdot, dashdotdot."
    print "Outermost cardioid becomes a thick solid curve."
    g1.plot()
    paws ()
    ValueError = "ValueError"
    x=a3(-1,1,26)
    y=transpose (x)
    zz=x+1j*y
    zz=5.*zz/(5.+zz*zz)
    xx=zz.real
    yy=zz.imag
    q1 = QuadMesh ( x=array(xx, copy = 1), y=array(yy, copy = 1) )
    g1.new(q1, plotter = pl, titles = "Round mesh with bites out of sides",
       axis_limits = [[min(ravel(xx)),max(ravel(xx))],
                      [min(ravel(yy)),max(ravel(yy))]])
    g1.plot()
    print "\nQuadrilateral mesh -- round with bites out of its sides."
    paws (  )
    q1.set (boundary = 1, vx = x+.5, vy=y-.5,ktype = "none", ltype = "none")
    g1.change(titles = "Vector field on mesh.")
    g1.plot ( )
    print "\nVelocity vectors. Try zooming and panning with mouse."
    paws ( )
    q1.set (vx = None, vy = None, z = mag (x+.5,y-.5),marks = 1,
       boundary=1,boundary_type="dash",marker="A")
    g1.change(titles = "Lettered contour plot, dashed boundary.")
    g1.plot ( )
    print "\nLettered contours, with boundary dashed."
    paws ( )
    q1.set (filled=1, type = "dash", color = "white")
    g1.plot ( )
    print "\nFilled lettered dashed contours, with boundary dashed."
    paws ()
    q1.set(marks = 0,boundary_type="solid",levels=array([0.5,1.0,1.5]),
        filled=1, contours = 1, type = "dash", color = "white",
        width = 3)
    g1.change(titles = "Filled mesh, dashed contours")
    g1.plot ( )
    print "\nFilled mesh (color only) with three dashed contours overlaid."
    paws()
    print "\nAfter each new palette is installed, hit <RETURN> for the next."
    pal=["heat.gp","stern.gp","rainbow.gp","gray.gp","yarg.gp","earth.gp"]
    for i in range(6):
        g1.quick_plot(color_card = pal[i],titles = "Palette " + pal[i])
    #  g1.plot ( )
        paws ( )
    pal = ["vg.gs", "boxed.gs", "vgbox.gs", "nobox.gs", "work.gs"]
    q1.set (marks = 1,boundary_type="dash",levels = 8, filled = 0, color = "fg")
    for i in range (5) :
        pl.set_style (pal [i])
##    g1 = Graph2d (q1, plotter = pl, titles = "Style Name: " + pal[i])
        g1.change (plotter = pl, titles = "Style Name: " + pal[i])
        g1.plot ( )
        paws ( )
    x=a3(-6,6,200)
    y=transpose (x)
    r=mag(y,x)
    theta=arctan2(y,x)
    funky=cos(r)**2*cos(3*theta)
    c1 = CellArray(z=funky)
    g1.replace (1,c1)
    g1.change (color_card = "earth.gp",
            titles ="Cell array, three cycles in theta,r",
            axis_limits = "defaults")
    g1.plot()
    paws()

    theta = a2 (0, 2*pi, 18)
    x = cos (theta)
    y = sin (theta)

    ln = Lines (x0 = x, y0 = y, x1 = transpose (x), y1 = transpose (y))
    g1 = Graph2d (ln, plotter = pl, xyequal = 1, titles = "Seventeen pointed star.")
    g1.plot ()
    print "\nAll 17 pointed stars."
    paws ( )

    print "\nNext we will see a lissajous-style animation."
    print "First run without animation mode."
    print "Second run with animation mode."


    anim = Animation2d ( initialize = init, calculations = [calc1, calc2],
                      update = incr, animation = 0, nsteps = 200 )

    g1 = Graph2d ( anim , plotter = pl)
    g1.plot ( )
    paws ( )
    anim.set (animation = 1)
    g1.plot ( )
Example #45
0
class SpineJoints(JointChain):
    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()

    # BASE SETUP METHODS
    def set_zero_joint(self):

        #Removes Zero Joint from Joint Chain
        pm.joint(self.jointChain[0], e=True, zso=True, oj='xyz', sao='xup')
        self.zeroJoint = self.jointChain[0]

        self._zeroPos = pm.dt.Point(pm.getAttr(self._zeroJoint.translate))
        self.jointChain.remove(self.jointChain[0])
        self.jointPos.remove(self.jointPos[0])
        pm.joint(self.jointChain[1], e=True, zso=True, oj='xyz', sao='yup')
        for i in range(1, len(self.jointChain)):
            pm.joint(self.jointChain[i], e=True, zso=True, oj='xyz', sao='yup')
            #sets Start End Num Of Joints again
        self._numOfJoints = len(self._jointChain)
        #Orient Zero Joint
        temporalGroup = DrawNode(Shape.transform, 'temporalGroup')
        pm.parent(self.startJoint, temporalGroup.drawnNode)

        print (pm.getAttr(self.zeroJoint.jointOrient))
        pm.setAttr(self.zeroJoint.jointOrientX, 0)
        pm.parent(self.startJoint, self.zeroJoint)
        temporalGroup.delete()

    def _get_curve_points(self):
        self._jointPos = []

        firstCVPos = self._curve.cvPositions[0]
        zeroCVsPos = pm.dt.Vector(self._curve.cvPositions[0])

        if not self.horizontalSpine:
            zeroCVsPos[1] = zeroCVsPos[1] - (self._curve.arclen / 10)
        else:
            zeroCVsPos[2] = zeroCVsPos[2] - (self._curve.arclen / 10)

        self._jointsPos.append(zeroCVsPos)
        self._jointsPos.append(firstCVPos)

        for i in range(2, (self._curve.numCVs - 2)):
            self._jointsPos.append(self._curve.cvPositions[i])
        lastCVPos = self._curve.cvPositions[self._curve.numCVs - 1]
        self._jointsPos.append(lastCVPos)

    # PROPERTIES
    @property
    def curve(self):
        return self._curve

    @property
    def horizontalSpine(self):
        return self._horizontalSpine

    @horizontalSpine.setter
    def horizontalSpine(self, horizontal_in):
        self._horizontalSpine = horizontal_in

    @property
    def frontAxis(self):
        return self._frontAxis

    @frontAxis.setter
    def frontAxis(self, frontAxis):
        self._frontAxis = frontAxis

    @property
    def zeroJoint(self):
        return self._zeroJoint

    @zeroJoint.setter
    def zeroJoint(self, joint_in):
        self._zeroJoint = pm.nt.Joint(joint_in)

    @property
    def zeroPos(self):
        return self._zeroPos

    # METHODS
    def orient_spine(self, frontAxis):
        self.orient_joint_chain(self.startJoint, self.endJoint, frontAxis)
Example #46
0
def demo () :

    vsf = 0.
    c = 1
    s = 1000.
    kmax = 25
    lmax = 35

    pl1 = gr.Plotter (" ")
    c1 = Curve ( y = arange (1, kmax+1, dtype = Float) , color = "yellow" )
    g2 = Graph2d ( c1 , plotter = [pl1], titles = ["Bottom of the Barrel", "Top Dog",
                                  "Leftist", "Reaganist"] )
    g2.plot ( )
    paws ( )
    c2 = Curve ( y = sqrt (arange (1, kmax+1, dtype = Float)**3) , color = "blue")
    g2.add ( c2 )
    g2.plot ( )
    paws ( )
    c1.set (marks = 1, marker = "A")
    c2.set (marks = 1, marker = "B")
    g2.plot ( )
    paws ( )
    c1.set (marks = 0)
    c2.set (marks = 0)
    c1.set (width = 3.0)
    c2.set (width = 4.0)
    g2.plot ( )
    paws ( )
    c1.set (type = "dash")
    c2.set (type = "dashdot")
    g2.plot ( )
    paws ( )
    g2.delete ( 1 )
    g2.plot ( )
    paws ( )
    mycolor= ["red", "blue", "yellow", "green", "orange", "purple"]
    markers= ["+", "*", "o", "x", "."]
    c5 = [ ]
    for i in range (len (markers)) :
        c5.append ( Curve (
           y = exp (array (multiply ((1.0+(i+1)/10.), log (range (1, kmax))))) ,
                    color = mycolor [i] , marks = 1, marker = markers [i] ,
                    type = "none" )
                  )
    g2.new ( c5 , text="Line style and grid test" , text_color="black" ,
              plotter = [pl1],
              text_pos = array ( [.2, .8]) , text_size = 60 ,
              titles = "Figure 1")
    g2.plot ( )
    paws ( )
    g2.quick_plot ( grid_type = "wide" )
    paws ( )
    part1 = abs (array ( [-5, -4, -3, -2, -1, .0000000001] ) )
    c1.new (  y = part1, x = arange (-5, 1, dtype = Float) ,
             type="line" , color = "blue" )
    part2 = array ( [.0000000001, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] )
    c2.new ( y = part2 , x = arange (0, 11, dtype = Float) ,
             type = "line" , color = "blue" )
    g2.new ( [c1, c2] , text = " " , axis_scales = "linlog" , titles = " " ,
              old_plotter = 1,
              axis_limits = array ( [[-6., 10.], [1.e-6, 10.]]))
    g2.plot ( )
    paws ( )
    c1.new ( y = array (exp (multiply (log (10.0), range (-50, 1)))) ,
             x = arange (1, 52, dtype = Float) )
    g2.new ( c1 , axis_scales = "loglog" ,
              old_plotter = 1,
                  axis_limits = array ( [[1., 100.], [1.e-8, 1.]]))
    g2.plot ( )
    paws ( )
    c1.new ( y = array ( [1.e-48, 1.e-21, 0., 0., 0.]) )
    g2.new ( c1 , axis_scales = "linlin" ,
              old_plotter = 1,
                  axis_limits = array  ( [[0., 0.], [0., 0.]]))
    g2.plot ( )