API Reference

load

Load and return formal context from file.

load_csv

Load and return formal context from CSV file.

load_cxt

Load and return formal context from CXT file.

make_context

Return a new context from source string in the given format.

Context

Formal context defining a relation between objects and properties.

Definition

Mutable triple of (objects, properties, bools) for creating a context.

concepts.lattices.Lattice

Formal concept lattice as directed acyclic graph of concepts.

concepts.lattices.Concept

Formal concept as pair of extent and intent.

Top-level functions

Short-cuts to the most common uses of Context.fromfile() and Context.fromstring():

concepts.load(filename, encoding='utf-8', frmat=None)

Load and return formal context from file.

Parameters
  • filename – Path to the file to load the context from.

  • encoding (str) – Encoding of the file ('utf-8', 'latin1', 'ascii', …).

  • frmat (str) – Format of the file ('table', 'cxt', 'csv'). If None (default), infer frmat from filename suffix.

Returns

New Context instance.

Return type

Context

Example

>>> load('examples/liveinwater.txt')  
<Context object mapping 8 objects to 9 properties [b1e86589] at 0x...>
concepts.load_csv(filename, dialect='excel', encoding='utf-8')

Load and return formal context from CSV file.

Parameters
  • filename – Path to the CSV file to load the context from.

  • dialect – Syntax variant of the CSV file ('excel', 'excel-tab').

  • encoding (str) – Encoding of the file ('utf-8', 'latin1', 'ascii', …).

Returns

New Context instance.

Return type

Context

Example

>>> load_csv('examples/vowels.csv')  
<Context object mapping 12 objects to 8 properties [a717eee4] at 0x...>
concepts.load_cxt(filename, encoding=None)

Load and return formal context from CXT file.

Parameters
  • filename – Path to the CXT file to load the context from.

  • encoding (str) – Encoding of the file ('utf-8', 'latin1', 'ascii', …).

Returns

New Context instance.

Return type

Context

Example

>>> load_cxt('examples/digits.cxt')  
<Context object mapping 10 objects to 7 properties [51e571e6] at 0x...>
concepts.make_context(source, frmat='table')

Return a new context from source string in the given format.

Parameters
  • source (str) – Formal context table as plain-text string.

  • frmat (str) – Format of the context string ('table', 'cxt', 'csv').

Returns

New Context instance.

Return type

Context

Example

>>> make_context('''
...      |male|female|adult|child|
... man  |  X |      |  X  |     |
... woman|    |   X  |  X  |     |
... boy  |  X |      |     |  X  |
... girl |    |   X  |     |  X  |
... ''')  
<Context object mapping 4 objects to 4 properties [65aa9782] at 0x...>

Context

class concepts.Context(objects, properties, bools)

Formal context defining a relation between objects and properties.

Create context from objects, properties, and bools correspondence.

Parameters
  • objects – Iterable of object label strings.

  • properties – Iterable of property label strings.

  • bools – Iterable of len(objects) tuples of len(properties) booleans.

Returns

New Context instance.

Return type

Context

Example

>>> Context(['man', 'woman'], ['male', 'female'], [(True, False), (False, True)])  
<Context object mapping 2 objects to 2 properties [47e29724] at 0x...>
__eq__(other)

Return whether two contexts are equivalent.

Parameters

other (Context) – Another Context instance.

Returns

True if the contexts are equal, False otherwise.

Return type

bool

Ignores self.lattice and other.lattice objects.

__getitem__(items, raw=False)

Return (extension, intension) pair by shared objects or properties.

Parameters
  • items – Iterable of str labels either taken from self.objects or from self.properties.

  • raw (bool) – Return raw (extent, intent) pair instead of str tuples.

Returns

The smallest concept having all items as (extent, intent) pair.

Return type

tuple[tuple[str, ..], tuple[str, ..]]

__ne__(other)

Return whether two contexts are inequivalent.

Parameters

other (Context) – Another Context instance.

Returns

True if the contexts are unequal, False otherwise.

Return type

bool

Ignores self.lattice and other.lattice objects.

property bools

Row-wise boolean relation matrix between objects and properties.

Type

list[tuple[bool, ..]]

crc32(encoding='utf-8')

Return hex-encoded unsigned CRC32 over encoded context table string.

Parameters

encoding (str) – Encoding of the serialzation ('utf-8', 'latin1', 'ascii', …).

Returns

The unsigned CRC32 checksum as hex-string.

Return type

str

definition()

Return (objects, properties, bools) triple as mutable object.

Returns

New Definition instance.

Return type

Definition

extension(properties, raw=False)

Return all objects sharing the given properties.

Parameters
  • properties – Iterable of str labels taken from self.properties.

  • raw (bool) – Return raw extent instead of str tuple.

Returns

A tuple of str labels taken from self.objects.

Return type

tuple[str, ..]

classmethod fromdict(d, ignore_lattice=False, require_lattice=False, raw=False)

Return a new context from dict d.

Parameters
  • d (dict) – serialized context with optional 'lattice'

  • ignore_lattice (bool) – don’t load lattice from d

  • require_lattice (bool) – raise if no lattice in d

  • raw (bool) – If set, sort so the input sequences can be in any order. If unset (default), assume input is already ordered for speedup

Returns

New Context instance.

Return type

Context

classmethod fromfile(filename, frmat='cxt', encoding=None, **kwargs)

Return a new context from file source in given format.

Parameters
  • filename – Path to the file to load the context from.

  • encoding (str) – Encoding of the file ('utf-8', 'latin1', 'ascii', …).

  • frmat (str) – Format of the file ('table', 'cxt', 'csv'). If None (default), infer frmat from filename suffix.

Returns

New Context instance.

Return type

Context

classmethod fromjson(path_or_fileobj, encoding='utf-8', ignore_lattice=False, require_lattice=False, raw=False)

Return a new context from json path or file-like object.

Parameters
  • path_or_fileobjstr, os.PathLike, or file-like object open for reading.

  • encoding (str) – Ignored for file-like objects under Python 3.

  • ignore_lattice (bool) – Don’t load lattice from json serialization.

  • require_lattice (bool) – Raise if no lattice in json serialization.

  • raw (bool) – If set, sort so the input sequences can be in any order. If unset (default), assume input is already ordered for speedup

Returns

New Context instance.

Return type

Context

classmethod fromstring(source, frmat='table', **kwargs)

Return a new context from string source in given format.

Parameters
  • source (str) – Formal context table as plain-text string.

  • frmat (str) – Format of the context string ('table', 'cxt', 'csv').

Returns

New Context instance.

Return type

Context

intension(objects, raw=False)

Return all properties shared by the given objects.

Parameters
  • objects – Iterable of str labels taken from self.objects.

  • raw (bool) – Return raw intent instead of str tuple.

Returns

A tuple of str labels taken from self.properties.

Return type

tuple[str, ..]

lattice

The concept lattice of the formal context.

Type

Lattice

neighbors(objects, raw=False)

Return the upper neighbors of the concept having all given objects.

Parameters
  • objects – Iterable of str labels taken from self.objects.

  • raw (bool) – Return raw (extent, intent) pairs instead of str tuples.

Returns

A list of upper neighbor concepts as (extent, intent) pairs.

Return type

list[tuple[tuple[str, ..], tuple[str, ..]]

property objects

(Names of the) objects described by the context.

Type

tuple[str, ..]

property properties

(Names of the) properties that describe the objects.

Type

tuple[str, ..]

relations(include_unary=False)

Return the logical relations between the context properties.

Returns

Return type

Relations

todict(ignore_lattice=False)

Return serialized context with optional lattice.

Parameters

ingnore_lattice (bool) – Omit 'lattice' in result. If None, 'lattice' is omitted if it has not yet been computed.

Returns

A new dict with the serialized context.

Return type

dict

tofile(filename, frmat='cxt', encoding='utf-8', **kwargs)

Save the context serialized to file in the given format.

Parameters
  • frmat (str) – Format of the string ('table', 'cxt', 'csv').

  • encoding (str) – Encoding of the file ('utf-8', 'latin1', 'ascii', …).

tojson(path_or_fileobj, encoding='utf-8', indent=None, sort_keys=True, ignore_lattice=False)

Write serialized context as json to path or file-like object.

Parameters
  • path_or_fileobjstr, os.PathLike, or file-like object open for writing.

  • encoding (str) – Ignored for file-like objects under Python 3.

  • indent (int) – json.dump() indent for pretty-printing.

  • sort_keys (bool) – json.dump() sort_keys for diffability.

  • ingnore_lattice (bool) – Omit 'lattice' in result. If None, 'lattice' is omitted if it has not yet been computed.

tostring(frmat='table', **kwargs)

Return the context serialized in the given string-based format.

Parameters

frmat (str) – Format of the string ('table', 'cxt', 'csv').

Returns

The context as seralized string.

Return type

str

Definition

class concepts.Definition(objects=(), properties=(), bools=())

Mutable triple of (objects, properties, bools) for creating a context.

Create definition from objects, properties, and bools correspondence.

Parameters
  • objects – Iterable of object label strings.

  • properties – Iterable of property label strings.

  • bools – Iterable of len(objects) tuples of len(properties) booleans.

Returns

New Definition instance.

Return type

Definition

Example

>>> Definition(['man', 'woman'], ['male', 'female'], [(True, False), (False, True)])
<Definition(['man', 'woman'], ['male', 'female'], [(True, False), (False, True)])>
__getitem__(pair)

Return the relation value for an (object, property) pair.

Returns

True if object has property else False.

Return type

bool

__iter__()

Yield objects, properties, and bools (e.g. for triple unpacking).

add_object(obj, properties=())

Add an object to the definition and add properties as related.

Parameters
  • obj (str) – Name of the object to add.

  • properties – Iterable of property name strings.

add_property(prop, objects=())

Add a property to the definition and add objects as related.

Parameters
  • obj (str) – Name of the object to add.

  • objects – Iterable of object name strings.

property bools

Row-major list of boolean tuples.

Type

list[tuple[bool, ..]]

copy()

Return an independent copy of the instance.

Returns

An instance of type(self).

crc32(encoding='utf-8')

Return hex-encoded unsigned CRC32 over encoded definition table string.

Parameters

encoding (str) – Encoding of the serialzation ('utf-8', 'latin1', 'ascii', …).

Returns

The unsigned CRC32 checksum as hex-string.

Return type

str

classmethod fromfile(filename, frmat='cxt', encoding=None, **kwargs)

Return a new definiton from file source in given format.

Args:

filename: Path to the file to load the context from. frmat (str): Format of the file ('table', 'cxt', 'csv'). encoding (str): Encoding of the file ('utf-8', 'latin1', 'ascii', …).

Returns

A new Definition instance.

Return type

Definition

intersection(other, ignore_conflicts=False)

Return a new definition from the intersection of the definitions.

Parameters
Returns

A new Definition instance.

Return type

Definition

intersection_update(other, ignore_conflicts=False)

Update the definition with the intersection of the other.

Parameters
inverted()

Return a new definition flipping all booleans.

Returns

A new Definition instance.

Return type

Definition

move_object(obj, index)

Reorder the definition such that object is at index.

Parameters
  • obj (str) – Name of the object to move.

  • index (int) – Index for the object to move to.

move_property(prop, index)

Reorder the definition such that property is at index.

Parameters
  • prop (str) – Name of the property to move.

  • index (int) – Index for the property to move to.

property objects

(Names of the) objects described by the definition.

Type

tuple[str, ..]

property properties

(Names of the) properties that describe the objects.

Type

tuple[str, ..]

remove_object(obj)

Remove an object from the definition.

Parameters

obj (str) – Name of the object to remove.

remove_property(prop)

Remove a property from the definition.

Parameters

prop (str) – Name of the property to remove.

rename_object(old, new)

Replace the name of an object by a new one.

Parameters
  • old (str) – Current name of the object.

  • new (str) – New name for the object.

rename_property(old, new)

Replace the name of a property by a new one.

Parameters
  • old (str) – Current name of the property.

  • new (str) – New name for the property.

set_object(obj, properties)

Add an object to the definition and set its properties.

Parameters
  • obj (str) – Name of the object to add.

  • properties – Iterable of property name strings.

set_property(prop, objects)

Add a property to the definition and set its objects.

Parameters
  • prop (str) – Name of the property to add.

  • objectss – Iterable of object name strings.

take(objects=None, properties=None, reorder=False)

Return a subset with given objects/properties as new definition.

Parameters
  • objects – Iterable of object label strings.

  • properties – Iterable of property label strings.

  • reorder (bool) –

Returns

A new Definition instance.

Return type

Definition

tostring(frmat='table', **kwargs)

Return the definition serialized in the given string-based format.

Parameters

frmat (str) – Format of the string ('table', 'cxt', 'csv').

Returns

The definition as seralized string.

Return type

str

transposed()

Return a new definition swapping objects and properties.

Returns

A new Definition instance.

Return type

Definition

union(other, ignore_conflicts=False)

Return a new definition from the union of the definitions.

Parameters
Returns

A new Definition instance.

Return type

Definition

union_update(other, ignore_conflicts=False)

Update the definition with the union of the other.

Parameters

Lattice

class concepts.lattices.Lattice(context, infimum=())

Formal concept lattice as directed acyclic graph of concepts.

__call__(properties)

Return concept having all given properties as intension.

Parameters

properties (tuple[str]) – Tuple of property names.

Returns

Concept instance from this lattice.

Return type

Concept

__getitem__(key)

Return concept by index, intension, or extension.

Parameters

key – Integer index, properties tuple, or objects tuple.

Returns

Concept instance from this lattice.

Return type

Concept

__iter__()

Yield all concepts of the lattice.

Yields

All Concept instances from this lattice.

__len__()

Return the number of concepts in the lattice.

Returns

Number of lattice concepts.

Return type

int

property atoms

The minimal non-infimum concepts of the lattice.

Type

tuple[Concept, ..]

downset_union(concepts, _sortkey=operator.attrgetter('dindex'), _next_concepts=operator.attrgetter('lower_neighbors'))

Yield all concepts that imply any of the given ones.

Parameters

concepts – Iterable of Concept instances from this lattice.

Yields

Concept instances from this lattice.

graphviz(filename=None, directory=None, render=False, view=False, make_object_label=<built-in method join of str object>, make_property_label=<built-in method join of str object>, **kwargs)

Return DOT source for visualizing the lattice graph.

Parameters
  • filename – Path to the DOT source file for the Digraph.

  • directory – (Sub)directory for DOT source saving and rendering.

  • render (bool) – Call .render() on the result.

  • view (bool) – Call .render(view=True) on the result.

  • make_object_label – Callable with iterable of objects argument returning a string to be used as object label.

  • make_property_label – Callable with iterable of properties argument returning a string to be used as object label.

Returns

A graphviz.Digraph instance.

property infimum

The most specific concept of the lattice.

Type

Concept

join(concepts)

Return the nearest concept that subsumes all given concepts.

Parameters

concepts – Iterable of Concept instances from this lattice.

Returns

Concept instance from this lattice.

Return type

Concept

meet(concepts)

Return the nearest concept that implies all given concepts.

Parameters

concepts – Iterable of Concept instances from this lattice.

Returns

Concept instance from this lattice.

Return type

Concept

property supremum

The most general concept of the lattice.

Type

Concept

upset_generalization(concepts)

Yield all concepts that subsume only the given ones.

Parameters

concepts – Iterable of Concept instances from this lattice.

Yields

Concept instances from this lattice.

upset_union(concepts, _sortkey=operator.attrgetter('index'), _next_concepts=operator.attrgetter('upper_neighbors'))

Yield all concepts that subsume any of the given ones.

Parameters

concepts – Iterable of Concept instances from this lattice.

Yields

Concept instances from this lattice.

Concept

class concepts.lattices.Concept(lattice, extent, intent, upper, lower)

Formal concept as pair of extent and intent.

__iter__()

Yield extent and intent (e.g. for pair unpacking).

attributes()

Yield properties generating the concept in shortlex order.

Yields

Tuples of property name strings.

complement_of(other)

Infimum meet and supremum join comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self is the complement of other else False.

Return type

bool

downset(_sortkey=operator.attrgetter('dindex'), _next_concepts=operator.attrgetter('lower_neighbors'))

Yield subsumed concepts including self.

Yields

Concept instances.

property extent

tuple[str, …] The objects subsumed by the concept.

implies(other)

Implication comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self implies other else False.

Return type

bool

incompatible_with(other)

Infimum meet comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self is incompatible with other else False.

Return type

bool

property intent

tuple[str, …] The properties implied by the concept.

join(other)

Least upper bound, supremum, or, generalization.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

Concept instance from the same lattice.

Return type

Concept

lattice

The lattice containing the concept.

lower_neighbors

The directly subsumed concepts.

meet(other)

Greatest lower bound, infimum, and, unification.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

Concept instance from the same lattice.

Return type

Concept

minimal()

Shortlex minimal properties generating the concept.

Returns

Property name strings.

Return type

tuple[str, ..]

orthogonal_to(other)

Non-infimum meet, incomparable, and non-supremum join comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self is orthogonal to other else False.

Return type

bool

properly_implies(other)

Proper implication comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self properly implies other else False.

Return type

bool

properly_subsumes(other)

Proper subsumption comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self properly subsumes other else False.

Return type

bool

subcontrary_with(other)

Non-infimum meet and supremum join comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self is the subcontrary to other else False.

Return type

bool

subsumes(other)

Subsumption comparison.

Parameters

other (Concept) – Concept instance from the same lattice.

Returns

True if self subsumes other else False.

Return type

bool

upper_neighbors

The directly implied concepts.

upset(_sortkey=operator.attrgetter('index'), _next_concepts=operator.attrgetter('upper_neighbors'))

Yield implied concepts including self.

Yields

Concept instances.