Full API
ConstraintCommons.USUAL_CONSTRAINT_PARAMETERS Constant
const USUAL_CONSTRAINT_PARAMETERS
List of usual constraints parameters (based on XCSP3-core
constraints). The list is based on the nature of each kind of parameter instead of the keywords used in the XCSP3-core
format.
const USUAL_CONSTRAINT_PARAMETERS = [
:bool, # boolean parameter
:dim, # dimension, an integer parameter used along the pair_vars or vals parameters
:id, # index to target one variable in the input vector
:language, # describe a regular language such as an automaton or a MDD
:op, # an operator such as comparison or arithmetic operator
:pair_vars, # a list of parameters that are paired with each variable in the input vector
:val, # one scalar value
:vals, # a list of scalar values (independent of the input vector size)
]
ConstraintCommons.AbstractAutomaton Type
AbstractAutomaton
An abstract interface for automata used in Julia Constraints packages. Requirements:
accept(a<:AbstractAutomaton, word)
: returntrue
ifa
acceptsword
.
ConstraintCommons.AbstractMultivaluedDecisionDiagram Type
AbstractMultivaluedDecisionDiagram
An abstract interface for Multivalued Decision Diagrams (MDD) used in Julia Constraints packages. Requirements:
accept(a<:AbstractMultivaluedDecisionDiagram, word)
: returntrue
ifa
acceptsword
.
ConstraintCommons.Automaton Type
Automaton{S, T, F <: Union{S, Vector{S}, Set{S}}} <: AbstractAutomaton
A minimal implementation of a deterministic automaton structure.
ConstraintCommons.MDD Type
MDD{S,T} <: AbstractMultivaluedDecisionDiagram
A minimal implementation of a multivalued decision diagram structure.
ConstraintCommons.accept Method
accept(a::Union{Automaton, MDD}, w)
Return true
if a
accepts the word w
and false
otherwise.
ConstraintCommons.at_end Method
at_end(a::Automaton, s)
Internal method used by accept
with Automaton
.
ConstraintCommons.consin Method
consin(::Any, ::Nothing)
Extends Base.in
(or ∈
) when the set is nothing
. Returns false
.
ConstraintCommons.consisempty Method
consisempty(::Nothing)
Extends Base.isempty
when the set is nothing
. Returns true
.
ConstraintCommons.extract_parameters Method
extract_parameters(m::Union{Method, Function}; parameters)
Extracts the intersection between the kargs
of m
and parameters
(defaults to USUAL_CONSTRAINT_PARAMETERS
).
ConstraintCommons.incsert! Function
incsert!(d::Union{AbstractDict, AbstractDictionary}, ind, val = 1)
Increase or insert a counter in a dictionary-based collection. The counter insertion defaults to val = 1
.
ConstraintCommons.oversample Method
oversample(X, f)
Oversample elements of X
until the boolean function f
has as many true
and false
configurations.
ConstraintCommons.symcon Function
symcon(s1::Symbol, s2::Symbol, connector::AbstractString="_")
Extends *
to Symbol
s multiplication by connecting the symbols by an _
.
ConstraintCommons.δ_extrema Method
δ_extrema(X...)
Compute both the difference between the maximum and the minimum of over all the collections of X
.
ConstraintDomains.AbstractDomain Type
AbstractDomain
An abstract super type for any domain type. A domain type D <: AbstractDomain
must implement the following methods to properly interface AbstractDomain
.
Base.∈(val, ::D)
Base.rand(::D)
Base.length(::D)
that is the number of elements in a discrete domain, and the distance between bounds or similar for a continuous domain
Additionally, if the domain is used in a dynamic context, it can extend
add!(::D, args)
delete!(::D, args)
where args
depends on D
's structure
ConstraintDomains.BoolParameterDomain Type
BoolParameterDomain <: AbstractDomain
A domain to store boolean values. It is used to generate random parameters.
ConstraintDomains.ContinuousDomain Type
ContinuousDomain{T <: Real} <: AbstractDomain
An abstract supertype for all continuous domains.
ConstraintDomains.DimParameterDomain Type
DimParameterDomain <: AbstractDomain
A domain to store dimensions. It is used to generate random parameters.
ConstraintDomains.DiscreteDomain Type
DiscreteDomain{T <: Number} <: AbstractDomain
An abstract supertype for discrete domains (set, range).
ConstraintDomains.ExploreSettings Method
ExploreSettings(
domains;
complete_search_limit = 10^6,
max_samplings = sum(domain_size, domains),
search = :flexible,
solutions_limit = floor(Int, sqrt(max_samplings)),
)
Create settings for the exploration of a search space composed by a collection of domains.
Arguments
domains
: A collection of domains representing the search space.complete_search_limit
: Maximum size of the search space for complete search.max_samplings
: Maximum number of samples to take during partial search.search
: Search strategy (:flexible
,:complete
, or:partial
).solutions_limit
: Maximum number of solutions to store.
Returns
An ExploreSettings
object.
Example
domains = [domain([1, 2, 3]), domain([4, 5, 6])]
settings = ExploreSettings(domains, search = :complete)
ConstraintDomains.Explorer Type
Explorer(concepts, domains, objective = nothing; settings = ExploreSettings(domains))
Create an Explorer object for searching a constraint satisfaction problem space.
Arguments
concepts
: A collection of tuples, each containing a concept function and its associated variable indices.domains
: A collection of domains representing the search space.objective
: An optional objective function for optimization problems.settings
: AnExploreSettings
object to configure the exploration process.
Returns
An Explorer
object ready for exploration.
Example
domains = [domain([1, 2, 3]), domain([4, 5, 6])]
concepts = [(sum, [1, 2])]
objective = x -> x[1] + x[2]
explorer = Explorer(concepts, domains, objective)
ConstraintDomains.FakeAutomaton Type
FakeAutomaton{T} <: ConstraintCommons.AbstractAutomaton
A structure to generate pseudo automaton enough for parameter exploration.
ConstraintDomains.IdParameterDomain Type
IdParameterDomain <: AbstractDomain
A domain to store ids. It is used to generate random parameters.
ConstraintDomains.Intervals Type
Intervals{T <: Real} <: ContinuousDomain{T}
An encapsuler to store a vector of PatternFolds.Interval
. Dynamic changes to Intervals
are not handled yet.
ConstraintDomains.LanguageParameterDomain Type
LanguageParameterDomain <: AbstractDomain
A domain to store languages. It is used to generate random parameters.
ConstraintDomains.OpParameterDomain Type
OpParameterDomain{T} <: AbstractDomain
A domain to store operators. It is used to generate random parameters.
ConstraintDomains.PairVarsParameterDomain Type
PairVarsParameterDomain{T} <: AbstractDomain
A domain to store values paired with variables. It is used to generate random parameters.
ConstraintDomains.RangeDomain Type
RangeDomain
A discrete domain defined by a range <: AbstractRange{Real}
. As ranges are immutable in Julia, changes in RangeDomain
must use set_domain!
.
ConstraintDomains.SetDomain Type
SetDomain{T <: Number} <: DiscreteDomain{T}
Domain that stores discrete values as a set of (unordered) points.
ConstraintDomains.ValParameterDomain Type
ValParameterDomain{T} <: AbstractDomain
A domain to store one value. It is used to generate random parameters.
ConstraintDomains.ValsParameterDomain Type
ValsParameterDomain{T} <: AbstractDomain
A domain to store values. It is used to generate random parameters.
Base.convert Method
Base.convert(::Type{Union{Intervals, RangeDomain}}, d::Union{Intervals, RangeDomain})
Extends Base.convert
for domains.
Base.delete! Method
Base.delete!(d::SetDomain, value)(d::SetDomain, value)
Delete value
from the list of points in d
.
Base.in Method
Base.in(x, itv::Intervals)
Return true
if x ∈ I
for any 'I ∈ itv, false otherwise.
x ∈ I` is equivalent to
a < x < b
ifI = (a, b)
a < x ≤ b
ifI = (a, b]
a ≤ x < b
ifI = [a, b)
a ≤ x ≤ b
ifI = [a, b]
Base.in Method
Base.in(value, d <: AbstractDomain)
Fallback method for value ∈ d
that returns false
.
Base.in Method
Base.in(value, d::D) where D <: DiscreteDomain
Return true
if value
is a point of d
.
Base.isempty Method
Base.isempty(d <: AbstractDomain)
Fallback method for isempty(d)
that return length(d) == 0
which default to 0
.
Base.length Method
Base.length(itv::Intervals)
Return the sum of the length of each interval in itv
.
Base.push! Method
push!(explorer::Explorer, domain::AbstractDomain)
Add a new domain to the Explorer
object.
Arguments
explorer
: TheExplorer
object to modify.domain
: AnAbstractDomain
object to add to the search space.
Returns
The key (index) of the newly added domain.
Example
explorer = Explorer()
key = push!(explorer, domain([1, 2, 3]))
Base.push! Method
push!(explorer::Explorer, concept::Tuple{Function,Vector{Int}})
Add a new concept to the Explorer
object.
Arguments
explorer
: TheExplorer
object to modify.concept
: A tuple containing a concept function and its associated variable indices.
Returns
The key (index) of the newly added concept.
Example
explorer = Explorer()
key = push!(explorer, (sum, [1, 2]))
Base.rand Method
Base.rand(d::Union{Vector{D},Set{D}, D}) where {D<:AbstractDomain}
Extends Base.rand
to (a collection of) domains.
Base.rand Method
Base.rand(itv::Intervals)
Base.rand(itv::Intervals, i)
Return a random value from itv
, specifically from the i
th interval if i
is specified.
Base.string Method
Base.string(D::Vector{<:AbstractDomain})
Base.string(d<:AbstractDomain)
Extends the string
method to (a vector of) domains.
ConstraintCommons.accept Method
ConstraintCommons.accept(fa::FakeAutomaton, word)
Implement the accept
methods for FakeAutomaton
.
ConstraintDomains.ArbitraryDomain Method
ArbitraryDomain{T} <: DiscreteDomain{T}
A domain type that stores arbitrary values, possibly non numeric, of type T
.
ConstraintDomains._explore! Method
_explore(args...)
Internals of the explore!
function. Behavior is automatically adjusted on the kind of exploration: :flexible
, :complete
, :partial
.
ConstraintDomains.delete_concept! Method
delete_concept!(explorer::Explorer, key::Int)
Remove a concept from the Explorer
object by its key.
Arguments
explorer
: TheExplorer
object to modify.key
: The key (index) of the concept to remove.
Returns
Nothing. The Explorer
object is modified in-place.
Example
explorer = Explorer([(sum, [1, 2])], [domain([1, 2, 3])])
delete_concept!(explorer, 1)
ConstraintDomains.delete_domain! Method
delete_domain!(explorer::Explorer, key::Int)
Remove a domain from the Explorer
object by its key.
Arguments
explorer
: TheExplorer
object to modify.key
: The key (index) of the domain to remove.
Returns
Nothing. The Explorer
object is modified in-place.
Example
explorer = Explorer([], [domain([1, 2, 3])])
delete_domain!(explorer, 1)
ConstraintDomains.domain Method
domain(values)
domain(range::R) where {T <: Real, R <: AbstractRange{T}}
Construct either a SetDomain
or a RangeDomain
.
d1 = domain(1:5)
d2 = domain([53.69, 89.2, 0.12])
d3 = domain([2//3, 89//123])
d4 = domain(4.3)
d5 = domain(1,42,86.9)
ConstraintDomains.domain Method
domain(a::Tuple{T, Bool}, b::Tuple{T, Bool}) where {T <: Real}
domain(intervals::Vector{Tuple{Tuple{T, Bool},Tuple{T, Bool}}}) where {T <: Real}
Construct a domain of continuous interval(s).
ConstraintDomains.domain_size Method
domain_size(itv::Intervals)
Return the difference between the highest and lowest values in itv
.
ConstraintDomains.domain_size Method
domain_size(d <: AbstractDomain)
Fallback method for domain_size(d)
that return length(d)
.
ConstraintDomains.domain_size Method
domain_size(d::D) where D <: DiscreteDomain
Return the maximum distance between two points in d
.
ConstraintDomains.explore! Method
explore!(explorer::Explorer)
Perform exploration on the search space defined by the Explorer
object.
This function explores the search space according to the settings specified in the Explorer
object. It updates the Explorer
's state with found solutions and non-solutions.
Arguments
explorer
: AnExplorer
object containing the problem definition and exploration settings.
Returns
Nothing. The Explorer
's state is updated in-place.
Example
explorer = Explorer(concepts, domains)
explore!(explorer)
println("Solutions found: ", length(explorer.state.solutions))
ConstraintDomains.explore Method
explore(domains, concept; settings = ExploreSettings(domains), parameters...)
Explore a search space defined by domains and a concept.
Arguments
domains
: A collection of domains representing the search space.concept
: The concept function defining the constraint.settings
: AnExploreSettings
object to configure the exploration process.parameters
: Additional parameters to pass to the concept function.
Returns
A tuple containing two sets: (solutions, non_solutions).
Example
domains = [domain([1, 2, 3]), domain([4, 5, 6])]
solutions, non_solutions = explore(domains, allunique)
ConstraintDomains.generate_parameters Method
generate_parameters(d<:AbstractDomain, param)
Generates random parameters based on the domain d
and the kind of parameters param
.
ConstraintDomains.get_domain Method
get_domain(::AbstractDomain)
Access the internal structure of any domain type.
ConstraintDomains.intersect_domains! Method
intersect_domains!(is, i, new_itvls)
Compute the intersections of a domain with an interval and store the results in new_itvls
.
Arguments
is::IS
: a collection of intervals.i::I
: an interval.new_itvls::Vector{I}
: a vector to store the results.
ConstraintDomains.intersect_domains Method
intersect_domains(d₁, d₂)
Compute the intersections of two domains.
ConstraintDomains.merge_domains Method
merge_domains(d₁::AbstractDomain, d₂::AbstractDomain)
Merge two domains of same nature (discrete/contiuous).
ConstraintDomains.set! Method
set!(explorer::Explorer, objective::Function)
Set the objective function for the Explorer
object.
Arguments
explorer
: TheExplorer
object to modify.objective
: A function to use as the objective for optimization.
Returns
Nothing. The Explorer
object is modified in-place.
Example
explorer = Explorer()
set!(explorer, x -> sum(x))
ConstraintDomains.size Method
Base.size(i::I) where {I <: Interval}
Defines the size of an interval as its span
.
ConstraintDomains.to_domains Method
to_domains(args...)
Convert various arguments into valid domains format.
Constraints.USUAL_CONSTRAINTS Constant
USUAL_CONSTRAINTS::Dict
Dictionary that contains all the usual constraints defined in Constraint.jl. It is based on XCSP3-core specifications available at https://arxiv.org/abs/2009.00514
Adding a new constraint is as simple as defining a new function with the same name as the constraint and using the @usual
macro to define it. The macro will take care of adding the new constraint to the USUAL_CONSTRAINTS
dictionary.
Example
@usual concept_all_different(x; vals=nothing) = xcsp_all_different(list=x, except=vals)
Constraints.USUAL_SYMMETRIES Constant
USUAL_SYMMETRIES
A Dictionary that contains the function to apply for each symmetry to avoid searching a whole space.
Constraints.Constraint Type
Constraint
Parametric structure with the following fields.
concept
: a Boolean function that, given an assignmentx
, outputstrue
ifx
satisfies the constraint, andfalse
otherwise.error
: a positive function that works as preferences over invalid assignments. Return0.0
if the constraint is satisfied, and a strictly positive real otherwise.
ConstraintCommons.extract_parameters Function
extract_parameters(s::Symbol, constraints_dict=USUAL_CONSTRAINTS; parameters=ConstraintCommons.USUAL_CONSTRAINT_PARAMETERS)
Return the parameters of the constraint s
in constraints_dict
.
Arguments
s::Symbol
: the constraint name.constraints_dict::Dict{Symbol,Constraint}
: dictionary of constraints. Default isUSUAL_CONSTRAINTS
.parameters::Vector{Symbol}
: vector of parameters. Default isConstraintCommons.USUAL_CONSTRAINT_PARAMETERS
.
Example
extract_parameters(:all_different)
Constraints.args Method
args(c::Constraint)
Return the expected length restriction of the arguments in a constraint c
. The value nothing
indicates that any strictly positive number of value is accepted.
Constraints.concept Method
concept(c::Constraint)
Return the concept (function) of constraint c
. concept(c::Constraint, x...; param = nothing) Apply the concept of c
to values x
and optionally param
.
Constraints.concept Method
concept(s::Symbol, args...; kargs...)
Return the concept of the constraint s
applied to args
and kargs
. This is a shortcut for concept(USUAL_CONSTRAINTS[s])(args...; kargs...)
.
Arguments
s::Symbol
: the constraint name.args...
: the arguments to apply the concept to.kargs...
: the keyword arguments to apply the concept to.
Example
concept(:all_different, [1, 2, 3])
Constraints.concept_vs_error Method
concept_vs_error(c, e, args...; kargs...)
Compare the results of a concept function and an error function for the same inputs. It is mainly used for testing purposes.
Arguments
c
: The concept function.e
: The error function.args...
: Positional arguments to be passed to both the concept and error functions.kargs...
: Keyword arguments to be passed to both the concept and error functions.
Returns
- Boolean: Returns true if the result of the concept function is not equal to whether the result of the error function is greater than 0.0. Otherwise, it returns false.
Examples
concept_vs_error(all_different, make_error(:all_different), [1, 2, 3]) # Returns false
Constraints.constraints_descriptions Function
constraints_descriptions(C=USUAL_CONSTRAINTS)
Return a pretty table with the descriptions of the constraints in C
.
Arguments
C::Dict{Symbol,Constraint}
: dictionary of constraints. Default isUSUAL_CONSTRAINTS
.
Example
constraints_descriptions()
Constraints.constraints_parameters Function
constraints_parameters(C=USUAL_CONSTRAINTS)
Return a pretty table with the parameters of the constraints in C
.
Arguments
C::Dict{Symbol,Constraint}
: dictionary of constraints. Default isUSUAL_CONSTRAINTS
.
Example
constraints_parameters()
Constraints.describe Function
describe(constraints::Dict{Symbol,Constraint}=USUAL_CONSTRAINTS; width=150)
Return a pretty table with the description of the constraints in constraints
.
Arguments
constraints::Dict{Symbol,Constraint}
: dictionary of constraints to describe. Default isUSUAL_CONSTRAINTS
.width::Int
: width of the table.
Example
describe()
Constraints.error_f Method
error_f(c::Constraint)
Return the error function of constraint c
. error_f(c::Constraint, x; param = nothing) Apply the error function of c
to values x
and optionally param
.
Constraints.make_error Method
make_error(symb::Symbol)
Create a function that returns an error based on the predicate of the constraint identified by the symbol provided.
Arguments
symb::Symbol
: The symbol used to determine the error function to be returned. The function first checks if a predicate with the prefix "icn_" exists in the Constraints module. If it does, it returns that function. If it doesn't, it checks for a predicate with the prefix "error_". If that exists, it returns that function. If neither exists, it returns a function that evaluates the predicate with the prefix "concept_" and returns the negation of its result cast to Float64.
Returns
- Function: A function that takes in a variable
x
and an arbitrary number of parametersparams
. The function returns a Float64.
Examples
e = make_error(:all_different)
e([1, 2, 3]) # Returns 0.0
e([1, 1, 3]) # Returns 1.0
Constraints.params_length Method
params_length(c::Constraint)
Return the expected length restriction of the arguments in a constraint c
. The value nothing
indicates that any strictly positive number of parameters is accepted.
Constraints.shrink_concept Method
shrink_concept(s)
Simply delete the concept_
part of symbol or string starting with it. TODO: add a check with a warning if s
starts with something different.
Constraints.xcsp_all_different Method
xcsp_all_different(list::Vector{Int})
Return true
if all the values of list
are different, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.
Variants
:all_different
: Global constraint ensuring that the values inx
are all different.
concept(:all_different, x; vals)
concept(:all_different)(x; vals)
Examples
c = concept(:all_different)
c([1, 2, 3, 4])
c([1, 2, 3, 1])
c([1, 0, 0, 4]; vals=[0])
c([1, 0, 0, 1]; vals=[0])
Constraints.xcsp_all_equal Method
xcsp_all_equal(list::Vector{Int}, val::Int)
Return true
if all the values of list
are equal to val
, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.val::Int
: value to compare to.
Variants
:all_equal
: Global constraint ensuring that the values inx
are all equal.
concept(:all_equal, x; val=nothing, pair_vars=zeros(x), op=+)
concept(:all_equal)(x; val=nothing, pair_vars=zeros(x), op=+)
Examples
c = concept(:all_equal)
c([0, 0, 0, 0])
c([1, 2, 3, 4])
c([3, 2, 1, 0]; pair_vars=[0, 1, 2, 3])
c([0, 1, 2, 3]; pair_vars=[0, 1, 2, 3])
c([1, 2, 3, 4]; op=/, val=1, pair_vars=[1, 2, 3, 4])
c([1, 2, 3, 4]; op=*, val=1, pair_vars=[1, 2, 3, 4])
Constraints.xcsp_cardinality Method
xcsp_cardinality(list, values, occurs, closed)
Return true
if the number of occurrences of the values in values
in list
satisfies the given condition, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.values::Vector{Int}
: list of values to check.occurs::Vector{Int}
: list of occurrences to check.closed::Bool
: whether the constraint is closed or not.
Variants
:cardinality
: Global constraint that restricts the number of times specific values in a listvalues
can appear inx
.
concept(:cardinality, x; bool=false, vals)
concept(:cardinality)(x; bool=false, vals)
:cardinality_closed
: Global constraint that restricts the number of times in a listvalues
can appear inx
. It is closed, meaning that the variables inx
cannot have values outside the ones inlist
.
concept(:cardinality_closed, x; vals)
concept(:cardinality_closed)(x; vals)
:cardinality_open
: Global constraint that restricts the number of times in a listvalues
can appear inx
. It is open, meaning that the variables inx
can have values outside the ones inlist
.
concept(:cardinality_open, x; vals)
concept(:cardinality_open)(x; vals)
Examples
c = concept(:cardinality)
c([2, 5, 10, 10]; vals=[2 0 1; 5 1 3; 10 2 3])
c([8, 5, 10, 10]; vals=[2 0 1; 5 1 3; 10 2 3], bool=false)
c([8, 5, 10, 10]; vals=[2 0 1; 5 1 3; 10 2 3], bool=true)
c([2, 5, 10, 10]; vals=[2 1; 5 1; 10 2])
c([2, 5, 10, 10]; vals=[2 0 1 42; 5 1 3 7; 10 2 3 -4])
c([2, 5, 5, 10]; vals=[2 0 1; 5 1 3; 10 2 3])
c([2, 5, 10, 8]; vals=[2 1; 5 1; 10 2])
c([5, 5, 5, 10]; vals=[2 0 1 42; 5 1 3 7; 10 2 3 -4])
cc = concept(:cardinality_closed)
cc([8, 5, 10, 10]; vals=[2 0 1; 5 1 3; 10 2 3])
co = concept(:cardinality_open)
co([8, 5, 10, 10]; vals=[2 0 1; 5 1 3; 10 2 3])
Constraints.xcsp_channel Method
xcsp_channel(; list)
Return true
if the channel constraint is satisfied, false
otherwise. The channel constraint ensures that if the i-th element of list
is assigned the value j, then the j-th element of list
must be assigned the value i.
Arguments
list::Union{AbstractVector, Tuple}
: list of values to check.
Variants
:channel
: Ensures that if the i-th element ofx
is assigned the value j, then the j-th element ofx
must be assigned the value i.
concept(:channel, x; dim=1, id=nothing)
concept(:channel)(x; dim=1, id=nothing)
Examples
c = concept(:channel)
c([2, 1, 4, 3])
c([1, 2, 3, 4])
c([2, 3, 1, 4])
c([2, 1, 5, 3, 4, 2, 1, 4, 5, 3]; dim=2)
c([2, 1, 4, 3, 5, 2, 1, 4, 5, 3]; dim=2)
c([false, false, true, false]; id=3)
c([false, false, true, false]; id=1)
Constraints.xcsp_circuit Method
xcsp_circuit(; list, size)
Return true
if the circuit constraint is satisfied, false
otherwise. The circuit constraint is a global constraint ensuring that the values of x
form a circuit, i.e., a sequence where each value is the index of the next value in the sequence, and the sequence eventually loops back to the start.
Arguments
list::AbstractVector
: list of values to check.size::Int
: size of the circuit.
Variants
:circuit
: Global constraint ensuring that the values ofx
form a circuit, i.e., a sequence where each value is the index of the next value in the sequence, and the sequence eventually loops back to the start. Often used for routing problems.
concept(:circuit, x; op, val)
concept(:circuit)(x; op, val)
Examples
c = concept(:circuit)
c([1, 2, 3, 4])
c([2, 3, 4, 1])
c([2, 3, 1, 4]; op = ==, val = 3)
c([4, 3, 1, 3]; op = >, val = 0)
Constraints.xcsp_count Method
xcsp_count(list, values, condition)
Return true
if the number of occurrences of the values in values
in list
satisfies the given condition, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.values::Vector{Int}
: list of values to check.condition
: condition to satisfy.
Variants
:count
: Constraint ensuring that the number of occurrences of the values invals
inx
satisfies the given condition.
concept(:count, x; vals, op, val)
concept(:count)(x; vals, op, val)
:at_least
: Constraint ensuring that the number of occurrences of the values invals
inx
is at leastval
.
concept(:at_least, x; vals, val)
concept(:at_least)(x; vals, val)
:at_most
: Constraint ensuring that the number of occurrences of the values invals
inx
is at mostval
.
concept(:at_most, x; vals, val)
concept(:at_most)(x; vals, val)
:exactly
: Constraint ensuring that the number of occurrences of the values invals
inx
is exactlyval
.
concept(:exactly, x; vals, val)
concept(:exactly)(x; vals, val)
Examples
c = concept(:count)
c([2, 1, 4, 3]; vals=[1, 2, 3, 4], op=≥, val=2)
c([1, 2, 3, 4]; vals=[1, 2], op==, val=2)
c([2, 1, 4, 3]; vals=[1, 2], op=≤, val=1)
Constraints.xcsp_cumulative Method
xcsp_cumulative(; origins, lengths, heights, condition)
Return true
if the cumulative constraint is satisfied, false
otherwise. The cumulative constraint is a global constraint operating on a set of tasks, defined by origin
(starting times), length
, and height
. This constraint ensures that, at each point in time, the sum of the height
of tasks that overlap that point, respects a numerical condition.
Arguments
origins::AbstractVector
: list of origins of the tasks.lengths::AbstractVector
: list of lengths of the tasks.heights::AbstractVector
: list of heights of the tasks.condition::Tuple
: condition to check.
Variants
:cumulative
: Global constraint operating on a set of tasks, defined byorigin
(starting times),length
, andheight
. This constraint ensures that, at each point in time, the sum of theheight
of tasks that overlap that point, respects a numerical condition.
concept(:cumulative, x; pair_vars, op, val)
concept(:cumulative)(x; pair_vars, op, val)
Examples
c = concept(:cumulative)
c([1, 2, 3, 4, 5]; val = 1)
c([1, 2, 2, 4, 5]; val = 1)
c([1, 2, 3, 4, 5]; pair_vars = [3 2 5 4 2; 1 2 1 1 3], op = ≤, val = 5)
c([1, 2, 3, 4, 5]; pair_vars = [3 2 5 4 2; 1 2 1 1 3], op = <, val = 5)
Constraints.xcsp_element Method
xcsp_element(; list, index, condition)
Return true
if the element constraint is satisfied, false
otherwise. The element constraint is a global constraint specifying that a variable in x
indexed by id
should be equal to a value
.
Arguments
list::Union{AbstractVector, Tuple}
: list of values to check.index::Int
: index of the value to check.condition::Tuple
: condition to check.
Variants
:element
: Global constraint specifying that a variable inx
indexed byid
should be equal to avalue
.
concept(:element, x; id=nothing, op===, val=nothing)
concept(:element)(x; id=nothing, op===, val=nothing)
Examples
c = concept(:element)
c([1, 2, 3, 4, 5]; id=1, val=1)
c([1, 2, 3, 4, 5]; id=1, val=2)
c([1, 2, 3, 4, 2])
c([1, 2, 3, 4, 1])
Constraints.xcsp_extension Method
xcsp_extension(; list, supports=nothing, conflicts=nothing)
Global constraint enforcing that x
matches a configuration within the supports set pair_vars[1]
or does not match any configuration within the conflicts set pair_vars[2]
. It embodies the logic: x ∈ pair_vars[1] || x ∉ pair_vars[2]
, providing a comprehensive way to define valid (supported) and invalid (conflicted) configurations for constraint satisfaction problems.
Arguments
list::Vector{Int}
: A list of variablessupports::Vector{Vector{Int}}
: A set of supported tuples. Default to nothing.conflicts::Vector{Vector{Int}}
: A set of conflicted tuples. Default to nothing.
Variants
:extension
: Global constraint enforcing thatx
matches a configuration within the supports setpair_vars[1]
or does not match any configuration within the conflicts setpair_vars[2]
. It embodies the logic:x ∈ pair_vars[1] || x ∉ pair_vars[2]
, providing a comprehensive way to define valid (supported) and invalid (conflicted) configurations for constraint satisfaction problems.
concept(:extension, x; pair_vars)
concept(:extension)(x; pair_vars)
:supports
: Global constraint ensuring thatx
matches a configuration listed within the support setpair_vars
. This constraint is derived from the extension model, specifying thatx
must be one of the explicitly defined supported configurations:x ∈ pair_vars
. It is utilized to directly declare the configurations that are valid and should be included in the solution space.
concept(:supports, x; pair_vars)
concept(:supports)(x; pair_vars)
:conflicts
: Global constraint ensuring thatx
does not match any configuration listed within the conflict setpair_vars
. This constraint, originating from the extension model, stipulates thatx
must avoid all configurations defined as conflicts:x ∉ pair_vars
. It is useful for specifying configurations that are explicitly forbidden and should be excluded from the solution space.
concept(:conflicts, x; pair_vars)
concept(:conflicts)(x; pair_vars)
Examples
c = concept(:extension)
c([1, 2, 3, 4, 5]; pair_vars=[[1, 2, 3, 4, 5]])
c([1, 2, 3, 4, 5]; pair_vars=([[1, 2, 3, 4, 5]], [[1, 2, 1, 4, 5], [1, 2, 3, 5, 5]]))
c([1, 2, 3, 4, 5]; pair_vars=[[1, 2, 1, 4, 5], [1, 2, 3, 5, 5]])
c = concept(:supports)
c([1, 2, 3, 4, 5]; pair_vars=[[1, 2, 3, 4, 5]])
c = concept(:conflicts)
c([1, 2, 3, 4, 5]; pair_vars=[[1, 2, 1, 4, 5], [1, 2, 3, 5, 5]])
Constraints.xcsp_instantiation Method
xcsp_instantiation(; list, values)
Return true
if the instantiation constraint is satisfied, false
otherwise. The instantiation constraint is a global constraint ensuring that x
takes on a specific set of values
in a specific order.
Arguments
list::AbstractVector
: list of values to check.values::AbstractVector
: list of values to check against.
Variants
:instantiation
: Global constraint ensuring thatx
takes on a specific set ofvalues
in a specific order.
concept(:instantiation, x; pair_vars)
concept(:instantiation)(x; pair_vars)
Examples
c = concept(:instantiation)
c([1, 2, 3, 4, 5]; pair_vars=[1, 2, 3, 4, 5])
c([1, 2, 3, 4, 5]; pair_vars=[1, 2, 3, 4, 6])
Constraints.xcsp_intension Method
xcsp_intension(list, predicate)
An intensional constraint is usually defined from a predicate
over list
. As such it encompass any generic constraint.
Arguments
list::Vector{Int}
: A list of variablespredicate::Function
: A predicate overlist
Variants
:dist_different
: Given a 4-dimensional vectorx
, ensures that the absolute difference betweenx[1]
andx[2]
, and betweenx[3]
andx[4]
, are different. This constraint is fundamental in ensuring the validity of a Golomb ruler, where no two pairs of marks should have the same distance between them.
concept(:dist_different, x)
concept(:dist_different)(x)
Examples
using Constraints # hide
c = concept(:dist_different)
c([1, 2, 3, 3]) && !c([1, 2, 3, 4])
Constraints.xcsp_maximum Method
xcsp_maximum(; list, condition)
Return true
if the maximum constraint is satisfied, false
otherwise. The maximum constraint is a global constraint specifying that a certain condition should hold for the maximum value in a list of variables.
Arguments
list::Union{AbstractVector, Tuple}
: list of values to check.condition::Tuple
: condition to check.
Variants
:maximum
: Global constraint ensuring that a certain numerical condition holds for the maximum value inx
.
concept(:maximum, x; op, val)
concept(:maximum)(x; op, val)
Examples
c = concept(:maximum)
c([1, 2, 3, 4, 5]; op = ==, val = 5)
c([1, 2, 3, 4, 5]; op = ==, val = 6)
Constraints.xcsp_mdd Method
xcsp_mdd(; list, diagram)
Return a function that checks if the list of values list
satisfies the MDD diagram
.
Arguments
list::Vector{Int}
: list of values to check.diagram::MDD
: MDD to check.
Variants
:mdd
: Multi-valued Decision Diagram (MDD) constraint.
The MDD constraint is a constraint that can be used to model a wide range of problems. It is a directed graph where each node is labeled with a value and each edge is labeled with a value. The constraint is satisfied if there is a path from the first node to the last node such that the sequence of edge labels is a valid sequence of the value labels.
concept(:mdd, x; language)
concept(:mdd)(x; language)
Examples
c = concept(:mdd)
states = [
Dict( # level x1
(:r, 0) => :n1,
(:r, 1) => :n2,
(:r, 2) => :n3,
),
Dict( # level x2
(:n1, 2) => :n4,
(:n2, 2) => :n4,
(:n3, 0) => :n5,
),
Dict( # level x3
(:n4, 0) => :t,
(:n5, 0) => :t,
),
]
a = MDD(states)
c([0,2,0]; language = a)
c([1,2,0]; language = a)
c([2,0,0]; language = a)
c([2,1,2]; language = a)
c([1,0,2]; language = a)
c([0,1,2]; language = a)
Constraints.xcsp_minimum Method
xcsp_minimum(; list, condition)
Return true
if the minimum constraint is satisfied, false
otherwise. The minimum constraint is a global constraint specifying that a certain condition should hold for the minimum value in a list of variables.
Arguments
list::Union{AbstractVector, Tuple}
: list of values to check.condition::Tuple
: condition to check.
Variants
:minimum
: Global constraint ensuring that a certain numerical condition holds for the minimum value inx
.
concept(:minimum, x; op, val)
concept(:minimum)(x; op, val)
Examples
c = concept(:minimum)
c([1, 2, 3, 4, 5]; op = ==, val = 1)
c([1, 2, 3, 4, 5]; op = ==, val = 0)
Constraints.xcsp_no_overlap Method
xcsp_no_overlap(; origins, lengths, zero_ignored)
Return true
if the no_overlap constraint is satisfied, false
otherwise. The no_overlap constraint is a global constraint used in constraint programming, often in scheduling problems. It ensures that tasks do not overlap in time, i.e., for any two tasks, either the first task finishes before the second task starts, or the second task finishes before the first task starts.
Arguments
origins::AbstractVector
: list of origins of the tasks.lengths::AbstractVector
: list of lengths of the tasks.zero_ignored::Bool
: whether to ignore zero-length tasks.
Variants
:no_overlap
: Global constraint operating on a set of tasks, defined byorigin
(starting times), andlength
. This constraint ensures that tasks do not overlap in time, i.e., for any two tasks, either the first task finishes before the second task starts, or the second task finishes before the first task starts. Often used in scheduling problems.
concept(:no_overlap, x; pair_vars, bool)
concept(:no_overlap)(x; pair_vars, bool)
:no_overlap_no_zero
: Global constraint operating on a set of tasks, defined byorigin
(starting times), andlength
. This constraint ensures that tasks do not overlap in time, i.e., for any two tasks, either the first task finishes before the second task starts, or the second task finishes before the first task starts. This variant ignores zero-length tasks. Often used in scheduling problems.
concept(:no_overlap_no_zero, x; pair_vars)
concept(:no_overlap_no_zero)(x; pair_vars)
:no_overlap_with_zero
: Global constraint operating on a set of tasks, defined byorigin
(starting times), andlength
. This constraint ensures that tasks do not overlap in time, i.e., for any two tasks, either the first task finishes before the second task starts, or the second task finishes before the first task starts. This variant includes zero-length tasks. Often used in scheduling problems.
concept(:no_overlap_with_zero, x; pair_vars)
concept(:no_overlap_with_zero)(x; pair_vars)
Examples
c = concept(:no_overlap)
c([1, 2, 3, 4, 5])
c([1, 2, 3, 4, 1])
c([1, 2, 4, 6, 3]; pair_vars = [1, 1, 1, 1, 1])
c([1, 2, 4, 6, 3]; pair_vars = [1, 1, 1, 3, 1])
c([1, 2, 4, 6, 3]; pair_vars = [1, 1, 3, 1, 1])
c([1, 1, 1, 3, 5, 2, 7, 7, 5, 12, 8, 7]; pair_vars = [2, 4, 1, 4 ,2 ,3, 5, 1, 2, 3, 3, 2], dim = 3)
c([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]; pair_vars = [2, 4, 1, 4 ,2 ,3, 5, 1, 2, 3, 3, 2], dim = 3)
Constraints.xcsp_nvalues Method
xcsp_nvalues(list, condition, except)
Return true
if the number of distinct values in list
satisfies the given condition, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.condition
: condition to satisfy.except::Union{Nothing, Vector{Int}}
: list of values to exclude. Default isnothing
.
Variants
:nvalues
: Ensures that the number of distinct values inx
satisfies a given numerical condition.
The constraint is defined by the following expression: nValues(x, op, val)
where x
is a list of variables, op
is a comparison operator, and val
is an integer value.
concept(:nvalues, x; op, val)
concept(:nvalues)(x; op, val)
Examples
c = concept(:nvalues)
c([1, 2, 3, 4, 5]; op = ==, val = 5)
c([1, 2, 3, 4, 5]; op = ==, val = 2)
c([1, 2, 3, 4, 3]; op = <=, val = 5)
c([1, 2, 3, 4, 3]; op = <=, val = 3)
Constraints.xcsp_ordered Method
xcsp_ordered(list::Vector{Int}, operator, lengths)
Return true
if all the values of list
are in an increasing order, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.operator
: comparison operator to use.lengths
: list of lengths to use. Defaults tonothing
.
Variants
:ordered
: Global constraint ensuring that all the values ofx
are in a total order defined by a comparison operator.
concept(:ordered, x; op=≤, pair_vars=nothing)
concept(:ordered)(x; op=≤, pair_vars=nothing)
:increasing
: Global constraint ensuring that all the values ofx
are in an increasing order.
concept(:increasing, x; op=≤, pair_vars=nothing)
concept(:increasing)(x; op=≤, pair_vars=nothing)
:decreasing
: Global constraint ensuring that all the values ofx
are in a decreasing order.
concept(:decreasing, x; op=≥, pair_vars=nothing)
concept(:decreasing)(x; op=≥, pair_vars=nothing)
:strictly_increasing
: Global constraint ensuring that all the values ofx
are in a strictly increasing order.
concept(:strictly_increasing, x; op=<, pair_vars=nothing)
concept(:strictly_increasing)(x; op=<, pair_vars=nothing)
:strictly_decreasing
: Global constraint ensuring that all the values ofx
are in a strictly decreasing order.
concept(:strictly_decreasing, x; op=>, pair_vars=nothing)
concept(:strictly_decreasing)(x; op=>, pair_vars=nothing)
Examples
c = concept(:ordered)
c([1, 2, 3, 4, 4]; op=≤)
c([1, 2, 3, 4, 5]; op=<)
!c([1, 2, 3, 4, 3]; op=≤)
!c([1, 2, 3, 4, 3]; op=<)
Constraints.xcsp_regular Method
xcsp_regular(; list, automaton)
Ensures that a sequence x
(interpreted as a word) is accepted by the regular language represented by a given automaton. This constraint verifies the compliance of x
with the language rules encoded within the automaton
parameter, which must be an instance of <:AbstractAutomaton
.
Arguments
list::Vector{Int}
: A list of variablesautomaton<:AbstractAutomaton
: An automaton representing the regular language
Variants
:regular
: Ensures that a sequencex
(interpreted as a word) is accepted by the regular language represented by a given automaton. This constraint verifies the compliance ofx
with the language rules encoded within theautomaton
parameter, which must be an instance of<:AbstractAutomaton
.
concept(:regular, x; language)
concept(:regular)(x; language)
Examples
c = concept(:regular)
states = Dict(
(:a, 0) => :a,
(:a, 1) => :b,
(:b, 1) => :c,
(:c, 0) => :d,
(:d, 0) => :d,
(:d, 1) => :e,
(:e, 0) => :e,
)
start = :a
finish = :e
a = Automaton(states, start, finish)
c([0,0,1,1,0,0,1,0,0]; language = a)
c([1,1,1,0,1]; language = a)
Constraints.xcsp_sum Method
xcsp_sum(list, coeffs, condition)
Return true
if the sum of the variables in list
satisfies the given condition, false
otherwise.
Arguments
list::Vector{Int}
: list of values to check.coeffs::Vector{Int}
: list of coefficients to use.condition
: condition to satisfy.
Variants
:sum
: Global constraint ensuring that the sum of the variables inx
satisfies a given numerical condition.
concept(:sum, x; op===, pair_vars=ones(x), val)
concept(:sum)(x; op===, pair_vars=ones(x), val)
Examples
c = concept(:sum)
c([1, 2, 3, 4, 5]; op===, val=15)
c([1, 2, 3, 4, 5]; op===, val=2)
c([1, 2, 3, 4, 3]; op=≤, val=15)
c([1, 2, 3, 4, 3]; op=≤, val=3)
Constraints.@usual Macro
usual(ex::Expr)
This macro is used to define a new constraint or update an existing one in the USUAL_CONSTRAINTS dictionary. It takes an expression ex as input, which represents the definition of a constraint.
Here's a step-by-step explanation of what the macro does:
It first extracts the symbol of the concept from the input expression. This symbol is expected to be the first argument of the first argument of the expression. For example, if the expression is @usual all_different(x; y=1), the symbol would be :all_different.
It then calls the shrink_concept function on the symbol to get a simplified version of the concept symbol.
It initializes a dictionary defaults to store whether each keyword argument of the concept has a default value or not.
It checks if the expression has more than two arguments. If it does, it means that there are keyword arguments present. It then loops over these keyword arguments. If a keyword argument is a symbol, it means it doesn't have a default value, so it adds an entry to the defaults dictionary with the keyword argument as the key and false as the value. If a keyword argument is not a symbol, it means it has a default value, so it adds an entry to the defaults dictionary with the keyword argument as the key and true as the value.
It calls the make_error function on the simplified concept symbol to generate an error function for the constraint.
It evaluates the input expression to get the concept function.
It checks if the USUAL_CONSTRAINTS dictionary already contains an entry for the simplified concept symbol. If it does, it adds the defaults dictionary to the parameters of the existing constraint. If it doesn't, it creates a new constraint with the concept function, a description, the error function, and the defaults dictionary as the parameters, and adds it to the USUAL_CONSTRAINTS dictionary.
This macro is used to make it easier to define and update constraints in a consistent and possibly automated way.
Arguments
ex::Expr
: expression to parse.
Example
@usual concept_all_different(x; vals=nothing) = xcsp_all_different(list=x, except=vals)
CompositionalNetworks.Composition Type
struct Composition{F<:Function}
Store the all the information of a composition learned by an ICN.
CompositionalNetworks.Composition Method
Composition(f::F, symbols) where {F<:Function}
Construct a Composition
.
CompositionalNetworks.ICN Type
ICN(; nvars, dom_size, param, transformation, arithmetic, aggregation, comparison)
Construct an Interpretable Compositional Network, with the following arguments:
nvars
: number of variable in the constraintdom_size: maximum domain size of any variable in the constraint
param
: optional parameter (default tonothing
)transformation
: a transformation layer (optional)arithmetic
: a arithmetic layer (optional)aggregation
: a aggregation layer (optional)comparison
: a comparison layer (optional)
CompositionalNetworks.Layer Type
Layer
A structure to store a LittleDict
of operations that can be selected during the learning phase of an ICN. If the layer is exclusive, only one operation can be selected at a time.
CompositionalNetworks._compose Method
_compose(icn)
Internal function called by compose
and show_composition
.
CompositionalNetworks.ag_count_positive Method
ag_count_positive(x)
Count the number of strictly positive elements of x
.
CompositionalNetworks.aggregation_layer Method
aggregation_layer()
Generate the layer of aggregations of the ICN. The operations are mutually exclusive, that is only one will be selected.
CompositionalNetworks.ar_prod Method
ar_prod(x)
Reduce k = length(x)
vectors through product to a single vector.
CompositionalNetworks.ar_sum Method
ar_sum(x)
Reduce k = length(x)
vectors through sum to a single vector.
CompositionalNetworks.arithmetic_layer Method
arithmetic_layer()
Generate the layer of arithmetic operations of the ICN. The operations are mutually exclusive, that is only one will be selected.
CompositionalNetworks.as_bitvector Function
as_bitvector(n::Int, max_n::Int = n)
Convert an Int to a BitVector of minimal size (relatively to max_n
).
CompositionalNetworks.co_abs_diff_var_val Method
co_abs_diff_var_val(x; val)
Return the absolute difference between x
and val
.
CompositionalNetworks.co_abs_diff_var_vars Method
co_abs_diff_var_vars(x; nvars)
Return the absolute difference between x
and the number of variables nvars
.
CompositionalNetworks.co_euclidean Method
co_euclidean(x; dom_size)
Compute an euclidean norm with domain size dom_size
of a scalar.
CompositionalNetworks.co_euclidean_val Method
co_euclidean_val(x; val, dom_size)
Compute an euclidean norm with domain size dom_size
, weighted by val
, of a scalar.
CompositionalNetworks.co_identity Method
co_identity(x)
Identity function. Already defined in Julia as identity
, specialized for scalars in the comparison
layer.
CompositionalNetworks.co_val_minus_var Method
co_val_minus_var(x; val)
Return the difference val - x
if positive, 0.0
otherwise.
CompositionalNetworks.co_var_minus_val Method
co_var_minus_val(x; val)
Return the difference x - val
if positive, 0.0
otherwise.
CompositionalNetworks.co_var_minus_vars Method
co_var_minus_vars(x; nvars)
Return the difference x - nvars
if positive, 0.0
otherwise, where nvars
denotes the numbers of variables.
CompositionalNetworks.co_vars_minus_var Method
co_vars_minus_var(x; nvars)
Return the difference nvars - x
if positive, 0.0
otherwise, where nvars
denotes the numbers of variables.
CompositionalNetworks.code Function
code(c::Composition, lang=:maths; name="composition")
Access the code of a composition c
in a given language lang
. The name of the generated method is optional.
CompositionalNetworks.comparison_layer Function
comparison_layer(param = false)
Generate the layer of transformations functions of the ICN. Iff param
value is set, also includes all the parametric comparison with that value. The operations are mutually exclusive, that is only one will be selected.
CompositionalNetworks.compose Function
compose(icn, weights=nothing)
Return a function composed by some of the operations of a given ICN. Can be applied to any vector of variables. If weights
are given, will assign to icn
.
CompositionalNetworks.compose_to_file! Method
compose_to_file!(concept, name, path; domains, param = nothing, language = :Julia, search = :complete, global_iter = 10, local_iter = 100, metric = hamming, popSize = 200)
Explore, learn and compose a function and write it to a file.
Arguments:
concept
: the concept to learnname
: the name to give to the constraintpath
: path of the output file
Keywords arguments:
domains
: domains that defines the search spaceparam
: an optional parameter of the constraintlanguage
: the language to export to, default to:julia
search
: either:partial
or:complete
searchglobal_iter
: number of learning iterationlocal_iter
: number of generation in the genetic algorithmmetric
: the metric to measure the distance between a configuration and known solutionspopSize
: size of the population in the genetic algorithm
CompositionalNetworks.composition Method
composition(c::Composition)
Access the actual method of an ICN composition c
.
CompositionalNetworks.composition_to_file! Function
composition_to_file!(c::Composition, path, name, language=:Julia)
Write the composition code in a given language
into a file at path
.
CompositionalNetworks.exclu Method
exclu(layer)
Return true
if the layer has mutually exclusive operations.
CompositionalNetworks.explore_learn_compose Method
explore_learn_compose(concept; domains, param = nothing, search = :complete, global_iter = 10, local_iter = 100, metric = hamming, popSize = 200, action = :composition)
Explore a search space, learn a composition from an ICN, and compose an error function.
Arguments:
concept
: the concept of the targeted constraintdomains
: domains of the variables that define the training spaceparam
: an optional parameter of the constraintsearch
: eitherflexible
,:partial
or:complete
search. Flexible search will usesearch_limit
andsolutions_limit
to determine if the search space needs to be partially or completely exploredglobal_iter
: number of learning iterationlocal_iter
: number of generation in the genetic algorithmmetric
: the metric to measure the distance between a configuration and known solutionspopSize
: size of the population in the genetic algorithmaction
: either:symbols
to have a description of the composition or:composition
to have the composed function itself
CompositionalNetworks.functions Method
functions(layer)
Access the operations of a layer. The container is ordered.
CompositionalNetworks.generate Method
generate(c::Composition, name, lang)
Generates the code of c
in a specific language lang
.
CompositionalNetworks.generate_exclusive_operation Method
generate_exclusive_operation(max_op_number)
Generates the operations (weights) of a layer with exclusive operations.
CompositionalNetworks.generate_inclusive_operations Method
generate_inclusive_operations(predicate, bits)
generate_exclusive_operation(max_op_number)
Generates the operations (weights) of a layer with inclusive/exclusive operations.
CompositionalNetworks.generate_weights Method
generate_weights(layers)
generate_weights(icn)
Generate the weights of a collection of layers or of an ICN.
CompositionalNetworks.hamming Method
hamming(x, X)
Compute the hamming distance of x
over a collection of solutions X
, i.e. the minimal number of variables to switch in x
to reach a solution.
CompositionalNetworks.is_viable Method
is_viable(layer, w)
is_viable(icn)
is_viable(icn, w)
Assert if a pair of layer/icn and weights compose a viable pattern. If no weights are given with an icn, it will check the current internal value.
CompositionalNetworks.lazy Method
lazy(funcs::Function...)
Generate methods extended to a vector instead of one of its components. A function f
should have the following signature: f(i::Int, x::V)
.
CompositionalNetworks.lazy_param Method
lazy_param(funcs::Function...)
Generate methods extended to a vector instead of one of its components. A function f
should have the following signature: f(i::Int, x::V; param)
.
CompositionalNetworks.learn_compose Method
learn_compose(;
nvars, dom_size, param=nothing, icn=ICN(nvars, dom_size, param),
X, X_sols, global_iter=100, local_iter=100, metric=hamming, popSize=200
)
Create an ICN, optimize it, and return its composition.
CompositionalNetworks.make_comparisons Method
make_comparisons(param::Symbol)
Generate the comparison functions for the given parameter.
CompositionalNetworks.make_transformations Method
make_transformations(param::Symbol)
Generates a dictionary of transformation functions based on the specified parameterization. This function facilitates the creation of parametric layers for constraint transformations, allowing for flexible and dynamic constraint manipulation according to the needs of different constraint programming models.
Parameters
param::Symbol
: Specifies the type of transformations to generate. It can be:none
for basic transformations that do not depend on external parameters, or:val
for transformations that operate with respect to a specific value parameter.
Returns
LittleDict{Symbol, Function}
: A dictionary mapping transformation names (Symbol
) to their corresponding functions (Function
). The functions encapsulate various types of transformations, such as counting, comparison, and contiguous value processing.
Transformation Types
When
param
is:none
, the following transformations are available::identity
: No transformation is applied.:count_eq
,:count_eq_left
,:count_eq_right
: Count equalities under different conditions.:count_greater
,:count_lesser
: Count values greater or lesser than a threshold.:count_g_left
,:count_l_left
,:count_g_right
,:count_l_right
: Count values with greater or lesser comparisons from different directions.:contiguous_vals_minus
,:contiguous_vals_minus_rev
: Process contiguous values with subtraction in normal and reverse order.
When
param
is:val
, the transformations relate to operations involving a parameter value::count_eq_param
,:count_l_param
,:count_g_param
: Count equalities or comparisons against a parameter value.:count_bounding_param
: Count values bounding a parameter value.:val_minus_param
,:param_minus_val
: Subtract a parameter value from values or vice versa.
The function delegates to a version that uses Val(param)
for dispatch, ensuring compile-time selection of the appropriate transformation set.
Examples
# Get basic transformations
basic_transforms = make_transformations(:none)
# Apply an identity transformation
identity_result = basic_transforms[:identity](data)
# Get value-based transformations
val_transforms = make_transformations(:val)
# Apply a count equal to parameter transformation
count_eq_param_result = val_transforms[:count_eq_param](data, param)
CompositionalNetworks.map_tr! Method
map_tr!(f, x, X, param)
Return an anonymous function that applies f
to all elements of x
and store the result in X
, with a parameter param
(which is set to nothing
for function with no parameter).
CompositionalNetworks.nbits Method
nbits(icn)
Return the expected number of bits of a viable weight of an ICN.
CompositionalNetworks.nbits_exclu Method
nbits_exclu(layer)
Convert the length of an exclusive layer into a number of bits.
CompositionalNetworks.reduce_symbols Function
reduce_symbols(symbols, sep)
Produce a formatted string that separates the symbols by sep
. Used internally for show_composition
.
CompositionalNetworks.regularization Method
regularization(icn)
Return the regularization value of an ICN weights, which is proportional to the normalized number of operations selected in the icn layers.
CompositionalNetworks.selected_size Method
selected_size(layer, layer_weights)
Return the number of operations selected by layer_weights
in layer
.
CompositionalNetworks.show_layer Method
show_layer(layer)
Return a string that contains the elements in a layer.
CompositionalNetworks.show_layers Method
show_layers(icn)
Return a formatted string with each layers in the icn.
CompositionalNetworks.symbol Method
symbol(layer, i)
Return the i-th symbols of the operations in a given layer.
CompositionalNetworks.symbols Method
symbols(c::Composition)
Output the composition as a layered collection of Symbol
s.
CompositionalNetworks.tr_contiguous_vars_minus Method
tr_contiguous_vars_minus(i, x)
tr_contiguous_vars_minus(x)
tr_contiguous_vars_minus(x, X::AbstractVector)
Return the difference x[i] - x[i + 1]
if positive, 0.0
otherwise. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_contiguous_vars_minus_rev Method
tr_contiguous_vars_minus_rev(i, x)
tr_contiguous_vars_minus_rev(x)
tr_contiguous_vars_minus_rev(x, X::AbstractVector)
Return the difference x[i + 1] - x[i]
if positive, 0.0
otherwise. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_bounding_val Method
tr_count_bounding_val(i, x; val)
tr_count_bounding_val(x; val)
tr_count_bounding_val(x, X::AbstractVector; val)
Count the number of elements bounded (not strictly) by x[i]
and x[i] + val
. An extended method to vector with sig (x, val)
is generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_eq Method
tr_count_eq(i, x)
tr_count_eq(x)
tr_count_eq(x, X::AbstractVector)
Count the number of elements equal to x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_eq_left Method
tr_count_eq_left(i, x)
tr_count_eq_left(x)
tr_count_eq_left(x, X::AbstractVector)
Count the number of elements to the left of and equal to x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_eq_right Method
tr_count_eq_right(i, x)
tr_count_eq_right(x)
tr_count_eq_right(x, X::AbstractVector)
Count the number of elements to the right of and equal to x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_eq_val Method
tr_count_eq_val(i, x; val)
tr_count_eq_val(x; val)
tr_count_eq_val(x, X::AbstractVector; val)
Count the number of elements equal to x[i] + val
. Extended method to vector with sig (x, val)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_g_left Method
tr_count_g_left(i, x)
tr_count_g_left(x)
tr_count_g_left(x, X::AbstractVector)
Count the number of elements to the left of and greater than x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_g_right Method
tr_count_g_right(i, x)
tr_count_g_right(x)
tr_count_g_right(x, X::AbstractVector)
Count the number of elements to the right of and greater than x[i]
. Extended method to vector with sig (x)
are generated.
CompositionalNetworks.tr_count_g_val Method
tr_count_g_val(i, x; val)
tr_count_g_val(x; val)
tr_count_g_val(x, X::AbstractVector; val)
Count the number of elements greater than x[i] + val
. Extended method to vector with sig (x, val)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_greater Method
tr_count_greater(i, x)
tr_count_greater(x)
tr_count_greater(x, X::AbstractVector)
Count the number of elements greater than x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_l_left Method
tr_count_l_left(i, x)
tr_count_l_left(x)
tr_count_l_left(x, X::AbstractVector)
Count the number of elements to the left of and lesser than x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_l_right Method
tr_count_l_right(i, x)
tr_count_l_right(x)
tr_count_l_right(x, X::AbstractVector)
Count the number of elements to the right of and lesser than x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_l_val Method
tr_count_l_val(i, x; val)
tr_count_l_val(x; val)
tr_count_l_val(x, X::AbstractVector; val)
Count the number of elements lesser than x[i] + val
. Extended method to vector with sig (x, val)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_count_lesser Method
tr_count_lesser(i, x)
tr_count_lesser(x)
tr_count_lesser(x, X::AbstractVector)
Count the number of elements lesser than x[i]
. Extended method to vector with sig (x)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_identity Method
tr_identity(i, x)
tr_identity(x)
tr_identity(x, X::AbstractVector)
Identity function. Already defined in Julia as identity
, specialized for vectors. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_in Function
tr_in(tr, X, x, param)
Application of an operation from the transformation layer. Used to generate more efficient code for all compositions.
CompositionalNetworks.tr_val_minus_var Method
tr_val_minus_var(i, x; val)
tr_val_minus_var(x; val)
tr_val_minus_var(x, X::AbstractVector; val)
Return the difference val - x[i]
if positive, 0.0
otherwise. Extended method to vector with sig (x, val)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.tr_var_minus_val Method
tr_var_minus_val(i, x; val)
tr_var_minus_val(x; val)
tr_var_minus_val(x, X::AbstractVector; val)
Return the difference x[i] - val
if positive, 0.0
otherwise. Extended method to vector with sig (x, val)
are generated. When X
is provided, the result is computed without allocations.
CompositionalNetworks.transformation_layer Function
transformation_layer(param = Vector{Symbol}())
Generate the layer of transformations functions of the ICN. Iff param
value is non empty, also includes all the related parametric transformations.
CompositionalNetworks.weights! Method
weights!(icn, weights)
Set the weights of an ICN with a BitVector
.
CompositionalNetworks.weights_bias Method
weights_bias(x)
A metric that bias x
towards operations with a lower bit. Do not affect the main metric.
QUBOConstraints.AbstractOptimizer Type
AbstractOptimizer
An abstract type (interface) used to learn QUBO matrices from constraints. Only a train
method is required.
QUBOConstraints.QUBO_base Function
QUBO_base(n, weight = 1)
A basic QUBO matrix to ensure that binarized variables keep a valid encoding.
QUBOConstraints.QUBO_linear_sum Method
QUBO_linear_sum(n, σ)
One valid QUBO matrix given n
variables and parameter σ
for the linear sum constraint.
QUBOConstraints.binarize Method
binarize(x[, domain]; binarization = :one_hot)
Binarize x
following the binarization
encoding. If x
is a vector (instead of a number per say), domain
is optional.
QUBOConstraints.debinarize Method
debinarize(x[, domain]; binarization = :one_hot)
Transform a binary vector into a number or a set of number. If domain
is not given, it will compute a default value based on binarization
and x
.
QUBOConstraints.is_valid Function
is_valid(x, encoding::Symbol = :none)
Check if x
has a valid format for encoding
.
For instance, if encoding == :one_hot
, at most one bit of x
can be set to 1.