boofun.core
- class boofun.core.BooleanFunction(*args, **kwargs)[source]
- compose(other: BooleanFunction) BooleanFunction[source]
Compose this function with another BooleanFunction.
Semantics mirror the legacy
BooleanFunc.compose: ifselfdepends onnvariables andotherdepends onmvariables, the result is a function onn * mvariables obtained by substitutingotherinto each input ofselfon disjoint variable blocks.
- evaluate(inputs, rep_type=None, **kwargs)[source]
Evaluate function with automatic input type detection and representation selection.
- Parameters:
inputs – Input data (array, list, or scipy random variable)
rep_type – Optional specific representation to use
**kwargs – Additional evaluation parameters
- Returns:
Boolean result(s) or distribution (with error model applied)
- Raises:
InvalidInputError – If inputs are empty or have unsupported type
EvaluationError – If evaluation fails
- get_conversion_options(max_cost: float | None = None) Dict[str, Any][source]
Get available conversion options from current representations.
- Parameters:
max_cost – Maximum acceptable conversion cost
- Returns:
Dictionary with conversion options and costs
- estimate_conversion_cost(target_rep: str) Any | None[source]
Estimate cost to convert to target representation.
- Parameters:
target_rep – Target representation name
- Returns:
Conversion cost estimate or None if impossible
- to(representation_type: str)[source]
Convert to specified representation (convenience method).
- Parameters:
representation_type – Target representation type
- Returns:
Self (for method chaining)
- fix(var, val)[source]
Fix variable(s) to specific value(s), returning a new function on fewer variables.
This is a fundamental operation for Boolean function analysis, used in: - Decision tree computation - Certificate analysis - Influence computation via derivatives
- Parameters:
var – Variable index (int) or list of variable indices
val – Value (0 or 1) or list of values to fix variables to
- Returns:
New BooleanFunction with fixed variables removed
Example
>>> f = bf.create([0, 1, 1, 0]) # XOR on 2 vars >>> g = f.fix(0, 1) # Fix x_0 = 1, get function on x_1 only
- restrict(var: int, val: int) BooleanFunction[source]
Alias for fix() - restrict a variable to a specific value.
This terminology is often used in the literature (e.g., random restrictions).
- derivative(var: int) BooleanFunction[source]
Compute the discrete derivative with respect to variable var.
- The derivative D_i f is defined as:
D_i f(x) = f(x) XOR f(x ⊕ e_i)
where e_i is the i-th unit vector. The derivative is 1 exactly when variable i is influential at input x.
- Parameters:
var – Variable index to differentiate with respect to
- Returns:
New BooleanFunction representing the derivative
Note
The influence of variable i equals E[D_i f] = Pr[D_i f(x) = 1]
- shift(s: int) BooleanFunction[source]
Shift the function: f_s(x) = f(x ⊕ s).
This applies an XOR mask to all inputs, effectively translating the function in the Boolean cube.
- Parameters:
s – Shift mask (integer representing the XOR offset)
- Returns:
New BooleanFunction with shifted inputs
- negation() BooleanFunction[source]
Return the negation of this function: NOT f.
- Returns:
New BooleanFunction where all outputs are flipped
- bias() float[source]
Compute the bias of the function: E[(-1)^f(x)] = 1 - 2*Pr[f(x)=1].
The bias is in [-1, 1]: - bias = 1 means f is constantly 0 - bias = -1 means f is constantly 1 - bias = 0 means f is balanced
- Returns:
Bias value in [-1, 1]
- is_balanced() bool[source]
Check if the function is balanced (equal 0s and 1s in truth table).
- Returns:
True if the function outputs 0 and 1 equally often
- query_model(max_queries: int = 10000000) QueryModel[source]
Get the query model for this function.
The query model helps understand computational costs and prevents accidentally running exponential-time operations on huge functions.
- Parameters:
max_queries – Maximum acceptable number of function evaluations
- Returns:
QueryModel instance with cost estimation methods
Example
>>> f = bf.create(huge_neural_net, n=100) >>> qm = f.query_model() >>> qm.can_compute("is_linear") # True - O(k) queries >>> qm.can_compute("fourier") # False - would need 2^100 queries
- access_type() AccessType[source]
Get the access type for this function.
- Returns:
AccessType.EXPLICIT if we have the full truth table AccessType.QUERY if we can only evaluate on demand AccessType.SYMBOLIC if we have a formula
- fourier(force_recompute: bool = False) ndarray[source]
Compute Fourier coefficients f̂(S) for all subsets S ⊆ [n].
The Fourier expansion is: f(x) = Σ_S f̂(S) χ_S(x) where χ_S(x) = ∏_{i∈S} x_i are the Walsh characters.
- Returns:
Array of Fourier coefficients indexed by subset bitmask
Example
>>> xor = bf.create([0, 1, 1, 0]) >>> coeffs = xor.fourier() >>> coeffs[3] # f̂({0,1}) = -1 for XOR
- spectrum(force_recompute: bool = False) ndarray[source]
Alias for fourier() - returns Fourier spectrum.
- degree(gf2: bool = False) int[source]
Compute the degree of the function.
- Parameters:
gf2 – If True, compute GF(2) (algebraic) degree If False, compute Fourier (real) degree
- Returns:
Maximum degree of non-zero coefficient
Example
>>> xor = bf.create([0, 1, 1, 0]) >>> xor.degree() # Fourier degree = 2 >>> xor.degree(gf2=True) # GF(2) degree = 1
- influences(force_recompute: bool = False) ndarray[source]
Compute influences of all variables: Inf_i[f] = Pr[f(x) ≠ f(x ⊕ e_i)].
- Returns:
Array of influences, one per variable
Example
>>> maj = bf.majority(3) >>> maj.influences() # All equal for symmetric function
- influence(var: int) float[source]
Compute influence of a single variable.
- Parameters:
var – Variable index (0-indexed)
- Returns:
Influence value in [0, 1]
- total_influence() float[source]
Compute total influence: I[f] = Σ_i Inf_i[f].
Also called average sensitivity.
- Returns:
Sum of all variable influences
- noise_stability(rho: float) float[source]
Compute noise stability at correlation ρ.
Stab_ρ[f] = E[f(x)f(y)] where y is ρ-correlated with x. In Fourier: Stab_ρ[f] = Σ_S f̂(S)² ρ^|S|
- Parameters:
rho – Correlation parameter in [-1, 1]
- Returns:
Noise stability value
- W(k: int) float[source]
Compute Fourier weight at exactly degree k: W^{=k}[f] = Σ_{|S|=k} f̂(S)².
- Parameters:
k – Degree level
- Returns:
Sum of squared Fourier coefficients at degree k
- W_leq(k: int) float[source]
Compute Fourier weight up to degree k: W^{≤k}[f] = Σ_{|S|≤k} f̂(S)².
This measures spectral concentration on low-degree coefficients.
- Parameters:
k – Maximum degree
- Returns:
Sum of squared Fourier coefficients up to degree k
- sparsity(threshold: float = 1e-10) int[source]
Count non-zero Fourier coefficients.
From O’Donnell: degree-k functions have at most 4^k non-zero coefficients.
- Parameters:
threshold – Minimum magnitude to count as non-zero
- Returns:
Number of significant Fourier coefficients
- spectral_weight_by_degree() dict[source]
Compute spectral weight at each degree level.
- Returns:
Dict mapping degree k -> W^{=k}[f] = Σ_{|S|=k} f̂(S)²
Example
>>> maj = bf.majority(5) >>> maj.spectral_weight_by_degree() {0: 0.0, 1: 0.625, 3: 0.3125, 5: 0.0625}
- heavy_coefficients(tau: float = 0.1) list[source]
Find Fourier coefficients with |f̂(S)| ≥ τ.
- Parameters:
tau – Threshold for “heavy” coefficient
- Returns:
List of (subset_tuple, coefficient) pairs sorted by magnitude
Example
>>> maj = bf.majority(3) >>> maj.heavy_coefficients(0.3) [((0,), 0.5), ((1,), 0.5), ((2,), 0.5)]
- variance() float[source]
Compute variance: Var[f] = E[f²] - E[f]² = Σ_{S≠∅} f̂(S)².
- Returns:
Variance of the function (0 for constant, 1 for balanced ±1 function)
- max_influence() float[source]
Compute maximum influence: max_i Inf_i[f].
Important for KKL theorem: max_i Inf_i[f] ≥ Ω(log n / n) for balanced f.
- Returns:
Maximum influence value
- analyze() dict[source]
Quick analysis returning common metrics.
- Returns:
- n_vars, is_balanced, variance, degree,
total_influence, max_influence, noise_stability_0.5
- Return type:
Dict with
Example
>>> bf.majority(5).analyze() {'n_vars': 5, 'is_balanced': True, 'variance': 1.0, ...}
- negate_inputs() BooleanFunction[source]
Compute g(x) = f(-x) where -x flips all bits.
In Fourier: ĝ(S) = (-1)^|S| f̂(S) (odd-degree coefficients flip sign)
- Returns:
New function with negated inputs
- is_linear(num_tests: int = 100) bool[source]
Test if function is linear (affine over GF(2)).
Uses BLR linearity test.
- is_monotone(num_tests: int = 100) bool[source]
Test if function is monotone: x ≤ y implies f(x) ≤ f(y).
- is_symmetric(num_tests: int = 100) bool[source]
Test if function is symmetric (invariant under variable permutations).
- hamming_weight() int[source]
Count number of 1s in truth table (outputs where f(x) = 1).
Also called the “weight” or “on-set size” of the function.
- Returns:
Number of inputs x where f(x) = 1
Example
>>> bf.majority(3).hamming_weight() # 4 (inputs with ≥2 ones) >>> bf.AND(3).hamming_weight() # 1 (only 111)
- support() list[source]
Return all inputs where f(x) = 1.
Also called the “on-set” or “satisfying assignments”.
- Returns:
List of input indices (as integers) where f(x) = 1
Example
>>> bf.AND(2).support() # [3] (binary 11) >>> bf.OR(2).support() # [1, 2, 3] (01, 10, 11)
- restriction(fixed_vars: dict) BooleanFunction[source]
Create restriction of f by fixing some variables.
Alias for fix() with more standard mathematical terminology.
- Parameters:
fixed_vars – Dict mapping variable index -> fixed value (0 or 1)
- Returns:
Restricted function on remaining variables
Example
>>> f = bf.majority(3) >>> g = f.restriction({0: 1}) # Fix x₀=1, get 2-variable function
- cofactor(var: int, val: int) BooleanFunction[source]
Compute Shannon cofactor f|_{x_i=b}.
The cofactor is the restriction of f with variable i fixed to val. Shannon expansion: f = x_i · f|_{x_i=1} + (1-x_i) · f|_{x_i=0}
- Parameters:
var – Variable index to fix
val – Value to fix it to (0 or 1)
- Returns:
Cofactor function (one fewer variable)
Example
>>> f = bf.majority(3) >>> f0 = f.cofactor(0, 0) # f with x₀=0 >>> f1 = f.cofactor(0, 1) # f with x₀=1
- sensitivity_at(x: int) int[source]
Compute sensitivity of f at input x.
s(f, x) = |{i : f(x) ≠ f(x ⊕ eᵢ)}|
- Parameters:
x – Input (as integer)
- Returns:
Number of sensitive coordinates at x
- sensitivity() int[source]
Compute sensitivity: s(f) = max_x s(f, x).
Maximum number of sensitive bits over all inputs. Huang’s theorem: s(f) ≥ √deg(f)
- Returns:
Maximum sensitivity
- xor(other: BooleanFunction) BooleanFunction[source]
XOR with another function (chainable).
Equivalent to f ^ g but more readable in chains.
Example
>>> f.xor(g).fourier() >>> f.restrict(0, 1).xor(g).influences()
- and_(other: BooleanFunction) BooleanFunction[source]
AND with another function (chainable).
Named with underscore to avoid Python keyword conflict. Equivalent to f & g.
- or_(other: BooleanFunction) BooleanFunction[source]
OR with another function (chainable).
Named with underscore to avoid Python keyword conflict. Equivalent to f | g.
- not_() BooleanFunction[source]
Negate output (chainable).
Equivalent to ~f. Returns function g where g(x) = NOT f(x).
- apply_noise(rho: float, samples: int = 100) BooleanFunction[source]
Apply noise to get a new Boolean function via sampling.
For each input x, outputs the majority vote of f(y) over multiple y, where each y is independently ρ-correlated with x.
This gives a Boolean approximation to the noise operator T_ρ.
- Parameters:
rho – Correlation parameter in [-1, 1]
samples – Number of samples for majority vote (default: 100)
- Returns:
New Boolean function representing noisy version of f
Example
>>> f = bf.parity(5) >>> noisy_f = f.apply_noise(0.9) # High noise correlation >>> # Noisy version has lower degree (high-degree parts attenuated)
- noise_expectation(rho: float) ndarray[source]
Compute (T_ρ f)(x) = E_y[f(y)] for all inputs x.
This returns the real-valued expectations, not a Boolean function. Useful for analysis of noise stability.
In Fourier: (T_ρ f)^(S) = ρ^|S| · f̂(S)
- Parameters:
rho – Correlation parameter in [-1, 1]
- Returns:
Array of expectations E[f(y)|x] in {-1,+1} representation
Example
>>> f = bf.parity(5) >>> expectations = f.noise_expectation(0.9) >>> # All values close to 0 (noise destroys parity signal)
- permute(perm: list) BooleanFunction[source]
Permute variables according to given permutation.
Creates g where g(x_{perm[0]}, …, x_{perm[n-1]}) = f(x_0, …, x_{n-1}).
- Parameters:
perm – List defining the permutation, where perm[i] = j means variable i in the new function corresponds to variable j in self.
- Returns:
New function with permuted variables
Example
>>> f = bf.dictator(3, 0) # f(x) = x_0 >>> g = f.permute([2, 0, 1]) # g(x) = x_2 (old position 0 → new position 2)
- dual() BooleanFunction[source]
Compute the dual function f*(x) = 1 - f(1-x) = NOT f(NOT x).
The dual swaps the roles of AND and OR. For monotone functions, f* is the De Morgan dual.
- Returns:
Dual function
Example
>>> bf.AND(3).dual() # Returns OR(3) >>> bf.OR(3).dual() # Returns AND(3)
- extend(new_n: int, method: str = 'dummy') BooleanFunction[source]
Extend function to more variables.
- Parameters:
new_n – New number of variables (must be >= current n)
method – How to extend: - “dummy”: New variables don’t affect output (default) - “xor”: XOR new variables with output
- Returns:
Extended function
Example
>>> f = bf.AND(2) # f(x0, x1) = x0 AND x1 >>> g = f.extend(4) # g(x0,x1,x2,x3) = x0 AND x1 (x2,x3 ignored)
- named(name: str) BooleanFunction[source]
Return same function with a descriptive name (for display/debugging).
This is a fluent method that returns self with updated nickname.
Example
>>> f = bf.majority(5).named("MAJ_5") >>> f.nickname 'MAJ_5'
- pipe(func, *args, **kwargs)[source]
Apply an arbitrary function to self (for maximum fluency).
Allows inserting custom transformations into a chain.
- Parameters:
func – Function to apply, receives self as first argument
*args – Additional arguments to func
**kwargs –
Additional arguments to func
- Returns:
Example
>>> def custom_transform(f, scale): ... return f.apply_noise(scale) >>> f.pipe(custom_transform, 0.9).fourier()
- class boofun.core.BooleanFunctionBuiltins[source]
Collection of standard Boolean functions used in research and testing.
- classmethod majority(n: int) BooleanFunction[source]
Create majority function on n variables.
Returns 1 if more than half of the inputs are 1, 0 otherwise. For even n, ties are broken by returning 0.
- Parameters:
n – Number of input variables (must be positive)
- Returns:
BooleanFunction implementing the majority function
- classmethod dictator(n: int, i: int = 0) BooleanFunction[source]
Create dictator function (output equals i-th input).
The function returns the value of the i-th input variable, ignoring all other inputs: f(x) = x_i.
- Parameters:
n – Total number of input variables
i – Index of the dictating variable (0-indexed, default 0)
- Returns:
BooleanFunction that outputs x_i
Examples
>>> bf.dictator(5) # 5-var dictator on x₀ >>> bf.dictator(5, 2) # 5-var dictator on x₂
- classmethod tribes(k: int, n: int) BooleanFunction[source]
Generate tribes function (k-wise AND of n/k ORs).
The tribes function divides n variables into groups of k, computes OR within each group, then AND across groups.
- Parameters:
k – Size of each tribe (group)
n – Total number of variables (should be divisible by k)
- Returns:
BooleanFunction implementing the tribes function
Note
If n is not divisible by k, the last group will have fewer variables.
- classmethod parity(n: int) BooleanFunction[source]
Create parity function on n variables.
Returns 1 if an odd number of inputs are 1, 0 otherwise.
- Parameters:
n – Number of input variables
- Returns:
BooleanFunction implementing the parity function
- classmethod constant(value: bool, n: int) BooleanFunction[source]
Create constant function.
- Parameters:
value – Constant value to return (True or False)
n – Number of input variables (for compatibility)
- Returns:
BooleanFunction that always returns the constant value
- class boofun.core.BooleanFunctionFactory[source]
Factory for creating BooleanFunction instances from various representations.
- classmethod create(boolean_function_cls: Type, data: Any = None, **kwargs)[source]
Main factory method that dispatches to specialized creators based on input data type.
- Parameters:
boolean_function_cls – The BooleanFunction class to instantiate
data – Input data in one of the supported formats
**kwargs – Additional arguments (n_vars, space, rep_type, etc.)
- Returns:
BooleanFunction instance
- Raises:
InvalidRepresentationError – If data type is not supported
InvalidTruthTableError – If truth table has invalid structure
Example
>>> bf.create([0, 1, 1, 0]) # From truth table >>> bf.create(lambda x: x[0] ^ x[1], n=2) # From function
- classmethod from_truth_table(boolean_function_cls, truth_table, rep_type='truth_table', **kwargs)[source]
Create from truth table data.
- Parameters:
boolean_function_cls – The BooleanFunction class to instantiate
truth_table – List or array of boolean values (length must be power of 2)
rep_type – Representation type name (default “truth_table”)
**kwargs – Additional arguments
- Returns:
BooleanFunction instance
- Raises:
InvalidTruthTableError – If truth table size is not a power of 2
- classmethod from_function(boolean_function_cls, func, rep_type='function', domain_size=None, **kwargs)[source]
Create from callable function
- classmethod from_scipy_distribution(boolean_function_cls, distribution, rep_type='distribution', **kwargs)[source]
Create from scipy.stats distribution
- classmethod from_polynomial(boolean_function_cls, coeffs, rep_type='polynomial', **kwargs)[source]
Create from polynomial coefficients
- classmethod from_multilinear(boolean_function_cls, coeffs, rep_type='fourier_expansion', **kwargs)[source]
Create from multilinear polynomial coefficients
- classmethod from_iterable(boolean_function_cls, data, rep_type='iterable_rep', **kwargs)[source]
Create from streaming truth table
- classmethod from_symbolic(boolean_function_cls, expression, rep_type='symbolic', **kwargs)[source]
Create from symbolic expression string
- classmethod from_input_invariant_truth_table(boolean_function_cls, true_inputs, rep_type='truth_table', **kwargs)[source]
Create from set of true input vectors
- classmethod create_composite(boolean_function_cls, operator, left_func, right_func, rep_type='symbolic', **kwargs)[source]
Create composite function from BooleanFunctions or scalars.
Prefers truth-table composition when both operands are BooleanFunction instances on the same domain/space, while still recording the symbolic expression for readability. Falls back to symbolic-only composition when truth tables are unavailable (e.g., mixing scalars or mismatched domains).
- classmethod compose_truth_tables(boolean_function_cls, outer_func, inner_func, rep_type: str = 'truth_table', **kwargs)[source]
Compose two BooleanFunction instances via truth tables.
Mirrors the legacy
BooleanFunc.composesemantics: ifouterhasnvariables andinnerhasmvariables, the result is a function onn * mvariables obtained by feeding disjoint copies ofinnerinto each input ofouter.
- classmethod from_dnf(boolean_function_cls, dnf_formula, rep_type='dnf', **kwargs)[source]
Create from DNF (Disjunctive Normal Form) formula.
- Parameters:
boolean_function_cls – The BooleanFunction class to instantiate
dnf_formula – A DNFFormula object
rep_type – Representation type (default “dnf”)
**kwargs – Additional arguments (n_vars, space, etc.)
- Returns:
BooleanFunction instance
- classmethod from_cnf(boolean_function_cls, cnf_formula, rep_type='cnf', **kwargs)[source]
Create from CNF (Conjunctive Normal Form) formula.
- Parameters:
boolean_function_cls – The BooleanFunction class to instantiate
cnf_formula – A CNFFormula object
rep_type – Representation type (default “cnf”)
**kwargs – Additional arguments (n_vars, space, etc.)
- Returns:
BooleanFunction instance
- classmethod from_file(boolean_function_cls, path, **kwargs)[source]
Create from file (JSON, .bf, or DIMACS CNF).
- Parameters:
boolean_function_cls – The BooleanFunction class to instantiate
path – Path to file (str or Path object)
**kwargs – Additional arguments passed to the loader
- Returns:
BooleanFunction instance
Example
>>> bf.create("function.json") >>> bf.create("function.bf") >>> bf.create("function.cnf")
- class boofun.core.BooleanFunctionRepresentation[source]
Abstract base class for all Boolean function representations
- abstractmethod evaluate(inputs: ndarray, data: Any, space: Space, n_vars: int) ndarray[source]
Evaluate the function on given inputs using the provided data.
- Parameters:
inputs – Input values (binary array or boolean values)
data – Representation-specific data (coefficients, truth table, etc.)
- Returns:
Boolean result or array of results
- abstractmethod dump(data: DataType, space: Space = None, **kwargs) Dict[str, Any][source]
Export the representation data in a serializable format.
- Parameters:
data – The representation data to export
space – Optional space specification (some representations need this)
**kwargs – Representation-specific options
- Returns:
Dictionary containing the exported representation
- abstractmethod convert_from(source_repr: BooleanFunctionRepresentation, source_data: Any, space: Space, n_vars: int, **kwargs) ndarray[source]
Convert from another representation to this representation.
- Parameters:
source_repr – Source representation strategy
source_data – Data in source format
**kwargs – Conversion options
- Returns:
Data in this representation’s format
- abstractmethod convert_to(target_repr: BooleanFunctionRepresentation, source_data: Any, space: Space, n_vars: int, **kwargs) ndarray[source]
Convert from this representation to target representation.
- Parameters:
target_repr – Target representation strategy
data – Data in this representation’s format
**kwargs – Conversion options
- Returns:
Data in target representation’s format
- abstractmethod create_empty(n_vars: int, **kwargs) DataType[source]
Create empty representation data structure for n variables.
- abstractmethod is_complete(data: DataType) bool[source]
Check if the representation contains complete information.
- class boofun.core.LegacyAdapter(evaluation_method: str = 'evaluate', input_format: str = 'auto', output_format: str = 'auto', n_vars: int | None = None)[source]
Adapter for legacy Boolean function implementations.
Wraps legacy functions that may have different interfaces to work with the modern BooFun system.
- __init__(evaluation_method: str = 'evaluate', input_format: str = 'auto', output_format: str = 'auto', n_vars: int | None = None)[source]
Initialize legacy adapter.
- Parameters:
evaluation_method – Name of evaluation method in legacy function
input_format – Expected input format (“binary”, “integer”, “auto”)
output_format – Expected output format (“boolean”, “integer”, “auto”)
n_vars – Number of variables if known
- adapt(legacy_function: Any) BooleanFunction[source]
Adapt legacy function to BooFun interface.
- class boofun.core.ErrorModel[source]
Abstract base class for all error models.
- abstractmethod apply_error(result: Any) Any[source]
Apply error model to a computation result.
- Parameters:
result – The original computation result
- Returns:
Result with error model applied
- class boofun.core.PACErrorModel(epsilon: float = 0.1, delta: float = 0.1)[source]
PAC (Probably Approximately Correct) error model.
Provides probabilistic guarantees with specified error and confidence bounds.
- __init__(epsilon: float = 0.1, delta: float = 0.1)[source]
Initialize PAC error model.
- Parameters:
epsilon – Approximation error bound (0 < epsilon < 1)
delta – Confidence failure probability (0 < delta < 1)
- apply_error(result: Any) Dict[str, Any][source]
Apply PAC bounds to result.
- Returns:
Dictionary with result and PAC bounds
- combine_pac_bounds(error1: PACErrorModel, error2: PACErrorModel, operation: str) PACErrorModel[source]
Combine PAC learning error bounds for two results.
- Parameters:
error1 – PAC error models to combine
error2 – PAC error models to combine
operation – Type of operation (‘addition’, ‘multiplication’, etc.)
- Returns:
Combined PAC error model
- class boofun.core.ExactErrorModel[source]
Exact error model - no errors or uncertainty.
This model assumes perfect computation with no noise or approximation.
- class boofun.core.NoiseErrorModel(noise_rate: float = 0.01, random_seed: int | None = None)[source]
Noise error model for handling bit-flip and measurement errors.
Simulates realistic noise in Boolean function evaluation and analysis.
- __init__(noise_rate: float = 0.01, random_seed: int | None = None)[source]
Initialize noise error model.
- Parameters:
noise_rate – Probability of bit flip (0 <= noise_rate <= 0.5)
random_seed – Random seed for reproducible noise
- class boofun.core.LinearErrorModel[source]
Linear error propagation model using uncertainties library.
Provides automatic differentiation-based error propagation.
- apply_error(result: Any, std_dev: float = 0.01) Any[source]
Apply linear error propagation.
- Parameters:
result – Computation result
std_dev – Standard deviation of error
- Returns:
Result with uncertainty information
- propagate_binary_op(left_error: Any, right_error: Any, operation: callable) Any[source]
Automatic error propagation for binary operations.
- Parameters:
left_error – Left operand with uncertainty
right_error – Right operand with uncertainty
operation – Operation function
- Returns:
Result with propagated uncertainty
- class boofun.core.Space(value)[source]
- BOOLEAN_CUBE = 1
- PLUS_MINUS_CUBE = 2
- REAL = 3
- LOG = 4
- GAUSSIAN = 5
- static translate(input: int | float | ndarray, source_space: Space, target_space: Space) int | float | ndarray[source]
Translate a scalar or array from one space to another.
- Parameters:
input – Input value(s) to translate
source_space – Source mathematical space
target_space – Target mathematical space
- Returns:
Translated value(s) in target space
Examples
>>> Space.translate([0, 1], Space.BOOLEAN_CUBE, Space.PLUS_MINUS_CUBE) array([-1, 1]) >>> Space.translate([-1, 1], Space.PLUS_MINUS_CUBE, Space.BOOLEAN_CUBE) array([0, 1])
- class boofun.core.QueryModel(f: BooleanFunction, max_queries: int = 10000000)[source]
Manages query complexity and safety for Boolean function operations.
This class helps users understand and control the computational cost of operations on their functions.
Example
>>> f = bf.create(my_function, n=30) >>> qm = QueryModel(f) >>> qm.can_compute("fourier") False >>> qm.can_compute("is_linear", num_queries=100) True >>> qm.estimate_cost("influences") {'queries': 32212254720, 'feasible': False}
- __init__(f: BooleanFunction, max_queries: int = 10000000)[source]
Initialize query model for a function.
- Parameters:
f – BooleanFunction to analyze
max_queries – Maximum acceptable query count
- estimate_cost(operation: str, num_queries: int = 100) Dict[str, Any][source]
Estimate computational cost of an operation.
- Returns:
queries: Estimated number of function evaluations
feasible: Whether this is computationally reasonable
time_estimate: Rough time estimate (assuming 1µs per query)
description: Human-readable description
- Return type:
Dict with keys
- class boofun.core.AccessType(value)[source]
How can we access the function’s values?
- EXPLICIT = 1
- QUERY = 2
- STREAMING = 3
- SYMBOLIC = 4
- boofun.core.get_access_type(f: BooleanFunction) AccessType[source]
Determine how the function’s values can be accessed.
- Parameters:
f – BooleanFunction to check
- Returns:
AccessType indicating safest access pattern
- boofun.core.check_query_safety(f: BooleanFunction, operation: str, max_safe_n: int = 20, num_queries: int = 100, strict: bool = False) bool[source]
Check if an operation is safe to perform on this function.
- Parameters:
f – BooleanFunction to check
operation – Name of operation (e.g., “fourier”, “is_linear”)
max_safe_n – Maximum n for which we allow unsafe operations
num_queries – Number of queries for safe operations
strict – If True, raise error instead of warning
- Returns:
True if operation is safe to proceed
- Raises:
ExplicitEnumerationError – If strict=True and operation is unsafe
Example
>>> f = bf.create(huge_function, n=100) >>> check_query_safety(f, "fourier") # Returns False, warns >>> check_query_safety(f, "is_linear") # Returns True
- exception boofun.core.QuerySafetyWarning[source]
Warning when an operation may be unsafe for query-access functions.
- exception boofun.core.ExplicitEnumerationError[source]
Raised when trying to enumerate a query-access function.
This protects users from accidentally trying to compute 2^n evaluations on a huge function.
- boofun.core.load(path: str | Path, format: str | None = None, **kwargs) BooleanFunction[source]
Load a Boolean function from file.
- Parameters:
path – Path to the file
format – Optional format override (“json”, “bf”, “dimacs_cnf”)
**kwargs – Format-specific options
- Returns:
BooleanFunction instance
- Raises:
FileIOError – If file cannot be loaded
FileNotFoundError – If file does not exist
- boofun.core.save(func: BooleanFunction, path: str | Path, format: str | None = None, **kwargs) None[source]
Save a Boolean function to file.
- Parameters:
func – BooleanFunction to save
path – Destination path
format – Optional format override (“json”, “bf”, “dimacs_cnf”)
**kwargs – Format-specific options
- Raises:
FileIOError – If file cannot be saved
- boofun.core.load_json(path: str | Path, **kwargs) BooleanFunction[source]
Load Boolean function from JSON file.
JSON format stores the full representation including metadata.
- Parameters:
path – Path to JSON file
- Returns:
BooleanFunction instance
- boofun.core.save_json(func: BooleanFunction, path: str | Path, representation: str = 'truth_table', pretty: bool = True, **kwargs) None[source]
Save Boolean function to JSON file.
- Parameters:
func – BooleanFunction to save
path – Destination path
representation – Which representation to save
pretty – Whether to format with indentation
- boofun.core.load_bf(path: str | Path, **kwargs) BooleanFunction[source]
Load Boolean function from .bf file (Aaronson format).
- Format:
n (number of variables) 00…0 v₀ (optional input string, then output value) 00…1 v₁ … 11…1 v_{2^n-1}
Values can be 0, 1, or -1 (partial function, undefined).
- Parameters:
path – Path to .bf file
- Returns:
BooleanFunction instance
- boofun.core.save_bf(func: BooleanFunction, path: str | Path, include_inputs: bool = True, **kwargs) None[source]
Save Boolean function to .bf file (Aaronson format).
- Parameters:
func – BooleanFunction to save
path – Destination path
include_inputs – Whether to include input bit strings
- boofun.core.load_dimacs_cnf(path: str | Path, **kwargs) BooleanFunction[source]
Load Boolean function from DIMACS CNF file.
- DIMACS CNF is the standard format for SAT solvers:
c comment line p cnf <n_vars> <n_clauses> 1 -2 3 0 (clause: x1 OR NOT x2 OR x3) -1 2 0 (clause: NOT x1 OR x2) …
Positive integers are positive literals, negative are negated. Each clause ends with 0.
- Parameters:
path – Path to .cnf file
- Returns:
BooleanFunction with CNF representation
- boofun.core.save_dimacs_cnf(func: BooleanFunction, path: str | Path, comment: str | None = None, **kwargs) None[source]
Save Boolean function to DIMACS CNF file.
Note: Converts function to CNF if not already in that representation.
- Parameters:
func – BooleanFunction to save
path – Destination path
comment – Optional comment to include
- boofun.core.detect_format(path: str | Path) str[source]
Detect file format from extension or content.
- Parameters:
path – Path to the file
- Returns:
“json”, “bf”, or “dimacs_cnf”
- Return type:
Format string
- Raises:
FileIOError – If format cannot be detected
- exception boofun.core.FileIOError(message: str, path: str | None = None, **kwargs)[source]
Error during file I/O operations.
Modules
Adapters for integrating legacy Boolean function implementations and external libraries. |
|
Automatic representation selection for Boolean functions. |
|
Comprehensive batch processing infrastructure for Boolean function operations. |
|
Lazy conversion graph system for Boolean function representations. |
|
Error models for Boolean function analysis. |
|
GPU Acceleration for Boolean Function Operations. |
|
GPU acceleration infrastructure for Boolean function computations. |
|
File I/O for Boolean functions. |
|
Legacy adapter for converting old BooleanFunc objects to new BooleanFunction. |
|
Numba JIT optimizations for Boolean function operations. |
|
Performance Optimizations for BooFun |
|
Query Model for Boolean Functions. |
|