Exemplo n.º 1
0
 def setUp(self):
     table = [[True, False, False, True],
              [True, False, True, False],
              [False, True, True, False],
              [False, True, True, True]]
     objs = ['1', '2', '3', '4']
     attrs = ['a', 'b', 'c', 'd']
     cxt = fca.Context(table, objs, attrs)
     self.db = ExplorationDB(cxt, list())
Exemplo n.º 2
0
def scale_mvcontext(mvcontext, scales):
    """Scale many-valued context to one-valued. 
    Return fca.Context
    
    scales is a list of the scales(fca.Scale) applied
    to current many-valued context. Number of the scales
    in the list must agree with number of attributes in 
    many-valued context.
    
    Example
    =======
    
    >>> s = fca.read_cxt("tests/scale.cxt")
    >>> mvc = fca.read_mv_txt("../readwrite/tests/table.txt")
    >>> for o in mvc:
    ...     print o
    ...
    ['7', '6', '7']
    ['7', '2', '9']
    ['1', '3', '4']
    >>> c = scale_mvcontext(mvc, [s]*len(mvc.attributes))
    >>> for o in c:
    ...     print o
    ...
    [True, False, True, False, True, False]
    [True, False, False, False, True, False]
    [False, True, False, False, False, False]
    >>> print c.attributes
    ['attr1>5', 'attr1==1', 'attr2>5', 'attr2==1', 'attr3>5', 'attr3==1']
    >>> print c.objects
    ['g1', 'g2', 'g3']
    
    """
    derived_context = fca.Context([[] for i in xrange(len(mvcontext.objects))],
                                  mvcontext.objects, [])
    for attr_index in range(len(mvcontext.attributes)):
        scale = scales[attr_index]
        for col in xrange(len(scale.attributes)):
            derived_attr = [False for i in xrange(len(mvcontext.objects))]
            for row in xrange(len(scale.objects)):
                for obj in xrange(len(mvcontext.objects)):
                    if derived_attr[obj]:
                        continue
                    else:
                        try:
                            value = float(mvcontext[obj][attr_index])
                        except:
                            value = str(mvcontext[obj][attr_index])
                        if eval(scale.objects[row], {"value": value}):
                            derived_attr[obj] = scale[row][col]
            new_attribute_name = ":".join(
                [mvcontext.attributes[attr_index], scale.attributes[col]])
            derived_context.add_column(derived_attr, new_attribute_name)
    return derived_context
 def get_cxt():
     intents = []
     objs = []
     for i, (docname, preds) in enumerate(doc2preds.items()):
         preds = set(preds)
         intents.append(preds)
         objs.append(docname)
     atts = list({x for intent in intents for x in intent})
     table = [[att in intent for att in atts] for intent in intents]
     cxt = fca.Context(cross_table=table, objects=objs, attributes=atts)
     return cxt
Exemplo n.º 4
0
 def _get_self_as_fca_object_context(self, pk=True):
     objects = self.group.content_objects(FObject)
     attributes = self.group.content_objects(FAttribute)
     if pk:
         object_names = [obj.pk for obj in objects]
         attribute_names = [attr.pk for attr in attributes]
     else:
         object_names = [obj.name for obj in objects]
         attribute_names = [attr.name for attr in attributes]
     table = []
     for obj in objects:
         table.append(obj.get_as_boolean_list(self.group))
     return fca.Context(zip(*table), attribute_names, object_names)
Exemplo n.º 5
0
 def test_cxt1(self):
     ct = [[1, 0, 0, 0], [0, 0, 0, 1]]
     atts = list('abcd')
     objs = [1, 2]
     cxt1 = fca.Context(ct, objs, atts)
     factors_iter = fca.algorithms.algorithm2_w_condition(
         cxt1,
         fidelity=1,
         allow_repeatitions=True,
         min_atts_and_objs=3,
         objs_ge_atts=True)
     with nose.tools.assert_raises(StopIteration):
         next(factors_iter)
Exemplo n.º 6
0
 def test_cxt2(self):
     cxt2_str = """
     0	...........X...............................X..........
     1	.X.....X...X.......XX............XX......X......X.....
     2	XX.....XX..XX.X.X..X..XX...XX.X..X..XX.....X.....X....
     3	...........XX...X......X.....X...X.........XX.........
     4	.XX........XXX..X..X....X........XXX......XX..........
     5	.X.........XX..XX.XX...X.XX.X......X..X.....X..X...X..
     6	X....X.....XX..XX.XX......X.X..X.XX..X.....XXX.X...X..
     7	.X.X.X..XX.XXXXXX...X......X..XXXX..XX.XX.X...X..X..X.
     8	XXX.XX.....XX..XX.XXX.XX..X...X..X...X....X.XX.....X.X
     9	.XXX....XXXX.XX.X.X.....XX.X.X..X...X.XX......X..X....
     10	.X.X.XX.XXXX.XXXX.X.....XX.X.X.XX.......X.X..XX..X....
     11	.X.........X........X............X.........X..........
     12	...........X.....................X.........X......X...
     13	XXXXXX....XXX.XXX......XX..X...X....XX...XXX.XX..X..X.
     14	.XX.XX......XXXXX...X.XX.X.X..XX.X.XXX..X...XX.X..X.XX
     15	.X..XX.....XXXXXX......X...X..XX.X..XXX...X.XX.X.XXXXX
     16	.X...........X.......X...........X..............X.X...
     17	.................X...X...........X..............X.X...
     18	.................X...............X....................
     19	.X....X......X...X...X...........XX....XXX......X.....
     20	......X....X.............................X.X..........
     21	......XX...X........X....................X.X..........
     22	.X.........XX.......X.............X......X.X..........
     23	......XX.....X...................X....................
     """
     ct = []
     objs = []
     for line in cxt2_str.split('\n'):
         line = line.strip()
         if not line:
             continue
         line_match = re.match(r'(\d+)\s+([.X]+)', line)
         obj = line_match.group(1)
         cross_str = line_match.group(2)
         crosses = [c == 'X' for c in cross_str]
         ct.append(crosses)
         objs.append(obj)
     cxt2 = fca.Context(ct,
                        objects=objs,
                        attributes=[f'a{i}' for i in range(len(ct[0]))])
     factors_iter = fca.algorithms.algorithm2_w_condition(
         cxt2,
         fidelity=1,
         allow_repeatitions=False,
         min_atts_and_objs=3,
         objs_ge_atts=False)
     for i, x in enumerate(factors_iter):
         print(x)
     assert i > 0
Exemplo n.º 7
0
def make_factor_cxts(factors=None):
    """
    Make two contexts: objects-factors and factors-attributes out of tuple of
    given concepts.
    
    @param factors: tuple of *fca.Concept*s (or anything that has *extent* and 
    *intent* instance variables).
    """
    def el_ind(el, el_dict):
        try:
            return el_dict[el]
        except KeyError:
            num_els = len(el_dict)
            el_dict[el] = num_els
            return num_els

    if factors is None:
        factors = []
    objs_dict = dict()
    atts_dict = dict()
    table_objs_fcts = []
    table_fcts_atts = []
    for c in factors:
        table_objs_fcts.append(set(el_ind(obj, objs_dict) for obj in c.extent))
        table_fcts_atts.append(set(el_ind(att, atts_dict) for att in c.intent))
    # sort objs and atts in order of appearance to get correct factor ex/intents
    attributes = sorted(list(atts_dict.keys()), key=atts_dict.__getitem__)
    objects = sorted(list(objs_dict.keys()), key=objs_dict.__getitem__)
    num_atts = len(attributes)
    num_objs = len(objects)
    names_fcts = ['f{}'.format(x) for x in range(len(factors))]
    table_objs_fcts = list(zip(*[[(x in row) for x in range(num_objs)]
                            for row in table_objs_fcts]))
    table_fcts_atts = [[(x in row) for x in range(num_atts)]
                       for row in table_fcts_atts]
    return (fca.Context(table_objs_fcts, objects, names_fcts),
            fca.Context(table_fcts_atts, names_fcts, attributes))
Exemplo n.º 8
0
def read_txt_with_names(path):
    """Read context from path, which is tab separated txt file

    Format
    ======

    First line is tab separated attributes' names
    Next an empty line
    The first value in every line is on object name.
    Then tab separated 1 and 0, each line corresponds to one object.

    """
    input_file = open(path, "r")
    rdr = csv.reader(input_file, delimiter="\t")
    rec = next(rdr)  # read attributes names

    attributes = []
    for attr in rec:
        attributes.append(str(attr).strip())

    next(rdr)  # empty line

    table = []
    objects = []
    for rec in rdr:
        objects.append(rec[0])  # read objects names
        line = []
        for num in rec:
            if num == "0":
                line.append(False)
            elif num == "1":
                line.append(True)
        table.append(line)
    input_file.close()

    if len(attributes) != len(table[0]):
        input_file = open(path, "r")
        attributes = input_file.readline().split("\t")[:-1]
        input_file.close()

    return fca.Context(table, objects, attributes)
Exemplo n.º 9
0
    def NewContext(self, parent, name):
        def _Error(message):
            dlg = wx.MessageDialog(self._view.GetParent(), message, "Error!",
                                   wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return None

        if name in [child.name for child in parent.children]:
            return _Error(
                "Can't create new context, file '{0}' already exists".format(
                    name))
        new_path = os.path.join(parent.path, name)
        try:
            fca.write_cxt(fca.Context(), new_path)
        except:
            #TODO: Error handler
            return _Error("Can't create new context, something wrong")

        new_item = WorkspaceItem(name, new_path, False, parent)
        self.SaveWorkspace()
        return new_item
Exemplo n.º 10
0
    #            'Ansett Australia', 'The Australian Airlines Group',
    #            'British Midland', 'Lufthansa', 'Mexicana',
    #            'Scandinavian Airlines', 'Singapore Airlines',
    #            'Thai Airways International', 'United Airlines',
    #            'VARIG']
    # attributes = ['Latin America', 'Europe', 'Canada', 'Asia Pasific',
    #               'Middle East', 'Africa', 'Mexico', 'Carribean',
    #               'United States']
    # table = [[True, True, True, True, True, False, True, True, True],
    #          [False, True, False, True, False, False, False, False, True],
    #          [False, True, False, True, False, False, False, False, True],
    #          [False, False, False, True, False, False, False, False, False],
    #          [False, True, True, True, True, True, False, False, True],
    #          [False, True, False, False, False, False, False, False, False],
    #          [True, True, True, True ,True, True, True, False, True],
    #          [True, False, True, False, False, False, True, True, True],
    #          [True, True, False, True, False, True, False, False, True],
    #          [False, True, True, True, True, True, False, False, True],
    #          [True, True, False, True, False, False, False, True, True],
    #          [True, True, True, True, False, False, True, True, True],
    #          [True, True, False, True, False, True, True, False, True]]
    # cxt = fca.Context(table, objects, attributes)
    ct = [[True]]
    objs = ['1']
    attrs = ['a']
    cxt = fca.Context(ct, objs, attrs)

    imp_basis = compute_dg_basis(cxt, imp_basis=[Implication(set(), {'a'})])

    for imp in imp_basis:
        print(imp)
Exemplo n.º 11
0
def read_cxt(path):
    """Read context from path, which is .cxt file

    Format
    ======

    Example of .cxt file (tests/context.cxt):

    B

    4
    4

    Obj 1
    Obj 2
    Obj 3
    Obj 4
    a
    b
    c
    d
    X..X
    X.X.
    .XX.
    .XXX

    Examples
    ========

    Load example file from tests directory

    >>> c = read_cxt('tests/context.cxt')
    >>> len(c)
    4
    >>> len(c[0])
    4
    >>> for o in c:
    ...     print o
    ...
    [True, False, False, True]
    [True, False, True, False]
    [False, True, True, False]
    [False, True, True, True]
    >>> print c.objects
    ['Obj 1', 'Obj 2', 'Obj 3', 'Obj 4']
    >>> print c.attributes
    ['a', 'b', 'c', 'd']
    >>> c = read_cxt('tests/context.txt')
    Traceback (most recent call last):
        ...
    AssertionError: File is not valid cxt

    """
    input_file = open(path, "r")
    assert input_file.readline().strip() == "B",\
        "File is not valid cxt"
    input_file.readline()  # Empty line
    number_of_objects = int(input_file.readline().strip())
    number_of_attributes = int(input_file.readline().strip())
    input_file.readline()  # Empty line

    objects = [
        input_file.readline().strip() for i in xrange(number_of_objects)
    ]
    attributes = [
        input_file.readline().strip() for i in xrange(number_of_attributes)
    ]

    table = []
    for i in xrange(number_of_objects):
        line = map(lambda c: c == "X", input_file.readline().strip())
        table.append(line)

    input_file.close()

    return fca.Context(table, objects, attributes)
Exemplo n.º 12
0
            raise BasisConflict(extent)
        else:
            self.context.add_attribute_with_extent(extent, name)
            self.recompute_basis()

    def edit_attribute(self, new_extent, name):
        if not self.check_extent_for_conflicts(new_extent):
            raise BasisConflict(new_extent)
        else:
            self.context.set_attribute_extent(new_extent, name)
            self.recompute_basis()

    def edit_object(self, new_intent, name):
        if not self.check_intent_for_conflicts(new_intent):
            raise BasisConflict(new_intent)
        else:
            self.context.set_object_intent(new_intent, name)
            self.recompute_basis()


if __name__ == "__main__":
    table = [[True, False, False, True], [True, False, True, False],
             [False, True, True, False], [False, True, True, True]]
    objs = ['1', '2', '3', '4']
    attrs = ['a', 'b', 'c', 'd']
    cxt = fca.Context(table, objs, attrs)
    exp = BasicExploration(cxt)
    print(exp)
    exp.confirm_object_implication(1)
    exp.counter_example_for_obj_implication('test', {'3'}, 0)
    print(exp)
Exemplo n.º 13
0
def read_txt(path):
    """Read context from path, which is tab separated txt file

    Format
    ======

    First line is tab separated attributes' names
    Next an empty line
    Then tab separated 1 and 0, each line corresponds to one object.

    Examples
    ========

    Load example file from tests directory

    >>> c = read_txt('tests/context.txt')
    >>> len(c)
    4
    >>> len(c[0])
    4
    >>> for o in c:
    ...     print o
    ...
    [True, False, False, True]
    [True, False, True, False]
    [False, True, True, False]
    [False, True, True, True]
    >>> print c.objects
    ['g1', 'g2', 'g3', 'g4']
    >>> print c.attributes
    ['a', 'b', 'c', 'd']

    """
    input_file = open(path, "rb")
    rdr = csv.reader(input_file, delimiter="\t")
    rec = rdr.next()  # read attributes names

    attributes = []
    for attr in rec:
        attributes.append(str(attr).strip())

    rdr.next()  # empty line

    table = []
    for rec in rdr:
        line = []
        for num in rec:
            if num == "0":
                line.append(False)
            elif num == "1":
                line.append(True)
        table.append(line)
    input_file.close()
    # i + 1 ?
    objects = ["".join(["g", str(i + 1)]) for i in range(len(table))]

    # TODO: It's hack
    # Strange things happen with csv in case of non standard characters
    if len(attributes) != len(table[0]):
        input_file = open(path, "rb")
        attributes = input_file.readline().split("\t")[:-1]
        input_file.close()

    return fca.Context(table, objects, attributes)
Exemplo n.º 14
0
        'Africa', 'Mexico', 'Carribean', 'United States'
    ]
    table = [[True, True, True, True, True, False, True, True, True],
             [False, True, False, True, False, False, False, False, True],
             [False, True, False, True, False, False, False, False, True],
             [False, False, False, True, False, False, False, False, False],
             [False, True, True, True, True, True, False, False, True],
             [False, True, False, False, False, False, False, False, False],
             [True, True, True, True, True, True, True, False, True],
             [True, False, True, False, False, False, True, True, True],
             [True, True, False, True, False, True, False, False, True],
             [False, True, True, True, True, True, False, False, True],
             [True, True, False, True, False, False, False, True, True],
             [True, True, True, True, False, False, True, True, True],
             [True, True, False, True, False, True, True, False, True]]
    cxt = fca.Context(table, objects, attributes)

    imp_basis = compute_implication_cover(cxt, closure_operators.closure)
    print_basis(imp_basis)
    minimize(imp_basis)
    print(len(imp_basis))
    for imp in imp_basis:
        print imp

    print '***'

    objects = [1, 2, 3, 4]
    attributes = ['a', 'b', 'c', 'd']
    table = [[True, False, True, True], [True, False, True, False],
             [False, True, True, False], [False, True, False, True]]
    cxt = fca.Context(table, objects, attributes)
Exemplo n.º 15
0
 def setUp(self):
     ct = [[True, True, True, True], [True, False, True, False],
           [False, True, True, False], [False, True, True, True]]
     objs = ['1', '2', '3', '4']
     attrs = ['a', 'b', 'c', 'd']
     self.cxt = fca.Context(ct, objs, attrs)