| Title: | Formal Concept Analysis |
|---|---|
| Description: | Provides tools to perform fuzzy formal concept analysis, presented in Wille (1982) <doi:10.1007/978-3-642-01815-2_23> and in Ganter and Obiedkov (2016) <doi:10.1007/978-3-662-49291-8>. It provides functions to load and save a formal context, extract its concept lattice and implications. In addition, one can use the implications to compute semantic closures of fuzzy sets and, thus, build recommendation systems. Matrix factorization is provided by the GreConD+ algorithm (Belohlavek and Trneckova, 2024 <doi:10.1109/TFUZZ.2023.3330760>). |
| Authors: | Domingo Lopez Rodriguez [aut, cre] (ORCID: <https://orcid.org/0000-0002-0172-1585>), Angel Mora [aut], Jesus Dominguez [aut], Ana Villalon [aut] |
| Maintainer: | Domingo Lopez Rodriguez <[email protected]> |
| License: | GPL-3 |
| Version: | 1.7.0 |
| Built: | 2026-05-25 06:13:53 UTC |
| Source: | https://github.com/malaga-fca-group/fcar |
Difference in Sets
S1 %-% S2S1 %-% S2
S1 |
A |
S2 |
A |
Both S1 and S2 must be Sets.
Returns the difference S1 - S2.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Difference S %-% T# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Difference S %-% T
Intersection (Logical AND) of Fuzzy Sets
S1 %&% S2S1 %&% S2
S1 |
A |
S2 |
A |
Both S1 and S2 must be Sets.
Returns the intersection of S1 and S2.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, C = 1) # Intersection S %&% T# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, C = 1) # Intersection S %&% T
Partial Order in Sets and Concepts
C1 %<=% C2C1 %<=% C2
C1 |
A |
C2 |
A |
Both C1 and C2 must be of the same class.
Returns TRUE if concept C1 is subconcept of C2 or if set C1 is subset of C2.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, B = 1) # Test whether S is subset of T S %<=% T# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, B = 1) # Test whether S is subset of T S %<=% T
Equality in Sets and Concepts
C1 %==% C2C1 %==% C2
C1 |
A |
C2 |
A |
Both C1 and C2 must be of the same class.
Returns TRUE if C1 is equal to C2.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Test whether S and T are equal S %==% T# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Test whether S and T are equal S %==% T
Equivalence of sets of implications
imps %~% imps2imps %~% imps2
imps |
A |
imps2 |
Another |
TRUE of and only if imps and imps2
are equivalent, that is, if every implication in imps
follows from imps2 and viceversa.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps2 <- imps$clone() imps2$apply_rules(c("simp", "rsimp")) imps %~% imps2 imps %~% imps2[1:9]fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps2 <- imps$clone() imps2$apply_rules(c("simp", "rsimp")) imps %~% imps2 imps %~% imps2[1:9]
Entailment between implication sets
imps %entails% imps2imps %entails% imps2
imps |
( |
imps2 |
( |
A logical vector, where element k is TRUE if the
k-th implication in imps2 follows from imps.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications[1:4]$clone() imps2 <- fc$implications[3:6]$clone() imps %entails% imps2fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications[1:4]$clone() imps2 <- fc$implications[3:6]$clone() imps %entails% imps2
Implications that hold in a Formal Context
imps %holds_in% fcimps %holds_in% fc
imps |
( |
fc |
( |
A logical vector, indicating if each implication holds in the formal context.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps %holds_in% fcfc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps %holds_in% fc
Union (Logical OR) of Fuzzy Sets
S1 %|% S2S1 %|% S2
S1 |
A |
S2 |
A |
Both S1 and S2 must be Sets.
Returns the union of S1 and S2.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(C = 1) # Union S %|% T# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(C = 1) # Union S %|% T
Check if Set or FormalContext respects an ImplicationSet
set %respects% impsset %respects% imps
set |
(list of |
imps |
( |
A logical matrix with as many rows as Sets and as many columns as implications in the ImplicationSet. A TRUE in element (i, j) of the result means that the i-th Set respects the j-th implication of the ImplicationSet.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() fc %respects% impsfc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() fc %respects% imps
Convert Named Vector to Set
as_Set(A)as_Set(A)
A |
A named vector or matrix to build a new |
A Set object.
A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) as_Set(A)A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) as_Set(A)
Convert Set to vector
as_vector(v)as_vector(v)
v |
A |
A vector.
A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) v <- as_Set(A) A2 <- as_vector(v) all(A == A2)A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) v <- as_Set(A) A2 <- as_vector(v) all(A == A2)
This class extends ConceptLattice to represent the lattice of bonds between
two formal contexts and .
It inherits all lattice operations (finding irreducible elements, subconcepts, etc.)
and provides specific methods to extract bonds as matrices and FormalContexts.
fcaR::ConceptSet -> fcaR::ConceptLattice -> BondLattice
elapsed(numeric) Time elapsed during bond computation (C++ level)
fcaR::ConceptSet$[()fcaR::ConceptSet$extents()fcaR::ConceptSet$intents()fcaR::ConceptSet$is_empty()fcaR::ConceptSet$size()fcaR::ConceptSet$sub()fcaR::ConceptSet$support()fcaR::ConceptSet$to_latex()fcaR::ConceptSet$to_list()fcaR::ConceptLattice$bottom()fcaR::ConceptLattice$decompose()fcaR::ConceptLattice$density()fcaR::ConceptLattice$dimension()fcaR::ConceptLattice$infimum()fcaR::ConceptLattice$is_atomic()fcaR::ConceptLattice$is_distributive()fcaR::ConceptLattice$is_modular()fcaR::ConceptLattice$is_semimodular()fcaR::ConceptLattice$join_irreducibles()fcaR::ConceptLattice$lower_neighbours()fcaR::ConceptLattice$meet_irreducibles()fcaR::ConceptLattice$plot()fcaR::ConceptLattice$separation()fcaR::ConceptLattice$set_state()fcaR::ConceptLattice$stability()fcaR::ConceptLattice$subconcepts()fcaR::ConceptLattice$sublattice()fcaR::ConceptLattice$superconcepts()fcaR::ConceptLattice$supremum()fcaR::ConceptLattice$to_json()fcaR::ConceptLattice$top()fcaR::ConceptLattice$upper_neighbours()fcaR::ConceptLattice$width()new()
Initialize a BondLattice object.
BondLattice$new(extents, intents, objects, attributes, I, fc1, fc2)
extents(dgCMatrix) The extents of all concepts
intents(dgCMatrix) The intents of all concepts
objects(character) Names of the objects (not required for bonds, can be generic)
attributes(character) Names of the attributes (flattened $G_1 \times M_2$)
I(matrix) Built incidence matrix
fc1(FormalContext) The first formal context
fc2(FormalContext) The second formal context
A new BondLattice object.
get_bonds()
Extract the bonds represented by the intents of the lattice.
BondLattice$get_bonds(indices = NULL)
indices(numeric or logical vector) The indices of the bonds (concepts) to extract. If NULL (default), extracts all.
A list of FormalContext objects, each representing one bond.
similarity()
Compute similarity, affinity, or complexity metrics between the two contexts.
BondLattice$similarity(
type = c("log-bond", "top-density", "complexity", "core-agreement", "entropy",
"stability", "width", "dimension", "width-index", "dimension-index")
)type(character) The type of metric to compute:
"log-bond": (Default) Normalized log-ratio of bonds. High value means high logical affinity.
"top-density": Density of the largest possible bond (the top of the lattice).
"complexity": Ratio of irreducible bonds to total bonds. Low value implies high structural emergence.
"core-agreement": Ratio of filled cells in the Core bond versus the Top bond. Measures fundamental consensus.
"entropy": Interaction entropy based on the log-size of the lattices.
"stability": Average stability of the bonds in the lattice.
A numeric value representing the metric.
get_core()
Get the 'Core' bond (the smallest possible bond).
BondLattice$get_core()
A FormalContext representing the minimal bond.
print()
Print the BondLattice object.
BondLattice$print()
Nothing, just prints the object summary.
is_bond()
Verify if a relation is a bond between the internal contexts.
BondLattice$is_bond(relation)
relation(matrix or FormalContext) The relation to verify.
TRUE if it's a bond, FALSE otherwise.
clone()
The objects of this class are cloneable with this method.
BondLattice$clone(deep = FALSE)
deepWhether to make a deep clone.
set.seed(42) mat1 <- matrix(sample(0:1, 15, replace = TRUE), nrow = 5, ncol = 3) rownames(mat1) <- paste0("O", 1:5) colnames(mat1) <- paste0("A", 1:3) fc1 <- FormalContext$new(mat1) mat2 <- matrix(sample(0:1, 12, replace = TRUE), nrow = 4, ncol = 3) rownames(mat2) <- paste0("P", 1:4) colnames(mat2) <- paste0("B", 1:3) fc2 <- FormalContext$new(mat2) bl <- bonds(fc1, fc2) # Extract all bonds as FormalContext objects my_bonds <- bl$get_bonds() print(my_bonds[[1]])set.seed(42) mat1 <- matrix(sample(0:1, 15, replace = TRUE), nrow = 5, ncol = 3) rownames(mat1) <- paste0("O", 1:5) colnames(mat1) <- paste0("A", 1:3) fc1 <- FormalContext$new(mat1) mat2 <- matrix(sample(0:1, 12, replace = TRUE), nrow = 4, ncol = 3) rownames(mat2) <- paste0("P", 1:4) colnames(mat2) <- paste0("B", 1:3) fc2 <- FormalContext$new(mat2) bl <- bonds(fc1, fc2) # Extract all bonds as FormalContext objects my_bonds <- bl$get_bonds() print(my_bonds[[1]])
A bond between two formal contexts and is a relation
between the objects of and the attributes of , such that
the relation is closed under the derivation operators of both contexts.
bonds(fc1, fc2, method = c("conexp", "mcis"), verbose = FALSE)bonds(fc1, fc2, method = c("conexp", "mcis"), verbose = FALSE)
fc1 |
( |
fc2 |
( |
method |
(character) The method to use. |
verbose |
(logical) If TRUE, print progress information. |
A BondLattice object whose intents represent the bonds.
set.seed(42) mat1 <- matrix(sample(0:1, 15, replace = TRUE), nrow = 5, ncol = 3) rownames(mat1) <- paste0("O", 1:5) colnames(mat1) <- paste0("A", 1:3) fc1 <- FormalContext$new(mat1) mat2 <- matrix(sample(0:1, 12, replace = TRUE), nrow = 4, ncol = 3) rownames(mat2) <- paste0("P", 1:4) colnames(mat2) <- paste0("B", 1:3) fc2 <- FormalContext$new(mat2) # Compute bonds returning a lattice bonds_lattice <- bonds(fc1, fc2, method = "conexp") bonds_lattice$print()set.seed(42) mat1 <- matrix(sample(0:1, 15, replace = TRUE), nrow = 5, ncol = 3) rownames(mat1) <- paste0("O", 1:5) colnames(mat1) <- paste0("A", 1:3) fc1 <- FormalContext$new(mat1) mat2 <- matrix(sample(0:1, 12, replace = TRUE), nrow = 4, ncol = 3) rownames(mat2) <- paste0("P", 1:4) colnames(mat2) <- paste0("B", 1:3) fc2 <- FormalContext$new(mat2) # Compute bonds returning a lattice bonds_lattice <- bonds(fc1, fc2, method = "conexp") bonds_lattice$print()
Computes bonds using Algorithm 1 from "Computing bonds between formal contexts", optimized with FastBitset in a unified C++ solver. Pre-computes concepts (extents of C1 and intents of C2) in R, then passes them to C++ for the backtracking search.
bonds_mcis(fc1, fc2, verbose = FALSE)bonds_mcis(fc1, fc2, verbose = FALSE)
fc1 |
( |
fc2 |
( |
verbose |
( |
A BondLattice object.
Computes bonds using implication merging and closed-set enumeration. Uses a FastBitset-optimized C++ implementation.
bonds_standard(fc1, fc2, verbose = FALSE)bonds_standard(fc1, fc2, verbose = FALSE)
fc1 |
( |
fc2 |
( |
verbose |
( |
A BondLattice object.
Calculates the density of each concept in the original matrix I.
calculate_density(extents, intents, I)calculate_density(extents, intents, I)
extents |
A |
intents |
A |
I |
The original numeric matrix (FormalContext$I). |
A numeric vector.
Calculates the grade (level) of each concept using the longest path from the bottom element. This is a fast C++ implementation.
calculate_grades(concept_ids, edge_from, edge_to)calculate_grades(concept_ids, edge_from, edge_to)
concept_ids |
A vector of concept IDs (integers). |
edge_from |
A vector of source concept IDs from the cover relation (Hasse diagram). |
edge_to |
A vector of target concept IDs from the cover relation (Hasse diagram). |
An integer vector of the calculated grade for each concept ID.
Computes the separation of each concept. Separation is defined as the number of objects in a concept's extent that are NOT covered by any of its immediate subconcepts (children).
calculate_separation(lattice)calculate_separation(lattice)
lattice |
A |
A numeric vector of separation values.
Calculates the intensional stability of each concept.
Calculates the intensional stability of each concept in the lattice directly from the sparse matrix representation. Stability measures the probability that a concept is preserved when a random subset of objects is removed.
calculate_stability(extents) calculate_stability(extents)calculate_stability(extents) calculate_stability(extents)
extents |
A |
A numeric vector.
A numeric vector with stability values in .
A subset of the COBRE dataset has been retrieved, by querying SchizConnect for 105 patients with neurological and clinical symptoms, collecting also their corresponding diagnosis.
cobre32cobre32
A matrix with 105 rows and 32 columns. Column names are related to different scales for depression and Schizophrenia:
The Simpson-Angus Scale, 7 items to evaluate Parkinsonism-like alterations, related to schizophrenia, in an individual.
The Calgary Depression Scale for Schizophrenia, 9 items (attributes) assessing the level of depression in schizophrenia, differentiating between positive and negative aspects of the disease.
The Structured Clinical Interview for DSM-III-R Personality Disorders, with 14 variables related to the presence of signs affecting personality.
if TRUE, the diagnosis is strict schizophrenia.
it TRUE, the diagnosis is other than schizophrenia, including schizoaffective, bipolar disorder and major depression.
In summary, the dataset consists in the previous 30 attributes related to signs or symptoms, and 2 attributes related to diagnosis (these diagnoses are mutually exclusive, thus only one of them is assigned to each patient). This makes a dataset with 105 objects (patients) and 32 attributes to explore. The symptom attributes are multi-valued.
Thus, according to the specific scales used, all attributes are fuzzy and graded. For a given attribute (symptom), the available grades range from absent to extreme, with minimal, mild, moderate, moderate severe and severe in between.
These fuzzy attributes are mapped to values in the interval [0, 1].
Aine, C. J., Bockholt, H. J., Bustillo, J. R., Cañive, J. M., Caprihan, A., Gasparovic, C., ... & Liu, J. (2017). Multimodal neuroimaging in schizophrenia: description and dissemination. Neuroinformatics, 15(4), 343-364. https://pubmed.ncbi.nlm.nih.gov/26142271/
A subset of the COBRE dataset has been retrieved, by querying SchizConnect for 105 patients with neurological and clinical symptoms, collecting also their corresponding diagnosis.
cobre61cobre61
A matrix with 105 rows and 61 columns. Column names are related to different scales for depression and Schizophrenia:
The Simpson-Angus Scale, 7 items to evaluate Parkinsonism-like alterations, related to schizophrenia, in an individual.
The Positive and Negative Syndrome Scale, a set of 29 attributes measuring different aspects and symptoms in schizophrenia.
The Calgary Depression Scale for Schizophrenia, 9 items (attributes) assessing the level of depression in schizophrenia, differentiating between positive and negative aspects of the disease.
The Structured Clinical Interview for DSM-III-R Personality Disorders, with 14 variables related to the presence of signs affecting personality.
if TRUE, the diagnosis is strict schizophrenia.
it TRUE, the diagnosis is other than schizophrenia, including schizoaffective, bipolar disorder and major depression.
In summary, the dataset consists in the previous 59 attributes related to signs or symptoms, and 2 attributes related to diagnosis (these diagnoses are mutually exclusive, thus only one of them is assigned to each patient). This makes a dataset with 105 objects (patients) and 61 attributes to explore. The symptom attributes are multi-valued.
Thus, according to the specific scales used, all attributes are fuzzy and graded. For a given attribute (symptom), the available grades range from absent to extreme, with minimal, mild, moderate, moderate severe and severe in between.
These fuzzy attributes are mapped to values in the interval [0, 1].
Aine, C. J., Bockholt, H. J., Bustillo, J. R., Cañive, J. M., Caprihan, A., Gasparovic, C., ... & Liu, J. (2017). Multimodal neuroimaging in schizophrenia: description and dissemination. Neuroinformatics, 15(4), 343-364. https://pubmed.ncbi.nlm.nih.gov/26142271/
Internal function to calculate node labels based on the selected mode.
compute_labels_and_colors( nodes_df, cover_edges, extents, intents, obj_names, att_names, mode )compute_labels_and_colors( nodes_df, cover_edges, extents, intents, obj_names, att_names, mode )
nodes_df |
Data frame with 'id'. |
cover_edges |
Data frame with 'from', 'to'. |
extents |
List of numeric vectors. |
intents |
List of numeric vectors. |
obj_names |
Character vector. |
att_names |
Character vector. |
mode |
Character: "full", "attributes", "reduced", "empty". |
A data frame extending nodes_df with labels and colors.
This class implements the data structure and methods for fuzzy concepts.
new()
Creator for objects of class Concept
Concept$new(extent, intent)
extent(Set) The extent of the concept.
intent(Set) The intent of the concept.
An object of class Concept.
get_extent()
Internal Set for the extent
Concept$get_extent()
The Set representation of the extent.
get_intent()
Internal Set for the intent
Concept$get_intent()
The Set representation of the intent.
print()
Prints the concept to console
Concept$print()
A string with the elements of the set and their grades between brackets .
to_latex()
Write the concept in LaTeX format
Concept$to_latex(print = TRUE)
print(logical) Print to output?
The fuzzy concept in LaTeX.
clone()
The objects of this class are cloneable with this method.
Concept$clone(deep = FALSE)
deepWhether to make a deep clone.
# Build a formal context and find its concepts fc_planets <- FormalContext$new(planets) fc_planets$find_concepts() # Print the first three concepts fc_planets$concepts[1:3] # Select the first concept: C <- fc_planets$concepts$sub(1) # Get its extent and intent C$get_extent() C$get_intent()# Build a formal context and find its concepts fc_planets <- FormalContext$new(planets) fc_planets$find_concepts() # Print the first three concepts fc_planets$concepts[1:3] # Select the first concept: C <- fc_planets$concepts$sub(1) # Get its extent and intent C$get_extent() C$get_intent()
This class implements the data structure and methods for concept lattices.
fcaR::ConceptSet -> ConceptLattice
new()
Create a new ConceptLattice object.
ConceptLattice$new(extents, intents, objects, attributes, I = NULL)
extents(dgCMatrix) The extents of all concepts
intents(dgCMatrix) The intents of all concepts
objects(character vector) Names of the objects in the formal context
attributes(character vector) Names of the attributes in the formal context
I(dgCMatrix) The matrix of the formal context
A new ConceptLattice object.
plot()
Plot the concept lattice
ConceptLattice$plot(
object_names = TRUE,
to_latex = FALSE,
method = c("sugiyama", "force"),
mode = NULL,
viewer = c("ggraph", "base"),
theme = "standard",
...
)object_names(logical) Deprecated. Use mode instead. If TRUE (default), implies mode = "reduced" or similar depending on heuristics. Kept for backward compatibility.
to_latex(logical) If TRUE, exports the plot as TikZ code (LaTeX) instead of drawing it. Returns an object of class tikz_code that prints the LaTeX code to console.
method(character) The layout algorithm to use. Options are:
"sugiyama" (default): A hierarchical layout that minimizes edge crossings and centers nodes (similar to ConExp or hasseDiagram).
"force": A force-directed (spring) layout, useful for large or non-hierarchical lattices.
mode(character) The labeling mode for the nodes. If NULL (default), a heuristic based on lattice size is used. Options are:
"reduced": Standard FCA labeling. Nodes are labeled with an attribute (or object) only if they are the supreme (or infimum) of that attribute (or object).
"full": Each node shows its complete extent and intent.
"attributes": Nodes show only their intent (attributes).
"empty": Nodes are drawn as points without labels. Recommended for very large lattices (>50 concepts).
viewer(character) The viewer to use for plotting. Options are:
"ggraph" (default): Use ggraph for drawing.
"base": Use R base graphics. This is a lightweight alternative that supports themes.
theme(character) The color theme to use for the "base" viewer. Options are: "standard", "nord", "latex", "vibrant".
...Other parameters passed to the internal plotting function (e.g., graphical parameters for ggraph or base).
If to_latex is FALSE, it returns (invisibly) the ggplot2 object representing the graph (for ggraph) or NULL (for base).
If to_latex is TRUE, it returns a tikz_code object containing the LaTeX code.
sublattice()
Sublattice
ConceptLattice$sublattice(...)
...See Details.
As argument, one can provide both integer indices or Concepts, separated by commas. The corresponding concepts are used to generate a sublattice.
The generated sublattice as a new ConceptLattice object.
top()
Top of a Lattice
ConceptLattice$top()
The top of the Concept Lattice
fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$top()
bottom()
Bottom of a Lattice
ConceptLattice$bottom()
The bottom of the Concept Lattice
fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$bottom()
join_irreducibles()
Join-irreducible Elements
ConceptLattice$join_irreducibles()
The join-irreducible elements in the concept lattice.
meet_irreducibles()
Meet-irreducible Elements
ConceptLattice$meet_irreducibles()
The meet-irreducible elements in the concept lattice.
decompose()
Decompose a concept as the supremum of meet-irreducible concepts
ConceptLattice$decompose(C)
CA list of Concepts
A list, each field is the set of meet-irreducible elements whose supremum is the corresponding element in C.
supremum()
Supremum of Concepts
ConceptLattice$supremum(...)
...See Details.
As argument, one can provide both integer indices or Concepts, separated by commas. The corresponding concepts are used to compute their supremum in the lattice.
The supremum of the list of concepts.
infimum()
Infimum of Concepts
ConceptLattice$infimum(...)
...See Details.
As argument, one can provide both integer indices or Concepts, separated by commas. The corresponding concepts are used to compute their infimum in the lattice.
The infimum of the list of concepts.
subconcepts()
Subconcepts of a Concept
ConceptLattice$subconcepts(C)
C(numeric or SparseConcept) The concept to which determine all its subconcepts.
A list with the subconcepts.
superconcepts()
Superconcepts of a Concept
ConceptLattice$superconcepts(C)
C(numeric or SparseConcept) The concept to which determine all its superconcepts.
A list with the superconcepts.
lower_neighbours()
Lower Neighbours of a Concept
ConceptLattice$lower_neighbours(C)
C(SparseConcept) The concept to which find its lower neighbours
A list with the lower neighbours of C.
upper_neighbours()
Upper Neighbours of a Concept
ConceptLattice$upper_neighbours(C)
C(SparseConcept) The concept to which find its upper neighbours
A list with the upper neighbours of C.
stability()
Computes the stability of each concept.
ConceptLattice$stability()
A numeric vector with the stability of each concept.
separation()
Computes the separation of each concept. Separation is the number of objects covered by the concept but not by any of its immediate subconcepts.
ConceptLattice$separation()
A numeric vector with the separation of each concept.
density()
Computes the fuzzy density of each concept.
ConceptLattice$density(I = NULL)
I(Optional) The original incidence matrix. If NULL, it tries to access it from the parent FormalContext if linked.
A numeric vector with the density of each concept.
is_distributive()
Check if the lattice is distributive.
A lattice is distributive if for all elements.
ConceptLattice$is_distributive()
Logical.
is_modular()
Check if the lattice is modular.
A lattice is modular if .
Distributive lattices are always modular.
ConceptLattice$is_modular()
Logical.
is_semimodular()
Check if the lattice is upper semimodular.
A lattice is upper semimodular if for every : if covers , then covers .
ConceptLattice$is_semimodular()
Logical.
is_atomic()
Check if the lattice is atomic.
A lattice is atomic if for every element , there exists an atom such that .
Atoms are elements that cover the bottom element.
ConceptLattice$is_atomic()
Logical.
width()
Computes the Dilworth's width of the lattice. The width is the size of the largest antichain.
ConceptLattice$width()
Integer.
dimension()
Computes the order dimension (Dushnik-Miller) of the lattice. Note: This uses a heuristic and may return an estimate for large lattices.
ConceptLattice$dimension()
Integer.
set_state()
Internal method to set state from JSON import
ConceptLattice$set_state(state)
stateList of internal state variables
to_json()
Export the concept lattice to JSON
ConceptLattice$to_json(file = NULL, return_list = FALSE)
file(character) The path of the file to save the JSON to.
return_list(logical) If TRUE, returns the list representation instead of the JSON string.
A JSON string representing the concept lattice, or a list if return_list is TRUE.
clone()
The objects of this class are cloneable with this method.
ConceptLattice$clone(deep = FALSE)
deepWhether to make a deep clone.
# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles() # Get concept support fc_planets$concepts$support() ## ------------------------------------------------ ## Method `ConceptLattice$top` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$top() ## ------------------------------------------------ ## Method `ConceptLattice$bottom` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$bottom()# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles() # Get concept support fc_planets$concepts$support() ## ------------------------------------------------ ## Method `ConceptLattice$top` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$top() ## ------------------------------------------------ ## Method `ConceptLattice$bottom` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$bottom()
Concept Miners Registry
conceptRegistryconceptRegistry
An object of class concept_miner_registry (inherits from registry) of length 3.
This is a registry that stores the concept miners that can be
applied using the find_concepts() method in an
FormalConcept.
One can obtain the list of available equivalence operators by:
conceptRegistry$get_entry_names()
This class implements the data structure and methods for concept sets.
new()
Create a new ConceptLattice object.
ConceptSet$new(extents, intents, objects, attributes, I = NULL)
extents(dgCMatrix) The extents of all concepts
intents(dgCMatrix) The intents of all concepts
objects(character vector) Names of the objects in the formal context
attributes(character vector) Names of the attributes in the formal context
I(dgCMatrix) The matrix of the formal context
A new ConceptLattice object.
size()
Size of the Lattice
ConceptSet$size()
The number of concepts in the lattice.
is_empty()
Is the lattice empty?
ConceptSet$is_empty()
TRUE if the lattice has no concepts.
extents()
Concept Extents
ConceptSet$extents()
The extents of all concepts, as a dgCMatrix.
intents()
Concept Intents
ConceptSet$intents()
The intents of all concepts, as a dgCMatrix.
print()
Print the Concept Set
ConceptSet$print()
Nothing, just prints the concepts
to_latex()
Write in LaTeX
ConceptSet$to_latex(print = TRUE, ncols = 1, numbered = TRUE, align = TRUE)
print(logical) Print to output?
ncols(integer) Number of columns of the output.
numbered(logical) Number the concepts?
align(logical) Align objects and attributes independently?
The LaTeX code to list all concepts.
to_list()
Returns a list with all the concepts
ConceptSet$to_list()
A list of concepts.
[()
Subsets a ConceptSet
ConceptSet$[(indices)
indices(numeric or logical vector) The indices of the concepts to return as a list of Concepts. It can be a vector of logicals where TRUE elements are to be retained.
Another ConceptSet.
sub()
Individual Concepts
ConceptSet$sub(index)
index(numeric) The index of the concept to return.
The Concept.
support()
Get support of each concept
ConceptSet$support()
A vector with the support of each concept.
stability()
Compute the stability of each concept
ConceptSet$stability()
A numeric vector with the stability of each concept.
clone()
The objects of this class are cloneable with this method.
ConceptSet$clone(deep = FALSE)
deepWhether to make a deep clone.
# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles()# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles()
Reconstructs a FormalContext object from a JSON string.
context_from_json(json_str)context_from_json(json_str)
json_str |
A JSON string generated by |
A FormalContext object.
S3 methods to enable dplyr verbs on RuleSet (and ImplicationSet) objects.
## S3 method for class 'RuleSet' arrange(.data, ...)## S3 method for class 'RuleSet' arrange(.data, ...)
.data |
An object of class |
... |
Expressions used for filtering, arranging, or slicing. |
S3 methods to enable dplyr verbs on FormalContext objects.
## S3 method for class 'FormalContext' select(.data, ...)## S3 method for class 'FormalContext' select(.data, ...)
.data |
An object of class |
... |
Arguments passed to the corresponding dplyr verbs. |
Equivalence Rules Registry
equivalencesRegistryequivalencesRegistry
An object of class equivalence_registry (inherits from registry) of length 6.
This is a registry that stores the equivalence rules that can be
applied using the apply_rules() method in an
ImplicationSet.
One can obtain the list of available equivalence operators by:
equivalencesRegistry$get_entry_names()
Generates TikZ code for the concept lattice.
export_to_tikz( plot_data, edges_df, width = 12, height = 12, standalone = FALSE, caption = NULL, ... )export_to_tikz( plot_data, edges_df, width = 12, height = 12, standalone = FALSE, caption = NULL, ... )
plot_data |
Data frame with node info. |
edges_df |
Data frame with edge info. |
width |
Numeric. Target width in cm (default: 12). |
height |
Numeric. Target height in cm (default: 12). |
standalone |
Logical. If TRUE, wraps code in a documentclass to be compiled directly. |
caption |
Character. Optional caption for the figure. |
... |
Additional arguments (currently unused). |
An object of class 'tikz_code'.
Set or get options for fcaR
fcaR_options(...)fcaR_options(...)
... |
Option names to retrieve option values or |
The following options are supported
decimal_places(numeric;2) The number of decimal places to show when printing or exporting to LaTeX sets, implications, concepts, etc.
latex_size(character;"normalsize") Size to use when exporting to LaTeX.
reduced\_lattice(logical;TRUE) Plot the reduced concept lattice?
Downloads a context file from the fcarepository.org (via GitHub mirror), parses it, and returns a FormalContext object.
fetch_context(filename, verbose = TRUE)fetch_context(filename, verbose = TRUE)
filename |
Character string. The ID/filename of the context (e.g., "animals_en.cxt"). |
verbose |
Logical. If TRUE, prints metadata and progress messages using cli/glue. |
A FormalContext object.
Functions to mine causal association rules from a formal context.
find_causal_rules( fc, response_var, min_support = 0.1, confidence_level = 0.95, max_length = 3, verbose = FALSE )find_causal_rules( fc, response_var, min_support = 0.1, confidence_level = 0.95, max_length = 3, verbose = FALSE )
fc |
A FormalContext object. |
response_var |
(character) The name of the response variable. |
min_support |
(numeric) Minimum support. |
confidence_level |
(numeric) Confidence level for the causality test. |
max_length |
(integer) Maximum length of the premise. |
verbose |
(logical) Show verbose output? |
A data frame with causal rules and their quality metrics.
This class implements the data structure and methods for formal contexts.
IThe table of the formal context as a matrix.
attributesThe attributes of the formal context.
objectsThe objects of the formal context.
grades_setThe set of degrees (in [0, 1]) the whole set of attributes can take.
expanded_grades_setThe set of degrees (in [0, 1]) each attribute can take.
conceptsThe concept lattice associated to the formal context as a ConceptLattice.
implicationsA set of implications on the formal context as an ImplicationSet.
descriptionAn optional description of the dataset
new()
Creator for the Formal Context class
FormalContext$new(I, filename, remove_const = FALSE)
I(numeric matrix) The table of the formal context.
filename(character) Path of a file to import.
remove_const(logical) If TRUE, remove constant columns. The default is FALSE.
Columns of I should be named, since they are the names of the attributes of the formal context.
If no I is used, the resulting FormalContext will be empty and not usable unless for loading a previously saved one. In this case, one can provide a filename to import. Only RDS, CSV and CXT files are currently supported.
If the file is not present, the fcarepository.org is looked for coincidences. If so, the corresponding context is loaded.
An object of the FormalContext class.
is_empty()
Check if the FormalContext is empty
FormalContext$is_empty()
TRUE if the FormalContext is empty, that is, has not been provided with a matrix, and FALSE otherwise.
scale()
Scale the context
FormalContext$scale(attributes, type, ...)
attributesThe attributes to scale
typeType of scaling.
...The types of scaling are implemented in a registry,
so that scalingRegistry$get_entries() returns
all types.
In the dots argument, the user can supply the value for bg (logical), which, if set to TRUE, indicates to compute background knowledge as implications on the scales; if FALSE, no implications will be computed on the scales.
The scaled formal context
filename <- system.file("contexts", "aromatic.csv", package = "fcaR")
fc <- FormalContext$new(filename)
fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3)
fc$scale("OS", "nominal", c("O", "S"))
fc$scale(attributes = "ring", type = "nominal")
get_scales()
Scales applied to the formal context
FormalContext$get_scales(attributes = names(private$scales))
attributes(character) Name of the attributes for which scales (if applied) are returned.
The scales that have been applied to the specified attributes
of the formal context. If no attributes are passed,
then all applied scales are returned.
filename <- system.file("contexts", "aromatic.csv", package = "fcaR")
fc <- FormalContext$new(filename)
fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3)
fc$scale("OS", "nominal", c("O", "S"))
fc$scale(attributes = "ring", type = "nominal")
fc$get_scales()
background_knowledge()
Background knowledge of a scaled formal context
FormalContext$background_knowledge()
An ImplicationSet with the implications
extracted from the application of scales.
filename <- system.file("contexts", "aromatic.csv", package = "fcaR")
fc <- FormalContext$new(filename)
fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3)
fc$scale("OS", "nominal", c("O", "S"))
fc$scale(attributes = "ring", type = "nominal")
fc$background_knowledge()
dual()
Get the dual formal context
FormalContext$dual()
A FormalContext where objects and attributes have interchanged their roles.
intent()
Get the intent of a fuzzy set of objects
FormalContext$intent(S)
S(Set) The set of objects to compute the intent for.
A Set with the intent.
uparrow()
Get the intent of a fuzzy set of objects
FormalContext$uparrow(S)
S(Set) The set of objects to compute the intent for.
A Set with the intent.
extent()
Get the extent of a fuzzy set of attributes
FormalContext$extent(S)
S(Set) The set of attributes to compute the extent for.
A Set with the intent.
downarrow()
Get the extent of a fuzzy set of attributes
FormalContext$downarrow(S)
S(Set) The set of attributes to compute the extent for.
A Set with the intent.
closure()
Get the closure of a fuzzy set of attributes
FormalContext$closure(S)
S(Set) The set of attributes to compute the closure for.
A Set with the closure.
obj_concept()
Object Concept
FormalContext$obj_concept(object)
object(character) Name of the object to compute its associated concept
The object concept associated to the object given.
att_concept()
Attribute Concept
FormalContext$att_concept(attribute)
attribute(character) Name of the attribute to compute its associated concept
The attribute concept associated to the attribute given.
is_concept()
Is a Concept?
FormalContext$is_concept(C)
CA Concept object
TRUE if C is a concept.
is_closed()
Testing closure of attribute sets
FormalContext$is_closed(S)
SA Set of attributes
TRUE if the set S is closed in this formal context.
clarify()
Clarify a formal context
FormalContext$clarify(copy = FALSE)
copy(logical) If TRUE, a new FormalContext object is created with the clarified context, otherwise the current one is overwritten.
The clarified FormalContext.
reduce()
Reduce a formal context
FormalContext$reduce(copy = FALSE, method = c("arrows", "concepts"))copy(logical) If TRUE, a new FormalContext object is created with the clarified and reduced context, otherwise the current one is overwritten.
method(character) The method to use for reduction. One of "arrows" (default, uses arrow relations, only for binary contexts) or "concepts" (uses irreducible concepts, works for fuzzy).
The clarified and reduced FormalContext.
standardize()
Build the Standard Context
FormalContext$standardize()
This is a wrapper around reduce(copy = TRUE, method = "arrows") for binary contexts,
or reduce(copy = TRUE, method = "concepts") for fuzzy contexts.
The standard context using the join- and meet- irreducible elements.
find_concepts()
Use Ganter Algorithm to compute concepts
FormalContext$find_concepts(method = "InClose", verbose = FALSE)
method(string) The name of a method for the computation of concepts. Available options can be listed with conceptRegistry$get_entries().
verbose(logical) TRUE will provide a verbose output.
A list with all the concepts in the formal context.
find_implications()
Use modified Ganter algorithm to compute both concepts and implications
FormalContext$find_implications(
save_concepts = TRUE,
verbose = FALSE,
method = c("LinCbO", "NextClosure")
)save_concepts(logical) TRUE will also compute and save the concept lattice. FALSE is usually faster, since it only computes implications.
verbose(logical) TRUE will provide a verbose output.
method(character) Algorithm to use for binary contexts. One of "LinCbO" (default, Janostik, Konecny, Krajca) or "NextClosure" (Ganter's algorithm). For non-binary (fuzzy) contexts, NextClosure is always used.
Nothing, just updates the internal fields concepts and implications.
find_protoconcepts()
Find protoconcepts
FormalContext$find_protoconcepts(verbose = FALSE)
verbose(logical) Show verbose output.
A list of protoconcepts, where each protoconcept is a list of two Sets (extent and intent).
find_causal_rules()
Find causal rules
FormalContext$find_causal_rules( response_var, min_support = 0.1, confidence_level = 0.95, max_length = 3, verbose = FALSE )
response_var(character) The name of the response variable.
min_support(numeric) Minimum support for the premise attributes.
confidence_level(numeric) Confidence level for the causality test.
max_length(integer) Maximum length of the premise.
verbose(logical) Show verbose output.
A RuleSet object containing the discovered causal rules and their quality metrics.
factorize()
Factorize the formal context using Boolean/Fuzzy Matrix Factorization algorithms.
FormalContext$factorize(method = "GreConD", ...)
method(character) The algorithm to use. Currently supported: "GreConD", "ASSO".
...Additional arguments:
For GreConD: w (weight, default 1.0), stop_threshold_ratio (error tolerance, default 0.0).
For ASSO: threshold (confidence threshold, default 0.7), w_pos (reward), w_neg (penalty).
A list with two FormalContext objects:
object_factor: The context mapping Objects to Factors (Matrix A).
factor_attribute: The context mapping Factors to Attributes (Matrix B).
to_transactions()
Convert the formal context to object of class transactions from the arules package
FormalContext$to_transactions()
A transactions object.
save()
Save a FormalContext to RDS or CXT format
FormalContext$save(filename = tempfile(fileext = ".rds"))
filename(character) Path of the file where to store the FormalContext.
The format is inferred from the extension of the filename.
Invisibly the current FormalContext.
load()
Load a FormalContext from a file
FormalContext$load(filename)
filename(character) Path of the file to load the FormalContext from.
Currently, only RDS, CSV and CXT files are supported.
The loaded FormalContext.
dim()
Dimensions of the formal context
FormalContext$dim()
A vector with (number of objects, number of attributes).
to_json()
Export the formal context to JSON
FormalContext$to_json(file = NULL)
file(character) The path of the file to save the JSON to.
A JSON string representing the formal context.
print()
Prints the formal context
FormalContext$print()
Prints information regarding the formal context.
calculate_arrow_relations()
Calculate arrow relations for a binary context.
FormalContext$calculate_arrow_relations()
This method computes the arrow relations (swarrow, nearrow, and double arrow).
Nothing, updates the internal state.
get_arrow_relations()
Get arrow relations
FormalContext$get_arrow_relations()
An integer matrix with the arrow relations.
get_irreducible_objects()
Get irreducible objects
FormalContext$get_irreducible_objects()
A character vector with the names of the irreducible objects.
get_irreducible_attributes()
Get irreducible attributes
FormalContext$get_irreducible_attributes()
A character vector with the names of the irreducible attributes.
is_distributive()
Check if the context (and its lattice) is distributive
FormalContext$is_distributive()
Logical: TRUE if the lattice is distributive.
reduce_arrows()
Reduce the formal context using arrow relations
FormalContext$reduce_arrows()
A new FormalContext object that is clarified and reduced.
get_core()
Get the Core of the Formal Context
FormalContext$get_core()
The core is the minimal subcontext that generates the same concept lattice.
For binary contexts, this is equivalent to standardize().
A new FormalContext object containing only irreducible rows and columns.
to_latex()
Write the context in LaTeX format
FormalContext$to_latex(table = TRUE, label = "", caption = "")
table(logical) If TRUE, surrounds everything between \begin{table} and \end{table}.
label(character) The label for the table environment.
caption(character) The caption of the table.
fraction(character) If none, no fractions are produced. Otherwise, if it is frac, dfrac or sfrac, decimal numbers are represented as fractions with the corresponding LaTeX typesetting.
A table environment in LaTeX.
incidence()
Incidence matrix of the formal context
FormalContext$incidence()
The incidence matrix of the formal context
fc <- FormalContext$new(planets) fc$incidence()
subcontext()
Generates a new FormalContext restricted to a subset of objects and/or attributes.
FormalContext$subcontext(objects, attributes)
objects(character or integer vector) The names or indices of the objects to keep. If NULL, keeps all.
attributes(character or integer vector) The names or indices of the attributes to keep. If NULL, keeps all.
A new FormalContext object representing the subcontext.
fc <- FormalContext$new(planets)
fc$subcontext(attributes = c("moon", "no_moon"))
[()
Subcontext of the formal context
FormalContext$[(objects, attributes)
objects(character array) Name of the objects to keep.
attributes(character array) Names of the attributes to keep.
A warning will be issued if any of the names is not present in the list of objects or attributes of the formal context.
If objects or attributes is empty, then it is
assumed to represent the whole set of objects or attributes
of the original formal context.
Another FormalContext that is a subcontext
of the original one, with only the objects and attributes
selected.
fc <- FormalContext$new(planets)
fc[, c("moon", "no_moon")]
plot()
Plot the formal context table
FormalContext$plot(to_latex = FALSE, ...)
to_latex(logical) If TRUE, export the plot as a tikzpicture environment that can be included in a LaTeX file.
...Other parameters to be passed to the tikzDevice that renders the lattice in LaTeX, or for the figure caption. See Details.
Particular parameters that control the size of the tikz output are: width, height (both in inches), and pointsize (in points), that should be set to the font size used in the documentclass header in the LaTeX file where the code is to be inserted.
If a caption is provided, the whole tikz picture will be wrapped by a figure environment and the caption set.
If to_latex is FALSE, it returns nothing, just plots the graph of the formal context. Otherwise, this function returns the LaTeX code to reproduce the formal context plot.
use_logic()
Sets the logic to use
FormalContext$use_logic(name = available_logics())
nameThe name of the logic to use. To see the available names, run available_logics().
get_logic()
Gets the logic used
FormalContext$get_logic()
A string with the name of the logic.
use_connection()
Sets the name of the Galois connection to use
FormalContext$use_connection(connection)
connectionThe name of the Galois connection. Available connections are "standard" (antitone), "benevolent1" and "benevolent2" (isotone)
get_connection()
Gets the name of the Galois connection
FormalContext$get_connection()
A string with the name of the Galois connection
clone()
The objects of this class are cloneable with this method.
FormalContext$clone(deep = FALSE)
deepWhether to make a deep clone.
Guigues J, Duquenne V (1986). “Familles minimales d'implications informatives résultant d'un tableau de données binaires.” Mathématiques et Sciences humaines, 95, 5-18.
Ganter B, Wille R (1999). Formal concept analysis : mathematical foundations. Springer. ISBN 3540627715.
Belohlavek R (2002). “Algorithms for fuzzy concept lattices.” In Proc. Fourth Int. Conf. on Recent Advances in Soft Computing. Nottingham, United Kingdom, 200-205.
Hahsler M, Grun B, Hornik K (2005). “arules - a computational environment for mining association rules and frequent item sets.” J Stat Softw, 14, 1-25.
# Build and print the formal context fc_planets <- FormalContext$new(planets) print(fc_planets) # Define a set of attributes S <- Set$new(attributes = fc_planets$attributes) S$assign(moon = 1, large = 1) # Compute the closure of S Sc <- fc_planets$closure(S) # Is Sc a closed set? fc_planets$is_closed(Sc) # Clarify and reduce the formal context fc2 <- fc_planets$reduce(TRUE) # Find implications fc_planets$find_implications() # Read a formal context from CSV filename <- system.file("contexts", "airlines.csv", package = "fcaR") fc <- FormalContext$new(filename) # Read a formal context from a CXT file filename <- system.file("contexts", "lives_in_water.cxt", package = "fcaR") fc <- FormalContext$new(filename) ## ------------------------------------------------ ## Method `FormalContext$scale` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") ## ------------------------------------------------ ## Method `FormalContext$get_scales` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$get_scales() ## ------------------------------------------------ ## Method `FormalContext$background_knowledge` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$background_knowledge() ## ------------------------------------------------ ## Method `FormalContext$incidence` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$incidence() ## ------------------------------------------------ ## Method `FormalContext$subcontext` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$subcontext(attributes = c("moon", "no_moon")) ## ------------------------------------------------ ## Method `FormalContext$[` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc[, c("moon", "no_moon")]# Build and print the formal context fc_planets <- FormalContext$new(planets) print(fc_planets) # Define a set of attributes S <- Set$new(attributes = fc_planets$attributes) S$assign(moon = 1, large = 1) # Compute the closure of S Sc <- fc_planets$closure(S) # Is Sc a closed set? fc_planets$is_closed(Sc) # Clarify and reduce the formal context fc2 <- fc_planets$reduce(TRUE) # Find implications fc_planets$find_implications() # Read a formal context from CSV filename <- system.file("contexts", "airlines.csv", package = "fcaR") fc <- FormalContext$new(filename) # Read a formal context from a CXT file filename <- system.file("contexts", "lives_in_water.cxt", package = "fcaR") fc <- FormalContext$new(filename) ## ------------------------------------------------ ## Method `FormalContext$scale` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") ## ------------------------------------------------ ## Method `FormalContext$get_scales` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$get_scales() ## ------------------------------------------------ ## Method `FormalContext$background_knowledge` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$background_knowledge() ## ------------------------------------------------ ## Method `FormalContext$incidence` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$incidence() ## ------------------------------------------------ ## Method `FormalContext$subcontext` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$subcontext(attributes = c("moon", "no_moon")) ## ------------------------------------------------ ## Method `FormalContext$[` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc[, c("moon", "no_moon")]
Connects to the official FCA Repository (https://fcarepository.org) and downloads the metadata for all available datasets.
get_fcarepository_contexts()get_fcarepository_contexts()
A list containing the metadata for each context (title, dimensions, description, source).
## Not run: meta <- get_fcarepository_contexts() ## End(Not run)## Not run: meta <- get_fcarepository_contexts() ## End(Not run)
A dataset representing the 24 classical characters from the Guess Who board game with their 19 binary attributes.
guesswhoguesswho
A matrix with 24 rows and 19 columns. Column names correspond to the physical attributes:
Male, Female.
BlackHair, WhiteHair, BlondeHair, BrownHair, RedHair.
Bald.
BlueEyes, BrownEyes.
Moustache, Beard.
Hat, Glasses, Earrings.
RosyCheeks, BigNose, BigMouth, Sad.
Each entry contains a 1 if the character possesses the trait and a 0 otherwise.
Extracted from the physical version of the Guess Who board game characters.
Reconstructs an ImplicationSet object from a JSON string.
implications_from_json(json_str)implications_from_json(json_str)
json_str |
A JSON string generated by |
An ImplicationSet object.
This class implements an implication set (LHS -> RHS) in the framework of
Formal Concept Analysis (FCA). It inherits from RuleSet and adds
FCA-specific methods such as closure computation, simplification, and
basis transformation.
fcaR::RuleSet -> ImplicationSet
fcaR::RuleSet$[()fcaR::RuleSet$cardinality()fcaR::RuleSet$confidence()fcaR::RuleSet$filter()fcaR::RuleSet$get_LHS_matrix()fcaR::RuleSet$get_RHS_matrix()fcaR::RuleSet$get_attributes()fcaR::RuleSet$get_implications()fcaR::RuleSet$get_quality()fcaR::RuleSet$is_empty()fcaR::RuleSet$size()fcaR::RuleSet$to_latex()new()
Initialize an ImplicationSet
ImplicationSet$new(...)
...A rules object (from arules) or named arguments:
name (string), attributes (character vector),
lhs and rhs (sparse matrices), I (incidence matrix).
A new ImplicationSet object.
add()
Add a precomputed implication set
ImplicationSet$add(...)
...An ImplicationSet object, a rules object, or a pair lhs, rhs of Set objects or dgCMatrix. The implications to add to this formal context.
Nothing, just updates the internal implications field.
to_arules()
Convert to arules format
ImplicationSet$to_arules(quality = TRUE)
quality(logical) Compute the interest measures for each rule?
A rules object as used by package arules.
print()
Print all implications to text
ImplicationSet$print()
A string with all the implications in the set.
support()
Compute support of each implication
ImplicationSet$support()
A vector with the support of each implication
closure()
Compute the semantic closure of a fuzzy set with respect to the implication set
ImplicationSet$closure(S, reduce = FALSE, verbose = FALSE)
S(a Set object) Fuzzy set to compute its closure. Use class Set to build it.
reduce(logical) Reduce the implications using simplification logic?
verbose(logical) Show verbose output?
If reduce == FALSE, the output is a fuzzy set corresponding to the closure of S. If reduce == TRUE, a list with two components: closure, with the closure as above, and implications, the reduced set of implications.
recommend()
Generate a recommendation for a subset of the attributes
ImplicationSet$recommend(S, attribute_filter)
S(a vector) Vector with the grades of each attribute (a fuzzy set).
attribute_filter(character vector) Names of the attributes to get recommendation for.
A fuzzy set describing the values of the attributes in attribute_filter within the closure of S.
apply_rules()
Apply rules to remove redundancies
ImplicationSet$apply_rules(
rules = c("composition", "generalization"),
batch_size = 25000L,
parallelize = FALSE,
reorder = FALSE
)rules(character vector) Names of the rules to use. See details.
batch_size(integer) If the number of rules is large, apply the rules by batches of this size.
parallelize(logical) If possible, should we parallelize the computation among different batches?
reorder(logical) Should the rules be randomly reordered previous to the computation?
Currently, the implemented rules are "generalization", "simplification", "reduction" and "composition".
Nothing, just updates the internal matrices for LHS and RHS.
to_basis()
Convert Implications to Canonical Basis
ImplicationSet$to_basis()
The canonical basis of implications obtained from the current ImplicationSet
to_direct_optimal()
Compute the Direct Optimal Basis using optimized C++ algorithms.
ImplicationSet$to_direct_optimal(
method = c("do_sp", "direct_optimal", "final_ts", "monotonic", "priority"),
verbose = FALSE
)method(character) The specific algorithm to run:
"direct_optimal": (Default) The Direct Optimal Saturation-Pruning algorithm.
"final_ts": Computes Transitive Closure then Prunes (Standard approach).
"monotonic": Incremental algorithm maintaining monotonicity.
"priority": Priority-based refinement algorithm.
verbose(logical) Print verbose output from the C++ backend.
Nothing, updates the ImplicationSet in place with the new basis.
use_logic()
Sets the logic to use
ImplicationSet$use_logic(name = available_logics())
nameThe name of the logic to use. To see the available names, run available_logics().
get_logic()
Gets the logic used
ImplicationSet$get_logic()
A string with the name of the logic.
get_standard_context()
Get the standard formal context associated with the implication set.
ImplicationSet$get_standard_context()
The standard formal context associated to a set of implications on is such that its concept lattice is isomorphic to the lattice of closed sets of the implication set.
The objects of this context are the meet-irreducible closed sets of the implication set.
A FormalContext object where the objects are the meet-irreducible closed sets and the attributes are the attributes of the implication set.
use_hedge()
Sets the hedge to use when computing closures
ImplicationSet$use_hedge(name = c("globalization", "identity"))nameThe name of the hedge to use. Only "globalization" and "identity" are allowed.
get_hedge()
Gets the hedge used to compute closures
ImplicationSet$get_hedge()
A string with the name of the hedge
to_json()
Export the implication set to JSON
ImplicationSet$to_json(file = NULL, return_list = FALSE)
file(character) The path of the file to save the JSON to.
return_list(logical) If TRUE, returns the list representation instead of the JSON string.
A JSON string representing the implication set, or a list if return_list is TRUE.
clone()
The objects of this class are cloneable with this method.
ImplicationSet$clone(deep = FALSE)
deepWhether to make a deep clone.
A bond between two formal contexts and
is a relation such that every row of is an intent
of and every column of is an extent of .
is_bond(fc1, fc2, relation)is_bond(fc1, fc2, relation)
fc1 |
( |
fc2 |
( |
relation |
(matrix) A binary matrix or |
TRUE if the relation is a bond, FALSE otherwise.
Reconstructs a ConceptLattice object from a JSON string.
lattice_from_json(json_str)lattice_from_json(json_str)
json_str |
A JSON string generated by |
A ConceptLattice object.
Visualization of the concept lattice using 'ggraph'.
lattice_plot( nodes_df, cover_matrix, method = "sugiyama", mode = NULL, objects = NULL, attributes = NULL, object_names = TRUE, to_latex = FALSE, extents = NULL, intents = NULL, viewer = c("ggraph", "base"), theme = "standard", ... )lattice_plot( nodes_df, cover_matrix, method = "sugiyama", mode = NULL, objects = NULL, attributes = NULL, object_names = TRUE, to_latex = FALSE, extents = NULL, intents = NULL, viewer = c("ggraph", "base"), theme = "standard", ... )
nodes_df |
Data frame with 'id'. |
cover_matrix |
Sparse matrix. |
method |
Layout method ("sugiyama", "force"). |
mode |
Labeling mode ("reduced", "full", "empty"). |
objects |
Character vector. |
attributes |
Character vector. |
object_names |
Logical (Deprecated). |
to_latex |
Logical. |
extents |
List of extents. |
intents |
List of intents. |
viewer |
The viewer to use for plotting: "ggraph" (default) or "base" (experimental, R base graphics). |
theme |
The theme to use for the "base" viewer ("standard", "nord", "latex", "vibrant"). |
... |
Extra args. |
Parses a string into an implication
parse_implication(string, attributes)parse_implication(string, attributes)
string |
(character) The string to be parsed |
attributes |
(character vector) The attributes' names |
Two vectors as sparse matrices representing the LHS and RHS of the implication
Parses several implications given as a string
parse_implications(input)parse_implications(input)
input |
(character) The string with the implications or a file containing the implications |
The format for the input file is:
Every implication in its own line or separated by semicolon (;)
Attributes are separated by commas (,)
The LHS and RHS of each implication are separated by an arrow (->)
An ImplicationSet
input <- system.file("implications", "ex_implications", package = "fcaR") imps <- parse_implications(input)input <- system.file("implications", "ex_implications", package = "fcaR") imps <- parse_implications(input)
This dataset records some properties of the planets in our solar system.
planetsplanets
A matrix with 9 rows (the planets) and 7 columns, representing additional features of the planets:
1 if the planet is small, 0 otherwise.
1 if the planet is medium-sized, 0 otherwise.
1 if the planet is large, 0 otherwise.
1 if the planet belongs in the inner solar system, 0 otherwise.
1 if the planet belongs in the outer solar system, 0 otherwise.
1 if the planet has a natural moon, 0 otherwise.
1 if the planet has no moon, 0 otherwise.
Wille R (1982). “Restructuring Lattice Theory: An Approach Based on Hierarchies of Concepts.” In Ordered Sets, pp. 445–470. Springer.
Prints a formatted summary of the contexts available in the FCA Repository to the console. It displays the filename, title, dimensions (objects x attributes), and description for each entry.
print_repo_details(meta)print_repo_details(meta)
meta |
A list of metadata objects, typically obtained via |
Prints the summary to the console. Returns NULL invisibly.
## Not run: meta <- get_fcarepository_contexts() print_repo_details(meta) ## End(Not run)## Not run: meta <- get_fcarepository_contexts() print_repo_details(meta) ## End(Not run)
Prints the TikZ code to the console.
## S3 method for class 'tikz_code' print(x, ...)## S3 method for class 'tikz_code' print(x, ...)
x |
An object of class |
... |
Additional arguments (currently unused). |
Functions to generate synthetic formal contexts using advanced statistical distributions. These methods allow creating datasets that mimic real-world properties (non-uniform density) or randomizing existing contexts while preserving their structural properties.
RandomContext( n_objects, n_attributes, density = 0.1, distribution = "uniform", alpha = 1, ... )RandomContext( n_objects, n_attributes, density = 0.1, distribution = "uniform", alpha = 1, ... )
n_objects |
(integer) Number of objects. |
n_attributes |
(integer) Number of attributes. |
density |
(numeric) Expected density of the context (proportion of 1s). Used for uniform distribution. |
distribution |
(character) The distribution to use for generating the context.
|
alpha |
(numeric) Concentration parameter for the Dirichlet distribution. Low values (e.g., 0.1) produce very skewed distributions (some objects have few attributes, others many). High values produce more uniform row sums. Default is 1.0. |
... |
Additional arguments passed to internal methods. |
A FormalContext object.
# 1. Uniform Random Context fc_uni <- RandomContext(10, 5, density = 0.2) print(fc_uni) # 2. Dirichlet Random Context (Mimicking real data structure) # Objects will have varying 'sizes' (number of attributes) fc_dir <- RandomContext(10, 5, distribution = "dirichlet", alpha = 0.5) print(fc_dir)# 1. Uniform Random Context fc_uni <- RandomContext(10, 5, density = 0.2) print(fc_uni) # 2. Dirichlet Random Context (Mimicking real data structure) # Objects will have varying 'sizes' (number of attributes) fc_dir <- RandomContext(10, 5, distribution = "dirichlet", alpha = 0.5) print(fc_dir)
Generates a random formal context that is guaranteed to produce a Distributive Concept Lattice.
It relies on Birkhoff's Representation Theorem: The lattice of order ideals
of a Poset is always distributive. The context is constructed such that
objects and attributes are the elements of the poset, and the incidence
relation is .
RandomDistributiveContext(n_elements, density = 0.1)RandomDistributiveContext(n_elements, density = 0.1)
n_elements |
Number of elements in the underlying Poset. |
density |
Probability of an order relation |
A FormalContext.
Modifies the incidence matrix of a formal context to create a random variation while preserving certain statistical properties. This is essential for statistical significance testing in FCA (e.g., "is this concept structure random?").
randomize_context(fc, method = "swap", iterations = NULL)randomize_context(fc, method = "swap", iterations = NULL)
fc |
( |
method |
(character) The randomization strategy:
|
iterations |
(integer) Number of swap/rewire operations to perform.
Default is |
A new FormalContext object with the randomized incidence.
data(planets) fc <- FormalContext$new(planets) # 1. Edge Swapping (Preserves degree distribution) # Useful for null-model testing fc_rand_swap <- randomize_context(fc, method = "swap") # Verify marginals are preserved colSums(fc$incidence()) colSums(fc_rand_swap$incidence()) # 2. Rewiring (Preserves only density) fc_rand_rewire <- randomize_context(fc, method = "rewire")data(planets) fc <- FormalContext$new(planets) # 1. Edge Swapping (Preserves degree distribution) # Useful for null-model testing fc_rand_swap <- randomize_context(fc, method = "swap") # Verify marginals are preserved colSums(fc$incidence()) colSums(fc_rand_swap$incidence()) # 2. Rewiring (Preserves only density) fc_rand_rewire <- randomize_context(fc, method = "rewire")
Reconstructs a RuleSet object from a JSON string.
rules_from_json(json_str)rules_from_json(json_str)
json_str |
A JSON string generated by |
A RuleSet object.
This class implements a generic rule set (LHS -> RHS), serving as the parent
class for ImplicationSet. It provides common functionality for
managing, filtering, and exporting rules.
new()
Initialize a RuleSet
RuleSet$new(...)
...A rules object (from arules) or named arguments:
name (string), attributes (character vector),
lhs and rhs (sparse matrices), I (incidence matrix),
quality (data.frame), confidence (numeric vector, backward compat).
A new RuleSet object.
get_attributes()
Get the names of the attributes
RuleSet$get_attributes()
A character vector with the names of the attributes used in the rules.
[()
Get a subset of the rule set
RuleSet$[(idx)
idx(integer or logical vector) Indices of the rules to extract or remove. If logical vector, only TRUE elements are retained and the rest discarded.
A new RuleSet with only the rules given by the idx indices.
to_arules()
Convert to arules format
RuleSet$to_arules(quality = TRUE)
quality(logical) Compute/include the interest measures for each rule?
A rules object as used by package arules.
add()
Add a precomputed rule set
RuleSet$add(...)
...A RuleSet object, or a pair lhs, rhs of dgCMatrix.
Nothing, just updates the internal field.
cardinality()
Cardinality: Number of rules in the set
RuleSet$cardinality()
The cardinality of the rule set.
is_empty()
Empty set
RuleSet$is_empty()
TRUE if the set of rules is empty, FALSE otherwise.
size()
Size: number of attributes in each of LHS and RHS
RuleSet$size()
A matrix with two columns: the number of attributes present in each of the LHS and RHS of each rule.
print()
Print all rules to text
RuleSet$print()
A string with all the rules in the set.
get_quality()
Get quality metrics
RuleSet$get_quality()
A data.frame with the quality metrics for each rule.
to_latex()
Export to LaTeX
RuleSet$to_latex( print = TRUE, ncols = 1, numbered = TRUE, numbers = seq_len(self$cardinality()) )
print(logical) Print to output?
ncols(integer) Number of columns for the output.
numbered(logical) If TRUE (default), implications will be numbered in the output.
numbers(vector) If numbered, use these elements to enumerate the implications. The default is to enumerate 1, 2, ..., but can be changed.
A string in LaTeX format that prints nicely all the rules.
get_LHS_matrix()
Get internal LHS matrix
RuleSet$get_LHS_matrix()
A sparse matrix representing the LHS of the rules in the set.
get_RHS_matrix()
Get internal RHS matrix
RuleSet$get_RHS_matrix()
A sparse matrix representing the RHS of the rules in the set.
filter()
Filter rules by attributes in LHS and RHS
RuleSet$filter( lhs = NULL, not_lhs = NULL, rhs = NULL, not_rhs = NULL, drop = FALSE )
lhs(character vector) Names of the attributes to filter the LHS by. If NULL, no filtering is done on the LHS.
not_lhs(character vector) Names of the attributes to not include in the LHS. If NULL (the default), it is not considered at all.
rhs(character vector) Names of the attributes to filter the RHS by. If NULL, no filtering is done on the RHS.
not_rhs(character vector) Names of the attributes to not include in the RHS. If NULL (the default), it is not considered at all.
drop(logical) Remove the rest of attributes in RHS?
A RuleSet (or subclass) that is a subset of the current set, only with those rules which have the attributes in lhs and rhs in their LHS and RHS, respectively.
get_implications()
Extract the implications with confidence 1
RuleSet$get_implications()
An ImplicationSet object containing only the rules with confidence 1.
support()
Compute support of each rule
RuleSet$support()
A vector with the support of each rule.
confidence()
Compute the confidence of each rule
RuleSet$confidence()
A numeric vector with the confidence of each rule.
to_json()
Export the rule set to JSON
RuleSet$to_json(file = NULL, return_list = FALSE)
file(character) The path of the file to save the JSON to.
return_list(logical) If TRUE, returns the list representation instead of the JSON string.
A JSON string representing the rule set, or a list if return_list is TRUE.
clone()
The objects of this class are cloneable with this method.
RuleSet$clone(deep = FALSE)
deepWhether to make a deep clone.
Exports the generated TikZ code to a .tex file.
save_tikz(x, file, ...)save_tikz(x, file, ...)
x |
An object of class 'tikz_code'. |
file |
Character. Path to the output file. |
... |
Additional arguments. |
Scaling Registry
scalingRegistryscalingRegistry
An object of class scaling_registry (inherits from registry) of length 6.
This is a registry that stores the implemented scales that can be
applied using the scale() method in an
FormalContext.
One can obtain the list of available equivalence operators by:
scalingRegistry$get_entry_names()
GUI to select and download a context from the repository
select_repository_context(meta)select_repository_context(meta)
meta |
A list of metadata objects (obtained via |
This class implements the data structure and methods for fuzzy sets.
new()
Creator for objects of class Set
Set$new(attributes, M = NULL, ...)
attributes(character vector) Names of the attributes that will be available in the fuzzy set.
M(numeric vector or column Matrix) Values (grades) to be assigned to the attributes.
...key = value pairs, where the value value is assigned to the key attribute name.
If M is omitted and no pair key = value, the fuzzy set is the empty set. Later, one can use the assign method to assign grades to any of its attributes.
An object of class Set.
assign()
Assign grades to attributes in the set
Set$assign(..., attributes = c(), values = c())
...key = value pairs, where the value value is assigned to the key attribute name.
attributes(character vector) Names of the attributes to assign a grade to.
values(numeric vector) Grades to be assigned to the previous attributes.
One can use both of:
S$assign(A = 1, B = 0.3)
S$assign(attributes = c(A, B), values = c(1, 0.3)).
[()
Get elements by index
Set$[(indices)
indices(numeric, logical or character vector) The indices of the elements to return. It can be a vector of logicals where TRUE elements are to be retained.
A Set but with only the required elements.
cardinal()
Cardinal of the Set
Set$cardinal()
the cardinal of the Set, counted
as the sum of the degrees of each element.
get_vector()
Internal Matrix
Set$get_vector()
The internal sparse Matrix representation of the set.
get_attributes()
Attributes defined for the set
Set$get_attributes()
A character vector with the names of the attributes.
length()
Number of attributes
Set$length()
The number of attributes that are defined for this fuzzy set.
print()
Prints the set to console
Set$print(eol = TRUE)
eol(logical) If TRUE, adds an end of line to the output.
A string with the elements of the set and their grades between brackets .
to_latex()
Write the set in LaTeX format
Set$to_latex(print = TRUE)
print(logical) Print to output?
The fuzzy set in LaTeX.
clone()
The objects of this class are cloneable with this method.
Set$clone(deep = FALSE)
deepWhether to make a deep clone.
S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) print(S) S$to_latex() S <- Set$new(c("A", "B", "C"), C = 1, B = 0.5) SS <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) print(S) S$to_latex() S <- Set$new(c("A", "B", "C"), C = 1, B = 0.5) S
The dataset vegas is the binary translation of the Las Vegas Strip dataset (@moro2017stripping), which records more than 500 TripAdvisor reviews of hotels in Las Vegas Strip. The uninformative attributes (such as the user continent or the weekday of the review) are removed.
vegasvegas
A matrix with 504 rows and 25 binary columns. Column names are related to different features of the hotels:
4 categories are present in the original data, which produces as many binary variables: Period of stay=Dec-Feb, Period of stay=Mar-May, Period of stay=Jun-Aug and Period of stay=Sep-Nov.
Five binary categories are created from the original data: Traveler type=Business, Traveler type=Couples, Traveler type=Families, Traveler type=Friends and Traveler type=Solo.
Binary variables for the services offered by each destination hotel
Five binary variables are created, according to the number of stars of the hotel, Stars=3, Stars=3.5, Stars=4, Stars=4.5 and Stars=5.
The score assigned in the review, from Score=1 to Score=5.
Moro, S., Rita, P., & Coelho, J. (2017). Stripping customers' feedback on hotels through data mining: The case of Las Vegas Strip. Tourism Management Perspectives, 23, 41-52.