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'), ())]
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)
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)
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
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)
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)]
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
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__
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)
def test_object_property_overlap(): with pytest.raises(ValueError, match=r'overlap'): concepts.Context(('spam', 'eggs'), ('eggs', 'ham'), [(True, False), (False, True)])
def test_ne_false(context): assert not context != concepts.Context(context.objects, context.properties, context.bools)
def test_ne_true(context): d = context.definition() d.move_object('3pl', 0) assert context != concepts.Context(*d)
def test_eq_false(context): d = context.definition() d.move_object('3pl', 0) assert not context == concepts.Context(*d)
def test_eq_true(context): assert context == concepts.Context(context.objects, context.properties, context.bools)
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, )
def test_minimum(): l = concepts.Context(('spam', ), ('ham', ), [(True, )]).lattice assert len(l) == 1 assert l.infimum is l.supremum assert l.atoms == ()
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')
def test_duplicate_property(): with pytest.raises(ValueError, match=r'duplicate properties'): concepts.Context(('spam', 'eggs'), ('ham', 'ham'), [(True, False), (False, True)])
def test_duplicate_object(): with pytest.raises(ValueError, match=r'duplicate objects'): concepts.Context(('spam', 'spam'), ('ham', 'eggs'), [(True, False), (False, True)])
def test_empty_properies(): with pytest.raises(ValueError, match=r'empty properties'): concepts.Context(('spam',), (), [(False,)])
def lattice(context): context = concepts.Context(context.objects, context.properties, context.bools) return context.lattice
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)])
def test_empty_objects(): with pytest.raises(ValueError, match=r'empty objects'): concepts.Context((), ('spam',), [(False,)])
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))