예제 #1
0
def test_nonatomic():
    m = concepts.Context(('spam', 'eggs'), ('ham', ), [(True, ),
                                                       (True, )]).lattice
    assert [tuple(c) for c in m] == [(('spam', 'eggs'), ('ham', ))]
    t = concepts.Context(('spam', 'eggs'), ('ham', ), [(False, ),
                                                       (False, )]).lattice
    assert [tuple(c) for c in t] == [((), ('ham', )), (('spam', 'eggs'), ())]
예제 #2
0
def test_eq(lattice):
    assert lattice._eq(lattice)

    d = lattice._context.definition()
    assert lattice._eq(concepts.Context(*d).lattice)

    d.add_object('X', ['mysterious', 'child'])
    assert not lattice._eq(concepts.Context(*d).lattice)
    d.remove_object('X')

    d.move_object('3pl', 0)
    assert not lattice._eq(concepts.Context(*d).lattice)
예제 #3
0
def graph_to_fca_context(graph, tokenize=True):
    '''
    Uses the given `graph` to generate an FCA context. 
    This feature is useful when you want to apply formal concept analysis
    to detect the possible semantic meaning of the the community structure of
    a bounded model checking problem instance.
    
    :param graph: the graph to use to produce the FCA context
    :param tokenize: split the semantic names into token (increases the chances
        of fca finding something interesting)
    '''
    d = concepts.Definition()
    
    for vertex in range(len(graph.vs)):
        repres = vertex_repr(graph, vertex)
        
        var_info   = repres.split(sep="*")
        var_name   = var_info[0]
        var_block  = var_info[-1]
        
        if tokenize:
            var_tokens = var_name.split(sep=".")
            d.add_object(str(vertex), var_tokens + [var_block] )
        else:
            d.add_object(str(vertex), [var_name, var_block] )
    
    return concepts.Context(*d)
예제 #4
0
def dataMatrix(filepath):
    """Construction of the complete matrix"""

    dict_object = {}
    with open(filepath, "rt") as matrix_file:
        readertext = csv.reader(matrix_file, delimiter=',')
        header = readertext.__next__()
        #print("HEADER:")
        #print(header)
        list_column_header = header[1:]
        number_columns = len(list_column_header)
        #for currentColHeader in list_column_header:
            #print("  " + currentColHeader)
        #print("  => " + str(number_columns) + " columns")
        #print("")
        for current_row in readertext:
            #print("")
            #print(current_row)
            current_object = current_row[0]
            dict_object[current_object] = []
            for i in range(number_columns):
                if current_row[i+1] == '1':
                    #print("  " + list_column_header[i])
                    dict_object[current_object].append(list_column_header[i])

    definition = concepts.Definition()
    for (current_object, current_values) in dict_object.items():
        definition.add_object(current_object, current_values)
    context = concepts.Context(*definition)
    return context
예제 #5
0
def test_eq_mapping(lattice):
    other = concepts.Context(*lattice._context.definition()).lattice
    k, v = other._mapping.popitem()
    assert not other._eq(lattice)

    k = k.__class__.frommembers(['1sg', '3pl'])
    other._mapping[k] = v
    assert not other._eq(lattice)
예제 #6
0
def test_init():
    c = concepts.Context(('spam', 'eggs'),
                         ('camelot', 'launcelot'),
                         [(True, False), (False, True)])

    assert c.objects == ('spam', 'eggs')
    assert c.properties == ('camelot', 'launcelot')
    assert c.bools == [(True, False), (False, True)]
예제 #7
0
def line_diagram(graph, filename=LATTICE_FILENAME):
    import concepts
    diag = concepts.Definition()
    for node in sorted(graph.keys()):
        diag.add_object(node, graph[node])
    context = concepts.Context(*diag)
    context.lattice.graphviz().render(filename=os.path.basename(filename),
                                      directory=os.path.dirname(filename),
                                      cleanup=True)  # cleanup the dot file
    assert os.path.exists(filename + '.pdf')  # output is pdf
예제 #8
0
def test_copy(context):
    context = concepts.Context(context.objects,
                               context.properties,
                               context.bools)
    assert context.lattice is not None

    copy = context.copy()

    assert copy == context
    assert 'lattice' not in copy.__dict__
예제 #9
0
def test_eq_concepts(lattice):
    other = concepts.Context(*lattice._context.definition()).lattice
    c = other[16]

    for attname in ('index', 'dindex'):
        i = getattr(c, attname)
        setattr(c, attname, -1)
        assert not other._eq(lattice)
        setattr(c, attname, i)

    for attname in ('atoms', 'properties', 'objects'):
        t = tuple(getattr(c, attname))
        if attname == 'objects':
            setattr(c, attname, ('spam', ))
        else:
            setattr(c, attname, tuple(reversed(t)))
        assert not other._eq(lattice)
        setattr(c, attname, t)
예제 #10
0
def test_object_property_overlap():
    with pytest.raises(ValueError, match=r'overlap'):
        concepts.Context(('spam', 'eggs'),
                         ('eggs', 'ham'),
                         [(True, False), (False, True)])
예제 #11
0
def test_ne_false(context):
    assert not context != concepts.Context(context.objects,
                                           context.properties,
                                           context.bools)
예제 #12
0
def test_ne_true(context):
    d = context.definition()
    d.move_object('3pl', 0)
    assert context != concepts.Context(*d)
예제 #13
0
def test_eq_false(context):
    d = context.definition()
    d.move_object('3pl', 0)
    assert not context == concepts.Context(*d)
예제 #14
0
def test_eq_true(context):
    assert context == concepts.Context(context.objects,
                                       context.properties,
                                       context.bools)
예제 #15
0
def test_trivial():
    l = concepts.Context(('spam', ), ('ham', ), [(False, )]).lattice
    assert len(l) == 2
    assert l.infimum is not l.supremum
    assert l.atoms == (l.supremum, )
예제 #16
0
def test_minimum():
    l = concepts.Context(('spam', ), ('ham', ), [(True, )]).lattice
    assert len(l) == 1
    assert l.infimum is l.supremum
    assert l.atoms == ()
예제 #17
0
    context.tofile(DAT, frmat='fimi')
    print(DAT, f'{DAT.stat().st_size:_d} bytes')

    definition = concepts.Definition.fromfile(CXT)
    removed = definition.remove_empty_properties()
    assert removed == ['gill-attachment:descending',
                       'gill-attachment:notched',
                       'gill-spacing:distant',
                       'stalk-root:cup',
                       'stalk-root:rhizomorphs',
                       'veil-type:universal',
                       'ring-type:cobwebby',
                       'ring-type:sheathing',
                       'ring-type:zone']

    context = concepts.Context(*definition)
    assert context.shape == (8_124, 119), f'{context.shape} != (8_124, 119)'

    context.tofile(CXT_MINIMAL, frmat='cxt')  # examples/mushroom.cxt
    print(CXT_MINIMAL, f'{CXT_MINIMAL.stat().st_size:_d} bytes')

    context.tofile(CSV_MINIMAL_STR, frmat='csv',
                   object_header=MUSHROOM.stem, bools_as_int=False)
    print(CSV_MINIMAL_STR, f'{CSV_MINIMAL_STR.stat().st_size:_d} bytes')

    context.tofile(CSV_MINIMAL_INT, frmat='csv',
                   object_header=MUSHROOM.stem, bools_as_int=True)
    print(CSV_MINIMAL_INT, f'{CSV_MINIMAL_INT.stat().st_size:_d} bytes')

    context.tofile(DAT_MINIMAL, frmat='fimi')
    print(DAT_MINIMAL, f'{DAT_MINIMAL.stat().st_size:_d} bytes')
예제 #18
0
def test_duplicate_property():
    with pytest.raises(ValueError, match=r'duplicate properties'):
        concepts.Context(('spam', 'eggs'),
                         ('ham', 'ham'),
                         [(True, False), (False, True)])
예제 #19
0
def test_duplicate_object():
    with pytest.raises(ValueError, match=r'duplicate objects'):
        concepts.Context(('spam', 'spam'),
                         ('ham', 'eggs'),
                         [(True, False), (False, True)])
예제 #20
0
def test_empty_properies():
    with pytest.raises(ValueError, match=r'empty properties'):
        concepts.Context(('spam',), (), [(False,)])
예제 #21
0
def lattice(context):
    context = concepts.Context(context.objects, context.properties,
                               context.bools)
    return context.lattice
예제 #22
0
def test_invalid_bools_2():
    with pytest.raises(ValueError, match=r'bools is not 2 items of length 2'):
        concepts.Context(('spam', 'eggs'),
                         ('camelot', 'launcelot'),
                         [(True, False, False), (False, True)])
예제 #23
0
def test_empty_objects():
    with pytest.raises(ValueError, match=r'empty objects'):
        concepts.Context((), ('spam',), [(False,)])
예제 #24
0
def classbymutation(dict, list_mut, result_folder):
    list_class = list(dict.keys())
    mutations_row = []

    for mutation in list_mut:
        mutations_row.append((mutation, [0] * len(list_class)))
    col_width = 0
    d = concepts.Definition()
    for clas, value in dict.items():
        if col_width < len(clas): col_width = len(clas)

        d.add_object(clas, value[1])

        for val in value[1]:
            for elem in mutations_row:
                if elem[0] == val:
                    i = list_class.index(clas)
                    elem[1][i] = 1

    c = concepts.Context(*d)
    l = c.lattice
    graphe = l.graphviz()
    graphe = apply_styles(graphe, styles)
    graphe.render(filename=result_folder + "Treillis", cleanup=True)

    list_object = []
    list_attribute = []
    maxi = 0
    for extent, intent in c.lattice:
        if len(extent) > maxi: maxi = len(extent)
        list_object.append(extent)
        list_attribute.append(intent)
    list_attribute = overlap(list_object, list_attribute, maxi)

    rest_combination = []
    specifyFile = open(result_folder + "Class_Specific_Mutations.txt", "w")
    for i, elem in enumerate(list_object):
        if len(elem) == maxi:
            specifyFile.write(
                "All classes can be achieved by those mutations :\n")
            specifyFile.write("  /  ".join(list_attribute[i]) + "\n\n")
        elif len(list_attribute[i]) == 0:
            rest_combination.append(elem)
            pass
        else:
            specifyFile.write("Only " + str(elem) +
                              " can be achieved by those mutations :\n")
            specifyFile.write("  /  ".join(list_attribute[i]) + "\n\n")
    specifyFile.write(
        "Other combination of class don't have specific mutations :\n")
    for rest in rest_combination:
        specifyFile.write(str(rest) + " ")

    df = pd.DataFrame.from_items(mutations_row,
                                 orient='index',
                                 columns=list_class)
    df.sort_index(inplace=True)

    with open(result_folder + "result.tex", 'w') as latex_file:
        latex_file.write(r'''\documentclass[10pt,a4paper,landscape]{article}
            \usepackage[left=1.5cm, right=1.5cm, top=1.5cm, bottom=1.5cm]{geometry}
            \usepackage{array}
            \usepackage{booktabs}
            \usepackage{longtable}
            \begin{document}
            ''')
        p = 'p{4cm}|'
        #print(p) , col_space=10
        col_format = '|p{5cm}|' + 'c|' * len(list_class)
        latex_file.write(df.to_latex(column_format=col_format, longtable=True))
        latex_file.write('''
            \end{document}
            ''')
    os.system('pdflatex -output-directory={} result.tex > /dev/null'.format(
        result_folder))