Example #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))
Example #2
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))
                              ]))
Example #3
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))
         ]))
Example #4
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))
                              ]))
Example #5
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))
                              ]))
Example #6
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))
                              ]))
Example #7
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))
                                   ]))
Example #8
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))
                                   ]))
Example #9
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 #10
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()
Example #11
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()
Example #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)
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
Example #14
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)
Example #15
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)
Example #16
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))
Example #17
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"
Example #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"
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
Example #20
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
Example #21
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))
         ])
Example #22
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)
Example #23
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
Example #24
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
Example #25
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;
Example #26
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'),
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
Example #28
0
 def test_no_subdivision(self):
     self.assert_subdiv_equal(Arc(Vector(0.0, 0.0), 1.0, (d_0, d_180)), 0,
                              1.0, d_45, (Arc(Vector(0.0, 0.0), 1.0,
                                              (d_0, d_180)), []))
Example #29
0
 def test_no_subdivision_lim_deffer_from_extremes(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)), []))
Example #30
0
def test_create_app():
    app = Arc()
    assert isinstance(app, Arc)