Beispiel #1
0
    def test_anchored_creation(self):
        o1 = SObject.Create([3])
        o1_anc = SAnchored(o1, [], 3, 3)

        o2 = SObject.Create([40])
        o2_anc = SAnchored(o2, [], 4, 4)

        o3 = SObject.Create([30])
        o3_anc = SAnchored(o3, [], 5, 5)

        # Create expects anchored objects...
        self.assertRaises(FargError, SAnchored.Create, (o1, ))

        # With a single arg, the object is returned unchanged.
        self.assertEqual(o1_anc, SAnchored.Create((o1_anc, )))

        # With multiple args, we expect the positions of these to be adjacent.
        self.assertRaises(NonAdjacentGroupElementsException, SAnchored.Create,
                          (o1_anc, o3_anc))

        # This also implies that elements may not be repeated:
        self.assertRaises(NonAdjacentGroupElementsException, SAnchored.Create,
                          (o1_anc, o1_anc))

        # If ranges are fine, the group is constructed fine:
        o123_anc = SAnchored.Create((o1_anc, o2_anc, o3_anc))
        self.assertEqual((3, 5), o123_anc.Span())
        self.assertEqual((3, 40, 30), o123_anc.Structure())
Beispiel #2
0
    def test_sanity(self):
        # This test refers to things in the Seqsee app. Maybe the test should move there.
        a3 = SObject.Create([11, 12, 13])
        a4 = SObject.Create([11, 12, 13, 14])
        a5 = SObject.Create([11, 12, 13, 14, 15])

        a19_21 = SObject.Create([19, 20, 21])

        _ui = BatchUI(controller_class=Controller)
        controller = _ui.controller
        controller.ltm = LTMGraph(empty_ok_for_test=True)
        mapping = FindMapping(a3,
                              a4,
                              category=Ascending(),
                              controller=controller,
                              seqsee_ltm=controller.ltm)
        self.assertTrue(isinstance(mapping, StructuralMapping))
        self.assertEqual(Ascending(), mapping.category)
        self.assertFalse(mapping.slippages)

        mapping = FindMapping(a5,
                              a19_21,
                              category=Ascending(),
                              controller=controller,
                              seqsee_ltm=controller.ltm)
        self.assertEqual(None, mapping)
Beispiel #3
0
 def ApplyMapping(self, mapping, item):
     name = mapping.name
     if name == 'same':
         return item.DeepCopy()
     if name == 'pred':
         return SObject.Create([item.magnitude - 1])
     if name == 'succ':
         return SObject.Create([item.magnitude + 1])
 def Create(self, bindings):
   start = bindings.get('start', None)
   end = bindings.get('end', None)
   length = bindings.get('length', None)
   if not start:
     if not end or not length:
       raise FargError("Create called when attributes insufficient to build.")
     start_mag = end.magnitude - length.magnitude + 1
     return SObject.Create(list(range(start_mag, end.magnitude + 1)))
   if not end:
     if not start or not length:
       raise FargError("Create called when attributes insufficient to build.")
     end_mag = start.magnitude + length.magnitude - 1
     return SObject.Create(list(range(start.magnitude, end_mag + 1)))
   return SObject.Create(list(range(start.magnitude, end.magnitude + 1)))
 def StructuralIsInstance(self, structure, item):
   depth = StructureDepth(structure)
   if depth >= 2: return None
   if depth == 0:
     return Binding(start=structure, end=structure, length=1)
   # So depth = 1
   for idx, v in enumerate(structure[1:], 1):
     if v != structure[idx - 1] + 1:
       return None
   bindings = Binding(start=SObject.Create([structure[0]]),
                      end=SObject.Create([structure[-1]]),
                      length=SObject.Create([structure[-1] - structure[0] + 1]))
   bindings.GetBindingsForAttribute("start").AddCategoriesFrom(item.items[0])
   bindings.GetBindingsForAttribute("end").AddCategoriesFrom(item.items[-1])
   return bindings
Beispiel #6
0
    def test_with_slippages(self):
        a17_19 = SObject.Create([17, 18, 19])
        a19_21 = SObject.Create([19, 20, 21])

        _ui = BatchUI(controller_class=Controller)
        controller = _ui.controller
        controller.ltm = LTMGraph(empty_ok_for_test=True)
        mapping = FindMapping(a17_19,
                              a19_21,
                              category=Ascending(),
                              controller=controller,
                              seqsee_ltm=controller.ltm)
        self.assertTrue(isinstance(mapping, StructuralMapping))
        self.assertEqual(Ascending(), mapping.category)
        slippages_dict = dict(mapping.slippages)
        self.assertEqual('end', slippages_dict['start'])
Beispiel #7
0
 def ApplyMapping(self, mapping, item):
     name = mapping.name
     if name == 'same':
         return item.DeepCopy()
     if name == 'pred':
         val = self._PrevNumber(item.magnitude)
         if val:
             return SObject.Create([val])
         else:
             return None
     if name == 'succ':
         val = self._NextNumber(item.magnitude)
         if val:
             return SObject.Create([val])
         else:
             return None
Beispiel #8
0
 def Create(self, bindings):
     items = [SObject.Create([bindings['start']])]
     for _i in range(1, bindings['length'].magnitude):
         if not items[-1].DescribeAs(self.mapping.category):
             #        msg = 'Unable to create object. Cat: %s. Item (%s) not a %s' % (
             #              str(self), str(items[-1]), str(self.mapping.category))
             #        msg = msg + "Start: %s, Length: %s" % (str(bindings['start']),
             #                                               str(bindings['length']))
             #        raise FargException(msg)
             return None
         next_item = self.mapping.Apply(items[-1])
         if not next_item:
             # raise FargException("Unable to create object")
             return None
         items.append(next_item)
     return SObject.Create(items)
Beispiel #9
0
 def StructuralIsInstance(self, structure, item):
     if isinstance(structure, int):
         return None
     if len(structure) != self.size:
         return None
     bindings = {}
     for idx, structure_item in enumerate(structure, 1):
         bindings['pos_%d' % idx] = SObject.Create([structure_item])
         bindings['pos_%d' % idx].AddCategoriesFrom(item.items[idx - 1])
     return Binding(**bindings)
Beispiel #10
0
  def test_sanity(self):
    ws = Workspace()
    self.assertEqual(0, ws.num_elements)

    ws.InsertElement(SObject.Create([5]))
    self.assertEqual(1, ws.num_elements)
    self.assertEqual(5, ws.elements[0].object.magnitude)

    ws.InsertElements((6, 7))
    self.assertEqual(6, ws.elements[1].object.magnitude)
    self.assertEqual((1, 1), ws.elements[1].Span())
    self.assertEqual(3, ws.num_elements)
Beispiel #11
0
    def test_Prime(self):
        self.assertEqual(Prime(), Prime())
        self.assertTrue(Prime().IsInstance(SObject.Create([3])))
        self.assertFalse(Prime().IsInstance(SObject.Create([4])))
        self.assertFalse(Prime().IsInstance(SObject.Create([3, 5])))

        element = SObject.Create([17])
        binding = Prime().IsInstance(element)
        self.assertFalse(element.IsKnownAsInstanceOf(Prime()))
        self.assertTrue(binding)
        self.assertEqual(6, binding.GetBindingsForAttribute('index'))

        binding2 = element.DescribeAs(Prime())
        self.assertTrue(element.IsKnownAsInstanceOf(Prime()))
        self.assertTrue(binding2)
        self.assertEqual(6, binding2.GetBindingsForAttribute('index'))
        self.assertNotEqual(binding, binding2)

        # Same (stored) binding returned.
        binding3 = element.DescribeAs(Prime())
        self.assertEqual(binding3, binding2)

        element5 = SObject.Create([5])
        element7 = SObject.Create([7])
        mapping = Prime().GetMapping(element5, element7)
        self.assertTrue(isinstance(mapping, NumericMapping))
        self.assertEqual(Prime(), mapping.category)
        self.assertEqual("succ", mapping.name)

        self.assertEqual(11, mapping.Apply(element7).magnitude)
    def test_sanity(self):
        myltm = LTMGraph(filename=self.filename)
        o1 = SObject.Create([1])
        o1b = SObject.Create([1])
        o2 = SObject.Create([2])
        o12 = SObject.Create([1, 2])
        o123 = SObject.Create([1, 2, 3])
        o1_23 = SObject.Create([1, (2, 3)])

        self.assertNotEqual(o1, o1b)
        self.assertEqual(o1.GetLTMStorableContent(),
                         o1b.GetLTMStorableContent())
        self.assertEqual(myltm.GetNode(content=o1), myltm.GetNode(content=o1b))

        for content in (o1, o1b, o2, o12, o123, o1_23):
            myltm.GetNode(content=content)

        self.assertEqual(myltm.GetNode(content=o1),
                         myltm.GetNode(content=SAnchored(o1, None, 5, 5)))

        self.assertEqual(myltm.GetNode(content=SAnchored(o1b, None, 6, 6)),
                         myltm.GetNode(content=SAnchored(o1, None, 5, 5)))

        self.assertNotEqual(
            myltm.GetNode(content=SAnchored(o1b, None, 6, 6)),
            myltm.GetNode(content=SAnchored(o1_23, None, 5, 7)))

        node = myltm.GetNode(content=SAnchored(o1_23, None, 5, 7))
        self.assertEqual(LTMStorableSObject, node.content.__class__)
        self.assertEqual((1, (2, 3)), node.content.structure)

        myltm.DumpToFile()

        myltm2 = LTMGraph(filename=self.filename)
        self.assertEqual(5, len(myltm2.nodes))
Beispiel #13
0
    def test_object_creation(self):
        o1 = SObject.Create([3])
        self.assertTrue(isinstance(o1, SObject))
        self.assertFalse(o1.is_group)

        o1a = SObject.Create([[3]])
        self.assertTrue(isinstance(o1a, SObject))
        self.assertFalse(o1a.is_group)

        o2 = SObject.Create([3, 4])
        self.assertTrue(isinstance(o2, SObject))
        self.assertTrue(o2.is_group)
        self.assertEqual(4, o2.items[1].magnitude)

        o2a = SObject.Create([[3, 4]])
        self.assertTrue(isinstance(o2a, SObject))
        self.assertTrue(o2a.is_group)
        self.assertEqual(4, o2a.items[1].magnitude)

        o2b = SObject.Create([o2])
        self.assertTrue(isinstance(o2b, SObject))
        self.assertTrue(o2b.is_group)
        self.assertEqual(4, o2b.items[1].magnitude)
Beispiel #14
0
 def IsInstance(self, item):
     if isinstance(item, SElement):
         # Probably the wrong thing to do.
         return None
     for item_part in item.items:
         if not item_part.DescribeAs(self.mapping.category):
             return self.IsDegenerateInstance(item)
     # So all items can be described as members of category...
     for idx, itempart in enumerate(item.items[1:], 1):
         if not self.mapping.IsPairConsistent(item.items[idx - 1], itempart):
             return self.IsDegenerateInstance(item)
     # Okay, so valid
     return Binding(start=item.items[0].DeepCopy(),
                    length=SObject.Create([len(item.items)]))
Beispiel #15
0
    def test_sizen(self):
        Size2 = SizeNCategory(size=2)
        Size2p = SizeNCategory(size=2)
        Size3 = SizeNCategory(size=3)

        self.assertEqual(Size2, Size2p)
        self.assertNotEqual(Size2, Size3)

        self.assertTrue(Size2.IsInstance(SObject.Create([3, 4])))
        self.assertTrue(Size2.IsInstance(SObject.Create([3, 5])))
        self.assertTrue(Size2.IsInstance(SObject.Create([3, (4, 5)])))
        self.assertFalse(Size2.IsInstance(SObject.Create([3, 4, 6])))

        group = SObject.Create([3, 5])
        binding = Size2.IsInstance(group)
        self.assertFalse(group.IsKnownAsInstanceOf(Size2))
        self.assertTrue(binding)
        self.assertEqual(3, binding.GetBindingsForAttribute('pos_1').magnitude)
        self.assertEqual(5, binding.GetBindingsForAttribute('pos_2').magnitude)

        binding2 = group.DescribeAs(Size2)
        self.assertTrue(group.IsKnownAsInstanceOf(Size2))
        self.assertTrue(binding2)
        self.assertEqual(3,
                         binding2.GetBindingsForAttribute('pos_1').magnitude)
        self.assertNotEqual(binding, binding2)

        # Same (stored) binding returned.
        binding3 = group.DescribeAs(Size2)
        self.assertEqual(binding3, binding2)

        element5 = SObject.Create([3, 5])
        element6 = SObject.Create([3, 6])
        _ui = BatchUI(controller_class=Controller)
        controller = _ui.controller
        controller.ltm = LTMGraph(empty_ok_for_test=True)
        mapping = Size2.FindMapping(element5,
                                    element6,
                                    controller=controller,
                                    seqsee_ltm=controller.ltm)
        self.assertTrue(isinstance(mapping, StructuralMapping))
        self.assertEqual(Size2, mapping.category)

        self.assertEqual((3, 7), mapping.Apply(element6).Structure())
    def Create(items, *, underlying_mapping_set=None):
        """Given a list of items, each a SAnchored, creates another SAnchored, provided that the
       items are contiguous. Raises a NonAdjacentGroupElementsException if they are
       non-adjacent.

       The only acceptable kwarg is 'underlying_mapping_set'
    """
        if not items:
            raise FargError(
                "Empty group creation attempted. An error at the moment.")
        if len(items) == 1:
            if isinstance(items[0], SAnchored):
                return items[0]
            else:
                raise FargError(
                    "Attempt to SAnchored.Create() from non-anchored parts: %s"
                    % items[0].__repr__())

        # So there are multiple items...
        for item in items:
            if not isinstance(item, SAnchored):
                raise FargError(
                    "Attempt to SAnchored.Create() from non-anchored parts: %s"
                    % item.__repr__())
        # .. Note:: This can probably be speeded up and cleaned up.
        left_edge, right_edge = items[0].Span()
        for item in items[1:]:
            left, right = item.Span()
            if left != right_edge + 1:
                raise NonAdjacentGroupElementsException(items=items)
            right_edge = right
        new_object = SObject.Create(list(x.object for x in items))
        new_object.underlying_mapping_set = (underlying_mapping_set if
                                             underlying_mapping_set else set())
        if underlying_mapping_set:
            from farg.apps.seqsee.categories import MappingBasedCategory
            for mapping in underlying_mapping_set:
                new_object.DescribeAs(MappingBasedCategory(mapping=mapping))
        return SAnchored(new_object, items, left_edge, right_edge)
Beispiel #17
0
    def test_ascending(self):
        self.assertTrue(Ascending().IsInstance(SObject.Create([3])))
        self.assertTrue(Ascending().IsInstance(SObject.Create([3, 4, 5])))

        self.assertFalse(Ascending().IsInstance(SObject.Create([4, 6])))
        self.assertFalse(Ascending().IsInstance(SObject.Create([4, (5, 6)])))

        group = SObject.Create([3, 4, 5])
        binding = Ascending().IsInstance(group)
        self.assertFalse(group.IsKnownAsInstanceOf(Ascending()))
        self.assertTrue(binding)
        self.assertEqual(3, binding.GetBindingsForAttribute('start').magnitude)
        self.assertEqual(5, binding.GetBindingsForAttribute('end').magnitude)

        binding2 = group.DescribeAs(Ascending())
        self.assertTrue(group.IsKnownAsInstanceOf(Ascending()))
        self.assertTrue(binding2)
        self.assertEqual(3,
                         binding2.GetBindingsForAttribute('start').magnitude)
        self.assertNotEqual(binding, binding2)

        # Same (stored) binding returned.
        binding3 = group.DescribeAs(Ascending())
        self.assertEqual(binding3, binding2)

        element5 = SObject.Create([13, 14, 15])
        element7 = SObject.Create([13, 14, 15, 16])
        _ui = BatchUI(controller_class=Controller)
        controller = _ui.controller
        controller.ltm = LTMGraph(empty_ok_for_test=True)
        mapping = Ascending().FindMapping(element5,
                                          element7,
                                          controller=controller,
                                          seqsee_ltm=controller.ltm)
        self.assertTrue(isinstance(mapping, StructuralMapping))
        self.assertEqual(Ascending(), mapping.category)

        self.assertEqual((13, 14, 15, 16, 17),
                         mapping.Apply(element7).Structure())
Beispiel #18
0
    def test_mapping_based(self):
        Size2 = SizeNCategory(size=2)
        numeric_sameness = NumericMapping(name="same", category=Number())
        numeric_successor = NumericMapping(name="succ", category=Number())
        mapping_second_succ = StructuralMapping(
            category=Size2,
            bindings_mapping=frozenset((('pos_1', numeric_sameness),
                                        ('pos_2', numeric_successor))))
        mapping_first_succ = StructuralMapping(
            category=Size2,
            bindings_mapping=frozenset((('pos_2', numeric_sameness),
                                        ('pos_1', numeric_successor))))
        SecondSucc = MappingBasedCategory(mapping=mapping_second_succ)
        SecondSuccp = MappingBasedCategory(mapping=mapping_second_succ)
        FirstSucc = MappingBasedCategory(mapping=mapping_first_succ)

        self.assertEqual(SecondSucc, SecondSuccp)
        self.assertNotEqual(SecondSucc, FirstSucc)

        self.assertTrue(SecondSucc.IsInstance(
            SObject.Create([(3, 4), (3, 5)])))
        self.assertTrue(SecondSucc.IsInstance(SObject.Create([3, 5])))
        self.assertTrue(SecondSucc.IsInstance(
            SObject.Create([(3, 4), (3, 5), (3, 6)])))
        self.assertFalse(SecondSucc.IsInstance(SObject.Create([3, 4, 6])))
        self.assertFalse(SecondSucc.IsInstance(
            SObject.Create([(3, 4), (3, 6), (3, 7)])))

        group = SObject.Create([(3, 5), (3, 6)])
        binding = SecondSucc.IsInstance(group)
        self.assertFalse(group.IsKnownAsInstanceOf(SecondSucc))
        self.assertTrue(binding)
        self.assertEqual(
            (3, 5), binding.GetBindingsForAttribute('start').Structure())
        self.assertEqual(
            2, binding.GetBindingsForAttribute('length').magnitude)

        binding2 = group.DescribeAs(SecondSucc)
        self.assertTrue(group.IsKnownAsInstanceOf(SecondSucc))
        self.assertTrue(binding2)
        self.assertEqual(
            (3, 5), binding.GetBindingsForAttribute('start').Structure())
        self.assertEqual(
            2, binding.GetBindingsForAttribute('length').magnitude)
        self.assertNotEqual(binding, binding2)

        # Same (stored) binding returned.
        binding3 = group.DescribeAs(SecondSucc)
        self.assertEqual(binding3, binding2)

        element5 = SObject.Create([(13, 5), (13, 6)])
        element6 = SObject.Create([(14, 6), (14, 7), (14, 8)])
        controller = MockSeqseeController()
        mapping = SecondSucc.FindMapping(element5, element6,
                                         controller=controller,
                                         seqsee_ltm=controller.ltm)
        self.assertTrue(isinstance(mapping, StructuralMapping))
        self.assertEqual(SecondSucc, mapping.category)

        self.assertEqual(((15, 7), (15, 8), (15, 9), (15, 10)),
                         mapping.Apply(element6).Structure())
Beispiel #19
0
 def Create(self, bindings):
     structure = [bindings['pos_%d' % x] for x in range(1, self.size + 1)]
     return SObject.Create(structure)
Beispiel #20
0
 def test_position(self):
     o2a = SObject.Create([3, 4])
     o2a_anchored = SAnchored(o2a, [], 10, 12)
     self.assertEqual(10, o2a_anchored.start_pos)
Beispiel #21
0
 def IsDegenerateInstance(self, item):
     if not item.DescribeAs(self.mapping.category):
         return None
     return Binding(start=item, length=SObject.Create([1]))