Пример #1
0
 def test_extreme_intercepts(self):
     self.assertEqual(
         get_x_intercepts(Arc(Vector(0.0, 0.0), 1.0, (-d_90, d_90)), 1.0),
         (0.0, None))
     self.assertEqual(
         get_x_intercepts(Arc(Vector(0.0, 0.0), 1.0, (d_90, -d_90)), -1.0),
         (-1.2246467991473532e-16, None))
def valid_joint_range(point, length, limits, arc_bounded_area):
    '''
    returns a tuple, where 
      index 0 is the minimum angle in radians required to 
        achieve the point with the specified limits.
      index 1 is the maximum
    '''
    point_arc = Arc(Vector(0.0, 0.0), point.magnitude(),
                    (-math.pi + 0.0001, math.pi))

    transformed_area = [
        sweep_arc(arc, limits[0], length) for arc in arc_bounded_area
    ]

    intersections = []
    for arc in transformed_area:
        arc_intersections = point_arc.get_arc_intersections(arc)
        if len(arc_intersections) > 0:
            intersections.extend(arc_intersections)

    assert (len(intersections) == 2)
    point_rad = Vector(0.0, 0.0).get_angle(point)
    intersection_rads = [
        Vector(0.0, 0.0).get_angle(inter) for inter in intersections
    ]
    rads_to_point = [point_rad - rad for rad in intersection_rads]
    rads_to_point.sort()
    rads_to_point = [r + limits[0] for r in rads_to_point]

    limits_range = limits[1] - limits[0]
    if rads_to_point[1] > limits_range:
        rads_to_point[1] = limits_range

    return rads_to_point
Пример #3
0
    def graph_from_file(self, file_name):
        file = open(file_name, "r")
        first_line = [int(x) for x in file.readline().split()]
        self.nb_sommets = first_line[0]
        self.nb_arcs = first_line[1]
        self.oriente = (first_line[2] == 1)

        # ajout de tous les sommets
        for i in range(self.nb_sommets):
            line = [a for a in file.readline().split()]
            sommet_cur = Sommet(line[0],
                                lat=float(line[1]),
                                long=float(line[2]))
            self.sommets[line[0]] = sommet_cur

        # ajout de tous les arcs
        for i in range(self.nb_arcs):
            line = [a for a in file.readline().split()]
            if len(line) == 0:
                print(i)
            else:
                s_source = self.sommets[line[0]]
                s_cible = self.sommets[line[1]]
                arc_cur = Arc(s_source, s_cible, value=float(line[2]))
                self.arcs['%s%s' % (s_source.name, s_cible.name)] = arc_cur
                # si le graphe n'est pas orienté, on ajoute l'inverse de chaque arc
                if not self.oriente:
                    self.arcs['%s%s' % (s_cible.name,
                                        s_source.name)] = arc_cur.inverse()

        file.close()
Пример #4
0
    def __init__(self, foliation, coding):
        if coding.index >= foliation.num_intervals(coding.side):
            raise RestrictionError("Invalid interval index.")
        interval = Interval(coding.side, coding.index)

        # Checking if the curve is transverse
        if ((coding.num_flips1 % 2 == 1) != \
           (coding.num_flips2 % 2 == 1)) != \
                    interval.is_flipped(foliation):
            raise RestrictionError("Curve is not transverse to the foliation")


        other_int = interval.pair(foliation)
        other_end = coding.end
        if interval.is_flipped(foliation):
            other_end = (other_end + 1) % 2
        sep1 = Separatrix(foliation, interval, end = coding.end,
                          number_of_flips_to_stop = coding.num_flips1)
        sep2 = Separatrix(foliation, other_int, end = other_end,
                          number_of_flips_to_stop = coding.num_flips2)

        if sep1.is_flipped() == (coding.end == 1):
            openness = ('open','closed')
        else:
            openness = ('closed','open')

        self._sep = [sep1, sep2]
        # print self._sep
        arcs = [Arc(self._sep[i].endpoint, self._sep[(i+1)%2].endpoint,
                    *openness) for i in range(2)]
            

        self._arc = Arc(sep1.endpoint, sep2.endpoint, *openness)

        intersections = sep1.intersections()[:-1] + sep2.intersections()[:-1]

        # if one of the separatrices is longer, both arcs are considered,
        # so if the current one is wrong, we try the other one
        if coding.num_flips1 > 0 or coding.num_flips2 > 0:
            x = intersections[0]
            if self._arc.contains(x):
                self._arc = Arc(sep2.endpoint, sep1.endpoint, *openness)
                self._sep = [sep2, sep1]

        # if self._arc.length() > 0.5 and sep1.end_side == sep2.end_side:
        #     raise RestrictionError("There is either no such curve without "
        #                            "self-intersection or "
        #                            "the curve is one-sided and has length"
        #                            " greater than half, so we can't compute"
        #                            " the train track transition map. ")
        # print self._arc
        # print sep1, sep2
        for x in intersections:
            # print x
            if self._arc.contains(x):
                raise RestrictionError("The curve is self-intersecting")

        self._direction = RIGHT if openness[0] == 'closed' else LEFT
        self._coding = coding
Пример #5
0
 def test_subdivision_lim_0_is_neg_lim_1(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0, (-d_45, d_45)), 0,
                              1.0, d_90, (None, [
                                  Arc(Vector(1.0, 0.0), 1.0,
                                      (-0.7853981634, 0.0)),
                                  Arc(Vector(0.0, 0.0), 1.847759,
                                      (-0.3926990817, 0.3926990817))
                              ]))
Пример #6
0
 def test_subdivision_second_limit(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0,
                                  (d_0, -d_90)), 1, 1.0, d_90,
                              (Arc(Vector(0.0, 0.0), 1.0, (0.0, d_90)), [
                                  Arc(Vector(1.0, 0.0), 1.0,
                                      (-3.1415926536, -1.5707963268)),
                                  Arc(Vector(0.0, 0.0), 1.414214,
                                      (-0.7853981634, 0.7853981634))
                              ]))
Пример #7
0
 def test_subdivision_no_break_floating_point_error(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0,
                                  (-d_45, d_180)), 0, 1.0, d_45,
                              (Arc(Vector(0.0, 0.0), 1.0, (d_45, d_180)), [
                                  Arc(Vector(1.0, 0.0), 1.0,
                                      (-0.7853981634, 0.0)),
                                  Arc(Vector(0.0, 0.0), 1.847759,
                                      (-0.3926990817, 0.3926990817))
                              ]))
Пример #8
0
 def test_subdivision_only_first_limit(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0,
                                  (-d_45, -d_135)), 0, 1.0, d_90,
                              (Arc(Vector(0.0, 0.0), 1.0, (d_45, -d_135)), [
                                  Arc(Vector(1.0, 0.0), 1.0,
                                      (-0.7853981634, 0.0)),
                                  Arc(Vector(0.0, 0.0), 1.847759,
                                      (-0.3926990817, 0.3926990817))
                              ]))
Пример #9
0
 def test_basic_arc_bounds(self):
     self.assertEqual(
         get_swept_arc_bounds(Arc(Vector(0.0, 0.0), 1.0, (-d_90, d_45)),
                              1.0, (0.0, d_90)),
         ([Arc(Vector(1.0, 0.0), 1.0, (-1.5707963268, 0.0))], [
             Arc(Vector(0.0, 1.0), 1.0, (1.5707963268, 2.3561944902)),
             Arc(Vector(0.0, 0.0), 1.847759, (1.1780972451, 1.9634954085)),
             Arc(Vector(0.0, 1.0), 1.0, (0.0, 0.7853981634))
         ]))
Пример #10
0
 def test_subdivision_second_limit_no_break(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0,
                                  (d_0, -d_135)), 1, 1.0, d_15,
                              (Arc(Vector(0.0, 0.0), 1.0,
                                   (0.0, 3.1415926)), [
                                       Arc(Vector(1.0, 0.0), 1.0,
                                           (3.1415926, -2.356194)),
                                       Arc(Vector(0.0, 0.0), 0.7653668,
                                           (-1.178097, -0.916297)),
                                       Arc(Vector(0.966, 0.259), 1.0,
                                           (-2.879793, -2.094395))
                                   ]))
Пример #11
0
 def test_subdivision_no_break(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0,
                                  (-d_45, d_180)), 0, 1.0, d_15,
                              (Arc(Vector(0.0, 0.0), 1.0,
                                   (0.2617993878, d_180)), [
                                       Arc(Vector(1.0, 0.0), 1.0,
                                           (-0.7853981634, 0.0)),
                                       Arc(Vector(0.0, 0.0), 1.847759,
                                           (-0.3926990817, -0.1308996939)),
                                       Arc(Vector(0.966, 0.259), 1.0,
                                           (-0.5235987756, 0.0))
                                   ]))
Пример #12
0
 def __init__(
     self,
     parent=None,
     specMap={
         'value':
         0.5,
         'pos':
         QPointF(3.5, 3.5),
         'arc':
         Arc({
             'center': QPointF(),
             'radius': 0.5,
             'start': 0.0,
             'span': 90.0
         }),
         'outside':
         True,
         'format':
         FMTRIN
     }):
     if specMap['arc'].radius() <= 0:
         raise RadiusDimException("refrenced arc radius must be > 0.0")
     super(RadiusDim, self).__init__(parent)
     self.specMap = copy(specMap)
     self.arrow = DimArrow(self)
     self.config(specMap)
Пример #13
0
    def __init__(self, jsonDict):
        self.index = 1
        self.title = ""
        self.xtitle = ""
        self.ytitle = ""

        self.__dict__ = jsonDict

        self.items = []
        if "__items__" in jsonDict:
            for item in jsonDict["__items__"]:
                if item["type"] == "Line2D":
                    self.items.append(Line2D(item))
                elif item["type"] == "Point2D":
                    self.items.append(Line2D(item))
                elif item["type"] == "Histogram":
                    self.items.append(Histogram(item))
                elif item["type"] == "Text":
                    self.items.append(Text(item))
                elif item["type"] == "Annotation":
                    self.items.append(Annotation(item))
                elif item["type"] == "Hline":
                    self.items.append(Hline(item))
                elif item["type"] == "Vline":
                    self.items.append(Vline(item))
                elif item["type"] == "Arc":
                    self.items.append(Arc(item))

        if "grid" in jsonDict:
            self.grid = Grid(jsonDict["grid"])
        else:
            self.grid = Grid()
Пример #14
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
Пример #15
0
 def init_arcs(self, arcs_data):
     arcs = {}
     for arc in arcs_data:
         arcs[arc["id"]] = Arc(arc, self)
     for arc in arcs_data:
         for blocked_arc in arc["blocks"]:
             arcs[arc["id"]].blocks.append(arcs[blocked_arc])
     self.arcs = self.clean_duplicates_dict(arcs)
Пример #16
0
 def add_arc(self, origin: Node, dest: Node):
     """
     add arc to the network
     :param origin:
     :param dest:
     :return:
     """
     arc = Arc(origin, dest)
     self.arcs.append(arc)
Пример #17
0
    def addRevArcSeg(self, x1, y1, x2, y2, cx, cy, arcDir):  
        """Add a 360 degree revolved arc to this Patch.      
                                                             
        x1, y1 -- start vertex
        x2, y2 -- end vertex
        cx, cy -- center point
        arcDir -- 'cclw' or 'clw'

        It is assumes the points are in the XZ plane and the axis of
        revolution is parallel to the vector (0, 0, 1), and passes through the
        point (0, 0, 0).
        """
        a = x1 - cx
        b = y1 - cy
        r = sqrt(a*a + b*b)
        arc = Arc.fromVectors(QVector2D(a, b),
                              QVector2D(x2 - cx, y2 - cy),
                              r,
                              arcDir == 'cclw')
        # TODO: By halving the mesh segs ( * 0.5), fewer triangles are
        #       created. Shading is ok but arc edges look blocky.
        # angstep = 360.0 / (self._mesh.segs * 0.5)
        angstep = 360.0 / self._mesh.segs
        # minimum 2 segments in the arc
        segs = max(int(abs(arc.span()) / angstep), 3)
        step = arc.span() / segs
        sa = arc.startAngle()
        a1 = radians(sa)
        sa1 = sin(a1)
        ca1 = cos(a1)
        for i in range(1, segs):
            a2 = radians(sa + step * i)
            sa2 = sin(a2)
            ca2 = cos(a2)
            x1 = cx + r * ca1
            y1 = cy + r * sa1
            x2 = cx + r * ca2
            y2 = cy + r * sa2
            self.addRevLineSeg(x1, y1, x2, y2)
            a1 = a2
            sa1 = sa2
            ca1 = ca2
            if i == 1:
                # only blend the first strip
                self._mesh.blendTangent(False)
        # last strip
        else:
            a2 = radians(arc.endAngle())
            x1 = cx + r * ca1
            y1 = cy + r * sa1
            x2 = cx + r * cos(a2)
            y2 = cy + r * sin(a2)
            self.addRevLineSeg(x1, y1, x2, y2)
Пример #18
0
async def test_root():
    async def handler():
        return HTTPResponse("Hello, World")

    routes = [Route("/", handler)]
    app = Arc(routes=routes)

    async with AsyncClient(app=app, base_url="http://127.0.0.1:5000/") as ac:
        response = await ac.get("/")

    assert response.status_code == 200
    assert response.text == "Hello, World"
Пример #19
0
 def introduce_symbol(self, symbol, position):
     if symbol is None:
         return
     self.debug("Introducing symbol " + str(symbol))
     is_first = 1
     for rule in self.grammar.get_rules():
         if rule.get_mother().get_category() == symbol.get_category():
             if is_first:
                 self.debug("    Using the top-down rule,"
                            " new active arcs are added for " + str(symbol))
             is_first = 0
             self.introduce(Arc(rule, 0, position, position))
Пример #20
0
async def test_query_params():
    async def handler(bar: int = None):
        return HTTPResponse(f"{bar}")

    routes = [Route("/foo", handler)]
    app = Arc(routes=routes)

    async with AsyncClient(app=app, base_url="http://127.0.0.1:5000/") as ac:
        response = await ac.get("/foo?bar=10")

    assert response.status_code == 200
    assert response.text == "10"
def limited_n_jointed_arm_range(lengths, lower_limits, upper_limits):
    '''
    Defines a set of curves that makes an area
    '''
    if len(lengths) < 2:
        pass
    if len(lengths) != len(lower_limits) or \
       len(lengths) != len(upper_limits):
        raise LimitsException
    arcs = [
        Arc(Vector(0.0, 0.0), lengths[0], (lower_limits[0], upper_limits[0]))
    ]
    for i in range(1, len(lengths)):
        arcs = sweep_area(arcs, lengths[i], (lower_limits[i], upper_limits[i]))
    return arcs
Пример #22
0
def BuildTree(inputSoup,parentArc=None):
   
   #create new node
   newNode = Node(parentArc);

   for child in inputSoup.contents:
      if type(child) not in [NavigableString, Declaration, Comment, CData, ProcessingInstruction]:
         #create the arc for this child, with it's parent as newNode
         newArc = Arc(str(child.name), newNode, None);
         #store attributes
         for attribute in child.attrs:
            key = str(attribute[0]);
            val = str(attribute[1]);
            if key in newArc.attributes.keys():
               newArc.attributes[key].append(val);
            else:
               newArc.attributes[key] = [val];

         #add the arc to the newNOde
         newNode.AddArc(newArc);

         #set the child node of this arc to node created from 
         #recurse call to BuildTree
         childNode = BuildTree(child, newArc);
         newArc.SetChildNode(childNode);

         if newArc and newArc.listOfText:
            l = len(newArc.listOfText) - 1;
            newArc.listOfText[l].node = childNode;

      else:
         #put navigable string with previous tab
         if parentArc != None:
            parentArc.listOfText.append(TextBlock(str(child), None));

   return newNode;
Пример #23
0
    def _init_data(self):
        """
        Read in data from ephemeris file
        """
        if 'site_name' in self._config.keys():
            self.site = Site(self._config['site_name'])
        else:
            print('ConfigWarning: No site_name specified, defaulting to LaPalma')
            self.site = Site('LaPalma')

        if 'ephem_path' in self._config.keys():
            self.ephem_path = self._config['ephem_path']
            if os.path.exists(self.ephem_path):
                arc = Arc(self.site, Table.read(self.ephem_path, format='csv'))
            else:
                print('ConfigError: Input ephemeris path not found')
                sys.exit()
        else:
            print('ConfigError: No ephemeris file specified')
            sys.exit()

        times = []
        for t, time in enumerate(arc.ephem['UTC']):
            times.append(datetime.strptime(time, '%Y-%m-%dT%H:%M:%S.%f'))

        self.data = {'time': np.array(times),
                     'ra': np.array(arc.ephem['RA']),
                     'dec': np.array(arc.ephem['DEC']),
                     'raerr': np.array(arc.ephem['RAERR']),
                     'decerr': np.array(arc.ephem['DECERR'])}

        # pre-calculate repeatedly used terms in lnlike
        self.data.update({'ra_sigma2': self.data['raerr'] ** 2})
        self.data.update({'dec_sigma2': self.data['decerr'] ** 2})
        self.data.update({'ra_lnsigma2': np.log(self.data['ra_sigma2'])})
        self.data.update({'dec_lnsigma2': np.log(self.data['dec_sigma2'])})

        if 'out_dir' in self._config.keys():
            self.out_dir = self._config['out_dir']
            if not os.path.exists(self.out_dir):
                try:
                    os.mkdir(self.out_dir)
                except:
                    print('ConfigWarning: Failed to set up output directory')
                    self.out_dir = None
        else:
            print('ConfigWarning: No output directory specified')
            self.out_dir = None
Пример #24
0
 def test_sweep(self):
     self.assertEqual(
         sweep_area([Arc(Vector(0.0, 0.0), 1.0, [-d_90, d_90])], 1.0,
                    (d_0, d_90)),
         [
             Arc(Vector(0.0, 0.0), 2.0, (0.0, 1.5707963)),
             Arc(Vector(0.0, 1.0), 1.0, (1.5707963, 3.1415926)),
             Arc(Vector(0.0, 0.0), 1.4142135, (0.7853981, 2.3561944)),
             Arc(Vector(0.0, 0.0), 1.4142135, (-0.785398, 0.7853981)),
             Arc(Vector(1.0, 0.0), 1.0, (-1.570796, 0.0))
         ])
Пример #25
0
def fst_intersect(m, n):
    arcs = set()
    state_lookup = dict(
        (product_state(p, q), set()) for p, q in states_set_product(m, n))
    start = product_state(m.start, n.start)
    # Compute arcs for each state pair
    for ((x, y), (z, w)) in states_mega_product(m, n):
        labels_lists = similar_labels_between(m, x, y, n, z, w)
        elision_arcs = set()
        for labels_list in labels_lists:
            arcs_by_input = set()
            for (k, l) in labels_list:
                add_arc = False
                seg = ''
                if k.output == '':
                    # Faithfulness constraint; cares about input
                    if k.input == l.input:
                        if k.input not in elision_arcs:
                            add_arc = True
                            seg = k.input
                            elision_arcs.add(seg)
                elif ((k.input == '_') or
                      (k.input == l.input)) and (l.input not in arcs_by_input):
                    # Markedness constraint
                    add_arc = True
                    seg = l.input
                    arcs_by_input.add(seg)
                elif (l.input == '_') and (k.input not in arcs_by_input):
                    # Markedness constraint
                    add_arc = True
                    seg = k.input
                    arcs_by_input.add(seg)
                if add_arc:
                    intersection_arc = Arc(
                        product_state(x, z), product_state(y, w),
                        Label(seg, k.output, otimes(k.violation, l.violation)))
                    arcs.add(intersection_arc)
                    state_lookup[intersection_arc.start].add(intersection_arc)
    # Figure out the states reachable from the start
    fst_states = traverse_states(state_lookup, start)
    fst = FST(fst_states, start, fst_states,
              filter((lambda arc: arc.start in fst_states), arcs), 1)
    return fst
Пример #26
0
def fst_from_prohibited_string(input_alphabet, output_alphabet, banned_string,
                               violation_name):
    length = len(banned_string)
    fst = FST(set([""]), "", set(), set(), "")
    # Add arcs
    if length > 1:
        for i in range(1, length):
            fst.states.add(banned_string[0:i])
            add_alternation_arcs(fst, banned_string[0:i - 1],
                                 banned_string[0:i], '_', banned_string[i - 1])
    # Send a penalty arc to the longest valid suffix
    fst.arcs.add(
        Arc(banned_string[0:-1], longest_suffix(banned_string, fst.states),
            Label('_', banned_string[-1], Counter({violation_name: 1}))))
    # Add loopback arcs and return
    for state in fst.states:
        for char in input_alphabet:
            add_elision_arc(fst, state, char)
        for char in fst.chars_not_leaving(state, output_alphabet):
            add_alternation_arcs(fst, state,
                                 longest_suffix(state + char, fst.states), '_',
                                 char)
    return fst
Пример #27
0
    def config(self, specMap={}):
        if not super(AngleDim, self).config(specMap):
            return
        pp = QPainterPath()
        labelP = self.specMap['pos']
        tb = self.dimText.sceneBoundingRect()
        l1 = self.specMap['line1']
        l2 = self.specMap['line2']
        outside = self.specMap['outside']
        if l1.isNull() or l2.isNull():
            raise AngleDimException("refrenced line has zero length")
        # line intersection point
        xsectP = QPointF()
        xsectType = l1.intersect(l2, xsectP)
        if xsectType == QLineF.NoIntersection:
            raise AngleDimException("reference lines are parallel")
        # radius of arc leaders that pass through the label's center point
        labelV = QVector2D(labelP - xsectP)
        dp = labelV.dotProduct
        radius = labelV.length()
        # find fixed leader span angle
        chordLen = self.scene().pixelsToScene(self.leaderLen)
        rsq = radius * radius
        res = (rsq + rsq - chordLen * chordLen) / (2 * rsq)
        fixedLeaderSpan = degrees(acos(clamp(res, 0.0, 1.0)))
        # guess the line vectors
        v1 = QVector2D(l1.p2() - l1.p1()).normalized()
        v2 = QVector2D(l2.p2() - l2.p1()).normalized()
        # maybe reverse the line vectors so they point towards the quadrant
        # specified
        quadV = self.specMap['quadV'].normalized()
        if dp(v1, quadV) <= 0:
            v1 = -v1
        if dp(v2, quadV) <= 0:
            v2 = -v2
        # angle bisector
        bisectV = (v1 + v2).normalized()
        # angle bisector rotated 90 degrees cclw
        bisectV90 = QVector2D(-bisectV.y(), bisectV.x())
        # determine which side of the bisector the arrow tips lay
        lL = l1
        rL = l2
        lV = v1
        rV = v2
        lAp = xsectP + (lV * radius).toPointF()
        rAp = xsectP + (rV * radius).toPointF()
        if dp(bisectV90, v1) <= 0.0:
            lL, rL, lV, rV, lAp, rAp = rL, lL, rV, lV, rAp, lAp
        # find where the label lays
        lableV = labelV.normalized()
        lVperp = QVector2D(-lV.y(), lV.x())
        rVperp = QVector2D(rV.y(), -rV.x())
        # leader arc rectangle
        rect = QRectF(xsectP.x() - radius,
                      xsectP.y() + radius,
                      radius * 2, -radius * 2)

        # When left and right are mentioned, they are relative to the
        # intersection point of the two reference lines, looking in the
        # direction of the angle bisector.
        
        # label left of quad
        if dp(labelV, lVperp) > 0.0:
            if outside:
                # leader from lable to left arrow
                arc = Arc.fromVectors(labelV, lV, radius, False)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), lV,
                                         radius, False)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
                # fixed leader from right arrow
                sa = vectorToAbsAngle(rV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, -fixedLeaderSpan)
            else:
                # leader from label, through left arrow, to right arrow
                arc = Arc.fromVectors(labelV, rV, radius, False)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), rV,
                                         radius, False)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
        # label right of quad
        elif dp(labelV, rVperp) > 0.0:
            if outside:
                # leader from label to right arrow
                arc = Arc.fromVectors(labelV, rV, radius)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), rV,
                                         radius)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
                # fixed length leader from left arrow
                sa = vectorToAbsAngle(lV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, fixedLeaderSpan)
            else:
                # leader from label, through right arrow, to left arrow
                arc = Arc.fromVectors(labelV, lV, radius)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), lV,
                                         radius)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
        # label inside quad
        else:
            if outside:
                # fixed length leader from right arrow
                sa = vectorToAbsAngle(rV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, -fixedLeaderSpan)
                # from left arrow
                sa = vectorToAbsAngle(lV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, fixedLeaderSpan)
            else:
                # leader from label to left arrow
                clipP = xsectArcRect1(Arc.fromVectors(labelV, lV, radius), tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), lV,
                                          radius)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
                # to right arrow
                clipP = xsectArcRect1(Arc.fromVectors(labelV, rV, radius,
                                                      False), tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), rV,
                                          radius, False)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
        # arrow tips
        if outside:
            self.arrow1.config({'pos': lAp,
                                'dir': -QVector2D(-lV.y(), lV.x())})
            self.arrow2.config({'pos': rAp,
                                'dir': -QVector2D(rV.y(), -rV.x())})
        else:
            self.arrow1.config({'pos': lAp,
                                'dir': QVector2D(-lV.y(), lV.x())})
            self.arrow2.config({'pos': rAp,
                                'dir': QVector2D(rV.y(), -rV.x())})
        # Find the end points closest to their arrow tips for extension lines
        # Don't render the extension if the arrow tip is on its line.
        p1 = None
        if not isPointOnLineSeg(lAp, lL):
            p1 = lL.p1()
            if QVector2D(lAp - lL.p2()).length() \
                    < QVector2D(lAp - p1).length():
                p1 = lL.p2()
        p2 = None
        if not isPointOnLineSeg(rAp, rL):
            p2 = rL.p1()
            if QVector2D(rAp - rL.p2()).length() \
                    < QVector2D(rAp - p2).length():
                p2 = rL.p2()
        self._addExtensionLines(p1, p2, lAp, rAp, pp)
        self.setPath(pp)
Пример #28
0
 def config(self, specMap={}):
     if not super(RadiusDim, self).config(specMap):
         return
     arcRadius = self.specMap['arc'].radius()
     pos = self.specMap['pos']
     pp = QPainterPath()
     arcCenter = self.specMap['arc'].center()
     # is the label outside the arc
     labelOutside = QVector2D(pos - arcCenter).length() > arcRadius
     # is the label to the right of the arc's y axis?
     labelRight = pos.x() > arcCenter.x()
     br = self.dimText.sceneBoundingRect().normalized()
     # arrow pointing toward arc center point
     if self.specMap['outside']:
         if labelOutside:
             jogLen = self.scene().pixelsToScene(self.jogLineLen)
             if labelRight:
                 jogV = QVector2D(-1, 0).normalized()
                 jogSp = QPointF(br.left(), br.center().y())
             else:
                 jogV = QVector2D(1, 0).normalized()
                 jogSp = QPointF(br.right(), br.center().y())
             jogEp = jogSp + (jogV * jogLen).toPointF()
             ap = pointOnArc(jogEp, arcCenter, arcRadius)
             av = QVector2D(arcCenter - jogEp)
             self.arrow.config({'pos': ap, 'dir': av})
             pp.moveTo(jogSp)
             pp.lineTo(jogEp)
             pp.lineTo(ap)
         # label inside arc
         else:
             leaderLen = self.scene().pixelsToScene(self.leaderLen)
             ap = pointOnArc(pos, arcCenter, arcRadius)
             av = QVector2D(arcCenter - ap).normalized()
             self.arrow.config({'pos': ap, 'dir': av})
             # fixed len arrow leader
             ep = ap + (av * -1 * leaderLen).toPointF()
             pp.moveTo(ap)
             pp.lineTo(ep)
     # arrow pointing away from arc center
     else:
         if labelOutside:
             jogLen = self.scene().pixelsToScene(self.jogLineLen)
             if labelRight:
                 jogV = QVector2D(-1, 0).normalized()
                 jogSp = QPointF(br.left(), br.center().y())
             else:
                 jogV = QVector2D(1, 0).normalized()
                 jogSp = QPointF(br.right(), br.center().y())
             jogEp = jogSp + (jogV * jogLen).toPointF()
             ap = pointOnArc(jogEp, arcCenter, arcRadius)
             av = QVector2D(ap - arcCenter)
             self.arrow.config({'pos': ap, 'dir': av})
             pp.moveTo(arcCenter)
             pp.lineTo(ap)
             pp.lineTo(jogEp)
             pp.lineTo(jogSp)
         # label inside the arc
         else:
             ap = pointOnArc(pos, arcCenter, arcRadius)
             av = QVector2D(ap - arcCenter)
             self.arrow.config({'pos': ap, 'dir': av})
             # label to arc center leader
             xp1 = xsectLineRect1(QLineF(pos, arcCenter), br)
             if xp1:
                 pp.moveTo(xp1)
                 pp.lineTo(arcCenter)
             # label to arrow leader
             xp2 = xsectLineRect1(QLineF(pos, ap), br)
             if xp2:
                 pp.moveTo(xp2)
                 pp.lineTo(ap)
     # extension arc
     arc = self.specMap['arc']
     arcStart = arc.start()
     arcSpan = arc.span()
     if not isPointOnArc(ap, arcCenter, arcStart, arcSpan):
         # arc rect
         p = QPointF(arcRadius, arcRadius)
         r = QRectF(arcCenter - p, arcCenter + p)
         bisV = arc.bisector()
         # arc center to arrow tip vector
         apV = QVector2D(ap - arcCenter).normalized()
         # bisector rotated 90
         bis90V = QVector2D(-bisV.y(), bisV.x())
         spV = arc.startAngleVector()
         spLeftOfBisector = spV.dotProduct(spV, bis90V) >= 0.0
         epV = arc.endAngleVector()
         # is the arrow tip to the left of the bisector?
         if bis90V.dotProduct(apV, bis90V) >= 0.0:
             # is the start point left of the bisector?
             if spLeftOfBisector:
                 extensionArc = Arc.fromVectors(spV, apV, arcRadius, True)
             else:
                 extensionArc = Arc.fromVectors(epV, apV, arcRadius, True)
             pp.arcMoveTo(r, -extensionArc.start() - self.gapAngle)
             pp.arcTo(r, -extensionArc.start() - self.gapAngle,
                      -extensionArc.span() - self.extAngle)
         # arrow tip to right of bisector
         else:
             # is the start point left of the bisector?
             if spLeftOfBisector:
                 extensionArc = Arc.fromVectors(epV, apV, arcRadius, False)
             else:
                 extensionArc = Arc.fromVectors(spV, apV, arcRadius, False)
             pp.arcMoveTo(r, -extensionArc.start() + self.gapAngle)
             pp.arcTo(r, -extensionArc.start() + self.gapAngle,
                      -extensionArc.span() + self.extAngle)
     self.setPath(pp)
Пример #29
0
    def run(self):
        self.running = True
        while self.running:
            self.turn()


    def close(self):
        self.running = False
        self.monome.led_all(0)
        a.close()
        m.close()

# print list_monomes()
m = Monome((u'Sergios-MacBook-Pro.local.', 19636))
m.start()
a = Arc((u'Sergios-MacBook-Pro.local.', 10143))
a.start()
s = Play(m, a)
s.start()

while True:
    s.turn()

try:
    while True:
        pass
except KeyboardInterrupt:
    s.close()

Пример #30
0
import files
from files import renameFiles

import arc
from arc import Arc
from arc import ArcCollection

# Source and destination folder, they can be the same
src = './sample'
dst = './dist'

# Example of collection
ArcsOnePiece = ArcCollection('One Piece', [
    Arc(1, 3, 'Romance Dawn'),
    Arc(4, 8, 'Baggy le Clown'),
    Arc(9, 17, 'Capitaine Kuro'),
    Arc(18, 30, 'Baratie'),
    Arc(31, 45, 'Arlong'),
    Arc(46, 47, 'Les aventures a Baggy'),
    Arc(48, 53, 'Loguetown'),
    Arc(54, 61, 'Ile du Navire de Guerre'),
    Arc(61, 63, 'Laboon'),
    Arc(64, 67, 'Whiskey Peak'),
    Arc(68, 69, 'Koby & Hermep'),
    Arc(70, 77, 'Little Garden'),
    Arc(78, 91, 'Royaume de Drum'),
    Arc(92, 130, 'Alabasta'),
    Arc(131, 135, 'Post-Alabasta'),
    Arc(136, 138, 'Ile des Chevres'),
    Arc(139, 143, 'Brume Arc-en-Ciel'),
    Arc(144, 152, 'Jaya'),
Пример #31
0
 def extend_arcs(self, constituent):
     for arc in self.data:
         if (
             arc.get_end() == constituent.get_start()
             and arc.next_symbol().get_category()
             == constituent.get_symbol().get_category()
         ):
             new_arc = Arc(
                 arc.get_rule(), arc.get_progress(), arc.get_start(),
                 constituent.get_end())
             try:
                 new_arc.next_symbol().resolve(constituent.get_symbol())
                 new_arc.set_progress(new_arc.get_progress() + 1)
                 self.introduce(new_arc)
                 if new_arc.get_progress() == new_arc.size():
                     self.agenda.add_constituent(
                         new_arc.get_mother(), new_arc.get_start(),
                         new_arc.get_end())
             except Error as e:
                 self.debug(e)
def limited_n_jointed_arm_ik(lengths, lower_limits, upper_limits, weights,
                             point):
    '''
    Calculates ik angles for joints with angle limits
    lower and upper limits are in radians
    '''

    if not limited_n_jointed_arm_validity(lengths, lower_limits, upper_limits,
                                          point):
        raise OutOfRangeException

    if len(lengths) - 2 != len(weights):
        print("lengths: " + str(lengths))
        print("weights: " + str(weights))
        raise LengthsWeightsNotMatchException

    resulting_angles = [0] * len(lengths)
    for index in range(len(lengths) - 1):
        length_1 = lengths[index]
        length_2 = sum(lengths[index + 1:])
        a_1 = 0.0
        a_2 = 0.0
        if index < len(lengths) - 2:

            bounded_area = limited_n_jointed_arm_range(
                lengths[index + 1:], lower_limits[index + 1:],
                upper_limits[index + 1:])
            arc = Arc(point, length_1,
                      (lower_limits[index], upper_limits[index]))
            angle_tuple = valid_joint_range(
                point, length_1, (lower_limits[index], upper_limits[index]),
                bounded_area)

            angle_range = angle_tuple[1] - angle_tuple[0]
            #TODO work with cases where [0] > [1]

            weighted_range = weights[index] * angle_range
            weighted_angle = angle_tuple[0] + weighted_range
            angles = (weighted_angle, None)
        else:
            # Run a two jointed arm ik to find the angle for this joint
            angles = two_jointed_arm_ik(length_1, length_2, point)
            if angles == None:
                return None
            angles = (Arc_Radian(angles[0]), Arc_Radian(angles[1]))

            if angles[0] < lower_limits[index] or \
               angles[0] > upper_limits[index]:
                # If the angle doesnt fit our limits,
                #   use the other two joint solution
                #   flipped around the vector to the point
                ang_to_point = Vector(0.0, 0.0).get_angle(point)

                #The second angle is simply negated because
                #   it is relative to the first angle
                angles = (ang_to_point - (angles[0] - ang_to_point),
                          angles[1] * -1.0)
                angles = (Arc_Radian(angles[0]), Arc_Radian(angles[1]))

        a_1, a_2 = angles
        # Store relative angle values
        resulting_angles[index] = a_1
        resulting_angles[index] -= sum(resulting_angles[:index])
        if index == len(lengths) - 2:
            resulting_angles[index + 1] = a_2

        # Subtract current progress to the point
        absolute_angle = sum(resulting_angles[:index + 1])
        offset = Vector(lengths[index] * math.cos(absolute_angle),
                        lengths[index] * math.sin(absolute_angle))
        point = point - offset
    return resulting_angles
Пример #33
0
class TransverseCurve(SageObject):
    def __init__(self, foliation, coding):
        if coding.index >= foliation.num_intervals(coding.side):
            raise RestrictionError("Invalid interval index.")
        interval = Interval(coding.side, coding.index)

        # Checking if the curve is transverse
        if ((coding.num_flips1 % 2 == 1) != \
           (coding.num_flips2 % 2 == 1)) != \
                    interval.is_flipped(foliation):
            raise RestrictionError("Curve is not transverse to the foliation")


        other_int = interval.pair(foliation)
        other_end = coding.end
        if interval.is_flipped(foliation):
            other_end = (other_end + 1) % 2
        sep1 = Separatrix(foliation, interval, end = coding.end,
                          number_of_flips_to_stop = coding.num_flips1)
        sep2 = Separatrix(foliation, other_int, end = other_end,
                          number_of_flips_to_stop = coding.num_flips2)

        if sep1.is_flipped() == (coding.end == 1):
            openness = ('open','closed')
        else:
            openness = ('closed','open')

        self._sep = [sep1, sep2]
        # print self._sep
        arcs = [Arc(self._sep[i].endpoint, self._sep[(i+1)%2].endpoint,
                    *openness) for i in range(2)]
            

        self._arc = Arc(sep1.endpoint, sep2.endpoint, *openness)

        intersections = sep1.intersections()[:-1] + sep2.intersections()[:-1]

        # if one of the separatrices is longer, both arcs are considered,
        # so if the current one is wrong, we try the other one
        if coding.num_flips1 > 0 or coding.num_flips2 > 0:
            x = intersections[0]
            if self._arc.contains(x):
                self._arc = Arc(sep2.endpoint, sep1.endpoint, *openness)
                self._sep = [sep2, sep1]

        # if self._arc.length() > 0.5 and sep1.end_side == sep2.end_side:
        #     raise RestrictionError("There is either no such curve without "
        #                            "self-intersection or "
        #                            "the curve is one-sided and has length"
        #                            " greater than half, so we can't compute"
        #                            " the train track transition map. ")
        # print self._arc
        # print sep1, sep2
        for x in intersections:
            # print x
            if self._arc.contains(x):
                raise RestrictionError("The curve is self-intersecting")

        self._direction = RIGHT if openness[0] == 'closed' else LEFT
        self._coding = coding
        # print coding, self._direction, self._arc
        # print '\n'

    def _repr_(self):
        s = ''
        s += 'Arc: ' + repr(self._arc) #+ '(' + repr(self._arc.length()) + ')'
        return s

    def _latex_(self):
        return self._foliation.latex_options().tikz_picture(
            transverse_curves = [self], separatrices = self._get_separatrices())

    def _get_separatrices(self):
        return Separatrix.get_all(self._foliation, self._arc)

    @property
    def _foliation(self):
        return self._sep[0].foliation

    def separatrix(self, n):
        return self._sep[n]

    def direction(self):
        return self._direction

    def arc(self):
        return self._arc

    def coding(self):
        return self._coding
                           
    def is_one_sided(self):
        is_same_side = self._sep[0].end_side() == self._sep[1].end_side()
        return self.is_twisted() != is_same_side

    def is_twisted(self):
        return self._foliation.is_bottom_side_moebius() and \
           self._arc[0] > self._arc[1]

        
        

    def new_foliation(self):
        from transition_map import new_foliation
        fol = self._foliation
        adj_starting_side = self._sep[0].end_side() if self._direction == RIGHT \
                       else self._sep[1].end_side()
        # self.save('tc.save')
        return new_foliation(self._get_separatrices(), self._sep[0].endpoint,
                             adj_starting_side,
                             is_one_sided = self.is_one_sided(),
                             hdir = self._direction,
                             adj_ending_point = self._sep[1].endpoint,
                             transformation_coding = RestrictionCoding(fol, self._coding))
Пример #34
0
    def config(self, specMap={}):
        if not super(AngleDim, self).config(specMap):
            return
        pp = QPainterPath()
        labelP = self.specMap['pos']
        tb = self.dimText.sceneBoundingRect()
        l1 = self.specMap['line1']
        l2 = self.specMap['line2']
        outside = self.specMap['outside']
        if l1.isNull() or l2.isNull():
            raise AngleDimException("refrenced line has zero length")
        # line intersection point
        xsectP = QPointF()
        xsectType = l1.intersect(l2, xsectP)
        if xsectType == QLineF.NoIntersection:
            raise AngleDimException("reference lines are parallel")
        # radius of arc leaders that pass through the label's center point
        labelV = QVector2D(labelP - xsectP)
        dp = labelV.dotProduct
        radius = labelV.length()
        # find fixed leader span angle
        chordLen = self.scene().pixelsToScene(self.leaderLen)
        rsq = radius * radius
        res = (rsq + rsq - chordLen * chordLen) / (2 * rsq)
        fixedLeaderSpan = degrees(acos(clamp(res, 0.0, 1.0)))
        # guess the line vectors
        v1 = QVector2D(l1.p2() - l1.p1()).normalized()
        v2 = QVector2D(l2.p2() - l2.p1()).normalized()
        # maybe reverse the line vectors so they point towards the quadrant
        # specified
        quadV = self.specMap['quadV'].normalized()
        if dp(v1, quadV) <= 0:
            v1 = -v1
        if dp(v2, quadV) <= 0:
            v2 = -v2
        # angle bisector
        bisectV = (v1 + v2).normalized()
        # angle bisector rotated 90 degrees cclw
        bisectV90 = QVector2D(-bisectV.y(), bisectV.x())
        # determine which side of the bisector the arrow tips lay
        lL = l1
        rL = l2
        lV = v1
        rV = v2
        lAp = xsectP + (lV * radius).toPointF()
        rAp = xsectP + (rV * radius).toPointF()
        if dp(bisectV90, v1) <= 0.0:
            lL, rL, lV, rV, lAp, rAp = rL, lL, rV, lV, rAp, lAp
        # find where the label lays
        lableV = labelV.normalized()
        lVperp = QVector2D(-lV.y(), lV.x())
        rVperp = QVector2D(rV.y(), -rV.x())
        # leader arc rectangle
        rect = QRectF(xsectP.x() - radius,
                      xsectP.y() + radius, radius * 2, -radius * 2)

        # When left and right are mentioned, they are relative to the
        # intersection point of the two reference lines, looking in the
        # direction of the angle bisector.

        # label left of quad
        if dp(labelV, lVperp) > 0.0:
            if outside:
                # leader from lable to left arrow
                arc = Arc.fromVectors(labelV, lV, radius, False)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), lV,
                                          radius, False)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
                # fixed leader from right arrow
                sa = vectorToAbsAngle(rV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, -fixedLeaderSpan)
            else:
                # leader from label, through left arrow, to right arrow
                arc = Arc.fromVectors(labelV, rV, radius, False)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), rV,
                                          radius, False)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
        # label right of quad
        elif dp(labelV, rVperp) > 0.0:
            if outside:
                # leader from label to right arrow
                arc = Arc.fromVectors(labelV, rV, radius)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), rV,
                                          radius)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
                # fixed length leader from left arrow
                sa = vectorToAbsAngle(lV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, fixedLeaderSpan)
            else:
                # leader from label, through right arrow, to left arrow
                arc = Arc.fromVectors(labelV, lV, radius)
                arc.center(xsectP)
                clipP = xsectArcRect1(arc, tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), lV,
                                          radius)
                    arc.center(xsectP)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
        # label inside quad
        else:
            if outside:
                # fixed length leader from right arrow
                sa = vectorToAbsAngle(rV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, -fixedLeaderSpan)
                # from left arrow
                sa = vectorToAbsAngle(lV)
                pp.arcMoveTo(rect, sa)
                pp.arcTo(rect, sa, fixedLeaderSpan)
            else:
                # leader from label to left arrow
                clipP = xsectArcRect1(Arc.fromVectors(labelV, lV, radius), tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), lV,
                                          radius)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
                # to right arrow
                clipP = xsectArcRect1(
                    Arc.fromVectors(labelV, rV, radius, False), tb)
                if clipP:
                    arc = Arc.fromVectors(QVector2D(clipP - xsectP), rV,
                                          radius, False)
                    pp.arcMoveTo(rect, arc.start())
                    pp.arcTo(rect, arc.start(), arc.span())
        # arrow tips
        if outside:
            self.arrow1.config({
                'pos': lAp,
                'dir': -QVector2D(-lV.y(), lV.x())
            })
            self.arrow2.config({
                'pos': rAp,
                'dir': -QVector2D(rV.y(), -rV.x())
            })
        else:
            self.arrow1.config({'pos': lAp, 'dir': QVector2D(-lV.y(), lV.x())})
            self.arrow2.config({'pos': rAp, 'dir': QVector2D(rV.y(), -rV.x())})
        # Find the end points closest to their arrow tips for extension lines
        # Don't render the extension if the arrow tip is on its line.
        p1 = None
        if not isPointOnLineSeg(lAp, lL):
            p1 = lL.p1()
            if QVector2D(lAp - lL.p2()).length() \
                    < QVector2D(lAp - p1).length():
                p1 = lL.p2()
        p2 = None
        if not isPointOnLineSeg(rAp, rL):
            p2 = rL.p1()
            if QVector2D(rAp - rL.p2()).length() \
                    < QVector2D(rAp - p2).length():
                p2 = rL.p2()
        self._addExtensionLines(p1, p2, lAp, rAp, pp)
        self.setPath(pp)
Пример #35
0
 def config(self, specMap={}):
     if not super(RadiusDim, self).config(specMap):
         return
     arcRadius = self.specMap['arc'].radius()
     pos = self.specMap['pos']
     pp = QPainterPath()
     arcCenter = self.specMap['arc'].center()
     # is the label outside the arc
     labelOutside = QVector2D(pos - arcCenter).length() > arcRadius
     # is the label to the right of the arc's y axis?
     labelRight = pos.x() > arcCenter.x()
     br = self.dimText.sceneBoundingRect().normalized()
     # arrow pointing toward arc center point
     if self.specMap['outside']:
         if labelOutside:
             jogLen = self.scene().pixelsToScene(self.jogLineLen)
             if labelRight:
                 jogV = QVector2D(-1, 0).normalized()
                 jogSp = QPointF(br.left(), br.center().y())
             else:
                 jogV = QVector2D(1, 0).normalized()
                 jogSp = QPointF(br.right(), br.center().y())
             jogEp = jogSp + (jogV * jogLen).toPointF()
             ap = pointOnArc(jogEp, arcCenter, arcRadius)
             av = QVector2D(arcCenter - jogEp)
             self.arrow.config({'pos': ap, 'dir': av})
             pp.moveTo(jogSp)
             pp.lineTo(jogEp)
             pp.lineTo(ap)
         # label inside arc
         else:
             leaderLen = self.scene().pixelsToScene(self.leaderLen)
             ap = pointOnArc(pos, arcCenter, arcRadius)
             av = QVector2D(arcCenter - ap).normalized()
             self.arrow.config({'pos': ap, 'dir': av})
             # fixed len arrow leader
             ep = ap + (av * -1 * leaderLen).toPointF()
             pp.moveTo(ap)
             pp.lineTo(ep)
     # arrow pointing away from arc center
     else:
         if labelOutside:
             jogLen = self.scene().pixelsToScene(self.jogLineLen)
             if labelRight:
                 jogV = QVector2D(-1, 0).normalized()
                 jogSp = QPointF(br.left(), br.center().y())
             else:
                 jogV = QVector2D(1, 0).normalized()
                 jogSp = QPointF(br.right(), br.center().y())
             jogEp = jogSp + (jogV * jogLen).toPointF()
             ap = pointOnArc(jogEp, arcCenter, arcRadius)
             av = QVector2D(ap - arcCenter)
             self.arrow.config({'pos': ap, 'dir': av})
             pp.moveTo(arcCenter)
             pp.lineTo(ap)
             pp.lineTo(jogEp)
             pp.lineTo(jogSp)
         # label inside the arc
         else:
             ap = pointOnArc(pos, arcCenter, arcRadius)
             av = QVector2D(ap - arcCenter)
             self.arrow.config({'pos': ap, 'dir': av})
             # label to arc center leader
             xp1 = xsectLineRect1(QLineF(pos, arcCenter), br)
             if xp1:
                 pp.moveTo(xp1)
                 pp.lineTo(arcCenter)
             # label to arrow leader
             xp2 = xsectLineRect1(QLineF(pos, ap), br)
             if xp2:
                 pp.moveTo(xp2)
                 pp.lineTo(ap)
     # extension arc
     arc = self.specMap['arc']
     arcStart = arc.start()
     arcSpan = arc.span()
     if not isPointOnArc(ap, arcCenter, arcStart, arcSpan):
         # arc rect
         p = QPointF(arcRadius, arcRadius)
         r = QRectF(arcCenter - p, arcCenter + p)
         bisV = arc.bisector()
         # arc center to arrow tip vector
         apV = QVector2D(ap - arcCenter).normalized()
         # bisector rotated 90
         bis90V = QVector2D(-bisV.y(), bisV.x())
         spV = arc.startAngleVector()
         spLeftOfBisector = spV.dotProduct(spV, bis90V) >= 0.0
         epV = arc.endAngleVector()
         # is the arrow tip to the left of the bisector?
         if bis90V.dotProduct(apV, bis90V) >= 0.0:
             # is the start point left of the bisector?
             if spLeftOfBisector:
                 extensionArc = Arc.fromVectors(spV, apV, arcRadius, True)
             else:
                 extensionArc = Arc.fromVectors(epV, apV, arcRadius, True)
             pp.arcMoveTo(r, -extensionArc.start() - self.gapAngle)
             pp.arcTo(r, -extensionArc.start() - self.gapAngle,
                      -extensionArc.span() - self.extAngle)
         # arrow tip to right of bisector
         else:
             # is the start point left of the bisector?
             if spLeftOfBisector:
                 extensionArc = Arc.fromVectors(epV, apV, arcRadius, False)
             else:
                 extensionArc = Arc.fromVectors(spV, apV, arcRadius, False)
             pp.arcMoveTo(r, -extensionArc.start() + self.gapAngle)
             pp.arcTo(r, -extensionArc.start() + self.gapAngle,
                      -extensionArc.span() + self.extAngle)
     self.setPath(pp)
Пример #36
0
def test_create_app():
    app = Arc()
    assert isinstance(app, Arc)