licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
docs
255
# Solution Extension Similar to extending the entities Problem and Algorithm, the Solution entity can be extended by subclassing : ```@docs Sol{T,O} ``` A current implemented concrete solution type is: ```@docs QuantizedSystemSolver.LightSol{T,O} ```
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "MIT" ]
1.0.1
b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1
docs
7006
# Tutorial ## Solving a Nonlinear ODE Problem with NLodeProblem in Julia In this tutorial, we will go through the process of setting up, solving, querying, and plotting a nonlinear ordinary differential equation (ODE) problem using the NLodeProblem function. We will use a buck converter circuit model as an example. ## Step 1: Define the ODE Problem The first step is to define the ODE problem using the NLodeProblem function. We provide the function with user code that specifies the parameters, variables, and differential equations. Here is the example code for a buck converter circuit model with detailed explanations: ```julia odeprob = NLodeProblem(quote name = (buck,) # Define the name of the problem for identification # Parameters C = 1e-4 # Capacitance in farads L = 1e-4 # Inductance in henrys R = 10.0 # Resistance in ohms U = 24.0 # Input voltage in volts T = 1e-4 # Switching period in seconds DC = 0.5 # Duty cycle ROn = 1e-5 # On-state resistance of the switch in ohms ROff = 1e5 # Off-state resistance of the switch in ohms # Discrete and continuous variables discrete = [1e5, 1e-5, 1e-4, 0.0, 0.0] # Initial discrete states u = [0.0, 0.0] # Initial continuous states # Rename for convenience rd = discrete[1] # Diode resistance rs = discrete[2] # Switch resistance nextT = discrete[3] # Next switching time lastT = discrete[4] # Last switching time diodeon = discrete[5] # Diode state (on/off) il = u[1] # Inductor current uc = u[2] # Capacitor voltage # Helper equations id = (il * rs - U) / (rd + rs) # Diode current calculation # Differential equations du[1] = (-id * rd - uc) / L # Derivative of inductor current du[2] = (il - uc / R) / C # Derivative of capacitor voltage # Events if t - nextT > 0.0 lastT = nextT # Update last switching time nextT = nextT + T # Schedule next switching time rs = ROn # Set switch to on-state end if t - lastT - DC * T > 0.0 rs = ROff # Set switch to off-state end if diodeon * id + (1.0 - diodeon) * (id * rd - 0.6) > 0 rd = ROn # Diode is on diodeon = 1.0 else rd = ROff # Diode is off diodeon = 0.0 end end) ``` ### Explanation: Parameters: These are constants used in the model. C, L, R, U, T, DC, ROn, ROff are physical constants related to the buck converter circuit.\ Discrete and continuous variables: These represent the initial states of discrete and continuous variables in the model.\ Renaming variables: For convenience, the elements of discrete and u are renamed to more descriptive variable names (rd, rs, nextT, lastT, diodeon, il, uc).\ Helper equations: These are intermediate expressions needed for the differential equations. id is the current through the diode.\ Differential equations: These represent the system's dynamics. du[1] is the rate of change of the inductor current. du[2] is the rate of change of the capacitor voltage.\ Events: These are conditions that modify the continous and discrete variables. They handle the switching behavior of the buck converter and the diode's state transitions. ## Step 2: Solve the ODE Problem Next, we solve the ODE problem using the solve function. We need to specify the problem, the algorithm, and the simulation settings. ```julia # Define the time span for the simulation tspan = (0.0, 0.001) # Start at 0 seconds, end at 0.001 seconds # Solve the ODE problem with the chosen algorithm and settings sol = solve(odeprob, nmliqss2(), tspan, abstol=1e-4, reltol=1e-3) ``` ### Explanation: Time span: tspan defines the interval over which the solution is computed, from 0.0 to 0.001 seconds.\ Solver function: solve is used to compute the solution.\ odeprob is the ODE problem we defined.\ nmliqss2() specifies the algorithm used to solve the problem (e.g., qss2,nmliqss1... might be other algorithms).\ abstol and reltol are the absolute and relative tolerances for the solver, controlling the accuracy of the solution. ## Step 3: Query the Solution After solving the problem, we can query the solution to extract useful information such as variable values at specific times, the number of steps, events, and more. ```julia # Get the value of variable 2 at time 0.0005 value_at_time = sol(2, 0.0005) # Get the total number of steps to end the simulation total_steps = sol.totalSteps # Get the number of simultaneous steps during the simulation simul_step_count = sol.simulStepCount # Get the total number of events during the simulation event_count = sol.evCount # Get the saved times and variables saved_times = sol.savedTimes saved_vars = sol.savedVars # Print the results println("Value of variable 2 at time 0.0005: ", value_at_time) println("Total number of steps: ", total_steps) println("Number of simultaneous steps: ", simul_step_count) println("Total number of events: ", event_count) ``` ### Explanation: Value of variable 2 at a specific time: sol(2, 0.0005) returns the value of the second variable (capacitor voltage uc) at time 0.0005 seconds. Total steps: sol.totalSteps gives the total number of steps taken by the solver to reach the end of the simulation.\ Simultaneous steps: sol.simulStepCount provides the number of steps where simultaneous updates occurred.\ Total events: sol.evCount gives the total number of events (e.g., switch state changes) during the simulation.\ Saved times and variables: sol.savedTimes and sol.savedVars store the time points and corresponding variable values computed during the simulation. ## Step 4: Plot the Solution Finally, we can plot the solution to visualize the results. We have two options: generate a plot object for further customization or save the plot directly to a file. ``` julia # Generate a plot object for all variables of the solution plot_obj = plot_Sol(sol) # Generate a plot object for variable 1 of the solution plot_Sol(sol,1) # Display the plot display(plot_obj) #plot variables 1 and 2 of the solution plot_Sol(sol,1,2,note=" ",xlims=(0.0,1.0),ylims=(-0.5,0.5),legend=false) #plot the sum of variables 1 and 2 of the solution plot_SolSum(sol,1,2) # Save the plot to a file save_Sol(sol, note=" ",xlims=(0.0,1.0),ylims=(-0.5,0.5),legend=false) ``` ### Explanation: Generate plot object: plot_Sol(sol) creates a plot object from the solution data. Display the plot: display(plot_obj) shows the plot in the current environment. Save the plot: save_Sol(sol, ...) saves the plot to a file *.png. ![plot_buck_qss2](./assets/img/plot_buck_qss2.png) ## User Documentation More about the user documentation can be found in: ### [Application Programming Interface](@ref) ### [Available Algorithms](@ref)
QuantizedSystemSolver
https://github.com/mongibellili/QuantizedSystemSolver.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
951
using Documenter, PDDL makedocs( sitename="PDDL.jl", format=Documenter.HTML( prettyurls=get(ENV, "CI", nothing) == "true", canonical="https://juliaplanners.github.io/PDDL.jl/stable", description="Documentation for the PDDL.jl automated planning library.", assets = ["assets/logo.ico"], highlights=["lisp"] # Use Lisp highlighting as PDDL substitute ), pages=[ "PDDL.jl" => "index.md", "Tutorials" => [ "tutorials/getting_started.md", "tutorials/writing_planners.md", "tutorials/speeding_up.md" ], "Reference" => [ "ref/overview.md", "ref/datatypes.md", "ref/interface.md", "ref/parser_writer.md", "ref/interpreter.md", "ref/compiler.md", "ref/absint.md", "ref/extensions.md", "ref/utilities.md" ] ] ) deploydocs( repo = "github.com/JuliaPlanners/PDDL.jl.git", )
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2621
module PDDL using Base: @kwdef using AutoHashEquals using Julog using ValSplit using DocStringExtensions # Logical formulae and terms export Term, Compound, Var, Const, Clause # Abstract data types export Domain, Problem, State, Action # Generic concrete data types export GenericDomain, GenericProblem, GenericState, GenericAction # Interface methods export satisfy, satisfiers, evaluate export initstate, goalstate, transition, transition! export available, execute, execute!, relevant, regress, regress! # Parsing and writing export parse_domain, parse_problem, parse_pddl, @pddl, @pddl_str export write_domain, write_problem, write_pddl export load_domain, load_problem export save_domain, save_problem # Simulators export Simulator, EndStateSimulator, StateRecorder # Abstract interpretation export abstracted, abstractstate export AbstractedDomain # Domain compilation export compiled, compilestate export CompiledDomain, CompiledAction, CompiledState # Domain and action grounding export ground, groundargs, groundactions, groundaxioms export GroundDomain, GroundAction, GroundActionGroup # Domain and method caching export CachedDomain # Extension interfaces export attach!, register!, @register, @pddltheory # Analysis tools export infer_affected_fluents, infer_static_fluents, infer_relevant_fluents export infer_axiom_hierarchy # Utilities export effect_diff, precond_diff # PDDL requirement definitions and dependencies include("requirements.jl") # Abstract interface for PDDL-based planners and applications include("interface/interface.jl") # Generic concrete representations of PDDL types include("generic/generic.jl") # Parser for PDDL files and formulae include("parser/parser.jl") # Writer for PDDL files and formulae include("writer/writer.jl") using .Parser, .Writer # Simulators for executing action sequences and recording outputs include("simulators/simulators.jl") # Built-in functions and operators recognized by interpreters / compilers include("builtins.jl") # Methods for extending built-in functions and operators include("extensions.jl") # Abstractions for fluents of various types include("abstractions/abstractions.jl") # Theories for fluents with non-standard data types (e.g. sets, arrays) include("theories/theories.jl") # Interpreter-based interface implementation include("interpreter/interpreter.jl") # Compiler-based interface implementations include("compiler/compiler.jl") # Domain and action grounding include("grounding/grounding.jl") # Caching for interface methods include("caching/caching.jl") # Tools for analyzing domains include("analysis/analysis.jl") end # module
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
5347
# Built in operators, functions, and effects """ equiv(a, b) Equivalence in concrete and abstract domains. Defaults to `a == b`. """ equiv(a, b) = a == b """ nequiv(a, b) Non-equivalence in concrete and abstract domains. Defaults to `a != b`. """ nequiv(a, b) = a != b """ val_to_term(datatype::Symbol, val) val_to_term(val) Express `val` as a `Term` based on the `datatype`. Wraps in `Const` by default. If `datatype` is unspecified, it will be inferred. """ @valsplit val_to_term(Val(datatype::Symbol), val) = val_to_term(nothing, val) val_to_term(datatype::Nothing, val) = Const(val) val_to_term(val::T) where {T} = val_to_term(infer_datatype(T), val) """ $(SIGNATURES) Mapping from PDDL data types to Julia types and default values. """ @valsplit datatype_def(Val(name::Symbol)) = error("Unknown datatype: $name") datatype_def(::Val{:boolean}) = (type=Bool, default=false) datatype_def(::Val{:integer}) = (type=Int, default=0) datatype_def(::Val{:number}) = (type=Float64, default=1.0) datatype_def(::Val{:numeric}) = (type=Float64, default=1.0) """ $(SIGNATURES) Mapping from PDDL datatype to Julia type. """ datatype_typedef(name::Symbol) = datatype_def(name).type """ $(SIGNATURES) Mapping from PDDL datatype to default value. """ datatype_default(name::Symbol) = datatype_def(name).default """ $(SIGNATURES) Return list of global datatypes. """ global_datatype_names() = valarg_params(datatype_def, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return whether a symbol refers to global datatype. """ is_global_datatype(name::Symbol) = valarg_has_param(name, datatype_def, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return dictionary mapping global datatype names to implementations. """ function global_datatypes() names = global_datatype_names() types = Base.to_tuple_type(getindex.(datatype_def.(names), 1)) return _generate_dict(Val(names), Val(types)) end """ $(SIGNATURES) Infer PDDL datatype from Julia type. """ function infer_datatype(T::Type) inferred = nothing mintype = Any for (name, type) in global_datatypes() if T <: type <: mintype inferred = name mintype = type end end return inferred end infer_datatype(val::T) where {T} = infer_datatype(T) """ $(SIGNATURES) Mapping from PDDL built-in predicates to Julia functions. """ @valsplit predicate_def(Val(name::Symbol)) = error("Unknown predicate or function: $name") predicate_def(::Val{:(==)}) = equiv predicate_def(::Val{:<=}) = <= predicate_def(::Val{:>=}) = >= predicate_def(::Val{:<}) = < predicate_def(::Val{:>}) = > """ $(SIGNATURES) Return list of all global predicate names. """ global_predicate_names() = valarg_params(predicate_def, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return whether a symbol refers to global predicate. """ is_global_pred(name::Symbol) = valarg_has_param(name, predicate_def, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return dictionary mapping global predicate names to implementations. """ function global_predicates() names = global_predicate_names() defs = predicate_def.(names) return _generate_dict(Val(names), Val(defs)) end """ $(SIGNATURES) Mapping from PDDL built-in functions to Julia functions. """ @valsplit function_def(Val(name::Symbol)) = predicate_def(name) # All predicates are also functions function_def(::Val{:+}) = + function_def(::Val{:-}) = - function_def(::Val{:*}) = * function_def(::Val{:/}) = / """ $(SIGNATURES) Return list of all global function names. """ global_function_names() = (valarg_params(function_def, Tuple{Val}, Val(1), Symbol)..., valarg_params(predicate_def, Tuple{Val}, Val(1), Symbol)...) """ $(SIGNATURES) Return whether a symbol refers to global function. """ is_global_func(name::Symbol) = valarg_has_param(name, function_def, Tuple{Val}, Val(1), Symbol) || is_global_pred(name) """ $(SIGNATURES) Return dictionary mapping global function names to implementations. """ function global_functions() names = global_function_names() defs = function_def.(names) return _generate_dict(Val(names), Val(defs)) end """ $(SIGNATURES) Mapping from PDDL modifiers (i.e. in-place assignments) to PDDL functions. """ @valsplit modifier_def(Val(name::Symbol)) = error("Unknown modifier: $name") modifier_def(::Val{:increase}) = :+ modifier_def(::Val{:decrease}) = :- modifier_def(::Val{Symbol("scale-up")}) = :* modifier_def(::Val{Symbol("scale-down")}) = :/ """ $(SIGNATURES) Return list of all global modifier names. """ global_modifier_names() = valarg_params(modifier_def, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return whether a symbol refers to global modifier. """ is_global_modifier(name::Symbol) = valarg_has_param(name, modifier_def, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return dictionary mapping global modifier names to implementations. """ function global_modifiers() names = global_modifier_names() defs = modifier_def.(names) return _generate_dict(Val(names), Val(defs)) end "Helper function that generates dictionary at compile time." @generated function _generate_dict(keys::Val{Ks}, values::Val{Vs}) where {Ks, Vs} Vs = Vs isa Tuple ? Vs : Tuple(Vs.parameters) # Handle tuple types dict = Dict(zip(Ks, Vs)) return :($dict) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
5752
""" @register([:datatype|:predicate|:function|:modifier|:converter], name, x) Register `x` as a global datatype, predicate, function, modifier, or term converter under the specified `name`. """ macro register(category, name, x) return register_expr(category, name, x) end function register_expr(category::Symbol, name::Symbol, x) if category == :datatype fname = GlobalRef(@__MODULE__, :datatype_def) elseif category == :abstraction fname = GlobalRef(@__MODULE__, :default_abstype) elseif category == :predicate fname = GlobalRef(@__MODULE__, :predicate_def) elseif category == :function fname = GlobalRef(@__MODULE__, :function_def) elseif category == :modifier fname = GlobalRef(@__MODULE__, :modifier_def) elseif category == :converter return register_converter_expr(name, x) else error("Unrecognized category: $category.") end return :($fname(::Val{$(QuoteNode(name))}) = $(esc(x))) end register_expr(category::QuoteNode, name, x) = register_expr(category.value, name, x) register_expr(category::Symbol, name::QuoteNode, x) = register_expr(category, name.value, x) register_expr(category::Symbol, name::AbstractString, x) = register_expr(category, Symbol(name), x) function register_converter_expr(name::Symbol, f) _val_to_term = GlobalRef(@__MODULE__, :val_to_term) return :($_val_to_term(::Val{$(QuoteNode(name))}, val)= $(esc(f))(val)) end """ register!([:datatype|:predicate|:function|:modifier|:converter], name, x) Register `x` as a global datatype, predicate, function or modifier, or term converter under the specified `name`. !!! warning "Top-Level Only" Because `register!` defines new methods, it should only be called at the top-level in order to avoid world-age errors. !!! warning "Precompilation Not Supported" Because `register!` evaluates code in the `PDDL` module, it will lead to precompilation errors when used in another module. For this reason, the `@register` macro is preferred, and this function should only be used in scripting contexts. """ function register!(category::Symbol, name::Symbol, x) if category == :datatype fname = GlobalRef(@__MODULE__, :datatype_def) elseif category == :abstraction fname = GlobalRef(@__MODULE__, :default_abstype) elseif category == :predicate fname = GlobalRef(@__MODULE__, :predicate_def) elseif category == :function fname = GlobalRef(@__MODULE__, :function_def) elseif category == :modifier fname = GlobalRef(@__MODULE__, :modifier_def) elseif category == :converter return register_converter!(name, x) else error("Unrecognized category: $category.") end @eval $fname(::Val{$(QuoteNode(name))}) = $(QuoteNode(x)) end register!(category::Symbol, name::AbstractString, x) = register!(category, Symbol(name), x) function register_converter!(name::Symbol, f) _val_to_term = GlobalRef(@__MODULE__, :val_to_term) @eval $_val_to_term(::Val{$(QuoteNode(name))}, val) = $(QuoteNode(f))(val) end """ deregister!([:datatype|:predicate|:function|:modifier|:converter], name) Deregister the datatype, predicate, function or modifier specified by `name`. !!! warning "Top-Level Only" Because `deregister!` deletes existing methods, it should only be called at the top-level in order to avoid world-age errors. It should primarily be used in scripting contexts, and not by other packages or modules. """ function deregister!(category::Symbol, name::Symbol) if category == :datatype f = datatype_def elseif category == :abstraction f = default_abstype elseif category == :predicate f = predicate_def elseif category == :function f = function_def elseif category == :modifier f = modifier_def elseif category == :converter return deregister_converter!(name) else error("Category must be :datatype, :predicate, :function or :modifier.") end if hasmethod(f, Tuple{Val{name}}) m = first(methods(f, Tuple{Val{name}})) Base.delete_method(m) else @warn "No registered $f :$name to deregister." end end deregister!(category::Symbol, name::AbstractString) = deregister!(category, Symbol(name)) function deregister_converter!(name::Symbol) if hasmethod(val_to_term, Tuple{Val{name}, Any}) m = first(methods(val_to_term, Tuple{Val{name}, Any})) Base.delete_method(m) else @warn "No registered converter for type $name to deregister." end end """ attach!(domain, :function, name, f) Attach the function `f` as the implementation of the functional fluent specified by `name`. attach!(domain, :datatype, name, ty) Attach the type `ty` as the implementation of the PDDL datatype specified by `name`. """ function attach!(domain::GenericDomain, category::Symbol, name::Symbol, f) if category == :datatype attach_datatype!(domain, name, f) elseif category == :function attach_function!(domain, name, f) else error("Category must be :datatype or :function.") end end attach!(domain::GenericDomain, category::Symbol, name::AbstractString, f) = attach!(domain, category, Symbol(name), f) """ $(SIGNATURES) Attach datatype to domain. """ function attach_datatype!(domain::GenericDomain, name::Symbol, ty) domain.datatypes[name] = ty end """ $(SIGNATURES) Attach function to domain. """ function attach_function!(domain::GenericDomain, name::Symbol, f) if name in keys(get_functions(domain)) domain.funcdefs[name] = f else error("Domain does not have a function named $name.") end end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1040
"Default PDDL requirements." const DEFAULT_REQUIREMENTS = Dict{Symbol,Bool}( Symbol("strips") => true, Symbol("typing") => false, Symbol("fluents") => false, Symbol("negative-preconditions") => false, Symbol("disjunctive-preconditions") => false, Symbol("equality") => false, Symbol("existential-preconditions") => false, Symbol("universal-preconditions") => false, Symbol("quantified-preconditions") => false, Symbol("conditional-effects") => false, Symbol("adl") => false, Symbol("derived-predicates") => false ) const IMPLIED_REQUIREMENTS = Dict{Symbol,Vector{Symbol}}( Symbol("adl") => [ Symbol("strips"), Symbol("typing"), Symbol("negative-preconditions"), Symbol("disjunctive-preconditions"), Symbol("equality"), Symbol("quantified-preconditions"), Symbol("conditional-effects") ], Symbol("quantified-preconditions") => [ Symbol("existential-preconditions"), Symbol("universal-preconditions") ] )
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1541
# Semantics for abstract values # """ lub(a, b) Compute the least upper bound (i.e. join) of abstract values `a` and `b`. lub(T, iter) Compute the least upper bound (i.e. join) of abstract values in `iter`, assuming that all values in `iter` are of type `T`. """ function lub end """ glb(a, b) Compute the greatest lower bound (i.e. meet) of abstract values `a` and `b`. glb(T, iter) Compute the greatest lower bound (i.e. meet) of abstract values in `iter`, assuming that all values in `iter` are of type `T`. """ function glb end """ widen(a, b) Compute the widening of abstract values `a` and `b`. """ function widen end include("boolean.jl") include("interval.jl") include("set.jl") """ $(SIGNATURES) Mapping from PDDL types to default abstraction types. """ @valsplit default_abstype(Val(name::Symbol)) = error("Unknown datatype: $name") default_abstype(::Val{:boolean}) = BooleanAbs default_abstype(::Val{:integer}) = IntervalAbs{Int} default_abstype(::Val{:number}) = IntervalAbs{Float64} default_abstype(::Val{:numeric}) = IntervalAbs{Float64} """ $(SIGNATURES) Return list of datatypes with default abstractions defined for them. """ default_abstype_names() = valarg_params(default_abstype, Tuple{Val}, Val(1), Symbol) """ $(SIGNATURES) Return dictionary mapping datatype names to default abstraction types. """ function default_abstypes() names = default_abstype_names() types = Base.to_tuple_type(default_abstype.(names)) return _generate_dict(Val(names), Val(types)) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2942
""" Both Type whose singleton instance `both` represents both `false` and `true`. """ struct Both end """ both Singleton value of type `Both` representing both `false` and `true`. """ const both = Both() Base.copy(::Both) = both Base.show(io::IO, ::Both) = print(io, "both") isboth(b::Both) = true isboth(b) = false """ BooleanAbs Belnap logic abstraction for Boolean values. In addition to `true`, `false` and `missing`, the abstract value `both` can be used to represent when a predicate is both false and true. """ const BooleanAbs = Union{Missing,Bool,Both} BooleanAbs(x::BooleanAbs) = x lub(a::Both, b::Both) = both lub(a::Both, b::Bool) = both lub(a::Bool, b::Bool) = a === b ? a : both lub(a::Both, b::Missing) = both lub(a::Bool, b::Missing) = a lub(a::BooleanAbs, b::BooleanAbs) = lub(b, a) function lub(::Type{BooleanAbs}, iter) val::BooleanAbs = missing for x in iter val = lub(val, x) isboth(val) && return val end return val end glb(a::Both, b::Both) = both glb(a::Both, b::Bool) = b glb(a::Bool, b::Bool) = a === b ? a : missing glb(a::Both, b::Missing) = missing glb(a::Bool, b::Missing) = missing glb(a::BooleanAbs, b::BooleanAbs) = glb(b, a) function glb(::Type{BooleanAbs}, iter) val::BooleanAbs = both for x in iter val = glb(val, x) ismissing(val) && return val end return val end widen(a::BooleanAbs, b::BooleanAbs) = lub(a, b) equiv(a::Both, b::Both) = both equiv(a::Both, b::Bool) = both equiv(a::Bool, b::Both) = both Base.:(!)(::Both) = both Base.:(&)(a::Both, b::Both) = both Base.:(&)(a::Both, b::Missing) = missing Base.:(&)(a::Both, b::Bool) = b ? both : false Base.:(&)(a::BooleanAbs, b::Both) = b & a Base.:(|)(a::Both, b::Both) = both Base.:(|)(a::Both, b::Missing) = missing Base.:(|)(a::Both, b::Bool) = b ? true : both Base.:(|)(a::BooleanAbs, b::Both) = b | a "Four-valued logical version of `Base.any`." function any4(itr) anymissing = false anyboth = false for x in itr if ismissing(x) anymissing = true elseif isboth(x) anyboth = true elseif x return true end end return anymissing ? missing : anyboth ? both : false end "Four-valued logical version of `Base.all`." function all4(itr) anymissing = false anyboth = false for x in itr if ismissing(x) anymissing = true elseif isboth(x) anyboth = true elseif x continue else return false end end return anymissing ? missing : anyboth ? both : true end # Teach GenericState the way of true contradictions function set_fluent!(state::GenericState, val::Both, term::Const) push!(state.facts, term, negate(term)) return val end function set_fluent!(state::GenericState, val::Both, term::Compound) push!(state.facts, term, negate(term)) return val end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
4972
""" IntervalAbs(lo::Real, hi::Real) Interval abstraction for real-valued numbers. """ struct IntervalAbs{T <: Real} lo::T hi::T function IntervalAbs{T}(lo::T, hi::T) where {T <: Real} lo > hi ? new{T}(typemax(T), typemin(T)) : new{T}(lo, hi) end end IntervalAbs{T}(x::Real) where {T} = IntervalAbs{T}(x, x) IntervalAbs(x::T) where {T <: Real} = IntervalAbs{T}(x, x) IntervalAbs{T}(lo::Real, hi::Real) where {T} = IntervalAbs{T}(convert(T, lo), convert(T, hi)) IntervalAbs(lo::T, hi::U) where {T <: Real, U <: Real} = IntervalAbs{promote_type(T, U)}(lo, hi) empty_interval(I::Type{IntervalAbs{T}}) where {T <: Real} = I(typemax(T), typemin(T)) empty_interval(x::IntervalAbs) = empty_interval(typeof(x)) Base.copy(x::IntervalAbs) = x Base.convert(I::Type{IntervalAbs{T}}, x::Real) where {T <: Real} = I(x) Base.show(io::IO, x::IntervalAbs) = print(io, "IntervalAbs($(x.lo), $(x.hi))") Base.hash(x::IntervalAbs, h::UInt) = hash(x.lo, hash(x.hi, h)) lub(a::IntervalAbs, b::IntervalAbs) = a ∪ b function lub(I::Type{IntervalAbs{T}}, iter) where {T} val = empty_interval(I) for x in iter val = lub(val, x) end return val end glb(a::IntervalAbs, b::IntervalAbs) = a ∩ b function glb(I::Type{IntervalAbs{T}}, iter) where {T} val = I(typemin(T), typemax(T)) for x in iter val = glb(val, x) end return val end widen(a::IntervalAbs, b::IntervalAbs) = a ∪ b Base.:(==)(a::IntervalAbs, b::IntervalAbs) = a.lo == b.lo && a.hi == b.hi Base.isapprox(a::IntervalAbs, b::IntervalAbs; kwargs...) = isapprox(a.lo, b.lo; kwargs...) && isapprox(a.hi, b.hi; kwargs...) Base.:+(a::IntervalAbs) = a Base.:-(a::IntervalAbs) = IntervalAbs(-a.hi, -a.lo) function Base.:+(a::IntervalAbs, b::IntervalAbs) return IntervalAbs(a.lo + b.lo, a.hi + b.hi) end function Base.:-(a::IntervalAbs, b::IntervalAbs) return IntervalAbs(a.lo - b.hi, a.hi - b.lo) end function Base.:*(a::IntervalAbs, b::IntervalAbs) lo = min(a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi) hi = max(a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi) return IntervalAbs(lo, hi) end function Base.:/(a::IntervalAbs, b::IntervalAbs) a * inv(b) end function Base.inv(a::IntervalAbs{T}) where {T} if a.lo == 0 && a.hi == 0 if T <: Integer throw(DivideError()) elseif signbit(a.lo) != signbit(a.hi) return IntervalAbs{T}(T(-Inf), T(Inf)) else return IntervalAbs{T}(T(copysign(Inf, a.lo))) end elseif a.lo < 0 && a.hi > 0 T <: Integer ? throw(DivideError()) : return IntervalAbs(-Inf, Inf) elseif a.lo == 0 return IntervalAbs(1 / a.hi, Inf) elseif a.hi == 0 return IntervalAbs(-Inf, 1 / a.lo) else return IntervalAbs(1 / a.hi, 1 / a.lo) end end Base.:+(a::IntervalAbs, b::Real) = IntervalAbs(a.lo + b, a.hi + b) Base.:-(a::IntervalAbs, b::Real) = IntervalAbs(a.lo - b, a.hi - b) Base.:*(a::IntervalAbs, b::Real) = signbit(b) ? IntervalAbs(a.hi*b, a.lo*b) : IntervalAbs(a.lo*b, a.hi*b) Base.:/(a::IntervalAbs, b::Real) = signbit(b) ? IntervalAbs(a.hi/b, a.lo/b) : IntervalAbs(a.lo/b, a.hi/b) Base.:+(a::Real, b::IntervalAbs) = b + a Base.:-(a::Real, b::IntervalAbs) = -b + a Base.:*(a::Real, b::IntervalAbs) = b * a Base.:/(a::Real, b::IntervalAbs) = inv(b) * a function Base.union(a::IntervalAbs, b::IntervalAbs) IntervalAbs(min(a.lo, b.lo), max(a.hi, b.hi)) end function Base.intersect(a::IntervalAbs{T}, b::IntervalAbs{U}) where {T, U} if a.lo > b.hi || a.hi < b.lo return empty_interval(promote_type{T, U}) else return IntervalAbs(max(a.lo, b.lo), min(a.hi, b.hi)) end end Base.issubset(a::IntervalAbs, b::IntervalAbs) = a.lo >= b.lo && a.hi <= b.hi Base.in(a::Real, b::IntervalAbs) = a >= b.lo && a <= b.hi equiv(a::IntervalAbs, b::IntervalAbs) = (a.lo > b.hi || a.hi < b.lo) ? false : ((a.lo == a.hi == b.lo == b.hi) ? true : both) nequiv(a::IntervalAbs, b::IntervalAbs) = (a.lo > b.hi || a.hi < b.lo) ? true : ((a.lo == a.hi == b.lo == b.hi) ? false : both) Base.:<(a::IntervalAbs, b::IntervalAbs) = a.hi < b.lo ? true : ((a.lo < b.hi) ? both : false) Base.:<=(a::IntervalAbs, b::IntervalAbs) = a.hi <= b.lo ? true : ((a.lo <= b.hi) ? both : false) equiv(a::IntervalAbs, b::Real) = (b in a) ? ((a.lo == a.hi) ? true : both) : false nequiv(a::IntervalAbs, b::Real) = (b in a) ? ((a.lo == a.hi) ? false : both) : true Base.:<(a::IntervalAbs, b::Real) = (a.hi < b) ? true : ((a.lo < b) ? both : false) Base.:<=(a::IntervalAbs, b::Real) = (a.hi <= b) ? true : ((a.lo <= b) ? both : false) equiv(a::Real, b::IntervalAbs) = equiv(b, a) nequiv(a::Real, b::IntervalAbs) = nequiv(b, a) Base.:<(a::Real, b::IntervalAbs) = (a < b.lo) ? true : ((a < b.hi) ? both : false) Base.:<=(a::Real, b::IntervalAbs) = (a <= b.lo) ? true : ((a <= b.hi) ? both : false)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3092
""" SetAbs(xs...) Set abstraction for arbitrary objects. """ struct SetAbs{T} set::Set{T} SetAbs{T}(; iter=(), set::Set{T} = Set{T}(iter)) where {T} = new(set) end function SetAbs{T}(x::T, xs::T...) where {T} y = SetAbs{T}() push!(y.set, x) for x in xs push!(y.set, x) end return y end SetAbs(xs::T...) where {T} = SetAbs{T}(xs...) SetAbs(xs...) = SetAbs{Any}(xs...) SetAbs(; set::Set{T}=Set{T}()) where {T} = SetAbs{T}(set=set) Base.copy(x::SetAbs{T}) where {T} = SetAbs{T}(set=copy(x.set)) Base.convert(S::Type{SetAbs{T}}, x::T) where {T} = S(x) Base.show(io::IO, x::SetAbs{T}) where {T} = print(io, "SetAbs", "(", join(x.set, ", "), ")") Base.hash(x::SetAbs, h::UInt) = hash(x.set, h) lub(a::SetAbs{T}, b::SetAbs{T}) where {T} = SetAbs{T}(; set=(a.set ∪ b.set)) function lub(S::Type{SetAbs{T}}, iter) where {T} val = SetAbs{T}() for x in iter union!(val.set, x) end return val end glb(a::SetAbs{T}, b::SetAbs{T}) where {T} = SetAbs{T}(; set=(a.set ∩ b.set)) function glb(S::Type{SetAbs{T}}, iter) where {T} val = SetAbs{T}() isfirst = true for x in iter if isfirst union!(val.set, x) isfirst = false else intersect!(val.set, x) isempty(val.set) && break end end return val end widen(a::SetAbs, b::SetAbs) = SetAbs(; set=(a.set ∪ b.set)) Base.:(==)(a::SetAbs, b::SetAbs) = a.set == b.set for f in (:+, :-, :inv) @eval Base.$f(a::SetAbs) = SetAbs(set=Set(($f(x) for x in a.set))) end for f in (:+, :-, :*, :/) @eval Base.$f(a::SetAbs, b::SetAbs) = SetAbs(set=Set(($f(x, y) for x in a.set, y in b.set))) @eval Base.$f(a::SetAbs, b::Real) = SetAbs(set=Set(($f(x, b) for x in a.set))) @eval Base.$f(a::Real, b::SetAbs) = SetAbs(set=Set(($f(a, y) for y in b.set))) end uniquely_equal(a::SetAbs, b::SetAbs) = (length(a.set) == length(b.set) == 1) && first(a.set) == first(b.set) equiv(a::SetAbs, b::SetAbs) = isdisjoint(a.set, b.set) ? false : (uniquely_equal(a, b) ? true : both) nequiv(a::SetAbs, b::SetAbs) = isdisjoint(a.set, b.set) ? true : (uniquely_equal(a, b) ? false : both) Base.:<(a::SetAbs, b::SetAbs) = lub(BooleanAbs, (x < y for x in a.set, y in b.set)) Base.:<=(a::SetAbs, b::SetAbs) = lub(BooleanAbs, (x <= y for x in a.set, y in b.set)) equiv(a::SetAbs{T}, b::T) where {T} = b in a.set ? (length(a.set) == 1 ? true : both) : false nequiv(a::SetAbs{T}, b::T) where {T} = b in a.set ? (length(a.set) == 1 ? false : both) : true Base.:<(a::SetAbs, b::Real) = lub(BooleanAbs, (x < b for x in a.set)) Base.:<=(a::SetAbs, b::Real) = lub(BooleanAbs, (x <= b for x in a.set)) equiv(a::T, b::SetAbs{T}) where {T} = a in b.set ? (length(b.set) == 1 ? true : both) : false nequiv(a::T, b::SetAbs{T}) where {T} = a in b.set ? (length(b.set) == 1 ? false : both) : true Base.:<(a::Real, b::SetAbs) = lub(BooleanAbs, (a < y for y in b.set)) Base.:<=(a::Real, b::SetAbs) = lub(BooleanAbs, (a <= y for y in b.set))
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2163
""" $(SIGNATURES) Check if term is affected by some action or composed of affected subterms. """ function is_affected(term::Term, domain::Domain, affected=infer_affected_fluents(domain)) if term.name in affected return true end fluents = constituents(term, domain) return any(f.name in affected for f in fluents) end """ $(SIGNATURES) Infer fluents that are modified by some action in a domain. """ function infer_affected_fluents(domain::Domain) # Infer fluents directly changed by actions affected = Symbol[] for action in values(get_actions(domain)) append!(affected, get_affected(action)) end # Infer affected derived predicates _, children = infer_axiom_hierarchy(domain) queue = copy(affected) while !isempty(queue) fluent = pop!(queue) derived = get!(children, fluent, Symbol[]) filter!(x -> !(x in affected), derived) append!(queue, derived) append!(affected, derived) end return unique!(affected) end """ $(SIGNATURES) Return the names of all fluents affected by an action. """ get_affected(action::Action) = get_affected(get_effect(action)) get_affected(effect::Term) = unique!(get_affected!(Symbol[], effect)) """ $(SIGNATURES) Accumulate affected fluent names given an effect formula. """ get_affected!(fluents::Vector{Symbol}, effect::Term) = get_affected!(effect.name, fluents, effect) # Use valsplit to switch on effect expression head @valsplit function get_affected!(Val(name::Symbol), fluents, effect) if is_global_modifier(effect.name) push!(fluents, effect.args[1].name) else push!(fluents, effect.name) end end get_affected!(::Val{:and}, fluents, effect) = (for e in effect.args get_affected!(fluents, e) end; fluents) get_affected!(::Val{:when}, fluents, effect) = get_affected!(fluents, effect.args[2]) get_affected!(::Val{:forall}, fluents, effect) = get_affected!(fluents, effect.args[2]) get_affected!(::Val{:assign}, fluents, effect) = push!(fluents, effect.args[1].name) get_affected!(::Val{:not}, fluents, effect) = push!(fluents, effect.args[1].name)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
137
# Tools for analyzing domains include("utils.jl") include("affected.jl") include("static.jl") include("relevant.jl") include("axiom.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1463
""" $(SIGNATURES) Infer dependency structure between axioms. """ function infer_axiom_hierarchy(domain::Domain) parents = Dict{Symbol,Vector{Symbol}}() for (name, ax) in pairs(get_axioms(domain)) body = length(ax.body) == 1 ? ax.body[1] : Compound(:and, ax.body) parents[name] = unique!([c.name for c in constituents(body, domain)]) end children = Dict{Symbol,Vector{Symbol}}() for (name, ps) in parents for p in ps cs = get!(children, p, Symbol[]) push!(cs, name) end end return parents, children end """ $(SIGNATURES) Substitute derived predicates in a term with their axiom bodies. """ function substitute_axioms(term::Term, domain::Domain; ignore=[]) if term.name in ignore return term elseif is_derived(term, domain) # Substitute with axiom body, avoiding recursion axiom = Julog.freshen(get_axiom(domain, term.name)) subst = unify(axiom.head, term) body = length(axiom.body) == 1 ? axiom.body[1] : Compound(:and, axiom.body) body = substitute(body, subst) body = substitute_axioms(body, domain, ignore=[term.name]) return body elseif term isa Compound # Substitute each constituent term args = Term[substitute_axioms(a, domain, ignore=ignore) for a in term.args] return Compound(term.name, args) else return term end end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3479
""" $(SIGNATURES) Infer fluents that are relevant to some action precondition. """ function infer_relevant_fluents(domain::Domain) fluents = Symbol[] for action in values(get_actions(domain)) append!(fluents, get_relevant(action)) end return unique!(fluents) end """ $(SIGNATURES) Infer fluents that are relevant to achieving a set of goal fluents. """ function infer_relevant_fluents(domain::Domain, goals::Vector{Symbol}, axiom_parents=infer_axiom_hierarchy(domain)[1]) new_goals = copy(goals) for g in goals append!(new_goals, get(axiom_parents, g, Symbol[])) end for action in values(get_actions(domain)) if any(eff in goals for eff in get_affected(action)) append!(new_goals, get_relevant(action)) end end unique!(new_goals) return issubset(new_goals, goals) ? new_goals : infer_relevant_fluents(domain, new_goals, axiom_parents) end infer_relevant_fluents(domain, goal::Nothing) = infer_relevant_fluents(domain) infer_relevant_fluents(domain, goal::Term) = infer_relevant_fluents(domain, [c.name::Symbol for c in constituents(goal, domain)]) infer_relevant_fluents(domain, goals::AbstractVector{<:Term}) = infer_relevant_fluents(domain, Compound(:and, goals)) """ $(SIGNATURES) Return the names of all fluents relevant to the preconditions of an action. """ function get_relevant(action::Action) fluents = Symbol[] get_relevant_preconds!(fluents, get_precond(action)) get_relevant_effconds!(fluents, get_effect(action)) return unique!(fluents) end """ $(SIGNATURES) Accumulate relevant fluent names given a precondition formula. """ get_relevant_preconds!(fluents::Vector{Symbol}, precond::Term) = get_relevant_preconds!(precond.name, fluents, precond) # Use valsplit to switch on precond expression head @valsplit get_relevant_preconds!(Val(name::Symbol), fluents, precond) = push!(fluents, precond.name) get_relevant_preconds!(::Val{:and}, fluents, precond) = (for e in precond.args get_relevant_preconds!(fluents, e) end; fluents) get_relevant_preconds!(::Val{:or}, fluents, precond) = (for e in precond.args get_relevant_preconds!(fluents, e) end; fluents) get_relevant_preconds!(::Val{:imply}, fluents, precond) = (get_relevant_preconds!(fluents, precond.args[1]); get_relevant_preconds!(fluents, precond.args[2])) get_relevant_preconds!(::Val{:forall}, fluents, precond) = get_relevant_preconds!(fluents, precond.args[2]) get_relevant_preconds!(::Val{:exists}, fluents, precond) = get_relevant_preconds!(fluents, precond.args[2]) get_relevant_preconds!(::Val{:not}, fluents, precond) = push!(fluents, precond.args[1].name) """ $(SIGNATURES) Accumulate relevant fluent names given an effect formula. """ get_relevant_effconds!(fluents::Vector{Symbol}, effect::Term) = get_relevant_effconds!(effect.name, fluents, effect) # Use valsplit to switch on effect expression head @valsplit get_relevant_effconds!(Val(name::Symbol), fluents, effect) = fluents get_relevant_effconds!(::Val{:and}, fluents, effect) = (for e in effect.args get_relevant_effconds!(fluents, e) end; fluents) get_relevant_effconds!(::Val{:when}, fluents, effect) = (get_relevant_preconds!(fluents, effect.args[1]); get_relevant_effconds!(fluents, effect.args[2])) get_relevant_effconds!(::Val{:forall}, fluents, effect) = get_relevant_effconds!(fluents, effect.args[2])
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3295
""" $(SIGNATURES) Check if term is static or composed of static subterms. """ function is_static(term::Term, domain::Domain, statics=infer_static_fluents(domain)) if term.name in statics return true end fluents = constituents(term, domain) return all(f.name in statics for f in fluents) end """ $(SIGNATURES) Infer fluents that are never modified by some action in a domain. """ function infer_static_fluents(domain::Domain) affected = infer_affected_fluents(domain) static = setdiff(keys(get_fluents(domain)), affected) return collect(static) end "Simplify away static fluents within a `term`." function simplify_statics(term::Term, domain::Domain, state::State, statics=infer_static_fluents(domain)) # Simplify logical compounds if term.name == :and new_args = nothing for (i, a) in enumerate(term.args) new_a = simplify_statics(a, domain, state, statics) new_a.name === false && return Const(false) if new_a !== a || new_args !== nothing new_args === nothing && (new_args = term.args[1:i-1]) new_a.name !== true && push!(new_args, new_a) end end new_args === nothing && return term # All subterms were preserved isempty(new_args) && return Const(true) # All subterms were true return length(new_args) == 1 ? new_args[1] : Compound(:and, new_args) elseif term.name == :or new_args = nothing for (i, a) in enumerate(term.args) new_a = simplify_statics(a, domain, state, statics) new_a.name === true && return Const(true) if new_a !== a || new_args !== nothing new_args === nothing && (new_args = term.args[1:i-1]) new_a.name !== false && push!(new_args, new_a) end end new_args === nothing && return term # All subterms were preserved isempty(new_args) && return Const(false) # All subterms were false return length(new_args) == 1 ? new_args[1] : Compound(:or, new_args) elseif term.name == :imply cond, query = term.args cond = simplify_statics(cond, domain, state, statics) cond.name == false && return Const(true) query = simplify_statics(query, domain, state, statics) cond.name == true && return query return Compound(:imply, Term[cond, query]) elseif term.name == :not new_arg = simplify_statics(term.args[1], domain, state, statics) new_arg === term.args[1] && return term val = new_arg.name return val isa Bool ? Const(!val) : Compound(:not, Term[new_arg]) elseif is_quantifier(term) typecond, body = term.args body = simplify_statics(body, domain, state, statics) body === term.args[2] && return term return Compound(term.name, Term[typecond, body]) elseif is_static(term, domain, statics) && is_ground(term) # Simplify predicates that are static and ground if is_pred(term, domain) return Const(satisfy(domain, state, term)) else return Const(evaluate(domain, state, term)::Bool) end else # Return term without simplifying return term end end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
4757
""" $(SIGNATURES) Check if term is a predicate. """ is_pred(term::Term, domain::Domain) = term.name in keys(get_predicates(domain)) """ $(SIGNATURES) Check if term is a non-Boolean fluent (i.e. function). """ is_func(term::Term, domain::Domain) = term.name in keys(get_functions(domain)) """ $(SIGNATURES) Check if term is an external function attached to a domain. """ is_attached_func(term::Term, domain::Domain) = term.name in keys(get_funcdefs(domain)) """ $(SIGNATURES) Check if term is an external function (attached or global). """ is_external_func(term::Term, domain::Domain) = is_global_func(term) || is_attached_func(term, domain) """ $(SIGNATURES) Check if term is a derived predicate """ is_derived(term::Term, domain::Domain) = term.name in keys(get_axioms(domain)) """ $(SIGNATURES) Check if term is a (non-external) domain fluent. """ is_fluent(term::Term, domain::Domain) = is_pred(term, domain) || is_func(term, domain) && !is_attached_func(term, domain) """ $(SIGNATURES) Check if term is a negation of another term. """ is_negation(term::Term) = term.name == :not """ $(SIGNATURES) Check if term is a universal or existential quantifier. """ is_quantifier(term::Term) = term.name == :forall || term.name == :exists """ $(SIGNATURES) Check if term is a global predicate (comparison, equality, etc.). """ is_global_pred(term::Term) = term.name isa Symbol && is_global_pred(term.name) """ $(SIGNATURES) Check if term is a global function, including global predicates. """ is_global_func(term::Term) = term.name isa Symbol && is_global_func(term.name) """ $(SIGNATURES) Check if term is a logical operator. """ is_logical_op(term::Term) = term.name in (:and, :or, :not, :imply, :exists, :forall) """ $(SIGNATURES) Check if term is a literal (an atomic formula or its negation.) """ is_literal(term::Term) = !is_logical_op(term) || term.name == :not && !is_logical_op(term) """ $(SIGNATURES) Check if term is a type predicate. """ is_type(term::Term, domain::Domain) = term.name in get_types(domain) """ $(SIGNATURES) Check if term is a type predicate with subtypes. """ has_subtypes(term::Term, domain::Domain) = !isempty(get_subtypes(domain, term.name)) "Check if `term` has a (sub-term with a) name in `names`." has_name(term::Const, names) = term.name in names has_name(term::Var, names) = false has_name(term::Compound, names) = term.name in names || any(has_name(f, names) for f in term.args) """ $(SIGNATURES) Check if term contains a predicate. """ has_pred(term::Term, domain::Domain) = has_name(term, keys(get_predicates(domain))) """ $(SIGNATURES) Check if term contains a global predicate. """ has_global_pred(term::Term) = has_name(term, global_predicate_names()) """ $(SIGNATURES) Check if term contains a non-Boolean fluent (i.e. function). """ has_func(term::Term, domain::Domain) = has_name(term, keys(get_functions(domain))) """ $(SIGNATURES) Check if term contains an external function attached to a domain. """ has_attached_func(term::Term, domain::Domain) = has_name(term, keys(get_funcdefs(domain))) """ $(SIGNATURES) Check if term contains a global function. """ has_global_func(term::Term) = has_name(term, global_function_names()) """ $(SIGNATURES) Check if term contains a logical operator. """ has_logical_op(term::Term) = has_name(term, (:and, :or, :not, :imply, :exists, :forall)) """ $(SIGNATURES) Check if term contains a derived predicate """ has_derived(term::Term, domain::Domain) = has_name(term, keys(get_axioms(domain))) """ $(SIGNATURES) Check if term contains a universal or existential quantifier. """ has_quantifier(term::Term) = has_name(term, (:forall, :exists)) """ $(SIGNATURES) Check if term contains a negated literal. """ has_negation(term::Term) = has_name(term, (:not,)) """ $(SIGNATURES) Check if term contains a fluent name. """ has_fluent(term::Term, domain::Domain) = has_pred(term, domain) || has_func(term, domain) """ $(SIGNATURES) Check if term contains a type predicate. """ has_type(term::Term, domain::Domain) = has_type(term, keys(get_types(domain))) """ $(SIGNATURES) Returns list of constituent fluents. """ constituents(term::Term, domain::Domain) = constituents!(Term[], term, domain) constituents!(fluents, term::Const, domain::Domain) = is_fluent(term, domain) ? push!(fluents, term) : fluents constituents!(fluents, term::Var, domain::Domain) = fluents function constituents!(fluents, term::Compound, domain::Domain) if is_fluent(term, domain) push!(fluents, term) else for arg in term.args constituents!(fluents, arg, domain) end end return fluents end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2475
"Helper macro for defining cached method implementations." macro _cached(key, signature, postcall=nothing) @assert signature.head == :call "Signature must be a typed function call." # Extract function name and arguments fname = signature.args[1]::Symbol if signature.args[2].head == :parameters args = signature.args[3:end] kwargs = signature.args[2] else args = signature.args[2:end] kwargs = nothing end argnames = map(args) do arg arg.head == :(::) ? arg.args[1] : arg end argtypes = map(args) do arg arg.head == :(::) ? arg.args[2] : :Any end domain = argnames[1] argnames = argnames[2:end] # Construct function expression for cached method call_expr = if isnothing(kwargs) :($fname($domain.source, $(argnames...))) else :($fname($kwargs, $domain.source, $(argnames...))) end orig_call_expr = call_expr if !isnothing(postcall) call_expr = :($postcall($call_expr)) end body = :( if haskey($domain.caches, $key) cache = domain.caches[$key] get!(cache, ($(argnames...),)) do $call_expr end else $orig_call_expr end ) signature.args[1] = GlobalRef(PDDL, fname) if isnothing(kwargs) signature.args[2]= :($domain::CachedDomain) else signature.args[3]= :($domain::CachedDomain) end f_expr = Expr(:function, signature, body) # Construct mapping from key to method type m_expr = :( function $(GlobalRef(PDDL, :_cached_method_type))(::Val{$key}) ($fname, ($(argtypes...),)) end ) return Expr(:block, f_expr, m_expr) end "Return type signature for method associated with key." @valsplit _cached_method_type(Val(key::Symbol)) = error("Unrecognized method key :$key") "Return inferred cache type for a domain type and method key." function _infer_cache_type(D::Type{<:Domain}, key::Symbol) S = statetype(D) f, argtypes = _cached_method_type(key) argtypes = map(argtypes) do type type === Domain ? D : (type === State ? S : type) end K = Tuple{argtypes[2:end]...} rtypes = Base.return_types(f, argtypes) if f in (available, relevant) V = Vector{Compound} else V = length(rtypes) > 1 ? Union{rtypes...} : rtypes[1] end return Dict{K, V} end include("domain.jl") include("interface.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2372
""" CachedDomain{D, Ks, Vs} Wraps an existing domain of type `D`, caching the outputs of calls to a subset of interface methods. `Ks` is a tuple of method identifiers, and `Vs` is a a tuple of corresponding cache types. """ struct CachedDomain{D <: Domain, Ks, Vs} <: Domain source::D caches::NamedTuple{Ks,Vs} end "Default methods to cache in a CachedDomain." const DEFAULT_CACHED_METHODS = [ :available, :relevant, :infer_static_fluents, :infer_affected_fluents, :infer_axiom_hierarchy ] """ CachedDomain(source::Domain) CachedDomain(source::Domain, method_keys) Construct a `CachedDomain` from a `source` domain, along with the associated caches for each cached method. A list of `method_keys` can be provided, where each key is a `Symbol` specifying the method to be cached. By default, the following methods are cached: `$DEFAULT_CACHED_METHODS`. """ function CachedDomain(source::D, method_keys=DEFAULT_CACHED_METHODS) where {D <: Domain} caches = (; (key => _infer_cache_type(D, key)() for key in method_keys)...) return CachedDomain(source, caches) end function CachedDomain(source::CachedDomain, method_keys=DEFAULT_CACHED_METHODS) return CachedDomain(source.source, method_keys) end get_name(domain::CachedDomain) = get_name(domain.source) get_source(domain::CachedDomain) = domain.source get_requirements(domain::CachedDomain) = get_requirements(domain.source) get_typetree(domain::CachedDomain) = get_typetree(domain.source) get_datatypes(domain::CachedDomain) = get_datatypes(domain.source) get_constants(domain::CachedDomain) = get_constants(domain.source) get_constypes(domain::CachedDomain) = get_constypes(domain.source) get_predicates(domain::CachedDomain) = get_predicates(domain.source) get_functions(domain::CachedDomain) = get_functions(domain.source) get_funcdefs(domain::CachedDomain) = get_funcdefs(domain.source) get_fluents(domain::CachedDomain) = get_fluents(domain.source) get_axioms(domain::CachedDomain) = get_axioms(domain.source) get_actions(domain::CachedDomain) = get_actions(domain.source) statetype(::Type{CachedDomain{D}}) where {D} = statetype(D) @_cached :infer_static_fluents infer_static_fluents(domain::Domain) @_cached :infer_affected_fluents infer_affected_fluents(domain::Domain) @_cached :infer_axiom_hierarchy infer_axiom_hierarchy(domain::Domain)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3421
# Define cached interface methods function maybe_collect(xs::AbstractVector{<:Term}) if all(isa.(xs, Compound)) return collect(Compound, xs) else return xs end end maybe_collect(xs::AbstractVector) = xs maybe_collect(xs::AbstractVector{Compound}) = collect(Compound, xs) maybe_collect(xs::Vector{Compound}) = xs maybe_collect(xs) = maybe_collect(collect(xs)) @_cached :satisfy satisfy(domain::Domain, state::State, terms::AbstractVector{<:Term}) @_cached :satisfiers satisfiers(domain::Domain, state::State, terms::AbstractVector{<:Term}) maybe_collect @_cached :evaluate evaluate(domain::Domain, state::State, term::Term) @_cached :available available(domain::Domain, state::State) maybe_collect @_cached :relevant relevant(domain::Domain, state::State) maybe_collect @_cached :is_available available(domain::Domain, state::State, term::Term) @_cached :is_relevant relevant(domain::Domain, state::State, term::Term) @_cached :transition transition(domain::Domain, state::State, term::Term; options...) @_cached :execute execute(domain::Domain, state::State, term::Term; options...) @_cached :regress regress(domain::Domain, state::State, term::Term; options...) # Forward uncached interface methods satisfy(domain::CachedDomain, state::State, term::Term) = satisfy(domain, state, [term]) satisfiers(domain::CachedDomain, state::State, term::Term) = satisfiers(domain.source, state, [term]) initstate(domain::CachedDomain, problem::Problem) = initstate(domain.source, problem) initstate(domain::CachedDomain, objtypes::AbstractDict, fluents) = initstate(domain.source, objtypes, fluents) goalstate(domain::CachedDomain, problem::Problem) = goalstate(domain.source, problem) goalstate(domain::CachedDomain, objtypes::AbstractDict, terms) = goalstate(domain.source, objtypes, terms) transition!(domain::CachedDomain, state::State, action::Term; options...) = transition!(domain.source, state, action; options...) transition!(domain::CachedDomain, state::State, actions; options...) = transition!(domain.source, state, action; options...) available(domain::CachedDomain, state::State, action::Action, args) = available(domain, state, Compound(get_name(action), args)) execute(domain::CachedDomain, state::State, action::Action, args; options...) = execute(domain, state, Compound(get_name(action), args); options...) execute!(domain::CachedDomain, state::State, action::Action, args; options...) = execute!(domain.source, state, action, args; options...) execute!(domain::CachedDomain, state::State, action::Term; options...) = execute!(domain.source, state, action; options...) relevant(domain::CachedDomain, state::State, action::Action, args) = relevant(domain, state, Compound(get_name(action), args)) regress(domain::CachedDomain, state::State, action::Action, args; options...) = regress(domain, state, Compound(get_name(action), args); options...) regress!(domain::CachedDomain, state::State, action::Action, args; options...) = regress!(domain.source, state, action, args; options...) regress!(domain::CachedDomain, state::State, action::Term; options...) = regress!(domain.source, state, action; options...) update!(domain::CachedDomain, state::State, diff::Diff) = update!(domain.source, state, diff) update(domain::CachedDomain, state::State, diff::Diff) = update(domain.source, state, diff)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3341
function generate_get_expr(domain::Domain, state::State, term::Const, varmap=Dict{Var,Any}(), state_var=:state) if is_derived(term, domain) return :(get_fluent($state_var, $(QuoteNode(term.name)))) else return :($state_var.$(term.name)) end end function generate_get_expr(domain::Domain, state::State, term::Var, varmap=Dict{Var,Any}(), state_var=:state) return :($(varmap[term])) end function generate_get_expr(domain::Domain, state::State, term::Compound, varmap=Dict{Var,Any}(), state_var=:state) if is_derived(term, domain) args = [varmap[a] for a in term.args] return :(get_fluent($state_var, $(QuoteNode(term.name)), $(args...))) else sig = get_fluent(domain, term.name) indices = generate_fluent_ids(domain, state, term, sig, varmap, state_var) return :($state_var.$(term.name)[$(indices...)]) end end function generate_set_expr(domain::Domain, state::State, term::Const, val, varmap=Dict{Var,Any}(), state_var=:state) if domain isa AbstractedDomain && domain.interpreter.autowiden && is_abstracted(term, domain) prev_val = generate_get_expr(domain, state, term, varmap, :prev_state) return :(setfield!($state_var, $(QuoteNode(term.name)), widen($prev_val, $val))) else return :(setfield!($state_var, $(QuoteNode(term.name)), $val)) end end function generate_set_expr(domain::Domain, state::State, term::Compound, val, varmap=Dict{Var,Any}(), state_var=:state) indices = generate_fluent_ids(domain, state, term, get_fluent(domain, term.name), varmap, state_var) if domain isa AbstractedDomain && domain.interpreter.autowiden && is_abstracted(term, domain) prev_val = generate_get_expr(domain, state, term, varmap, :prev_state) return :($state_var.$(term.name)[$(indices...)] = widen($prev_val, $val)) else return :($state_var.$(term.name)[$(indices...)] = $val) end end function generate_fluent_ids(domain::Domain, state::State, term::Term, sig::Signature, varmap=Dict{Var,Any}(), state_var=:state) if get_requirements(domain)[:typing] ids = map(zip(term.args, sig.argtypes)) do (arg, type) if arg isa Var :(objectindex($state_var, $(QuoteNode(type)), $(varmap[arg]))) else objects = sort(get_objects(domain, state, type), by=x->x.name) findfirst(isequal(arg), objects) end end else objects = sort(collect(get_objects(state)), by=x->x.name) ids = map(term.args) do arg if arg isa Var :(objectindex($state_var, $(varmap[arg]))) else findfirst(isequal(arg), objects) end end end return ids end function generate_fluent_dims(domain::Domain, state::State, pred::Signature) if get_requirements(domain)[:typing] dims = [length(get_objects(domain, state, ty)) for ty in pred.argtypes] else dims = fill(length(get_objects(state)), length(pred.args)) end return dims end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3664
function generate_action_defs(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) available_def = generate_available(domain, state, domain_type, state_type) execute_def = generate_execute(domain, state, domain_type, state_type) all_action_defs = [available_def, execute_def] all_action_names = sortedkeys(get_actions(domain)) all_action_types = Symbol[] for name in all_action_names action_defs = generate_action_defs(domain, state, domain_type, state_type, name) push!(all_action_types, action_defs[1]) append!(all_action_defs, action_defs[2:end]) end action_map = Expr(:tuple, (Expr(:(=), n, Expr(:call, act)) for (n, act) in zip(all_action_names, all_action_types))...) get_actions_def = :(get_actions(::$domain_type) = $action_map) push!(all_action_defs, get_actions_def) return Expr(:block, all_action_defs...) end function generate_action_defs(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol, action_name::Symbol) action_type = gensym("Compiled" * pddl_to_type_name(action_name) * "Action") action_typedef = :(struct $action_type <: CompiledAction end) groundargs_def = generate_groundargs(domain, state, domain_type, state_type, action_name, action_type) available_def = generate_available(domain, state, domain_type, state_type, action_name, action_type) execute_def = generate_execute(domain, state, domain_type, state_type, action_name, action_type) method_defs = generate_action_methods(domain, state, domain_type, state_type, action_name, action_type) return (action_type, action_typedef, method_defs, groundargs_def, available_def, execute_def) end function generate_action_methods(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol, action_name::Symbol, action_type::Symbol) action = get_action(domain, action_name) get_name_def = :(get_name(::$action_type) = $(QuoteNode(get_name(action)))) get_argvars_def = :(get_argvars(::$action_type) = $(QuoteNode(get_argvars(action)))) get_argtypes_def = :(get_argtypes(::$action_type) = $(QuoteNode(get_argtypes(action)))) get_precond_def = :(get_precond(::$action_type) = $(QuoteNode(get_precond(action)))) get_effect_def = :(get_effect(::$action_type) = $(QuoteNode(get_effect(action)))) method_defs = Expr(:block, get_name_def, get_argvars_def, get_argtypes_def, get_precond_def, get_effect_def) return method_defs end function generate_groundargs(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol, action_name::Symbol, action_type::Symbol) action = get_action(domain, action_name) argtypes = get_argtypes(action) if get_requirements(domain)[:typing] objs_exprs = [:(get_objects(state, $(QuoteNode(ty)))) for ty in argtypes] else objs_exprs = [:(get_objects(state)) for ty in argtypes] end iter_expr = :(Iterators.product($(objs_exprs...))) groundargs_def = quote function groundargs(domain::$domain_type, state::$state_type, action::$action_type) return $iter_expr end end return groundargs_def end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1949
function generate_available(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol, action_name::Symbol, action_type::Symbol) action = get_actions(domain)[action_name] varmap = Dict{Var,Any}(a => :(args[$i].name) for (i, a) in enumerate(get_argvars(action))) precond = to_nnf(get_precond(action)) precond = generate_check_expr(domain, state, precond, varmap) if domain isa AbstractedDomain available_def = quote function available(domain::$domain_type, state::$state_type, action::$action_type, args) precond = @inbounds $precond return precond == true || precond == both end end else available_def = quote function available(domain::$domain_type, state::$state_type, action::$action_type, args) return @inbounds $precond end end end return available_def end function generate_available(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) available_def = quote function available(domain::$domain_type, state::$state_type, term::Term) available(domain, state, get_actions(domain)[term.name], term.args) end function available(domain::$domain_type, state::$state_type) f = named_action -> begin name, action = named_action grounded_args = groundargs(domain, state, action) return (Compound(name, collect(args)) for args in grounded_args if available(domain, state, action, args)) end actions = Base.Generator(f, pairs(get_actions(domain))) return Iterators.flatten(actions) end end return available_def end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
4043
abstract type CompiledAction <: Action end # Utility functions include("utils.jl") # Compiled types include("domain.jl") include("state.jl") include("action.jl") # Helper functions for objects/accessors/formulas include("objects.jl") include("accessors.jl") include("formulas.jl") # Interface functions include("satisfy.jl") include("evaluate.jl") include("initstate.jl") include("transition.jl") include("available.jl") include("execute.jl") """ compiled(domain, state) compiled(domain, problem) Compile a `domain` and `state` and return the resulting compiled domain and compiled state. A `problem` maybe provided instead of a state. !!! warning "Top-Level Only" Because `compiled` defines new types and methods, it should only be called at the top-level in order to avoid world-age errors. !!! warning "Precompilation Not Supported" Because `compiled` evaluates code in the `PDDL` module, it will lead to precompilation errors when used in another module or package. Modules which call `compiled` should hence disable precompilation. """ function compiled(domain::Domain, state::State) # Generate definitions domain_type, domain_typedef, domain_defs = generate_domain_type(domain, state) state_type, state_typedef, state_defs = generate_state_type(domain, state, domain_type) object_defs = generate_object_defs(domain, state, domain_type, state_type) evaluate_def = generate_evaluate(domain, state, domain_type, state_type) satisfy_def = generate_satisfy(domain, state, domain_type, state_type) action_defs = generate_action_defs(domain, state, domain_type, state_type) transition_def = generate_transition(domain, state, domain_type, state_type) # Generate warm-up and return expressions warmup_expr = :(_compiler_warmup($domain_type(), $state_type($state))) return_expr = :($domain_type(), $state_type($state)) # Evaluate definitions expr = Expr(:block, domain_typedef, domain_defs, state_typedef, state_defs, object_defs, evaluate_def, satisfy_def, action_defs, transition_def, warmup_expr, return_expr) return eval(expr) end function compiled(domain::Domain, problem::Problem) return compiled(domain, initstate(domain, problem)) end """ compilestate(domain, state) Return compiled version of a state compatible with the compiled `domain`. """ function compilestate(domain::CompiledDomain, state::State) S = statetype(domain) return S(state) end # Abstract a domain that is already compiled function abstracted(domain::CompiledDomain, state::State; options...) absdom = abstracted(get_source(domain); options...) return compiled(absdom, GenericState(state)) end # If compiled state is abstract, we can just copy construct function abstractstate(domain::CompiledDomain, state::State) S = statetype(domain) return S(state) end "Warm up interface functions for a compiled domain and state." function _compiler_warmup(domain::CompiledDomain, state::CompiledState) # Warm up state constructors and accessors hash(state) copy(state) state == state term = first(get_fluent_names(state)) state[term] = state[term] # Warm up satisfy and evaluate for term in get_fluent_names(state) is_pred(term, domain) || continue satisfy(domain, state, term) evaluate(domain, state, term) break end # Warm up action availability, execution, and state transition available(domain, state) for (name, act) in pairs(get_actions(domain)) all_args = groundargs(domain, state, act) isempty(all_args) && continue args = first(all_args) term = Compound(name, collect(Term, args)) if available(domain, state, term) execute!(domain, copy(state), term) execute(domain, state, term) transition!(domain, copy(state), term) transition(domain, state, term) end end return nothing end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2054
abstract type CompiledDomain <: Domain end get_source(::CompiledDomain) = error("Not implemented.") function generate_domain_type(domain::Domain, state::State) name = pddl_to_type_name(get_name(domain)) if domain isa AbstractedDomain domain_type = gensym("CompiledAbstracted" * name * "Domain") else domain_type = gensym("Compiled" * name * "Domain") end domain_typedef = :(struct $domain_type <: CompiledDomain end) domain_method_defs = generate_domain_methods(domain, domain_type) return (domain_type, domain_typedef, domain_method_defs) end function generate_domain_methods(domain::Domain, domain_type::Symbol) get_name_def = :(get_name(::$domain_type) = $(QuoteNode(get_name(domain)))) get_source_def = :(get_source(::$domain_type) = $(QuoteNode(domain))) get_requirements_def = :(get_requirements(::$domain_type) = $(QuoteNode((; get_requirements(domain)...)))) get_typetree_def = :(get_typetree(::$domain_type) = $(QuoteNode((; get_typetree(domain)...)))) get_constants_def = :(get_constants(::$domain_type) = $(QuoteNode(Tuple(get_constants(domain))))) get_constypes_def = :(get_constypes(domain::$domain_type) = get_constypes(get_source(domain))) get_predicates_def = :(get_predicates(::$domain_type) = $(QuoteNode((; get_predicates(domain)...)))) get_functions_def = :(get_functions(::$domain_type) = $(QuoteNode((; get_functions(domain)...)))) get_funcdefs_def = :(get_funcdefs(::$domain_type) = $(QuoteNode((; get_funcdefs(domain)...)))) get_fluents_def = :(get_fluents(::$domain_type) = $(QuoteNode((; get_fluents(domain)...)))) get_axioms_def = :(get_axioms(::$domain_type) = $(QuoteNode((; get_axioms(domain)...)))) domain_defs = Expr(:block, get_name_def, get_source_def, get_requirements_def, get_typetree_def, get_constants_def, get_constypes_def, get_predicates_def, get_functions_def, get_funcdefs_def, get_fluents_def, get_axioms_def) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1174
function generate_evaluate(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) evaluate_def = quote function evaluate(domain::$domain_type, state::$state_type, term::Const) val = if !(term.name isa Symbol) term.name elseif hasfield($state_type, term.name) getfield(state, term.name) elseif is_global_func(term) function_def(term.name)() elseif is_derived(term, domain) get_fluent(state, term) else term.name end return val end function evaluate(domain::$domain_type, state::$state_type, term::Compound) val = if is_global_func(term.name) func = function_def(term.name) argvals = (evaluate(domain, state, arg) for arg in term.args) func(argvals...) elseif is_logical_op(term) satisfy(domain, state, term) else get_fluent(state, term) end return val end end return evaluate_def end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2571
function generate_execute(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) execute_def = quote function execute(domain::$domain_type, state::$state_type, term::Term; check::Bool=false) execute(domain, state, get_action(domain, term.name), term.args; check=check) end function execute!(domain::$domain_type, state::$state_type, term::Term; check::Bool=false) execute!(domain, state, get_action(domain, term.name), term.args; check=check) end end return execute_def end function generate_execute(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol, action_name::Symbol, action_type::Symbol) action = get_actions(domain)[action_name] varmap = Dict{Var,Any}(a => :(args[$i].name) for (i, a) in enumerate(get_argvars(action))) # TODO: Fix mutating execute to ensure parallel composition of effects precond = to_nnf(get_precond(action)) precond = generate_check_expr(domain, state, precond, varmap, :prev_state) if domain isa AbstractedDomain precond = :($precond == true || $precond == both) end effect = generate_effect_expr(domain, state, get_effect(action), varmap) meffect = generate_effect_expr(domain, state, get_effect(action), varmap, :prev_state, :prev_state) execute_def = quote function execute(domain::$domain_type, prev_state::$state_type, action::$action_type, args; check::Bool=false) if check && !(@inbounds $precond) action_str = Writer.write_formula(get_name(action), args) error("Could not execute $action_str: " * "Precondition does not hold.") end state = copy(prev_state) @inbounds $effect return state end function execute!(domain::$domain_type, prev_state::$state_type, action::$action_type, args; check::Bool=false) if check && !(@inbounds $precond) action_str = Writer.write_formula(get_name(action), args) error("Could not execute $action_str: " * "Precondition does not hold.") end @inbounds $meffect return prev_state end end return execute_def end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
8547
function generate_eval_expr(domain::Domain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state) if (term.name in keys(get_fluents(domain)) || term isa Var) return generate_get_expr(domain, state, term, varmap, state_var) elseif term isa Const return QuoteNode(term.name) end subexprs = [generate_eval_expr(domain, state, a, varmap, state_var) for a in term.args] expr = if is_global_func(term) op = function_def(term.name) Expr(:call, QuoteNode(op), subexprs...) else error("Unrecognized predicate or operator $(term.name).") end return expr end function generate_quantified_expr(domain::Domain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state) @assert length(term.args) == 2 "$(term.name) takes two arguments" varmap = copy(varmap) # Make local copy of variable context typeconds, query = flatten_conjs(term.args[1]), term.args[2] types, vars = Symbol[], Symbol[] for (i, cond) in enumerate(typeconds) v = gensym("o$i") # Create local variable name push!(vars, v) push!(types, cond.name) # Extract type name varmap[cond.args[1]] = :($v.name) end # Generate query expression with local variable context expr = generate_check_expr(domain, state, query, varmap, state_var) # Construct iterator over (typed) objects v, ty = pop!(vars), QuoteNode(pop!(types)) expr = :($expr for $v in get_objects($state_var, $ty)) while !isempty(types) v, ty = pop!(vars), QuoteNode(pop!(types)) expr = Expr(:flatten, :($expr for $v in get_objects($state_var, $ty))) end if domain isa AbstractedDomain accum = term.name == :forall ? :all4 : :any4 return :($accum($expr)) else accum = term.name == :forall ? :all : :any return :($accum($expr)) end end function generate_axiom_expr(domain::Domain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state) axiom = Julog.freshen(get_axiom(domain, term.name)) subst = unify(axiom.head, term) @assert subst !== nothing "Malformed derived predicate: $term" body = length(axiom.body) == 1 ? axiom.body[1] : Compound(:and, axiom.body) body = to_nnf(substitute(body, subst)) return generate_check_expr(domain, state, body, varmap, state_var) end function generate_check_expr(domain::Domain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state) if (is_global_func(term) || term.name in keys(get_funcdefs(domain))) return generate_eval_expr(domain, state, term, varmap, state_var) elseif (term.name in keys(get_fluents(domain)) || term isa Var) return generate_get_expr(domain, state, term, varmap, state_var) elseif term.name in (:forall, :exists) return generate_quantified_expr(domain, state, term, varmap, state_var) elseif term isa Const return QuoteNode(term.name::Bool) end subexprs = [generate_check_expr(domain, state, a, varmap, state_var) for a in term.args] expr = if term.name == :and foldr((a, b) -> Expr(:&&, a, b), subexprs) elseif term.name == :or foldr((a, b) -> Expr(:||, a, b), subexprs) elseif term.name == :imply @assert length(term.args) == 2 "imply takes two arguments" :(!$(subexprs[1]) || $(subexprs[2])) elseif term.name == :not @assert length(term.args) == 1 "not takes one argument" :(!$(subexprs[1])) else error("Unrecognized predicate or operator $(term.name).") end return expr end function generate_check_expr(domain::AbstractedDomain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state) if (is_global_func(term) || term.name in keys(get_funcdefs(domain))) return generate_eval_expr(domain, state, term, varmap, state_var) elseif (term.name in keys(get_fluents(domain)) || term isa Var) return generate_get_expr(domain, state, term, varmap, state_var) elseif term.name in (:forall, :exists) return generate_quantified_expr(domain, state, term, varmap, state_var) elseif term isa Const return QuoteNode(term.name::Bool) end subexprs = [generate_check_expr(domain, state, a, varmap, state_var) for a in term.args] expr = if term.name == :and generate_abstract_and_stmt(subexprs) elseif term.name == :or generate_abstract_or_stmt(subexprs) elseif term.name == :imply @assert length(term.args) == 2 "imply takes two arguments" :(!$(subexprs[1]) | $(subexprs[2])) elseif term.name == :not @assert length(term.args) == 1 "not takes one argument" :(!$(subexprs[1])) else error("Unrecognized predicate or operator $(term.name).") end return expr end function generate_forall_effect_expr(domain::Domain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state, prev_var=:prev_state) @assert length(term.args) == 2 "$(term.name) takes two arguments" varmap = copy(varmap) # Make local copy of variable context typeconds, effect = flatten_conjs(term.args[1]), term.args[2] types, vars = Symbol[], Symbol[] for (i, cond) in enumerate(typeconds) v = gensym("o$i") # Create local variable name push!(vars, v) push!(types, cond.name) # Extract type name varmap[cond.args[1]] = :($v.name) end # Generate effect expression with local variable context expr = generate_effect_expr(domain, state, effect, varmap, state_var, prev_var) # Special case if only one object variable is enumerated over if length(vars) == 1 v, ty = vars[1], QuoteNode(types[1]) expr = quote for $v in get_objects($state_var, $ty) $expr end end return expr end # Construct iterator over (typed) objects obj_exprs = (:(get_objects($state_var, $(QuoteNode(ty)))) for ty in types) expr = quote for ($(vars...),) in zip($(obj_exprs...)) $expr end end return expr end function generate_effect_expr(domain::Domain, state::State, term::Term, varmap=Dict{Var,Any}(), state_var=:state, prev_var=:prev_state) expr = if term.name == :and subexprs = [generate_effect_expr(domain, state, a, varmap, state_var, prev_var) for a in term.args] Expr(:block, subexprs...) elseif term.name == :assign @assert length(term.args) == 2 "assign takes two arguments" term, val = term.args val = generate_eval_expr(domain, state, val, varmap, prev_var) generate_set_expr(domain, state, term, val, varmap, state_var) elseif term.name == :not @assert length(term.args) == 1 "not takes one argument" term = term.args[1] @assert term.name in keys(get_predicates(domain)) "unrecognized predicate" generate_set_expr(domain, state, term, false, varmap, state_var) elseif term.name == :when @assert length(term.args) == 2 "when takes two arguments" cond, effect = term.args cond = generate_check_expr(domain, state, cond, varmap, prev_var) effect = generate_effect_expr(domain, state, effect, varmap, state_var, prev_var) :(cond = $cond; (cond == true || cond == both) && $effect) elseif term.name == :forall generate_forall_effect_expr(domain, state, term, varmap, state_var, prev_var) elseif is_global_modifier(term.name) @assert length(term.args) == 2 "$(term.name) takes two arguments" op = modifier_def(term.name) term, val = term.args prev_val = generate_get_expr(domain, state, term, varmap, prev_var) val = generate_eval_expr(domain, state, val, varmap, prev_var) new_val = Expr(:call, op, prev_val, val) generate_set_expr(domain, state, term, new_val, varmap, state_var) elseif term.name in keys(get_predicates(domain)) generate_set_expr(domain, state, term, true, varmap, state_var) else error("Unrecognized predicate or operator $(term.name).") end return expr end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
573
function initstate(domain::CompiledDomain, problem::GenericProblem) # Construct state using interpreter, then convert to compiled generic_state = initstate(get_source(domain), problem) compiled_state = statetype(domain)(generic_state) return compiled_state end function initstate(domain::CompiledDomain, objtypes::AbstractDict, fluents) # Construct state using interpreter, then convert to compiled generic_state = initstate(get_source(domain), objtypes, fluents) compiled_state = statetype(domain)(generic_state) return compiled_state end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1808
function generate_object_defs(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) objects = sort(collect(get_objects(state)), by=x->x.name) object_ids = (; ((o.name, i) for (i, o) in enumerate(objects))...) get_objects_def = :(get_objects(::$state_type) = $(QuoteNode(Tuple(objects)))) get_objtypes_def = :(get_objtypes(::$state_type) = $(QuoteNode(get_objtypes(state)))) objectindices_def = :(objectindices(::$state_type) = $(QuoteNode(object_ids))) objectindex_def = :(objectindex(state::$state_type, o::Symbol) = getfield(objectindices(state), o)) typed_defs = generate_object_typed_defs(domain, state, domain_type, state_type) return Expr(:block, get_objects_def, get_objtypes_def, objectindices_def, objectindex_def, typed_defs) end function generate_object_typed_defs(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) object_ids = Dict() for type in get_types(domain) objs = sort(get_objects(domain, state, type), by=x->x.name) object_ids[type] = (; ((o.name, i) for (i, o) in enumerate(objs))...) end object_ids = (; (ty => ids for (ty, ids) in object_ids)...) get_objects_def = :(get_objects(state::$state_type, type::Symbol) = Const.(keys(objectindices(state, type)))) objectindices_def = :(objectindices(state::$state_type, type::Symbol) = getfield($(QuoteNode(object_ids)), type)) objectindex_def = :(objectindex(state::$state_type, type::Symbol, obj::Symbol) = getfield(objectindices(state, type), obj)) return Expr(:block, get_objects_def, objectindices_def, objectindex_def) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
5268
function generate_satisfy(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) satisfy_def = quote function check(domain::$domain_type, state::$state_type, term::Var) return missing end function check(domain::$domain_type, state::$state_type, term::Const) val = if term.name isa Bool return term.name elseif hasfield($state_type, term.name) getfield(state, term.name) elseif is_global_pred(term) predicate_def(term.name)() elseif is_derived(term, domain) get_fluent(state, term) else false end return val end function check(domain::$domain_type, state::$state_type, term::Compound) val = if term.name == :and all(check(domain, state, a) for a in term.args) elseif term.name == :or any(check(domain, state, a) for a in term.args) elseif term.name == :imply !check(domain, state, term.args[1]) | check(domain, state, term.args[2]) elseif term.name == :not !check(domain, state, term.args[1]) elseif is_type(term, domain) term.args[1].name in keys(objectindices(state, term.name)) elseif !is_ground(term) missing elseif is_global_pred(term) predicate_def(term.name)(evaluate(domain, state, term.args[1]), evaluate(domain, state, term.args[2])) elseif is_derived(term, domain) get_fluent(state, term) else evaluate(domain, state, term) end return val end function satisfy(domain::$domain_type, state::$state_type, term::Term) val = check(domain, state, term) val !== missing ? val : !isempty(satisfiers(domain, state, term)) end function satisfy(domain::$domain_type, state::$state_type, terms::AbstractVector{<:Term}) val = all(check(domain, state, t) for t in terms) val !== missing ? val : !isempty(satisfiers(domain, state, terms)) end end return satisfy_def end function generate_satisfy(domain::AbstractedDomain, state::State, domain_type::Symbol, state_type::Symbol) satisfy_def = quote function check(domain::$domain_type, state::$state_type, term::Var) return missing end function check(domain::$domain_type, state::$state_type, term::Const) val = if term.name isa Bool return term.name elseif hasfield($state_type, term.name) getfield(state, term.name) elseif is_global_pred(term) predicate_def(term.name)() elseif is_derived(term, domain) get_fluent(state, term) else false end return val end function check(domain::$domain_type, state::$state_type, term::Compound) val = if term.name == :and all4(check(domain, state, a) for a in term.args) elseif term.name == :or any4(check(domain, state, a) for a in term.args) elseif term.name == :imply !check(domain, state, term.args[1]) | check(domain, state, term.args[2]) elseif term.name == :not !check(domain, state, term.args[1]) elseif is_type(term, domain) term.args[1].name in keys(objectindices(state, term.name)) elseif !is_ground(term) missing elseif is_global_pred(term) predicate_def(term.name)(evaluate(domain, state, term.args[1]), evaluate(domain, state, term.args[2])) elseif is_derived(term, domain) get_fluent(state, term) else evaluate(domain, state, term) end return val end function satisfy(domain::$domain_type, state::$state_type, term::Term) val = check(domain, state, term) return val !== missing ? (val == true || val == both) : !isempty(satisfiers(domain, state, term)) end function satisfy(domain::$domain_type, state::$state_type, terms::AbstractVector{<:Term}) val = all4(check(domain, state, t) for t in terms) return val !== missing ? (val == true || val == both) : !isempty(satisfiers(domain, state, terms)) end end return satisfy_def end function satisfiers(domain::CompiledDomain, state::CompiledState, terms::AbstractVector{<:Term}) gen_state = GenericState(state) return satisfiers(get_source(domain), gen_state, terms) end function satisfiers(domain::CompiledDomain, state::CompiledState, term::Term) gen_state = GenericState(state) return satisfiers(get_source(domain), gen_state, term) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
10640
abstract type CompiledState <: State end function generate_field_type(domain::Domain, sig::Signature{N}) where {N} dtype = get(get_datatypes(domain), sig.type, datatype_def(sig.type).type) return N == 0 ? dtype : (dtype == Bool ? BitArray{N} : Array{dtype,N}) end function generate_field_type(domain::AbstractedDomain, sig::Signature{N}) where {N} dtype = get(domain.interpreter.fluent_abstractions, sig.name) do get(domain.interpreter.type_abstractions, sig.type) do get(get_datatypes(domain), sig.type) do datatype_def(sig.type).type end end end return N == 0 ? dtype : Array{dtype,N} end function generate_pred_init(domain::Domain, state::State, sig::Signature{N}) where {N} if N == 0 return false end dims = generate_fluent_dims(domain, state, sig) return :(falses($(dims...))) end function generate_func_init(domain::Domain, state::State, sig::Signature{N}) where {N} default = QuoteNode(datatype_def(sig.type).default) if N == 0 return default end dims = generate_fluent_dims(domain, state, sig) return :(fill($default, $(dims...))) end function generate_func_init(domain::AbstractedDomain, state::State, sig::Signature{N}) where {N} abstype = get(domain.interpreter.fluent_abstractions, sig.name) do get(domain.interpreter.type_abstractions, sig.type, nothing) end if isnothing(abstype) default = QuoteNode(datatype_def(sig.type).default) else default = QuoteNode(abstype(datatype_def(sig.type).default)) end if N == 0 return default end dims = generate_fluent_dims(domain, state, sig) return :(fill($default, $(dims...))) end function generate_state_type(domain::Domain, state::State, domain_type::Symbol) # Generate type definition state_fields = Expr[] for (name, pred) in sortedpairs(get_predicates(domain)) name in keys(get_axioms(domain)) && continue # Skip derived predicates type = generate_field_type(domain, pred) field = Expr(:(::), pred.name, QuoteNode(type)) push!(state_fields, field) end for (name, fn) in sortedpairs(get_functions(domain)) type = generate_field_type(domain, fn) field = Expr(:(::), fn.name, QuoteNode(type)) push!(state_fields, field) end if domain isa AbstractedDomain name = "CompiledAbstracted" * pddl_to_type_name(get_name(domain)) * "State" else name = "Compiled" * pddl_to_type_name(get_name(domain)) * "State" end state_type = gensym(name) state_typesig = Expr(:(<:), state_type, QuoteNode(CompiledState)) state_typedef = :(@auto_hash_equals $(Expr(:struct, true, state_typesig, Expr(:block, state_fields...)))) state_constructor_defs = generate_state_constructors(domain, state, domain_type, state_type) state_method_defs = generate_state_methods(domain, state, domain_type, state_type) state_defs = Expr(:block, state_constructor_defs, state_method_defs) return (state_type, state_typedef, state_defs) end function generate_state_constructors(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) # Generate constructor with no arguments state_inits = [] state_copies = Expr[] for (name, pred) in sortedpairs(get_predicates(domain)) name in keys(get_axioms(domain)) && continue # Skip derived predicates push!(state_inits, generate_pred_init(domain, state, pred)) copy_expr = arity(pred) == 0 ? :(state.$name) : :(copy(state.$name)) push!(state_copies, copy_expr) end for (name, fn) in sortedpairs(get_functions(domain)) push!(state_inits, generate_func_init(domain, state, fn)) if arity(fn) == 0 copy_expr = :(isbits(state.$name) ? state.$name : copy(state.$name)) else copy_expr = :(isbitstype(eltype(state.$name)) ? copy(state.$name) : deepcopy(state.$name)) end push!(state_copies, copy_expr) end state_constructor_defs = quote $state_type() = $state_type($(state_inits...)) $state_type(state::$state_type) = $state_type($(state_copies...)) function $state_type(state::State) new = $state_type() for (term, val) in get_fluents(state) if val === false continue end set_fluent!(new, val, term) end return new end end return state_constructor_defs end function generate_state_methods(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) # Construct domaintype and statetype methods types_def = quote domaintype(::Type{$state_type}) = $domain_type domaintype(::$state_type) = $domain_type statetype(::Type{$domain_type}) = $state_type statetype(::$domain_type) = $state_type get_domain(::$state_type) = $domain_type() end # Fluent name listing get_fluent_names_def = quote function get_fluent_names(state::$state_type) domain = get_domain(state) f = name -> begin grounded_args = groundargs(domain, state, name) return (!isempty(args) ? Compound(name, collect(args)) : Const(name) for args in grounded_args) end fluents = Base.Generator(f, fieldnames($state_type)) return Iterators.flatten(fluents) end end # Fluent accessors fluent_conds, get_fluent_brs, set_fluent_brs, groundargs_defs = Expr[], Expr[], Expr[], Expr[] unpacked_conds, unpacked_get_brs, unpacked_set_brs = Expr[], Expr[], Expr[] for (name, sig) in pairs(get_fluents(domain)) # Ground args def = generate_groundargs(domain, state, domain_type, state_type, name) push!(groundargs_defs, def) # Generate accessor branch conditions push!(fluent_conds, :(term.name == $(QuoteNode(name)))) push!(unpacked_conds, :(name == $(QuoteNode(name)))) # Generate accesor branch defs for derived predicates if name in keys(get_axioms(domain)) term = convert(Term, sig) varmap = Dict(a => :(term.args[$i].name) for (i, a) in enumerate(sig.args)) get_expr = generate_axiom_expr(domain, state, term, varmap) set_expr = :(error("Cannot set value of derived predicate: $name")) push!(get_fluent_brs, get_expr) push!(set_fluent_brs, set_expr) varmap = Dict(a => :(args[$i]) for (i, a) in enumerate(sig.args)) get_expr = generate_axiom_expr(domain, state, term, varmap) push!(unpacked_get_brs, get_expr) push!(unpacked_set_brs, set_expr) continue end # Generate accessor branch defs for 0-arity fluents if length(sig.args) == 0 get_expr = :(state.$name) set_expr = :(state.$name = val) push!(get_fluent_brs, get_expr) push!(set_fluent_brs, set_expr) push!(unpacked_get_brs, get_expr) push!(unpacked_set_brs, set_expr) continue end # Generate accessor branch defs multiple-arity fluents term = convert(Term, sig) varmap = Dict(a => :(term.args[$i].name) for (i, a) in enumerate(sig.args)) idxs = generate_fluent_ids(domain, state, term, sig, varmap) push!(get_fluent_brs, :(@inbounds state.$name[$(idxs...)])) push!(set_fluent_brs, :(@inbounds state.$name[$(idxs...)] = val)) varmap = Dict(a => :(args[$i]) for (i, a) in enumerate(sig.args)) idxs = generate_fluent_ids(domain, state, term, sig, varmap) push!(unpacked_get_brs, :(@inbounds state.$name[$(idxs...)])) push!(unpacked_set_brs, :(@inbounds state.$name[$(idxs...)] = val)) end err_br = :(error("Unrecognized fluent: $(term.name)")) unpacked_err_br = :(error("Unrecognized fluent: $name")) get_fluent_def = quote function get_fluent(state::$state_type, term::Term) return $(generate_switch_stmt(fluent_conds, get_fluent_brs, err_br)) end function get_fluent(state::$state_type, name::Symbol, args...) return $(generate_switch_stmt(unpacked_conds, unpacked_get_brs, unpacked_err_br)) end end set_fluent_def = quote function set_fluent!(state::$state_type, val, term::Term) return $(generate_switch_stmt(fluent_conds, set_fluent_brs, err_br)) end function set_fluent!(state::$state_type, val, name::Symbol, args...) return $(generate_switch_stmt(unpacked_conds, unpacked_set_brs, unpacked_err_br)) end end state_method_defs = Expr(:block, types_def, get_fluent_names_def, groundargs_defs..., get_fluent_def, set_fluent_def) return state_method_defs end function generate_groundargs(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol, fluent::Symbol) sig = get_fluent(domain, fluent) argtypes = sig.argtypes if get_requirements(domain)[:typing] objs_exprs = [:(get_objects(state, $(QuoteNode(ty)))) for ty in argtypes] else objs_exprs = [:(get_objects(state)) for ty in argtypes] end iter_expr = :(Iterators.product($(objs_exprs...))) valtype = QuoteNode(Val{fluent}) groundargs_def = quote function groundargs(domain::$domain_type, state::$state_type, fluent::$valtype) return $iter_expr end end return groundargs_def end function (::Type{S})(state::State) where {S <: CompiledState} new = S() for (term, val) in get_fluents(state) if val === false continue end set_fluent!(new, val, term) end return new end Base.copy(state::S) where {S <: CompiledState} = S(state) groundargs(domain::CompiledDomain, state::State, fluent::Symbol) = groundargs(domain, state, Val(fluent)) get_fluents(state::CompiledState) = (term => get_fluent(state, term) for term in get_fluent_names(state)) get_facts(state::CompiledState) = (term for term in get_fluent_names(state) if get_fluent(state, term) in (true, both))
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1064
function generate_transition(domain::Domain, state::State, domain_type::Symbol, state_type::Symbol) transition_def = quote function transition(domain::$domain_type, state::$state_type, term::Term; check::Bool=false) if term.name == PDDL.no_op.name && isempty(term.args) execute(domain, state, PDDL.NoOp(), term.args; check=check) else execute(domain, state, get_action(domain, term.name), term.args; check=check) end end function transition!(domain::$domain_type, state::$state_type, term::Term; check::Bool=false) if term.name == PDDL.no_op.name && isempty(term.args) execute(domain, state, PDDL.NoOp(), term.args; check=check) else execute(domain, state, get_action(domain, term.name), term.args; check=check) end end end return transition_def end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1696
"Convert PDDL name-with-hyphens to CamelCase type name." function pddl_to_type_name(name) words = split(lowercase(string(name)), '-', keepempty=false) return join(uppercasefirst.(words)) end "Returns a list of pairs from a collection, sorted by key." sortedpairs(collection) = sort(collect(pairs(collection)), by=first) "Returns the sorted list of keys for a collection." sortedkeys(collection) = sort(collect(keys(collection))) "Generates a switch statement using `if` and `elseif`." function generate_switch_stmt(cond_exprs, branch_exprs, default_expr=:nothing) @assert length(cond_exprs) == length(branch_exprs) expr = default_expr for i in length(cond_exprs):-1:1 head = i == 1 ? :if : :elseif expr = Expr(head, cond_exprs[i], branch_exprs[i], expr) end return expr end "Generate short-circuiting and statement which handles `both` values." function generate_abstract_and_stmt(subexprs) foldr(subexprs) do a, b quote let u = $a if isboth(u) $b === false ? false : both elseif u $b else false end end end end |> Base.remove_linenums! end "Generate short-circuiting or statement which handles `both` values." function generate_abstract_or_stmt(subexprs) foldr(subexprs) do a, b quote let u = $a if isboth(u) $b === true ? true : both elseif u true else $b end end end end |> Base.remove_linenums! end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
859
"Generic PDDL action definition." struct GenericAction <: Action name::Symbol # Name of action args::Vector{Var} # GenericAction parameters types::Vector{Symbol} # Parameter types precond::Term # Precondition of action effect::Term # Effect of action end GenericAction(term::Term, precond::Term, effect::Term) = GenericAction(term.name, get_args(term), Symbol[], precond, effect) Base.:(==)(a1::GenericAction, a2::GenericAction) = (a1.name == a2.name && Set(a1.args) == Set(a2.args) && Set(a1.types) == Set(a2.types) && a1.precond == a2.precond && a1.effect == a2.effect) get_name(action::GenericAction) = action.name get_argvars(action::GenericAction) = action.args get_argtypes(action::GenericAction) = action.types get_precond(action::GenericAction) = action.precond get_effect(action::GenericAction) = action.effect
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2433
""" GenericDiff(add, del, ops) Generic state difference represented as additions, deletions, and assignments. # Fields $(FIELDS) """ struct GenericDiff <: Diff "List of added `Term`s" add::Vector{Term} "List of deleted `Term`s" del::Vector{Term} "Dictionary mapping fluents to their assigned expressions." ops::Dict{Term,Term} end GenericDiff() = GenericDiff(Term[], Term[], Dict{Term,Any}()) function combine!(d1::GenericDiff, d2::GenericDiff) append!(d1.add, d2.add) append!(d1.del, d2.del) merge!(d1.ops, d2.ops) return d1 end function as_term(diff::GenericDiff) add = diff.add del = [Compound(:not, [t]) for t in diff.del] ops = [Compound(:assign, [t, v]) for (t, v) in diff.ops] return Compound(:and, [add; del; ops]) end is_redundant(diff::GenericDiff) = issetequal(diff.add, diff.del) && all(k == v for (k, v) in diff.ops) Base.empty(diff::GenericDiff) = GenericDiff() Base.isempty(diff::GenericDiff) = isempty(diff.add) && isempty(diff.del) && isempty(diff.ops) """ ConditionalDiff(conds, diffs) Conditional state difference, represented as paired conditions and sub-diffs. # Fields $(FIELDS) """ struct ConditionalDiff{D <: Diff} <: Diff "List of list of condition `Term`s for each sub-diff." conds::Vector{Vector{Term}} "List of sub-diffs." diffs::Vector{D} end ConditionalDiff{D}() where {D} = ConditionalDiff{D}([], Vector{D}()) function combine!(d1::ConditionalDiff{D}, d2::D) where {D} for (i, cs) in enumerate(d1.conds) if isempty(cs) combine!(d1.diffs[i], d2) return d1 end end push!(d1.conds, Term[]) push!(d1.diffs, d2) return d1 end function combine!(d1::ConditionalDiff{D}, d2::ConditionalDiff{D}) where {D} append!(d1.conds, d2.conds) append!(d1.diffs, d2.diffs) return d1 end function as_term(diff::ConditionalDiff) branches = map(zip(diff.conds, diff.diffs)) do (cs, d) effect = as_term(d) isempty(cs) && return effect cond = length(cs) == 1 ? cs[1] : Compound(:and, cs) return Compound(:when, [cond, effect]) end return Compound(:and, branches) end is_redundant(diff::ConditionalDiff) = all(is_redundant.(diff.diffs)) Base.empty(diff::ConditionalDiff{D}) where {D} = ConditionalDiff{D}() Base.isempty(diff::ConditionalDiff) = all(isempty.(diff.conds)) && all(isempty.(diff.diffs))
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3666
"Generic PDDL planning domain." @kwdef mutable struct GenericDomain <: Domain name::Symbol # Name of domain requirements::Dict{Symbol,Bool} = # PDDL requirements copy(DEFAULT_REQUIREMENTS) typetree::Dict{Symbol,Vector{Symbol}} = # Types and their subtypes Dict(:object => Symbol[]) datatypes::Dict{Symbol,Type} = # Non-object data types Dict{Symbol,Type}() constants::Vector{Const} = # List of object constants Const[] constypes::Dict{Const,Symbol} = # Types of constants Dict{Const,Symbol}() predicates::Dict{Symbol,Signature} = # Predicate signatures Dict{Symbol,Signature}() functions::Dict{Symbol,Signature} = # Function signatures Dict{Symbol,Signature}() funcdefs::Dict{Symbol,Any} = # External function implementations Dict{Symbol,Any}() axioms::Dict{Symbol,Clause} = # Axioms / derived predicates Dict{Symbol,Clause}() actions::Dict{Symbol,Action} = # Action definitions Dict{Symbol,Any}() _extras::Dict{Symbol,Any} = # Extra fields for PDDL extensions Dict{Symbol,Any}() end function GenericDomain(name::Symbol, header::Dict{Symbol,Any}, body::Dict{Symbol,Any}) h_extras = filter(item -> !(first(item) in fieldnames(GenericDomain)), header) b_extras = filter(item -> !(first(item) in fieldnames(GenericDomain)), body) extras = merge!(h_extras, b_extras) header = filter(item -> first(item) in fieldnames(GenericDomain), header) axioms = Clause[get(body, :axioms, []); get(body, :deriveds, [])] body = filter(item -> first(item) in fieldnames(GenericDomain), body) body[:axioms] = Dict(ax.head.name => ax for ax in axioms) body[:actions] = Dict(act.name => act for act in body[:actions]) return GenericDomain(;name=name, _extras=extras, header..., body...) end Base.getproperty(d::GenericDomain, s::Symbol) = hasfield(GenericDomain, s) ? getfield(d, s) : d._extras[s] Base.setproperty!(d::GenericDomain, s::Symbol, val) = hasfield(GenericDomain, s) && s != :_extras ? setfield!(d, s, val) : setindex!(d._extras, val, s) function Base.propertynames(d::GenericDomain, private::Bool=false) if private tuple(fieldnames(GenericDomain)..., keys(d._extras)...) else tuple(filter(f -> f != :_extras, fieldnames(GenericDomain))..., keys(d._extras)...) end end Base.copy(domain::GenericDomain) = deepcopy(domain) get_name(domain::GenericDomain) = domain.name get_source(domain::GenericDomain) = domain get_requirements(domain::GenericDomain) = domain.requirements get_typetree(domain::GenericDomain) = domain.typetree get_datatypes(domain::GenericDomain) = domain.datatypes get_constants(domain::GenericDomain) = domain.constants get_constypes(domain::GenericDomain) = domain.constypes get_predicates(domain::GenericDomain) = domain.predicates get_functions(domain::GenericDomain) = domain.functions get_funcdefs(domain::GenericDomain) = domain.funcdefs get_fluents(domain::GenericDomain) = merge(domain.predicates, domain.functions) get_axioms(domain::GenericDomain) = domain.axioms get_actions(domain::GenericDomain) = domain.actions """ include_no_op!(domain::GenericDomain) Adds the [`NoOp`](@ref) action to the set of available actions. """ function include_no_op!(domain::GenericDomain) domain.actions[get_name(PDDL.NoOp())] = PDDL.NoOp() return domain end """ include_no_op(domain::GenericDomain) Returns a copy of the domain with the [`NoOp`](@ref) action added to the set of available actions. """ function include_no_op(domain::GenericDomain) return include_no_op!(deepcopy(domain)) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
278
# Generic concrete representations of PDDL domains, states, actions, etc. # include("domain.jl") include("problem.jl") include("state.jl") include("action.jl") include("diff.jl") domaintype(::Type{GenericState}) = GenericDomain statetype(::Type{GenericDomain}) = GenericState
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2640
"Generic PDDL planning problem." @kwdef mutable struct GenericProblem <: Problem name::Symbol # Name of problem domain::Symbol = gensym() # Name of associated domain objects::Vector{Const} = Const[] # List of objects objtypes::Dict{Const,Symbol} = Dict{Const,Symbol}() # Types of objects init::Vector{Term} = Term[] # Predicates that hold in initial state goal::Term = Compound(:and, []) # Goal formula metric::Union{Term,Nothing} = nothing # Metric formula constraints::Union{Term,Nothing} = nothing # Constraints formula end GenericProblem(problem::GenericProblem) = copy(problem) function GenericProblem(problem::Problem) return GenericProblem( get_name(problem), get_domain_name(problem), collect(Const, get_objects(problem)), Dict{Const,Symbol}(pairs(get_objtypes(state))...), collect(Term, get_init_terms(problem)), get_goal(problem), get_metric(problem), get_constraints(problem) ) end function GenericProblem( name::Symbol, header::Dict{Symbol,Any}, body::Dict{Symbol,Any} ) header = filter(item -> first(item) in fieldnames(GenericProblem), header) body = filter(item -> first(item) in fieldnames(GenericProblem), body) return GenericProblem(;name=name, header..., body...) end function GenericProblem( state::State; domain=:domain, name=Symbol(domain, "-problem"), goal::Term=Compound(:and, []), metric=nothing, constraints=nothing, ) objtypes = Dict{Const,Symbol}(pairs(get_objtypes(state))...) objects = collect(get_objects(state)) init = Term[] for (name, val) in get_fluents(state) if val isa Bool && val == true # Handle Boolean predicates term = name else # Handle non-Boolean fluents val = val_to_term(val) # Express value as term term = Compound(:(==), Term[name, val]) # Assignment expression end push!(init, term) end return GenericProblem(Symbol(name), Symbol(domain), objects, objtypes, init, goal, metric, constraints) end Base.copy(problem::GenericProblem) = deepcopy(problem) get_name(problem::GenericProblem) = problem.name get_domain_name(problem::GenericProblem) = problem.domain get_objects(problem::GenericProblem) = problem.objects get_objtypes(problem::GenericProblem) = problem.objtypes get_init_terms(problem::GenericProblem) = problem.init get_goal(problem::GenericProblem) = problem.goal get_metric(problem::GenericProblem) = problem.metric get_constraints(problem::GenericProblem) = problem.constraints
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3899
"Generic PDDL state description." mutable struct GenericState <: State types::Set{Compound} # Object type declarations facts::Set{Term} # Boolean-valued fluents values::Dict{Symbol,Any} # All other fluents end GenericState(types) = GenericState(types, Set{Term}(), Dict{Symbol,Any}()) GenericState(types, facts) = GenericState(types, facts, Dict{Symbol,Any}()) GenericState(state::GenericState) = copy(state) function GenericState(state::State) types = Set{Compound}((Compound(ty, [o]) for (o, ty) in get_objtypes(state))) new = GenericState(types) for (term, val) in get_fluents(state) if val === false continue end set_fluent!(new, val, term) end return new end Base.copy(s::GenericState) = GenericState(copy(s.types), copy(s.facts), deepcopy(s.values)) Base.:(==)(s1::GenericState, s2::GenericState) = issetequal(s1.types, s2.types) && issetequal(s1.facts, s2.facts) && isequal(s1.values, s2.values) Base.hash(s::GenericState, h::UInt) = hash(s.values, hash(s.facts, hash(s.types, h))) Base.issubset(s1::GenericState, s2::GenericState) = s1.types ⊆ s2.types && s1.facts ⊆ s2.facts stateindex(domain::GenericDomain, state::GenericState) = hash(state) get_objects(state::GenericState) = Const[ty.args[1] for ty in state.types] get_objects(state::GenericState, type::Symbol) = Const[ty.args[1] for ty in state.types if ty.name == type] get_objtypes(state::GenericState) = Dict(ty.args[1] => ty.name for ty in state.types) get_facts(state::GenericState) = state.facts function get_fluent(state::GenericState, term::Const) if term in state.facts return true elseif !(term.name isa Symbol) || is_global_func(term) error("$(write_pddl(term)) is not a fluent, use `evaluate` instead.") else return get(state.values, term.name, false) end end function get_fluent(state::GenericState, term::Compound) if term in state.facts return true else d = get(state.values, term.name, nothing) if !isnothing(d) return get(d, Tuple(a.name for a in term.args)) do error("Fluent $term undefined for arguments $(term.args)") end elseif is_logical_op(term) || is_global_func(term) error("$(write_pddl(term)) is not a fluent, use `evaluate` instead.") else return false end end end function set_fluent!(state::GenericState, val::Bool, term::Compound) if val push!(state.facts, term) else delete!(state.facts, term) end return val end function set_fluent!(state::GenericState, val::Bool, term::Const) if val push!(state.facts, term) else delete!(state.facts, term) end return val end function set_fluent!(state::GenericState, val::Any, term::Const) if !(term.name isa Symbol) || is_global_func(term) error("$(write_pddl(term)) is not a fluent and cannot be set.") end state.values[term.name] = val end function set_fluent!(state::GenericState, val::Any, term::Compound) d = get!(state.values, term.name) do is_logical_op(term) || is_global_func(term) ? error("$(write_pddl(term)) is not a fluent and cannot be set") : Dict() end d[Tuple(a.name for a in term.args)] = val end get_fluents(state::GenericState) = ((name => get_fluent(state, name)) for name in get_fluent_names(state)) function get_fluent_names(state::GenericState) f = x -> begin name, val = x if isa(val, Dict) return (Compound(name, Const.(collect(args))) for args in keys(val)) else return (Const(name),) end end fluent_names = Iterators.flatten(Base.Generator(f, state.values)) return Iterators.flatten((state.facts, fluent_names)) end get_fluent_values(state::GenericState) = (get_fluent(state, name) for name in get_fluent_names(state))
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
8469
""" GroundAction(name, term, preconds, effect) Ground action definition, represented by the `name` of its corresponding action schema, a `term` with grounded arguments, a list of `preconds`, and an `effect`, represented as a [`PDDL.GenericDiff`](@ref) or [`PDDL.ConditionalDiff`](@ref). """ struct GroundAction <: Action name::Symbol term::Compound preconds::Vector{Term} effect::Union{GenericDiff,ConditionalDiff} end get_name(action::GroundAction) = action.name get_argvals(action::GroundAction) = term.args get_precond(action::GroundAction) = Compound(:and, action.preconds) get_precond(action::GroundAction, args) = all(args .== action.term.args) ? get_precond(action) : error("Argument mismatch.") get_effect(action::GroundAction) = as_term(action.effect) get_effect(action::GroundAction, args) = all(args .== action.term.args) ? get_effect(action) : error("Argument mismatch.") Base.convert(::Type{Compound}, action::GroundAction) = action.term Base.convert(::Type{Const}, action::GroundAction) = isempty(action.term.args) ? action.term : error("Action has arguments.") "Group of ground actions with a shared schema." struct GroundActionGroup <: Action name::Symbol args::Vector{Var} types::Vector{Symbol} actions::Dict{Compound,GroundAction} end function GroundActionGroup(name::Symbol, args, types, actions::AbstractVector{GroundAction}) actions = Dict(act.term => act for act in actions) return GroundActionGroup(name, args, types, actions) end get_name(action::GroundActionGroup) = action.name get_argvars(action::GroundActionGroup) = action.args get_argtypes(action::GroundActionGroup) = action.types function get_precond(action::GroundActionGroup, args) term = Compound(action.name, args) return get_precond(action.actions[term]) end function get_effect(action::GroundActionGroup, args) term = Compound(action.name, args) return get_effect(action.actions[term]) end "Maximum limit for grounding by enumerating over typed objects." const MAX_GROUND_BY_TYPE_LIMIT = 250 "Minimum number of static conditions for grounding by static satisfaction." const MIN_GROUND_BY_STATIC_LIMIT = 1 "Returns an iterator over all ground arguments of an `action`." function groundargs(domain::Domain, state::State, action::Action; statics=nothing) if isempty(get_argtypes(action)) return ((),) end # Extract static preconditions statics = (statics === nothing) ? infer_static_fluents(domain) : statics preconds = flatten_conjs(get_precond(action)) filter!(p -> p.name in statics, preconds) # Decide whether to generate by satisfying static preconditions n_groundings = prod(get_object_count(domain, state, ty) for ty in get_argtypes(action)) use_preconds = n_groundings > MAX_GROUND_BY_TYPE_LIMIT && length(preconds) >= MIN_GROUND_BY_STATIC_LIMIT if use_preconds # Filter using preconditions # Add type conditions for correctness act_vars, act_types = get_argvars(action), get_argtypes(action) typeconds = (pddl"($ty $v)" for (v, ty) in zip(act_vars, act_types)) conds = [preconds; typeconds...] # Find all arguments that satisfy static preconditions argvars = get_argvars(action) iter = ([subst[v] for v in argvars] for subst in satisfiers(domain, state, conds)) return iter else # Iterate over domain of each type iters = (get_objects(domain, state, ty) for ty in get_argtypes(action)) return Iterators.product(iters...) end end """ groundactions(domain::Domain, state::State, action::Action) Returns ground actions for a lifted `action` in a `domain` and initial `state`. """ function groundactions(domain::Domain, state::State, action::Action; statics=infer_static_fluents(domain)) ground_acts = GroundAction[] # Dequantify and flatten preconditions and effects precond = to_nnf(dequantify(get_precond(action), domain, state, statics)) effects = flatten_conditions(dequantify(get_effect(action), domain, state, statics)) # Iterate over possible groundings for args in groundargs(domain, state, action; statics=statics) # Construct ground action for each set of arguments act = ground(domain, state, action, args; statics=statics, precond=precond, effects=effects) # Skip actions that are never satisfiable if (act === nothing) continue end push!(ground_acts, act) end return ground_acts end function groundactions(domain::Domain, state::State, action::GroundActionGroup, statics=nothing) return values(action.actions) end """ groundactions(domain::Domain, state::State) Returns all ground actions for a `domain` and initial `state`. """ function groundactions(domain::Domain, state::State; statics=infer_static_fluents(domain)) iters = (groundactions(domain, state, act; statics=statics) for act in values(get_actions(domain))) return collect(Iterators.flatten(iters)) end """ ground(domain::Domain, state::State, action::Action, args) Return ground action given a lifted `action` and action `args`. If the action is never satisfiable given the `domain` and `state`, return `nothing`. """ function ground(domain::Domain, state::State, action::Action, args; statics=infer_static_fluents(domain), precond=to_nnf(dequantify(get_precond(action), domain, state, statics)), effects=flatten_conditions(dequantify(get_effect(action), domain, state, statics)) ) act_name = get_name(action) act_vars = get_argvars(action) term = Compound(act_name, collect(args)) # Substitute and simplify precondition subst = Subst(var => val for (var, val) in zip(act_vars, args)) precond = substitute(precond, subst) precond = simplify_statics(precond, domain, state, statics) # Return nothing if unsatisfiable if (precond.name == false) return nothing end # Unpack effects into conditions and effects conds, effects = effects # Simplify conditions of conditional effects conds = map(conds) do cs isempty(cs) && return cs cond = substitute(Compound(:and, cs), subst) cond = simplify_statics(cond, domain, state, statics) return to_cnf_clauses(cond) end # Construct diffs from conditional effect terms diffs = map(effects) do es eff = substitute(Compound(:and, es), subst) return effect_diff(domain, state, eff) end # Delete unsatisfiable branches unsat_idxs = findall(cs -> Const(false) in cs, conds) deleteat!(conds, unsat_idxs) deleteat!(diffs, unsat_idxs) # Decide whether to simplify precondition to CNF if is_dnf(precond) # Split disjunctive precondition into conditional effects conds = map(precond.args) do clause terms = flatten_conjs(clause) return [Term[terms; cs] for cs in conds] end conds = reduce(vcat, conds) diffs = repeat(diffs, length(precond.args)) preconds = Term[] elseif is_cnf(precond) # Keep as CNF if possible preconds = precond.args else # Otherwise convert to CNF preconds = to_cnf_clauses(precond) end # Construct conditional diff if necessary if length(diffs) > 1 effect = ConditionalDiff(conds, diffs) elseif length(diffs) == 1 effect = diffs[1] preconds = append!(preconds, conds[1]) filter!(c -> c != Const(true), preconds) else # Return nothing if no satisfiable branches return nothing end # Return ground action return GroundAction(act_name, term, preconds, effect) end """ ground(domain::Domain, state::State, action::Action) Grounds a lifted `action` in a `domain` and initial `state`, returning a group of grounded actions. """ function ground(domain::Domain, state::State, action::Action; statics=infer_static_fluents(domain)) ground_acts = groundactions(domain, state, action; statics=statics) vars, types = get_argvars(action), get_argtypes(action) return GroundActionGroup(get_name(action), vars, types, ground_acts) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
837
function available(domain::GroundDomain, state::State) iters = ((t for (t, a) in group.actions if available(domain, state, a)) for (_, group) in domain.actions) return Iterators.flatten(iters) end function available(domain::GroundDomain, state::State, group::GroundActionGroup, args) term = Compound(group.name, args) return available(domain, state, group.actions[term]) end function available(domain::GroundDomain, state::State, term::Term) if term.name == PDDL.no_op.name return true end if (term isa Const) term = Compound(term.name, []) end action = domain.actions[term.name].actions[term] return available(domain, state, action) end function available(domain::GroundDomain, state::State, action::GroundAction) return satisfy(domain, state, action.preconds) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1471
# Utilities for converting axioms to ground actions "Converts a domain axiom to an action." function GenericAction(domain::Domain, axiom::Clause; negated::Bool=false) term = axiom.head name = term.name args = term.args types = collect(get_predicate(domain, name).argtypes) precond = Compound(:and, axiom.body) effect = axiom.head if negated name = Symbol(:not, :-, name) precond = Compound(:not, Term[precond]) effect = Compound(:not, Term[effect]) end return GenericAction(name, args, types, to_nnf(precond), effect) end """ groundaxioms(domain::Domain, state::State, axiom::Clause) Converts a PDDL axiom to a set of ground actions. """ function groundaxioms(domain::Domain, state::State, axiom::Clause; statics=infer_static_fluents(domain)) action = GenericAction(domain, axiom) neg_action = GenericAction(domain, axiom; negated=true) return [groundactions(domain, state, action; statics=statics); groundactions(domain, state, neg_action; statics=statics)] end """ groundaxioms(domain::Domain, state::State) Convert all axioms into ground actions for a `domain` and initial `state`. """ function groundaxioms(domain::Domain, state::State) statics = infer_static_fluents(domain) iters = (groundaxioms(domain, state, axiom; statics=statics) for axiom in values(get_axioms(domain))) return collect(Iterators.flatten(iters)) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1852
""" GroundDomain(name, source, actions) Ground PDDL domain, constructed from a lifted `source` domain, with a dictionary of ground `actions`. """ struct GroundDomain <: Domain name::Symbol # Domain name source::GenericDomain # Lifted source domain actions::Dict{Symbol,GroundActionGroup} end get_name(domain::GroundDomain) = domain.name get_source(domain::GroundDomain) = domain.source get_requirements(domain::GroundDomain) = get_requirements(domain.source) get_typetree(domain::GroundDomain) = get_typetree(domain.source) get_datatypes(domain::GroundDomain) = get_datatypes(domain.source) get_constants(domain::GroundDomain) = get_constants(domain.source) get_constypes(domain::GroundDomain) = get_constypes(domain.source) get_predicates(domain::GroundDomain) = get_predicates(domain.source) get_functions(domain::GroundDomain) = get_functions(domain.source) get_funcdefs(domain::GroundDomain) = get_funcdefs(domain.source) get_fluents(domain::GroundDomain) = get_fluents(domain.source) get_axioms(domain::GroundDomain) = get_axioms(domain.source) get_actions(domain::GroundDomain) = domain.actions """ ground(domain::Domain, state::State) ground(domain::Domain, problem::Problem) Grounds a lifted `domain` with respect to a initial `state` or `problem`. """ ground(domain::Domain, state::State) = ground(get_source(domain), GenericState(state)) ground(domain::Domain, problem::Problem) = ground(domain, initstate(domain, problem)) function ground(domain::GenericDomain, state::State) statics = infer_static_fluents(domain) ground_domain = GroundDomain(domain.name, domain, Dict()) for (name, act) in get_actions(domain) ground_domain.actions[name] = ground(domain, state, act; statics=statics) end return ground_domain end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1530
function execute(domain::GroundDomain, state::State, term::Term, options...) if term.name == PDDL.no_op.name return state end return execute!(domain, copy(state), term; options...) end function execute(domain::GroundDomain, state::State, action::GroundActionGroup, args; options...) return execute!(domain, copy(state), action, args; options...) end function execute(domain::GroundDomain, state::State, action::GroundAction; options...) return execute!(domain, copy(state), action; options...) end function execute!(domain::GroundDomain, state::State, term::Term; options...) if term.name == PDDL.no_op.name return state end if (term isa Const) term = Compound(term.name, []) end action = domain.actions[term.name].actions[term] return execute!(domain, state, action; options...) end function execute!(domain::GroundDomain, state::State, group::GroundActionGroup, args; options...) term = Compound(group.name, args) return execute!(domain, state, group.actions[term]; options...) end function execute!(domain::GroundDomain, state::State, action::GroundAction; check::Bool=true) # Check whether preconditions hold if check && !available(domain, state, action) action_str = write_pddl(action.term) error("Could not execute $action_str:\n" * "Precondition $(get_precond(action)) does not hold.") end # Update state with diff return update!(domain, state, action.effect) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
216
# Domain, action, and axiom grounding include("action.jl") include("axiom.jl") include("domain.jl") include("interface.jl") include("available.jl") include("execute.jl") include("transition.jl") include("utils.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1380
# Forward interface methods to concrete interpreter # satisfy(domain::GroundDomain, state::State, term::Term) = satisfy(ConcreteInterpreter(), domain, state, term) satisfy(domain::GroundDomain, state::State, terms::AbstractVector{<:Term}) = satisfy(ConcreteInterpreter(), domain, state, terms) satisfiers(domain::GroundDomain, state::State, term::Term) = satisfiers(ConcreteInterpreter(), domain, state, term) satisfiers(domain::GroundDomain, state::State, terms::AbstractVector{<:Term}) = satisfiers(ConcreteInterpreter(), domain, state, terms) evaluate(domain::GroundDomain, state::State, term::Term) = evaluate(ConcreteInterpreter(), domain, state, term) initstate(domain::GroundDomain, problem::Problem) = initstate(ConcreteInterpreter(), domain, problem) initstate(domain::GroundDomain, objtypes::AbstractDict, fluents) = initstate(ConcreteInterpreter(), domain, objtypes, fluents) goalstate(domain::GroundDomain, problem::Problem) = goalstate(ConcreteInterpreter(), domain, problem) goalstate(domain::GroundDomain, objtypes::AbstractDict, terms) = goalstate(ConcreteInterpreter(), domain, objtypes, terms) update!(domain::GroundDomain, state::State, diff::Diff) = update!(ConcreteInterpreter(), domain, state, diff) update(domain::GroundDomain, state::State, diff::Diff) = update(ConcreteInterpreter(), domain, state, diff)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
246
transition(domain::GroundDomain, state::State, action::Term; options...) = execute(domain, state, action; options...) transition!(domain::GroundDomain, state::State, action::Term; options...) = execute!(domain, state, action; options...)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
8606
# Various term manipulation utilities "Returns an iterator over all ground arguments of a `fluent`." function groundargs(domain::Domain, state::State, fluent::Symbol) if get_requirements(domain)[:typing] argtypes = get_fluent(domain, fluent).argtypes obj_iters = (get_objects(domain, state, ty) for ty in argtypes) else n = arity(get_fluent(domain, fluent)) obj_iters = (get_objects(state) for i in 1:n) end return Iterators.product(obj_iters...) end """ dequantify(term::Term, domain::Domain, state::State) Replaces universally or existentially quantified expressions with their corresponding conjuctions or disjunctions over the object types they quantify. """ function dequantify(term::Term, domain::Domain, state::State, statics=infer_static_fluents(domain)) if is_quantifier(term) conds, query = flatten_conjs(term.args[1]), term.args[2] query = dequantify(query, domain, state, statics) # Dequantify by type if no static fluents if statics === nothing || isempty(statics) return dequantify_by_type(term.name, conds, query, domain, state) else # Dequantify by static conditions otherwise return dequantify_by_stat_conds(term.name, conds, query, domain, state, statics) end elseif term.name in (:and, :or, :imply, :not, :when) args = Term[dequantify(arg, domain, state, statics) for arg in term.args] return Compound(term.name, args) else return term end end "Dequantifies a quantified expression by the types it is quantified over." function dequantify_by_type( name::Symbol, typeconds::Vector{Term}, query::Term, domain::Domain, state::State ) # Accumulate list of ground terms stack = Term[] subterms = Term[query] for cond in typeconds # Swap array references stack, subterms = subterms, stack # Substitute all objects of each type type, var = cond.name, cond.args[1] objects = get_objects(domain, state, type) while !isempty(stack) term = pop!(stack) for obj in objects push!(subterms, substitute(term, Subst(var => obj))) end end end # Return conjunction / disjunction of ground terms if name == :forall return isempty(subterms) ? Const(true) : Compound(:and, subterms) else # name == :exists return isempty(subterms) ? Const(false) : Compound(:or, subterms) end end "Dequantifies a quantified expression via static satisfaction (where useful)." function dequantify_by_stat_conds( name::Symbol, conds::Vector{Term}, query::Term, domain::Domain, state::State, statics::Vector{Symbol} ) vars = Var[c.args[1] for c in conds] types = Symbol[c.name for c in conds] # Determine conditions that potentially restrict dequantification if name == :forall extra_conds = query.name in (:when, :imply) ? query.args[1] : Term[] else # name == :exists extra_conds = query end # Add static conditions for c in flatten_conjs(extra_conds) c.name in statics || continue push!(conds, c) end # Default to dequantifying by types if no static conditions were added if length(conds) == length(vars) return dequantify_by_type(name, conds, query, domain, state) end # Check if static conditions actually restrict the number of groundings substs = satisfiers(domain, state, conds) if prod(get_object_count(domain, state, ty) for ty in types) < length(substs) conds = resize!(conds, length(vars)) return dequantify_by_type(name, conds, query, domain, state) end # Accumulate list of ground terms subterms = Term[] for s in substs length(s) > length(vars) && filter!(p -> first(p) in vars, s) push!(subterms, substitute(query, s)) end # Return conjunction / disjunction of ground terms if name == :forall return isempty(subterms) ? Const(true) : Compound(:and, subterms) else # name == :exists return isempty(subterms) ? Const(false) : Compound(:or, subterms) end end """ conds, effects = flatten_conditions(term::Term) Flattens a (potentially nested) conditional effect `term` into a list of condition lists (`conds`) and a list of effect lists (`effects`). """ function flatten_conditions(term::Term) if term.name == :when # Conditional case cond, effect = term.args[1], term.args[2] subconds, subeffects = flatten_conditions(effect) for sc in subconds prepend!(sc, flatten_conjs(cond)) end return subconds, subeffects elseif term.name == :and # Conjunctive case conds, effects = [Term[]], [Term[]] for effect in term.args subconds, subeffects = flatten_conditions(effect) for (c, e) in zip(subconds, subeffects) if isempty(c) append!(effects[1], e) else push!(conds, c) push!(effects, e) end end end if isempty(effects[1]) popfirst!(conds) popfirst!(effects) end return conds, effects elseif term.name == true # Empty effects (due to simplification) cond, effect = Term[], Term[] return [cond], [effect] else # Base case cond, effect = Term[], Term[term] return [cond], [effect] end end """ actions = flatten_conditions(action::GroundAction) Flattens ground actions with conditional effects into multiple ground actions. """ function flatten_conditions(action::GroundAction) if (action.effect isa GenericDiff) return [action] end actions = GroundAction[] for (conds, diff) in zip(action.effect.conds, action.effect.diffs) preconds = [action.preconds; conds] push!(actions, GroundAction(action.name, action.term, preconds, diff)) end return actions end "Checks if a term or list of terms is in conjunctive normal form." is_cnf(term::Term) = term.name == :and && is_cnf(term.args) is_cnf(terms::AbstractVector{<:Term}) = all(is_cnf_clause(t) for t in terms) "Checks if a term or list of terms is a CNF clause." is_cnf_clause(term::Term) = (term.name == :or && is_cnf_clause(term.args)) || is_literal(term) is_cnf_clause(terms::AbstractVector{<:Term}) = all(is_literal(t) for t in terms) "Checks if a term or list of terms is in disjunctive normal form." is_dnf(term::Term) = term.name == :or && is_dnf(term.args) is_dnf(terms::AbstractVector{<:Term}) = all(is_dnf_clause(t) for t in terms) "Checks if a term or list of terms is a CNF clause." is_dnf_clause(term::Term) = (term.name == :and && is_dnf_clause(term.args)) || is_literal(term) is_dnf_clause(terms::AbstractVector{<:Term}) = all(is_literal(t) for t in terms) """ clauses = to_cnf_clauses(term) Convert a `term` to CNF and return a list of the clauses as terms. Clauses with multiple literals have an `or` around them, but single-literal clauses do not. """ function to_cnf_clauses(term::Term) term = to_cnf(term) clauses = map!(similar(term.args), term.args) do c (length(c.args) == 1) ? c.args[1] : Compound(c.name, unique!(c.args)) end filter!(clauses) do c # Filter out clauses with conflicting literals c.name != :or && return true negated = [term.args[1] for term in c.args if term.name == :not] return !any(term in c.args for term in negated) end return clauses end to_cnf_clauses(terms::AbstractVector{<:Term}) = isempty(terms) ? Term[] : reduce(vcat, (to_cnf_clauses(t) for t in terms)) """ clauses = to_dnf_clauses(term) Convert a `term` to DNF and return a list of the clauses as terms. Clauses with multiple literals have an `and` around them, but single-literal clauses do not. """ function to_dnf_clauses(term::Term) term = to_dnf(term) clauses = map!(similar(term.args), term.args) do c (length(c.args) == 1) ? c.args[1] : Compound(c.name, unique!(c.args)) end filter!(clauses) do c # Filter out clauses with conflicting literals c.name != :and && return true negated = [term.args[1] for term in c.args if term.name == :not] return !any(term in c.args for term in negated) end return clauses end to_dnf_clauses(terms::AbstractVector{<:Term}) = isempty(terms) ? Term[] : reduce(vcat, (to_dnf_clauses(t) for t in terms))
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3341
""" Action Abstract supertype for action schemas, which specify the general semantics of an action parameterized by a set of arguments. """ abstract type Action end """ $(SIGNATURES) Returns the name of an action schema. """ get_name(action::Action) = error("Not implemented.") """ $(SIGNATURES) Returns the argument variables for an action schema. """ get_argvars(action::Action) = error("Not implemented.") """ $(SIGNATURES) Returns the argument types for an action schema. """ get_argtypes(action::Action) = error("Not implemented.") """ get_precond(action::Action) get_precond(action::Action, args) get_precond(domain::Domain, action::Term) Returns the precondition of an action schema as a `Term`, optionally parameterized by `args`. Alternatively, an action and its arguments can be specified as a `Term`. """ get_precond(action::Action) = error("Not implemented.") function get_precond(action::Action, args) argvars = get_argvars(action) subst = Subst(k => v for (k, v) in zip(argvars, args)) return substitute(get_precond(action), subst) end get_precond(domain::Domain, action::Term) = get_precond(get_actions(domain)[action.name], action.args) """ get_effect(action::Action) get_effect(action::Action, args) get_effect(domain::Domain, action::Term) Returns the effect of an action schema as a `Term`, optionally parameterized by `args`. Alternatively, an action and its arguments can be specified as a `Term`. """ get_effect(action::Action) = error("Not implemented.") function get_effect(action::Action, args) argvars = get_argvars(action) subst = Subst(k => v for (k, v) in zip(argvars, args)) return substitute(get_effect(action), subst) end get_effect(domain::Domain, term::Term) = get_effect(get_actions(domain)[term.name], term.args) Base.convert(::Type{Term}, action::Action) = convert(Compound, action) Base.convert(::Type{Compound}, action::Action) = Compound(get_name(action), get_argvars(action)) Base.convert(::Type{Const}, action::Action) = isempty(get_argvars(action)) ? Const(get_name(action)) : error("Action has arguments.") """ NoOp() Constructs a no-op action which has no preconditions or effects. """ struct NoOp <: Action end get_name(action::NoOp) = Symbol("--") get_argvars(action::NoOp) = () get_argtypes(action::NoOp) = () get_precond(action::NoOp) = Compound(:and, []) get_precond(action::NoOp, args) = Compound(:and, []) get_effect(action::NoOp) = Compound(:and, []) get_effect(action::NoOp, args) = Compound(:and, []) available(::Domain, state::State, ::NoOp, args) = true execute(::Domain, state::State, ::NoOp, args; options...) = state execute!(::Domain, state::State, ::NoOp, args; options...) = state relevant(::Domain, state::State, ::NoOp, args; options...) = false regress(::Domain, state::State, ::NoOp, args; options...) = state regress!(::Domain, state::State, ::NoOp, args; options...) = state Base.convert(::Type{Term}, ::NoOp) = convert(Compound, NoOp()) Base.convert(::Type{Compound}, act::NoOp) = Compound(get_name(act), Term[]) Base.convert(::Type{Const}, act::NoOp) = Const(get_name(act)) """ PDDL.no_op An alias for pddl"(--)", the action `Term` for a [`NoOp`](@ref) action which has no preconditions or effects. """ const no_op = Compound(get_name(NoOp()), Term[])
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1031
""" Diff Abstract type representing differences between states. """ abstract type Diff end """ combine!(diff::Diff, ds::Diff...) Combine state differences, modifying the first `Diff` in place. """ combine!(d::Diff) = d combine!(d1::Diff, d2::Diff) = error("Not implemented.") combine!(d1::Diff, d2::Diff, diffs::Diff...) = combine!(combine!(d1, d2), diffs...) """ combine(diff::Diff, ds::Diff...) Combine state differences, returning a fresh `Diff`. """ combine(diffs::Diff...) = combine!(empty(diffs[1]), diffs...) """ $(SIGNATURES) Convert a `Diff` to an equivalent `Term`. """ as_term(diff::Diff) = error("Not implemented.") """ $(SIGNATURES) Return whether a `Diff` is redundant (i.e. does nothing). """ is_redundant(diff::Diff) = error("Not implemented.") """ $(SIGNATURES) Return an empty `Diff` of the same type as the input `Diff`. """ Base.empty(diff::Diff) = error("Not implemented.") """ $(SIGNATURES) Returns if a Diff is empty. """ Base.isempty(diff::Diff) = error("Not implemented.")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3337
""" Domain Abstract supertype for planning domains, which specify a symbolic model of the environment and its transition dynamics. """ abstract type Domain end """ $(SIGNATURES) Returns the name of a domain. """ get_name(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns domain requirements as a map from requirement names to Boolean values. """ get_requirements(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns a map from domain types to subtypes. """ get_typetree(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns an iterator over types in the domain. """ get_types(domain::Domain) = keys(get_typetree(domain)) """ $(SIGNATURES) Returns an iterator over (immediate) subtypes of `type` in the domain. """ get_subtypes(domain::Domain, type::Symbol) = get_typetree(domain)[type] """ $(SIGNATURES) Returns a map from domain datatypes to Julia types. """ get_datatypes(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the Julia type associated with the domain `datatype`. """ get_datatype(domain::Domain, datatype::Symbol) = get_datatype(domain)[datatype] """ $(SIGNATURES) Returns the list of domain object constants. """ get_constants(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns a map from domain constants to their types. """ get_constypes(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the type of the domain constant `obj`. """ get_constype(domain::Domain, obj) = get_constypes[obj] """ $(SIGNATURES) Returns a map from predicate names to predicate [`Signature`](@ref)s. """ get_predicates(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the signature associated with a predicate `name`. """ get_predicate(domain::Domain, name::Symbol) = get_predicates(domain)[name] """ $(SIGNATURES) Returns a map from function names to function [`Signature`](@ref)s. """ get_functions(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the signature associated with a function `name`. """ get_function(domain::Domain, name::Symbol) = get_functions(domain)[name] """ $(SIGNATURES) Returns a map from function names to attached function definitions. """ get_funcdefs(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the definition associated with a function `name`. """ get_funcdef(domain::Domain, name::Symbol) = get_funcdefs(domain)[name] """ $(SIGNATURES) Returns a map from domain fluent names to fluent [`Signature`](@ref)s. """ get_fluents(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the signature associated with a fluent `name`. """ get_fluent(domain::Domain, name::Symbol) = get_fluents(domain)[name] """ $(SIGNATURES) Returns a map from names of derived predicates to their corresponding axioms. """ get_axioms(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the axiom assocated with a derived predicate `name`. """ get_axiom(domain::Domain, name::Symbol) = get_axioms(domain)[name] """ $(SIGNATURES) Returns a map from action names to action schemata. """ get_actions(domain::Domain) = error("Not implemented.") """ $(SIGNATURES) Returns the action schema specified by `name`. """ get_action(domain::Domain, name::Symbol) = get_actions(domain)[name]
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
8141
include("signature.jl") include("domain.jl") include("problem.jl") include("state.jl") include("action.jl") include("diff.jl") include("utils.jl") include("show.jl") """ satisfy(domain::Domain, state::State, term::Term) satisfy(domain::Domain, state::State, terms::AbstractVector{<:Term}) Returns whether the queried `term` or `terms` can be satisfied in the given `domain` and `state`. """ satisfy(domain::Domain, state::State, term::Term) = satisfy(domain, state, [term]) satisfy(domain::Domain, state::State, terms::AbstractVector{<:Term}) = error("Not implemented.") """ satisfiers(domain::Domain, state::State, term::Term) satisfiers(domain::Domain, state::State, terms::AbstractVector{<:Term}) Returns a list of satisfying substitutions of the queried `term` or `terms` within the given `domain` and `state`. """ satisfiers(domain::Domain, state::State, term::Term) = satisfiers(domain, state, [term]) satisfiers(domain::Domain, state::State, terms::AbstractVector{<:Term}) = error("Not implemented.") """ evaluate(domain::Domain, state::State, term::Term) Evaluates a grounded `term` in the given `domain` and `state`. If `term` refers to a numeric fluent, the value of the fluent is returned. For logical predicates, `evaluate` is equivalent to `satisfy`. """ evaluate(domain::Domain, state::State, term::Term) = error("Not implemented.") """ initstate(domain::Domain, problem::Problem) initstate(domain::Domain, objtypes[, fluents]) Construct the initial state for a given planning `domain` and `problem`, or from a `domain`, a map of objects to their types (`objtypes`), and an optional list of `fluents`. Fluents can either be provided as a list of `Term`s representing the initial fluents in a PDDL problem, or as a map from fluent names to fluent values. """ initstate(domain::Domain, problem::Problem) = error("Not implemented.") initstate(domain::Domain, objtypes::AbstractDict, fluents=Term[]) = error("Not implemented.") """ goalstate(domain::Domain, problem::Problem) goalstate(domain::Domain, objtypes, terms) Construct a (partial) goal state from a `domain` and `problem`, or from a `domain`, a map of objects to their types (`objtypes`), and goal `terms`. """ goalstate(domain::Domain, problem::Problem) = error("Not implemented.") goalstate(domain::Domain, objtypes::AbstractDict, terms) = error("Not implemented.") """ transition(domain::Domain, state::State, action::Term) transition(domain::Domain, state::State, actions) Returns the successor to `state` in the given `domain` after applying a single `action` or a set of `actions` in parallel. """ transition(domain::Domain, state::State, action::Term; options...) = error("Not implemented.") transition(domain::Domain, state::State, actions; options...) = error("Not implemented.") """ transition!(domain::Domain, state::State, action::Term) transition!(domain::Domain, state::State, actions) Variant of [`transition`](@ref) that modifies `state` in place. """ transition!(domain::Domain, state::State, action::Term; options...) = error("Not implemented.") transition!(domain::Domain, state::State, actions; options...) = error("Not implemented.") """ available(domain::Domain, state::State, action::Action, args) available(domain::Domain, state::State, action::Term) Check if an `action` parameterized by `args` can be executed in the given `state` and `domain`. Action parameters can also be specified as the arguments of a compound `Term`. """ available(domain::Domain, state::State, action::Action, args)::Bool = error("Not implemented.") available(domain::Domain, state::State, action::Term)::Bool = available(domain, state, get_actions(domain)[action.name], action.args) """ available(domain::Domain, state::State) Return an iterator over available actions in a given `state` and `domain`. """ available(domain::Domain, state::State) = error("Not implemented.") """ execute(domain::Domain, state::State, action::Action, args) execute(domain::Domain, state::State, action::Term) Execute an `action` parameterized by `args` in the given `state`, returning the resulting state. Action parameters can also be specified as the arguments of a compound `Term`. """ execute(domain::Domain, state::State, action::Action, args; options...) = error("Not implemented.") execute(domain::Domain, state::State, action::Term; options...) = if action.name == PDDL.no_op.name execute(domain, state, PDDL.NoOp(), (); options...) else execute(domain, state, get_actions(domain)[action.name], action.args; options...) end """ execute!(domain::Domain, state::State, action::Action, args) execute!(domain::Domain, state::State, action::Term) Variant of [`execute`](@ref) that modifies `state` in-place. """ execute!(domain::Domain, state::State, action::Action, args; options...) = error("Not implemented.") execute!(domain::Domain, state::State, action::Term; options...) = if action.name == PDDL.no_op.name execute!(domain, state, PDDL.NoOp(), (); options...) else execute!(domain, state, get_actions(domain)[action.name], action.args; options...) end """ relevant(domain::Domain, state::State, action::Action, args) relevant(domain::Domain, state::State, action::Term) Check if an `action` parameterized by `args` is relevant (can lead to) a `state` in the given `domain`. Action parameters can also be specified as the arguments of a compound `Term`. """ relevant(domain::Domain, state::State, action::Action, args)::Bool = error("Not implemented.") relevant(domain::Domain, state::State, action::Term)::Bool = relevant(domain, state, get_actions(domain)[action.name], action.args) """ relevant(domain::Domain, state::State) Return an iterator over relevant actions in a given `state` and `domain`. """ relevant(domain::Domain, state::State) = error("Not implemented.") """ regress(domain::Domain, state::State, action::Action, args) regress(domain::Domain, state::State, action::Term) Compute the pre-image of an `action` parameterized by `args` with respect to a `state`. Action parameters can also be specified as the arguments of a compound `Term`. """ regress(domain::Domain, state::State, action::Action, args; options...)= error("Not implemented.") regress(domain::Domain, state::State, action::Term; options...) = if action.name == PDDL.no_op.name regress(domain, state, PDDL.NoOp(), (); options...) else regress(domain, state, get_actions(domain)[action.name], action.args; options...) end """ regress!(domain::Domain, state::State, action::Action, args) regress!(domain::Domain, state::State, action::Term) Variant of [`regress`](@ref) that modifies `state` in-place. """ regress!(domain::Domain, state::State, action::Action, args; options...)= error("Not implemented.") regress!(domain::Domain, state::State, action::Term; options...) = if action.name == PDDL.no_op.name regress!(domain, state, PDDL.NoOp(), (); options...) else regress!(domain, state, get_actions(domain)[action.name], action.args; options...) end """ update(domain::Domain, state::State, diff::Diff) Updates a PDDL `state` with a state difference. """ update(domain::Domain, state::State, diff::Diff) = update(domain, copy(state), diff) """ update!(domain::Domain, state::State, diff::Diff) Updates a PDDL `state` in-place with a state difference. """ update!(domain::Domain, state::State, diff::Diff) = error("Not implemented.") """ domaintype(state::State) domaintype(S::Type{<:State}) Return the type of domain associated with the state. """ domaintype(state::S) where {S <: State} = domaintype(S) domaintype(::Type{<:State}) = Domain """ statetype(domain::Domain) statetype(D::Type{<:Domain}) Return the type of state associated with the domain. """ statetype(domain::D) where {D <: Domain} = statetype(D) statetype(::Type{<:Domain}) = State
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1218
""" Problem Abstract supertype for planning problems, which specify the initial state of a planning domain and the task specification to be achieved. """ abstract type Problem end """ $(SIGNATURES) Returns the name of a problem. """ get_name(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns the name of a problem's domain. """ get_domain_name(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns an iterator over objects in a `problem`. """ get_objects(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns a map from problem objects to their types. """ get_objtypes(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns a list of terms that determine the initial state. """ get_init_terms(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns the goal specification of a problem. """ get_goal(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns the metric specification of a problem. """ get_metric(problem::Problem) = error("Not implemented.") """ $(SIGNATURES) Returns the constraint specification of a problem. """ get_constraints(problem::Problem) = error("Not implemented.")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
9923
# Utilities # macro _maybe(call_expr, default_expr) @assert call_expr.head == :call "Must be a call expression." return quote try $(esc(call_expr)) catch MethodError $(esc(default_expr)) end end end function _line_limit(n_items::Int, remaining::Int) n_items == 0 && return 0 n_items + 1 <= remaining && return n_items + 1 n_displayed = min(remaining-1, n_items) return n_displayed <= 3 ? 1 : n_displayed + 1 end function _show_list(io::IO, list, limit::Int, indent) if length(list) > limit limit < 3 && return for line in list[1:(limit÷2-1)] print(io, "\n", indent, line) end print(io, "\n", indent, "⋮") for line in list[end-(limit÷2)+1:end] print(io, "\n", indent, line) end else for line in list print(io, "\n", indent, line) end end end function _show_objects(io::IO, objects, category, indent, limit::Int) isempty(objects) && return objects, objtypes = collect(keys(objects)), collect(values(objects)) print(io, "\n", indent, "$category: ", summary(objects)) if all(objtypes .== :object) objects = sort!(string.(objects)) _show_list(io, objects, limit, indent * " ") else objects = string.(objects) objtypes = string.(objtypes) order = sortperm(collect(zip(objtypes, objects))) objects = objects[order] objtypes = objtypes[order] max_chars = maximum(length.(objects)) lines = ["$(rpad(obj, max_chars)) - $type" for (obj, type) in zip(objects, objtypes)] _show_list(io, lines, limit-1, indent * " ") end end # Domains # function Base.show(io::IO, ::MIME"text/plain", domain::Domain) print(io, typeof(domain)) print(io, "\n", " name: ", get_name(domain)) # Extract fields typetree = @_maybe(get_typetree(domain), Dict()) predicates = @_maybe(get_predicates(domain), Dict()) functions = @_maybe(get_functions(domain), Dict()) constants = @_maybe(get_constypes(domain), Dict()) axioms = @_maybe(get_axioms(domain), Dict()) actions = @_maybe(get_actions(domain), Dict()) typing = !isempty(typetree) && collect(keys(typetree)) != [:object] # Compute line quotas based on display size remaining = get(io, :limit, false) ? first(displaysize(io)) - 6 : 80 max_action_lines = _line_limit(length(actions), remaining) remaining -= max_action_lines max_axiom_lines = _line_limit(length(axioms), remaining) remaining -= max_axiom_lines max_constant_lines = _line_limit(length(constants), remaining) remaining -= max_constant_lines max_function_lines = _line_limit(length(functions), remaining) remaining -= max_function_lines max_predicate_lines = _line_limit(length(predicates), remaining) remaining -= max_predicate_lines max_typetree_lines = _line_limit(length(typetree), remaining) # Display fields typing && _show_typetree(io, typetree, " ", max_typetree_lines) _show_predicates(io, predicates, " ", typing, max_predicate_lines) _show_functions(io, functions, " ", typing, max_function_lines) _show_objects(io, constants, "constants", " ", max_constant_lines) _show_axioms(io, axioms, " ", max_axiom_lines) _show_actions(io, actions, " ", max_action_lines) end function _show_typetree(io::IO, typetree, indent, limit::Int) isempty(typetree) && return print(io, "\n", indent, "typetree: ", summary(typetree)) max_chars = maximum(length.(repr.(keys(typetree)))) types = get_sorted_types(typetree) subtypes = [typetree[ty] for ty in types] typetree = ["$(rpad(repr(name), max_chars)) => $(isempty(ts) ? "[]" : ts)" for (name, ts) in zip(types, subtypes)] _show_list(io, typetree, limit-1, " " * indent) end function _show_fluents(io::IO, fluents, category, indent, typing::Bool, limit::Int) isempty(fluents) && return print(io, "\n", indent, "$category: ", summary(fluents)) max_chars = maximum(length.(repr.(keys(fluents)))) names = [rpad(repr(name), max_chars) for name in keys(fluents)] sigs = [typing ? repr(sig) : write_pddl(convert(Term, sig)) for sig in values(fluents)] fluents = ["$name => $sig" for (name, sig) in zip(names, sigs)] |> sort! _show_list(io, fluents, limit-1, " " * indent) end _show_predicates(io::IO, predicates, indent, typing::Bool, limit::Int) = _show_fluents(io, predicates, "predicates", indent, typing, limit) _show_functions(io::IO, functions, indent, typing::Bool, limit::Int) = _show_fluents(io, functions, "functions", indent, typing, limit) function _show_axioms(io::IO, axioms, indent, limit::Int) isempty(axioms) && return print(io, "\n", indent, "axioms: ", summary(axioms)) max_chars = maximum(length.(repr.(keys(axioms)))) axioms = ["$(rpad(repr(name), max_chars)) => " * Writer.write_axiom(ax) for (name, ax) in pairs(axioms)] sort!(axioms) _show_list(io, axioms, limit-1, " " * indent) end function _show_actions(io::IO, actions, indent, limit::Int) isempty(actions) && return print(io, "\n", indent, "actions: ") max_chars = maximum(length.(repr.(keys(actions)))) actions = ["$(rpad(repr(name), max_chars)) => " * Writer.write_action_sig(act) for (name, act) in pairs(actions)] sort!(actions) _show_list(io, actions, limit-1, " " * indent) end # Problems # function Base.show(io::IO, ::MIME"text/plain", problem::Problem) print(io, typeof(problem)) print(io, "\n", " name: ", get_name(problem)) # Extract fields domain = @_maybe(get_domain_name(domain), nothing) objects = @_maybe(get_objtypes(problem), Dict()) init = @_maybe(get_init_terms(problem), Term[]) goal = @_maybe(get_goal(problem), nothing) metric = @_maybe(get_metric(problem), nothing) constraints = @_maybe(get_constraints(problem), nothing) # Compute line quotas based on display size remaining = get(io, :limit, false) ? first(displaysize(io)) - 10 : 80 max_object_lines = _line_limit(length(objects), remaining) remaining -= max_object_lines max_init_lines = _line_limit(length(init), remaining) # Display fields if !isnothing(domain) print(io, "\n", " domain: ", domain) end _show_objects(io, objects, "objects", " ", max_object_lines) _show_init(io, init, " ", max_init_lines) if !isnothing(goal) print(io, "\n", " goal: ", write_pddl(goal)) end if !isnothing(metric) print(io, "\n", " metric: ", write_pddl(metric)) end if !isnothing(constraints) print(io, "\n", " constraints: ", write_pddl(constraints)) end end function _show_init(io::IO, init, indent, limit::Int) isempty(init) && return print(io, "\n", indent, "init: ", summary(init)) init = sort!(write_pddl.(init)) _show_list(io, init, limit-1, " " * indent) end # States # function Base.show(io::IO, ::MIME"text/plain", state::State) print(io, typeof(state)) # Extract fields objects = @_maybe(get_objtypes(state), Dict()) fluents = @_maybe(Dict(get_fluents(state)), Dict()) # Compute line quotas based on display size remaining = get(io, :limit, false) ? first(displaysize(io)) - 5 : 80 max_fluent_lines = _line_limit(length(fluents), remaining) remaining -= max_fluent_lines max_object_lines = _line_limit(length(objects), remaining) # Display fields _show_state_objects(io, objects, " ", max_object_lines) _show_state_fluents(io, fluents, " ", max_fluent_lines) end function _show_state_objects(io::IO, objects, indent, limit::Int) isempty(objects) && return objects, objtypes = collect(keys(objects)), collect(values(objects)) if all(objtypes .== :object) print(io, "\n", indent, "objects: ", length(objects), " (untyped)") objects = sort!(string.(objects)) _show_list(io, objects, limit, indent * " ") else print(io, "\n", indent, "objects: ", length(objects), " (typed)") objects = string.(objects) objtypes = string.(objtypes) order = sortperm(collect(zip(objtypes, objects))) objects = objects[order] objtypes = objtypes[order] max_chars = maximum(length.(objects)) lines = ["$(rpad(obj, max_chars)) - $type" for (obj, type) in zip(objects, objtypes)] _show_list(io, lines, limit - 1, indent * " ") end end function _show_state_fluents(io::IO, fluents, indent, limit::Int) isempty(fluents) && return fluents, vals = collect(keys(fluents)), collect(values(fluents)) ftype = infer_datatype(eltype(vals)) type_desc = isnothing(ftype) ? " (mixed)" : " ($ftype)" print(io, "\n", indent, "fluents: ", length(fluents), type_desc) fluents = write_pddl.(fluents) max_chars = maximum(length.(fluents)) lines = ["$(rpad(f, max_chars)) => $v" for (f, v) in zip(fluents, vals)] sort!(lines) _show_list(io, lines, limit, indent * " ") end # Actions # function Base.show(io::IO, ::MIME"text/plain", action::Action) print(io, typeof(action)) print(io, "\n", " name: ", get_name(action)) # Extract fields vars = @_maybe(get_argvars(action), Var[]) types = @_maybe(get_argtypes(action), Symbol[]) precond = @_maybe(get_precond(action), nothing) effect = @_maybe(get_effect(action), nothing) # Display fields if !isempty(vars) parameters = "(" * Writer.write_typed_list(vars, types) * ")" print(io, "\n", " parameters: ", parameters) end if !isnothing(precond) && precond != Const(true) print(io, "\n", " precond: ", write_pddl(precond)) end if !isnothing(effect) print(io, "\n", " effect: ", write_pddl(effect)) end end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1132
""" Signature Type signature for a PDDL fluent (i.e. predicate or function). # Fields $(FIELDS) """ struct Signature{N} "Name of fluent." name::Symbol "Output datatype of fluent, represented as a `Symbol`." type::Symbol "Argument variables." args::NTuple{N, Var} "Argument datatypes, represented as `Symbol`s." argtypes::NTuple{N, Symbol} end Signature(name, type, args, argtypes) = Signature{length(args)}(name, type, Tuple(args), Tuple(argtypes)) Signature(term::Term, argtypes, type) = Signature(term.name, type, term.args, argtypes) """ $(SIGNATURES) Returns the arity (i.e. number of arguments) of a fluent signature. """ arity(signature::Signature{N}) where {N} = N function Base.convert(::Type{Term}, sig::Signature{0}) return Const(sig.name) end function Base.convert(::Type{Term}, sig::Signature) return Compound(sig.name, collect(sig.args)) end function Base.show(io::IO, sig::Signature) args = ["?$(lowercase(string(a.name))) - $t" for (a, t) in zip(sig.args, sig.argtypes)] print(io, "($(join([sig.name; args], " "))) - $(sig.type)") end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2641
""" State Abstract supertype for symbolic states. A `State` is a symbolic description of the environment and its objects at a particular point in time. It consists of a set of objects, and a set of ground fluents (predicates or functions) with values defined over those objects. """ abstract type State end """ $(SIGNATURES) Returns an integer index for specified `state`. Defaults to hashing. """ stateindex(domain::Domain, state::State) = hash(state) """ get_objects(state::State, [type::Symbol]) get_objects(domain::Domain, state::State, type::Symbol) Returns an iterator over objects in the `state`. If a `type` is specified, the iterator will contain objects only of that type (but not its subtypes). If a `domain` is provided, then the iterator will contain all objects of that type or any of its subtypes. """ get_objects(state::State) = error("Not implemented.") get_objects(state::State, type::Symbol) = error("Not implemented.") """ $(SIGNATURES) Returns a map (dictionary, named tuple, etc.) from state objects to their types. """ get_objtypes(state::State) = error("Not implemented.") """ $(SIGNATURES) Returns the type of an `object` in a `state`. """ get_objtype(state::State, object) = get_objtypes(state)[object] """ $(SIGNATURES) Returns an iterator over true Boolean predicates in a `state`. """ get_facts(state::State) = error("Not implemented.") """ $(SIGNATURES) Gets the value of a (non-derived) fluent.Equivalent to using the index notation `state[term]`. """ get_fluent(state::State, term::Term) = error("Not implemented.") """ $(SIGNATURES) Sets the value of a (non-derived) fluent. Equivalent to using the index notation `state[term] = val`. """ set_fluent!(state::State, val, term::Term) = error("Not implemented.") """ $(SIGNATURES) Returns a map from fluent names to values (false predicates may be omitted). `Base.pairs` is an alias. """ get_fluents(state::State) = error("Not implemented.") """ $(SIGNATURES) Returns the names of fluents in a state (false predicates may be omitted). `Base.keys` is an alias. """ get_fluent_names(state::State) = (k for (k, v) in get_fluents(state)) """ $(SIGNATURES) Returns the values of fluents in a state (false predicates may be omitted). `Base.values` is an alias. """ get_fluent_values(state::State) = (v for (k, v) in get_fluents(state)) Base.getindex(state::State, term::Term) = get_fluent(state, term) Base.setindex!(state::State, val, term::Term) = set_fluent!(state, val, term) Base.pairs(state::State) = get_fluents(state) Base.keys(state::State) = get_fluent_names(state) Base.values(state::State) = get_fluent_values(state)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1830
# domain[state => f] shorthand for evaluating `f` within a domain and state Base.getindex(domain::Domain, statevar::Pair{<:State, <:Term}) = evaluate(domain, first(statevar), last(statevar)) Base.getindex(domain::Domain, statevar::Pair{<:State, Symbol}) = evaluate(domain, first(statevar), Const(last(statevar))) Base.getindex(domain::Domain, statevar::Pair{<:State, String}) = evaluate(domain, first(statevar), Parser.parse_formula(last(statevar))) get_objects(domain::Domain, state::State) = get_objects(state) function get_objects(domain::Domain, state::State, type::Symbol) return Const[o for (o, ty) in get_objtypes(state) if ty == type || ty in get_all_subtypes(domain, type)] end """ $(SIGNATURES) Return all (recursive) subtypes of `type` in a domain. """ function get_all_subtypes(domain::Domain, type::Symbol) subtypes = get_subtypes(domain, type) if isempty(subtypes) return subtypes end return reduce(vcat, [get_all_subtypes(domain, ty) for ty in subtypes], init=subtypes) end """ $(SIGNATURES) Return number of objects of particular type. """ get_object_count(domain::Domain, state::State, type::Symbol) = length(get_objects(domain, state, type)) """ $(SIGNATURES) Return number of objects of each type as a dictionary. """ get_object_counts(domain::Domain, state::State) = Dict(ty => get_object_count(domain, state, ty) for ty in get_types(domain)) """ $(SIGNATURES) Return types in a domain as a topologically sorted list. """ get_sorted_types(domain::Domain) = get_sorted_types(get_typetree(domain)) function get_sorted_types(typetree) types = Symbol[] queue = [:object] while !isempty(queue) ty = popfirst!(queue) push!(types, ty) append!(queue, typetree[ty]) end return types end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1918
function available(interpreter::Interpreter, domain::Domain, state::State) # Ground all action definitions with arguments actions = Compound[] for act in values(get_actions(domain)) act_name = get_name(act) act_vars, act_types = get_argvars(act), get_argtypes(act) # Directly check precondition if action has no parameters if isempty(act_vars) && satisfy(domain, state, get_precond(act)) push!(actions, Compound(act_name, Term[])) continue end # Include type conditions when necessary for correctness typecond = (pddl"($ty $v)" for (v, ty) in zip(act_vars, act_types)) conds = [get_precond(act); typecond...] # Find all substitutions that satisfy preconditions subst = satisfiers(interpreter, domain, state, conds) if isempty(subst) continue end for s in subst args = [s[v] for v in act_vars if v in keys(s)] if any(!is_ground(a) for a in args) continue end push!(actions, Compound(act_name, args)) end end return actions end function available(interpreter::Interpreter, domain::Domain, state::State, action::Action, args) if any(!is_ground(a) for a in args) error("Not all arguments are ground.") end act_vars, act_types = get_argvars(action), get_argtypes(action) subst = Subst(var => val for (var, val) in zip(act_vars, args)) # Construct type conditions of the form "type(val)" typecond = (all(ty == :object for ty in action.types) ? Term[] : [pddl"($ty $v)" for (v, ty) in zip(args, act_types)]) # Check whether preconditions hold precond = substitute(get_precond(action), subst) conds = has_func(precond, domain) || has_quantifier(precond) ? [typecond; precond] : [precond; typecond] return satisfy(interpreter, domain, state, conds) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
4777
## Effect differences ## "Convert effect formula to a state difference (additions, deletions, etc.)" function effect_diff(domain::Domain, state::State, effect::Term) return effect_diff!(GenericDiff(), domain, state, effect) end function effect_diff!(diff::GenericDiff, domain::Domain, state::State, effect::Term) return effect_diff!(effect.name, diff, domain, state, effect) end @valsplit function effect_diff!(Val(name::Symbol), diff::GenericDiff, domain::Domain, state::State, effect::Term) # Assume addition by default return add_effect!(diff, domain, state, effect) end function add_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) push!(diff.add, effect) return diff end function del_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) effect = effect.args[1] push!(diff.del, effect) return diff end effect_diff!(::Val{:not}, diff::Diff, d::Domain, s::State, e::Term) = del_effect!(diff, d, s, e) function and_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) for eff in get_args(effect) effect_diff!(diff, domain, state, eff) end return diff end effect_diff!(::Val{:and}, diff::Diff, d::Domain, s::State, e::Term) = and_effect!(diff, d, s, e) function when_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) cond, eff = effect.args[1], effect.args[2] if !satisfy(domain, state, cond) return diff end return effect_diff!(diff, domain, state, eff) end effect_diff!(::Val{:when}, diff::Diff, d::Domain, s::State, e::Term) = when_effect!(diff, d, s, e) function forall_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) cond, eff = effect.args[1], effect.args[2] for s in satisfiers(domain, state, cond) effect_diff!(diff, domain, state, substitute(eff, s)) end return diff end effect_diff!(::Val{:forall}, diff::Diff, d::Domain, s::State, e::Term) = forall_effect!(diff, d, s, e) function assign_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) term, val = effect.args[1], effect.args[2] diff.ops[term] = val return diff end effect_diff!(::Val{:assign}, diff::Diff, d::Domain, s::State, e::Term) = assign_effect!(diff, d, s, e) function modify_effect!(diff::GenericDiff, domain::Domain, state::State, effect::Term) term, val = effect.args[1], effect.args[2] op = modifier_def(effect.name) diff.ops[term] = Compound(op, Term[term, val]) return diff end for name in global_modifier_names() name = QuoteNode(name) @eval effect_diff!(::Val{$name}, diff::Diff, d::Domain, s::State, e::Term) = modify_effect!(diff, d, s, e) end ## Precondition differences ## const PRECOND_FUNCS = Dict{Symbol,Function}() "Convert precondition formula to a state difference." function precond_diff(domain::Domain, state::State, precond::Term) return precond_diff!(GenericDiff(), domain, state, precond) end function precond_diff!(diff::GenericDiff, domain::Domain, state::State, precond::Term) return precond_diff!(precond.name, diff, domain, state, precond) end @valsplit function precond_diff!(Val(name::Symbol), diff::GenericDiff, domain::Domain, state::State, precond::Term) # Assume addition by default return add_precond!(diff, domain, state, precond) end function add_precond!(diff::GenericDiff, domain::Domain, state::State, precond::Term) push!(diff.add, precond) return diff end function del_precond!(diff::GenericDiff, domain::Domain, state::State, precond::Term) push!(diff.del, precond.args[1]) return diff end precond_diff!(::Val{:not}, diff::Diff, d::Domain, s::State, p::Term) = del_precond!(diff, d, s, p) function and_precond!(diff::GenericDiff, domain::Domain, state::State, precond::Term) for pre in get_args(precond) precond_diff!(diff, domain, state, pre) end return diff end precond_diff!(::Val{:and}, diff::Diff, d::Domain, s::State, p::Term) = and_precond!(diff, d, s, p) function forall_precond!(diff::GenericDiff, domain::Domain, state::State, precond::Term) cond, pre = precond.args[1], precond.args[2] for s in satisfiers(domain, state, cond) precond_diff!(diff, domain, state, substitute(pre, s)) end return diff end precond_diff!(::Val{:forall}, diff::Diff, d::Domain, s::State, p::Term) = forall_precond!(diff, d, s, p)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
822
function evaluate(interpreter::Interpreter, domain::Domain, state::GenericState, term::Term) # Evaluate formula as fully as possible val = partialeval(domain, state, term) # Return if formula evaluates to a Const if isa(val, Const) && (!isa(val.name, Symbol) || !is_pred(val, domain)) return val.name elseif is_pred(val, domain) || is_type(val, domain) || is_logical_op(val) return satisfy(interpreter, domain, state, val) elseif val in get_objects(state) # Return object constant return val else error("Unrecognized term $term.") end end "Evaluate formula as fully as possible." function partialeval(domain::Domain, state::GenericState, term::Term) funcs = get_eval_funcs(domain, state) return eval_term(term, Subst(), funcs) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2129
function execute(interpreter::Interpreter, domain::Domain, state::State, action::Action, args; check::Bool=true, fail_mode::Symbol=:error) # Check whether references resolve and preconditions hold if check && !available(interpreter, domain, state, action, args) if fail_mode == :no_op return state end action_str = Writer.write_formula(get_name(action), args) error("Could not execute $action_str:\n" * "Precondition $(write_pddl(get_precond(action))) does not hold.") end return execute!(interpreter, domain, copy(state), action, args; check=false) end function execute(interpreter::Interpreter, domain::Domain, state::State, action::Term; options...) if action.name == PDDL.no_op.name return state end return execute(interpreter, domain, state, get_action(domain, action.name), action.args; options...) end function execute!(interpreter::Interpreter, domain::Domain, state::State, action::Action, args; check::Bool=true, fail_mode::Symbol=:error) # Check whether references resolve and preconditions hold if check && !available(interpreter, domain, state, action, args) if fail_mode == :no_op return state end action_str = Writer.write_formula(get_name(action), args) error("Could not execute $action_str:\n" * "Precondition $(write_pddl(get_precond(action))) does not hold.") end # Substitute arguments and preconditions subst = Subst(var => val for (var, val) in zip(get_argvars(action), args)) effect = substitute(get_effect(action), subst) # Compute effect as a state diffference diff = effect_diff(domain, state, effect) return update!(interpreter, domain, state, diff) end function execute!(interpreter::Interpreter, domain::Domain, state::State, action::Term; options...) if action.name == PDDL.no_op.name return state end return execute!(interpreter, domain, state, get_action(domain, action.name), action.args; options...) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
359
# Interpreter-based implementations of the PDDL.jl interface # abstract type Interpreter end include("utils.jl") include("diff.jl") include("evaluate.jl") include("transition.jl") include("available.jl") include("execute.jl") include("relevant.jl") include("regress.jl") include("update.jl") include("concrete/concrete.jl") include("abstract/abstract.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1660
function regress(interpreter::Interpreter, domain::Domain, state::State, action::Action, args; check::Bool=true, fail_mode::Symbol=:error) # Check whether action is relevant if check && !relevant(interpreter, domain, state, action, args) if fail_mode == :no_op return state end action_str = Writer.write_formula(get_name(action), args) error("Could not revert $action_str:\n" * "Effect $(write_pddl(get_effect(action))) is not relevant.") end return regress!(interpreter, domain, copy(state), action, args; check=false) end function regress!(interpreter::Interpreter, domain::Domain, state::State, action::Action, args; check::Bool=true, fail_mode::Symbol=:error) # Check whether action is relevant if check && !relevant(interpreter, domain, state, action, args) if fail_mode == :no_op return state end action_str = Writer.write_formula(get_name(action), args) error("Could not revert $action_str:\n" * "Effect $(write_pddl(get_effect(action))) is not relevant.") end subst = Subst(var => val for (var, val) in zip(get_argvars(action), args)) precond = substitute(get_precond(action), subst) effect = substitute(get_effect(action), subst) # Compute regression difference as Precond - Additions # TODO: Handle conditional effects, disjunctive preconditions, etc. pre_diff = precond_diff(domain, state, precond) eff_diff = effect_diff(domain, state, effect) append!(pre_diff.del, eff_diff.add) return update!(interpreter, domain, state, pre_diff) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1830
function relevant(interpreter::Interpreter, domain::Domain, state::State) actions = Compound[] for act in values(get_actions(domain)) act_name = get_name(act) act_vars, act_types = get_argvars(act), get_argtypes(act) # Compute postconditions from the action's effect diff = effect_diff(domain, state, get_effect(act)) addcond = [Compound(:or, diff.add)] delcond = [pddl"(not $t)" for t in diff.del] typecond = [pddl"($ty $v)" for (v, ty) in zip(act_vars, act_types)] conds = [addcond; typecond; delcond] # Find all substitutions that satisfy the postconditions subst = satisfiers(interpreter, domain, state, conds) if isempty(subst) continue end for s in subst args = [get(s, var, var) for var in act_vars] if any(!is_ground(a) for a in args) continue end push!(actions, Compound(act_name, args)) end end return actions end function relevant(interpreter::Interpreter, domain::Domain, state::State, action::Action, args) if any(!is_ground(a) for a in args) error("Not all arguments are ground.") end act_vars, act_types = get_argvars(action), get_argtypes(action) subst = Subst(var => val for (var, val) in zip(act_vars, args)) # Compute postconditions from the action's effect diff = effect_diff(domain, state, substitute(get_effect(action), subst)) postcond = Term[Compound(:or, diff.add); [pddl"(not $t)" for t in diff.del]] # Construct type conditions of the form "type(val)" typecond = (all(ty == :object for ty in act_types) ? Term[] : [pddl"($ty $v)" for (v, ty) in zip(args, act_types)]) # Check whether postconditions hold return satisfy(interpreter, domain, state, [postcond; typecond]) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
390
function transition(interpreter::Interpreter, domain::Domain, state::State, action::Term; options...) return execute(interpreter, domain, state, action; options...) end function transition!(interpreter::Interpreter, domain::Domain, state::State, action::Term; options...) return execute!(interpreter, domain, state, action; options...) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
691
## State updates ## function update!(interpreter::Interpreter, domain::Domain, state::State, diff::Diff) error("Not implemented.") end function update!(interpreter::Interpreter, domain::Domain, state::State, diff::ConditionalDiff) if isempty(diff.diffs) return state end combined = empty(diff.diffs[1]) for (cs, d) in zip(diff.conds, diff.diffs) satisfy(domain, state, cs) && combine!(combined, d) end return update!(interpreter, domain, state, combined) end function update(interpreter::Interpreter, domain::Domain, state::State, diff::Diff) return update!(interpreter, domain, copy(state), diff) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2352
"Get all functions needed for formula evaluation in a domain and state." function get_eval_funcs(domain::Domain, state::GenericState; include_both::Bool = false) if include_both funcs = merge!(Dict{Any, Any}(both => true), global_functions(), state.values, get_funcdefs(domain)) elseif isempty(state.values) && isempty(get_funcdefs(domain)) funcs = global_functions() else funcs = merge(global_functions(), state.values, get_funcdefs(domain)) end return funcs end "Get domain constant type declarations as a list of clauses." function get_const_clauses(domain::Domain) return [Clause(pddl"($ty $o)", Term[]) for (o, ty) in get_constypes(domain)] end "Get domain type hierarchy as a list of clauses." function get_type_clauses(domain::Domain) clauses = [[Clause(pddl"($ty ?x)", Term[pddl"($s ?x)"]) for s in subtys] for (ty, subtys) in get_typetree(domain) if length(subtys) > 0] return length(clauses) > 0 ? reduce(vcat, clauses) : Clause[] end "Get all proof-relevant Horn clauses for PDDL domain." function get_clauses(domain::Domain) return [collect(values(get_axioms(domain))); get_const_clauses(domain); get_type_clauses(domain)] end "Reorder query to ensure correctness while reducing search time." function reorder_query(domain::Domain, query::Term) query = flatten_conjs(query) reorder_query!(domain, query) return query end function reorder_query(domain::Domain, query::Vector{<:Term}) query = flatten_conjs(query) reorder_query!(domain, query) return query end function reorder_query!(domain::Domain, query::Vector{Term}) if isempty(query) return 1 end priorities = Vector{Int}(undef, length(query)) for (i, q) in enumerate(query) if q.name == :and || q.name == :or || q.name == :imply priorities[i] = reorder_query!(domain, q.args) elseif is_global_func(q) || is_func(q, domain) priorities[i] = 4 elseif is_negation(q) || is_quantifier(q) || is_derived(q, domain) priorities[i] = 3 elseif is_type(q, domain) priorities[i] = 2 else priorities[i] = 1 end end order = sortperm(priorities) permute!(query, order) return maximum(priorities) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3253
# Abstract interpreter semantics """ AbstractInterpreter( type_abstractions = PDDL.default_abstypes(), fluent_abstractions = Dict(), autowiden = false ) Abstract PDDL interpreter based on Cartesian abstract interpretation of the PDDL state. Fluents in the state are converted to abstract values based on either their concrete type or fluent name, with fluent-specific abstractions overriding type-based abstractions. # Arguments $(FIELDS) """ @kwdef struct AbstractInterpreter <: Interpreter "Mapping from PDDL types to the Julia type for abstract fluent values." type_abstractions::Dict{Symbol,Any} = default_abstypes() "Mapping from fluent names to the Julia type for abstract fluent values." fluent_abstractions::Dict{Symbol,Any} = Dict{Symbol,Any}() "Flag for automatic widening of values after a state transition." autowiden::Bool = false end include("domain.jl") include("interface.jl") include("satisfy.jl") include("initstate.jl") include("update.jl") include("utils.jl") """ abstracted(domain; options...) Construct an abstract domain from a concrete domain. See [`PDDL.AbstractInterpreter`](@ref) for the list of `options`. """ abstracted(domain::GenericDomain; options...) = AbstractedDomain(domain; options...) """ abstracted(domain, state; options...) abstracted(domain, problem; options...) Construct an abstract domain and state from a concrete `domain` and `state`. A `problem` can be provided instead of a `state`. See [`PDDL.AbstractInterpreter`](@ref) for the list of `options`. """ function abstracted(domain::GenericDomain, state::GenericState; options...) absdom = abstracted(domain; options...) return (absdom, abstractstate(absdom, state)) end abstracted(domain::GenericDomain, problem::GenericProblem) = abstracted(domain, initstate(domain, problem)) """ abstractstate(domain, state) Construct a state in an abstract `domain` from a concrete `state`. """ function abstractstate(domain::AbstractedDomain, state::GenericState) # Copy over facts abs_state = GenericState(copy(state.types), copy(state.facts)) # Abstract non-Boolean values if necessary funcsigs = get_functions(domain) if isempty(funcsigs) return abs_state end type_abstractions = domain.interpreter.type_abstractions fluent_abstractions = domain.interpreter.fluent_abstractions for (term, val) in get_fluents(state) if is_pred(term, domain) continue end abstype = get(fluent_abstractions, term.name) do get(type_abstractions, funcsigs[term.name].type, identity) end abs_state[term] = abstype(val) end return abs_state end abstractstate(domain::AbstractedDomain, problem::GenericProblem) = initstate(domain, problem) """ $(SIGNATURES) Check if term is an abstracted fluent. """ function is_abstracted(term::Term, domain::AbstractedDomain) return is_abstracted(term.name, domain) end function is_abstracted(name::Symbol, domain::AbstractedDomain) haskey(domain.interpreter.fluent_abstractions, name) && return true sigs = get_functions(domain) return (haskey(sigs, name) && haskey(domain.interpreter.type_abstractions, sigs[name].type)) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1152
"Abstractly interpreted PDDL domain." struct AbstractedDomain{D <: Domain} <: Domain domain::D interpreter::AbstractInterpreter end AbstractedDomain(domain::Domain; options...) = AbstractedDomain(domain, AbstractInterpreter(; options...)) Base.copy(domain::AbstractedDomain) = deepcopy(domain) get_name(domain::AbstractedDomain) = get_name(domain.domain) get_requirements(domain::AbstractedDomain) = get_requirements(domain.domain) get_typetree(domain::AbstractedDomain) = get_typetree(domain.domain) get_datatypes(domain::AbstractedDomain) = get_datatypes(domain.domain) get_constants(domain::AbstractedDomain) = get_constants(domain.domain) get_constypes(domain::AbstractedDomain) = get_constypes(domain.domain) get_predicates(domain::AbstractedDomain) = get_predicates(domain.domain) get_functions(domain::AbstractedDomain) = get_functions(domain.domain) get_funcdefs(domain::AbstractedDomain) = get_funcdefs(domain.domain) get_fluents(domain::AbstractedDomain) = get_fluents(domain.domain) get_axioms(domain::AbstractedDomain) = get_axioms(domain.domain) get_actions(domain::AbstractedDomain) = get_actions(domain.domain)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
966
function initstate(interpreter::AbstractInterpreter, domain::AbstractedDomain, problem::GenericProblem) concrete_state = initstate(ConcreteInterpreter(), domain.domain, problem) absdom = AbstractedDomain(domain, interpreter) return abstractstate(absdom, concrete_state) end function initstate(interpreter::AbstractInterpreter, domain::AbstractedDomain, objtypes::AbstractDict) concrete_state = initstate(ConcreteInterpreter(), domain.domain, objtypes) absdom = AbstractedDomain(domain, interpreter) return abstractstate(absdom, concrete_state) end function initstate(interpreter::AbstractInterpreter, domain::AbstractedDomain, objtypes::AbstractDict, fluents) concrete_state = initstate(ConcreteInterpreter(), domain.domain, objtypes, fluents) absdom = AbstractedDomain(domain, interpreter) return abstractstate(absdom, concrete_state) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2917
# Forward methods from abstracted domains to abstract interpreter # satisfy(domain::AbstractedDomain, state::State, term::Term) = satisfy(domain.interpreter, domain, state, term) satisfy(domain::AbstractedDomain, state::State, terms::AbstractVector{<:Term}) = satisfy(domain.interpreter, domain, state, terms) satisfiers(domain::AbstractedDomain, state::State, term::Term) = satisfiers(domain.interpreter, domain, state, term) satisfiers(domain::AbstractedDomain, state::State, terms::AbstractVector{<:Term}) = satisfiers(domain.interpreter, domain, state, terms) evaluate(domain::AbstractedDomain, state::State, term::Term) = evaluate(domain.interpreter, domain, state, term) initstate(domain::AbstractedDomain, problem::Problem) = initstate(domain.interpreter, domain, problem) initstate(domain::AbstractedDomain, objtypes::AbstractDict) = initstate(domain.interpreter, domain, objtypes) initstate(domain::AbstractedDomain, objtypes::AbstractDict, fluents) = initstate(domain.interpreter, domain, objtypes, fluents) transition(domain::AbstractedDomain, state::State, action::Term; options...) = transition(domain.interpreter, domain, state, action; options...) transition!(domain::AbstractedDomain, state::State, action::Term; options...) = transition!(domain.interpreter, domain, state, action; options...) available(domain::AbstractedDomain, state::State, action::Action, args) = available(domain.interpreter, domain, state, action, args) available(domain::AbstractedDomain, state::State) = available(domain.interpreter, domain, state) execute(domain::AbstractedDomain, state::State, action::Action, args; options...) = execute(domain.interpreter, domain, state, action, args; options...) execute!(domain::AbstractedDomain, state::State, action::Action, args; options...) = execute!(domain.interpreter, domain, state, action, args; options...) relevant(domain::AbstractedDomain, state::State, action::Action, args) = relevant(domain.interpreter, domain, state, action, args) relevant(domain::AbstractedDomain, state::State) = relevant(domain.interpreter, domain, state) regress(domain::AbstractedDomain, state::State, action::Action, args; options...) = regress(domain.interpreter, domain, state, action, args; options...) regress!(domain::AbstractedDomain, state::State, action::Action, args; options...) = regress!(domain.interpreter, domain, state, action, args; options...) update!(domain::AbstractedDomain, state::State, diff::Diff) = update!(domain.interpreter, domain, state, diff) update(domain::AbstractedDomain, state::State, diff::Diff) = update(domain.interpreter, domain, state, diff) widen!(domain::AbstractedDomain, state::State, diff::Diff) = widen!(domain.interpreter, domain, state, diff) widen(domain::AbstractedDomain, state::State, diff::Diff) = widen(domain.interpreter, domain, state, diff)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3775
function satisfy(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, terms::AbstractVector{<:Term}) # Quick check that avoids SLD resolution unless necessary sat = all4(check(interpreter, domain, state, to_nnf(t)) for t in terms) if sat !== missing return (sat == true || sat == both) end # Call SLD resolution only if there are free variables or axioms return !isempty(satisfiers(interpreter, domain, state, terms)) end function satisfy(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, term::Term) # Convert to NNF term = to_nnf(term) # Quick check that avoids SLD resolution unless necessary sat = check(interpreter, domain, state, term) if sat !== missing return (sat == true || sat == both) end # Call SLD resolution only if there are free variables or axioms return !isempty(satisfiers(interpreter, domain, state, term)) end function satisfiers(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, terms::AbstractVector{<:Term}) # Reify negations terms = [reify_negations(to_nnf(t), domain) for t in terms] # Initialize Julog knowledge base clauses = Clause[get_clauses(domain); # get_negation_clauses(domain); collect(state.types); collect(state.facts)] # Pass in fluents and function definitions as a dictionary of functions funcs = get_eval_funcs(domain, state, include_both=true) # Reorder query to reduce search time terms = reorder_query(domain, collect(terms)) # Find satisfying substitutions via SLD-resolution _, subst = resolve(terms, clauses; funcs=funcs, mode=:all, search=:dfs) return subst end function satisfiers(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, term::Term) return satisfiers(domain, state, [term]) end function check(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, term::Compound) sat = if term.name == :and all4(check(interpreter, domain, state, a) for a in term.args) elseif term.name == :or any4(check(interpreter, domain, state, a) for a in term.args) elseif term.name == :imply !check(interpreter, domain, state, term.args[1]) | check(interpreter, domain, state, term.args[2]) elseif term.name == :not !check(interpreter, domain, state, term.args[1]) | check(interpreter, domain, state, negate(term.args[1])) elseif term.name == :forall missing elseif term.name == :exists missing elseif !is_ground(term) missing elseif is_derived(term, domain) missing elseif is_type(term, domain) if has_subtypes(term, domain) missing elseif term in state.types true elseif !isempty(get_constants(domain)) domain.constypes[term.args[1]] == term.name else false end elseif is_global_pred(term) evaluate(interpreter, domain, state, term)::BooleanAbs elseif is_func(term, domain) evaluate(interpreter, domain, state, term)::BooleanAbs else term in state.facts end return sat end function check(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, term::Const) if term in state.facts || term in state.types || term.name == true return true elseif is_func(term, domain) || is_derived(term, domain) return missing else return false end end function check(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, term::Var) return missing end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2355
## State updates ## function update!(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, diff::GenericDiff) if interpreter.autowiden return widen!(interpreter, domain, state, diff) end union!(state.facts, negate.(diff.del)) setdiff!(state.facts, diff.del) union!(state.facts, diff.add) setdiff!(state.facts, negate.(diff.del)) vals = [evaluate(domain, state, v) for v in values(diff.ops)] for (term, val) in zip(keys(diff.ops), vals) set_fluent!(state, val, term) end return state end "Widen a state (in-place) with a state difference." function widen!(interpreter::AbstractInterpreter, domain::Domain, state::GenericState, diff::GenericDiff) union!(state.facts, negate.(diff.del)) if !haskey(interpreter.type_abstractions, :boolean) for term in diff.del is_abstracted(term, domain) && continue delete!(state.facts, term) end end union!(state.facts, diff.add) if !haskey(interpreter.type_abstractions, :boolean) for term in diff.add is_abstracted(term, domain) && continue delete!(state.facts, negate(term)) end end vals = [evaluate(domain, state, v) for v in values(diff.ops)] for (term, val) in zip(keys(diff.ops), vals) if is_abstracted(term, domain) widened = widen(get_fluent(state, term), val) set_fluent!(state, widened, term) else set_fluent!(state, val, term) end end return state end "Widen a state with a state difference." function widen(interpreter::AbstractInterpreter, state::GenericState, diff::Diff) return widen!(interpreter, copy(state), diff) end "Widen a state (in-place) with another state." function widen!(domain::AbstractedDomain, s1::GenericState, s2::GenericState) union!(s1.facts, s2.facts) if isempty(get_functions(domain)) return s1 end for (term, val) in get_fluents(s2) if is_pred(term, domain) continue end widened = widen(get_fluent(s1, term), val) set_fluent!(s1, widened, term) end return s1 end "Widen a state with another state." widen(domain::AbstractedDomain, s1::GenericState, s2::GenericState) = widen!(domain.interpreter, copy(s1), s2)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1198
negate(term::Const) = Const(Symbol(:¬, term.name)) negate(term::Compound) = Compound(Symbol(:¬, term.name), term.args) function reify_negations(term::Compound, domain::Domain) if term.name == :not && is_pred(term.args[1], domain) negate(term.args[1]) else Compound(term.name, [reify_negations(a, domain) for a in term.args]) end end reify_negations(term::Var, domain) = term reify_negations(term::Const, domain) = term function abstract_negations(term::Compound, domain::Domain) if term.name == :not && is_pred(term.args[1], domain) Compound(:or, Term[negate(term.args[1]), term]) else Compound(term.name, [abstract_negations(a, domain) for a in term.args]) end end abstract_negations(term::Var, domain) = term abstract_negations(term::Const, domain) = term function get_clauses(domain::AbstractedDomain) # Abstract negations in axioms axioms = map(collect(values(get_axioms(domain)))) do ax head = ax.head body = abstract_negations(to_nnf(Compound(:and, ax.body)), domain) return Clause(head, Term[body]) end return [axioms; get_const_clauses(domain); get_type_clauses(domain)] end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
225
# Concrete interpreter semantics "Concrete PDDL interpreter." struct ConcreteInterpreter <: Interpreter end include("interface.jl") include("satisfy.jl") include("initstate.jl") include("goalstate.jl") include("update.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1290
function goalstate(interpreter::ConcreteInterpreter, domain::Domain, problem::GenericProblem) types = Set{Term}([Compound(ty, Term[o]) for (o, ty) in problem.objtypes]) facts = Set{Term}(flatten_conjs(problem.goal)) state = GenericState(types, facts, Dict{Symbol,Any}()) return state end function goalstate(interpreter::ConcreteInterpreter, domain::Domain, objtypes::AbstractDict, terms) types = Set{Term}([Compound(ty, Term[o]) for (o, ty) in objtypes]) goal = GenericState(types, Set{Term}(), Dict{Symbol,Any}()) for t in flatten_conjs(terms) if t.name == :(==) # Function equality @assert length(t.args) == 2 "Assignments must have two arguments." term, val = t.args[1], t.args[2] @assert(is_func(term, domain) && !is_attached_func(term, domain), "Unrecognized function $(term.name).") @assert(is_ground(term), "Assigned terms must be ground.") @assert(isa(val, Const), "Terms must be equal to constants.") goal[term] = val.name elseif is_pred(t, domain) # Predicates push!(goal.facts, t) else error("Term $t in $terms cannot be handled.") end end return goal end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1393
function initstate(interpreter::ConcreteInterpreter, domain::Domain, problem::GenericProblem) return initstate(interpreter, domain, problem.objtypes, problem.init) end function initstate(interpreter::ConcreteInterpreter, domain::Domain, objtypes::AbstractDict) types = Set{Term}([Compound(ty, Term[o]) for (o, ty) in objtypes]) return GenericState(types, Set{Term}(), Dict{Symbol,Any}()) end function initstate(interpreter::ConcreteInterpreter, domain::Domain, objtypes::AbstractDict, fluents::AbstractVector) state = initstate(interpreter, domain, objtypes) for t in fluents if t.name == :(==) # Non-Boolean fluents @assert length(t.args) == 2 "Assignments must have two arguments." term, val = t.args[1], t.args[2] @assert !isa(term, Var) "Initial terms cannot be unbound variables." state[term] = evaluate(domain, state, val) else # Boolean fluents push!(state.facts, t) end end return state end function initstate(interpreter::ConcreteInterpreter, domain::Domain, objtypes::AbstractDict, fluents::AbstractDict) state = initstate(interpreter, domain, objtypes) for (name, val) in fluents set_fluent!(state, val, name) end return state end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2925
# Forward methods from generic domains to concrete interpreter # satisfy(domain::GenericDomain, state::State, term::Term) = satisfy(ConcreteInterpreter(), domain, state, term) satisfy(domain::GenericDomain, state::State, terms::AbstractVector{<:Term}) = satisfy(ConcreteInterpreter(), domain, state, terms) satisfiers(domain::GenericDomain, state::State, term::Term) = satisfiers(ConcreteInterpreter(), domain, state, term) satisfiers(domain::GenericDomain, state::State, terms::AbstractVector{<:Term}) = satisfiers(ConcreteInterpreter(), domain, state, terms) evaluate(domain::GenericDomain, state::State, term::Term) = evaluate(ConcreteInterpreter(), domain, state, term) initstate(domain::GenericDomain, problem::Problem) = initstate(ConcreteInterpreter(), domain, problem) initstate(domain::GenericDomain, objtypes::AbstractDict) = initstate(ConcreteInterpreter(), domain, objtypes) initstate(domain::GenericDomain, objtypes::AbstractDict, fluents) = initstate(ConcreteInterpreter(), domain, objtypes, fluents) goalstate(domain::GenericDomain, problem::Problem) = goalstate(ConcreteInterpreter(), domain, problem) goalstate(domain::GenericDomain, objtypes::AbstractDict, terms) = goalstate(ConcreteInterpreter(), domain, objtypes, terms) transition(domain::GenericDomain, state::State, action::Term; options...) = transition(ConcreteInterpreter(), domain, state, action; options...) transition!(domain::GenericDomain, state::State, action::Term; options...) = transition!(ConcreteInterpreter(), domain, state, action; options...) available(domain::GenericDomain, state::State, action::Action, args) = available(ConcreteInterpreter(), domain, state, action, args) available(domain::GenericDomain, state::State) = available(ConcreteInterpreter(), domain, state) execute(domain::GenericDomain, state::State, action::Action, args; options...) = execute(ConcreteInterpreter(), domain, state, action, args; options...) execute!(domain::GenericDomain, state::State, action::Action, args; options...) = execute!(ConcreteInterpreter(), domain, state, action, args; options...) relevant(domain::GenericDomain, state::State, action::Action, args) = relevant(ConcreteInterpreter(), domain, state, action, args) relevant(domain::GenericDomain, state::State) = relevant(ConcreteInterpreter(), domain, state) regress(domain::GenericDomain, state::State, action::Action, args; options...) = regress(ConcreteInterpreter(), domain, state, action, args; options...) regress!(domain::GenericDomain, state::State, action::Action, args; options...) = regress!(ConcreteInterpreter(), domain, state, action, args; options...) update!(domain::GenericDomain, state::State, diff::Diff) = update!(ConcreteInterpreter(), domain, state, diff) update(domain::GenericDomain, state::State, diff::Diff) = update(ConcreteInterpreter(), domain, state, diff)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3397
function satisfy(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, terms::AbstractVector{<:Term}) # Quick check that avoids SLD resolution unless necessary sat = all(check(interpreter, domain, state, t) for t in terms) if sat !== missing return sat end # Call SLD resolution only if there are free variables or axioms return !isempty(satisfiers(interpreter, domain, state, terms)) end function satisfy(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, term::Term) # Quick check that avoids SLD resolution unless necessary sat = check(interpreter, domain, state, term) if sat !== missing return sat end # Call SLD resolution only if there are free variables or axioms return !isempty(satisfiers(interpreter, domain, state, term)) end function satisfiers(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, terms::AbstractVector{<:Term}) # Initialize Julog knowledge base clauses = Clause[get_clauses(domain); collect(state.types); collect(state.facts)] # Pass in fluents and function definitions as a dictionary of functions funcs = get_eval_funcs(domain, state) # Reorder query to reduce search time terms = reorder_query(domain, collect(terms)) # Find satisfying substitutions via SLD-resolution _, subst = resolve(terms, clauses; funcs=funcs, mode=:all, search=:dfs) return subst end function satisfiers(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, term::Term) return satisfiers(interpreter, domain, state, [term]) end function check(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, term::Compound) sat = if term.name == :and all(check(interpreter, domain, state, a) for a in term.args) elseif term.name == :or any(check(interpreter, domain, state, a) for a in term.args) elseif term.name == :imply !check(interpreter, domain, state, term.args[1]) | check(interpreter, domain, state, term.args[2]) elseif term.name == :not !check(interpreter, domain, state, term.args[1]) elseif is_quantifier(term) missing elseif !is_ground(term) missing elseif is_derived(term, domain) missing elseif is_type(term, domain) if has_subtypes(term, domain) missing elseif term in state.types true elseif !isempty(get_constants(domain)) domain.constypes[term.args[1]] == term.name else false end elseif is_global_pred(term) evaluate(interpreter, domain, state, term)::Bool elseif is_func(term, domain) evaluate(interpreter, domain, state, term)::Bool else term in state.facts end return sat end function check(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, term::Const) if term in state.facts || term in state.types || term.name == true return true elseif is_func(term, domain) || is_derived(term, domain) return missing else return false end end function check(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, term::Var) return missing end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
397
## State updates ## function update!(interpreter::ConcreteInterpreter, domain::Domain, state::GenericState, diff::GenericDiff) setdiff!(state.facts, diff.del) union!(state.facts, diff.add) vals = [evaluate(domain, state, v) for v in values(diff.ops)] for (term, val) in zip(keys(diff.ops), vals) set_fluent!(state, val, term) end return state end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1353
""" $(SIGNATURES) Parse top-level PDDL descriptions (domains, problems, etc.). """ function parse_description(desc::Symbol, expr::Vector) @assert (expr[1] == :define) "'define' keyword is missing." @assert (expr[2][1] == desc) "'$desc' keyword is missing." name = expr[2][2] field_exprs = ((e[1].name, e) for e in expr[3:end]) # Parse description header (requirements, types, etc.) header = Dict{Symbol,Any}() for (fieldname::Symbol, e) in field_exprs if !is_header_field(Val(desc), fieldname) continue end if haskey(header, fieldname) error("Header field :$fieldname appears more than once.") end field = parse_header_field(Val(desc), fieldname, e) if isa(field, NamedTuple) merge!(header, Dict(pairs(field))) else header[fieldname] = field end end # Parse description body (actions, etc.) body = Dict{Symbol,Any}() for (fieldname::Symbol, e) in field_exprs if !is_body_field(Val(desc), fieldname) continue end field = parse_body_field(Val(desc), fieldname, e) fields = get!(body, Symbol(string(fieldname) * "s"), []) push!(fields, field) end return name, header, body end parse_description(desc::Symbol, str::AbstractString) = parse_description(desc, parse_string(str))
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
4584
""" $(SIGNATURES) Parse PDDL domain description. """ parse_domain(expr::Vector) = parse_domain(expr, GenericDomain) parse_domain(str::AbstractString) = parse_domain(parse_string(str)) parse_domain(expr::Vector, domain_type::Type) = domain_type(parse_description(:domain, expr)...) parse_domain(str::AbstractString, domain_type::Type) = parse_domain(parse_string(str), domain_type) @add_top_level(:domain, parse_domain) """ $(SIGNATURES) Parse domain requirements. """ function parse_requirements(expr::Vector) reqs = Dict{Symbol,Bool}(e.name => true for e in expr[2:end]) reqs = merge(DEFAULT_REQUIREMENTS, reqs) unchecked = [k for (k, v) in reqs if v == true] while length(unchecked) > 0 req = pop!(unchecked) deps = get(IMPLIED_REQUIREMENTS, req, Symbol[]) if length(deps) == 0 continue end reqs = merge(reqs, Dict{Symbol,Bool}(d => true for d in deps)) append!(unchecked, deps) end return reqs end @add_header_field(:domain, :requirements, parse_requirements) """ $(SIGNATURES) Parse type hierarchy. """ function parse_types(expr::Vector) @assert (expr[1].name == :types) ":types keyword is missing." types = Dict{Symbol,Vector{Symbol}}(:object => Symbol[]) all_subtypes = Set{Symbol}() accum = Symbol[] is_supertype = false for e in expr[2:end] if e == :- is_supertype = true continue end subtypes = get!(types, e, Symbol[]) if is_supertype append!(subtypes, accum) union!(all_subtypes, accum) accum = Symbol[] is_supertype = false else push!(accum, e) end end maxtypes = setdiff(keys(types), all_subtypes, [:object]) append!(types[:object], collect(maxtypes)) return (typetree=types,) end @add_header_field(:domain, :types, parse_types) """ $(SIGNATURES) Parse constants in a planning domain. """ function parse_constants(expr::Vector) @assert (expr[1].name == :constants) ":constants keyword is missing." objs, types = parse_typed_consts(expr[2:end]) types = Dict{Const,Symbol}(o => t for (o, t) in zip(objs, types)) return (constants=objs, constypes=types) end parse_constants(::Nothing) = (constants=Const[], constypes=Dict{Const,Symbol}()) @add_header_field(:domain, :constants, parse_constants) """ $(SIGNATURES) Parse predicate list. """ function parse_predicates(expr::Vector) @assert (expr[1].name == :predicates) ":predicates keyword is missing." preds = Dict{Symbol,Signature}() declarations, types = parse_typed_declarations(expr[2:end], :boolean) for ((term, argtypes), type) in zip(declarations, types) if type !== :boolean error("Predicate $term is not boolean.") end preds[term.name] = Signature(term, argtypes, type) end return preds end parse_predicates(::Nothing) = Dict{Symbol,Signature}() @add_header_field(:domain, :predicates, parse_predicates) """ $(SIGNATURES) Parse list of function (i.e. fluent) declarations. """ function parse_functions(expr::Vector) @assert (expr[1].name == :functions) ":functions keyword is missing." funcs = Dict{Symbol,Signature}() declarations, types = parse_typed_declarations(expr[2:end], :numeric) for ((term, argtypes), type) in zip(declarations, types) funcs[term.name] = Signature(term, argtypes, type) end return funcs end parse_functions(::Nothing) = Dict{Symbol,Signature}() @add_header_field(:domain, :functions, parse_functions) """ $(SIGNATURES) Parse axioms (a.k.a. derived predicates). """ function parse_axiom(expr::Vector) @assert (expr[1].name in [:axiom, :derived]) ":derived keyword is missing." head = parse_formula(expr[2]) body = parse_formula(expr[3]) return Clause(head, Term[body]) end @add_body_field(:domain, :axiom, parse_axiom) """ $(SIGNATURES) Parse axioms (a.k.a. derived predicates). """ parse_derived(expr::Vector) = parse_axiom(expr) @add_body_field(:domain, :derived, parse_derived) """ $(SIGNATURES) Parse action definition. """ function parse_action(expr::Vector) args = Dict(expr[i].name => expr[i+1] for i in 1:2:length(expr)) @assert (:action in keys(args)) ":action keyword is missing" name = args[:action] params, types = parse_typed_vars(get(args, :parameters, [])) precondition = parse_formula(get(args, :precondition, [])) effect = parse_formula(args[:effect]) return GenericAction(name, params, types, precondition, effect) end @add_body_field(:domain, :action, parse_action)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
4998
## Parsers for PDDL formulas ## """ $(SIGNATURES) Parse to first-order-logic formula. """ function parse_formula(expr::Vector; interpolate::Bool = false) if length(expr) == 0 return Const(:true) elseif length(expr) == 1 return parse_term(expr[1]) elseif length(expr) > 1 name = expr[1] if name in (:exists, :forall) # Handle exists and forall separately if interpolate vars, types = parse_typed_vars(expr[2]; interpolate = true) typeconds = [:(Compound($ty, Term[$v])) for (v, ty) in zip(vars, types)] cond = length(typeconds) > 1 ? :(Compound(:and, Term[$(typeconds...)])) : typeconds[1] body = parse_term(expr[3]; interpolate = true) return :(Compound($(QuoteNode(name)), Term[$cond, $body])) else vars, types = parse_typed_vars(expr[2]) typeconds = Term[Compound(ty, Term[v]) for (v, ty) in zip(vars, types)] cond = length(typeconds) > 1 ? Compound(:and, typeconds) : typeconds[1] body = parse_term(expr[3]) return Compound(name, Term[cond, body]) end else # Convert = to == so that Julog can handle equality checks name = (name == :(=)) ? :(==) : name if interpolate name = name isa Symbol ? QuoteNode(name) : name args = Any[parse_term(expr[i]; interpolate = true) for i in 2:length(expr)] return :(Compound($name, Term[$(args...)])) else args = Term[parse_term(expr[i]) for i in 2:length(expr)] return Compound(name, args) end end else error("Could not parse $(unparse(expr)) to PDDL formula.") end end parse_formula(expr::Union{Symbol,Number,Var}; interpolate::Bool = false) = parse_term(expr; interpolate = interpolate) parse_formula(str::AbstractString; interpolate::Bool = false) = parse_formula(parse_string(str); interpolate = interpolate) function parse_term(expr; interpolate::Bool = false) if expr isa Vector return parse_formula(expr; interpolate = interpolate) elseif expr isa Var return expr elseif expr isa Union{Symbol,Number,String} return Const(expr) elseif expr isa Expr if interpolate return :($expr isa Term ? $expr : Const($expr)) else error("Interpolation only supported in macro parsing of formulas.") end else error("Could not parse $(unparse(expr)) to PDDL term.") end end """ $(SIGNATURES) Parse predicates or function declarations with type signatures. """ function parse_declaration(expr::Vector) if length(expr) == 1 && isa(expr[1], Symbol) return Const(expr[1]), Symbol[] elseif length(expr) > 1 && isa(expr[1], Symbol) name = expr[1] args, types = parse_typed_vars(expr[2:end]) return Compound(name, Vector{Term}(args)), types else error("Could not parse $(unparse(expr)) to typed declaration.") end end """ $(SIGNATURES) Parse list of typed expressions. """ function parse_typed_list(expr::Vector, T::Type, default, parse_fn; interpolate::Bool = false) # TODO : Handle either-types terms = Vector{T}() types = interpolate ? Union{QuoteNode, Expr}[] : Symbol[] count, is_type = 0, false for e in expr if e == :- if is_type error("Repeated hyphens in $(unparse(expr)).") end is_type = true continue elseif is_type if interpolate e = e isa Symbol ? QuoteNode(e) : :($e::Symbol) end append!(types, fill(e, count)) count, is_type = 0, false else push!(terms, parse_fn(e)) count += 1 end end if interpolate default = default isa Symbol ? QuoteNode(default) : :($default::Symbol) end append!(types, fill(default, count)) return terms, types end """ $(SIGNATURES) Parse list of typed variables. """ function parse_typed_vars(expr::Vector, default=:object; interpolate::Bool = false) if interpolate varcheck(e) = e isa Var ? e : :($e::Var) return parse_typed_list(expr, Union{Var, Expr}, default, varcheck; interpolate = true) else return parse_typed_list(expr, Var, default, identity) end end """ $(SIGNATURES) Parse list of typed constants. """ parse_typed_consts(expr::Vector, default=:object) = parse_typed_list(expr, Const, default, Const) """ $(SIGNATURES) Parse list of typed declarations. """ parse_typed_declarations(expr::Vector, default=:boolean) = parse_typed_list(expr, Any, default, parse_declaration)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1880
## Parser combinator from strings to Julia expressions # Adapted from LispSyntax.jl (https://github.com/swadey/LispSyntax.jl) "Parser combinator for PDDL Lisp syntax." lisp = Delayed() white_space = p"(([\s\n\r]*(?<!\\);[^\n\r]+[\n\r\s]*)+|[\s\n\r]+)" opt_ws = white_space | e"" doubley = p"[-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?" > (x -> parse(Float64, x)) floaty_dot = p"[-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?[Ff]" > (x -> parse(Float32, x[1:end-1])) floaty_nodot = p"[-+]?[0-9]*[0-9]+([eE][-+]?[0-9]+)?[Ff]" > (x -> parse(Float32, x[1:end-1])) floaty = Alt!(floaty_dot, floaty_nodot) inty = p"[-+]?\d+" > (x -> parse(Int, x)) booly = p"(true|false)" > (x -> x == "true" ? true : false) stringy = p"(?<!\\)\".*?(?<!\\)\"" > (x -> convert(String, x[2:end-1])) keywordy = E":" + p"[\w_][\w_\-]*" > (x -> Keyword(lowercase(x))) vary = E"?" + p"[\w_][\w_\-]*" > (x -> Var(Symbol(uppercasefirst(lowercase(x))))) symboly = p"[\w_][\w_\-]*" > (x -> Symbol(lowercase(x))) opsymy = p"[^\d():\?{}'`,;~\[\]\s\w$]+" > Symbol insymy = E"$" + p"[\w_]+" > (x -> esc(Symbol(x))) inopeny = Seq!(E"${", ~opt_ws) inclosey = Alt!(E"}", Error("expected closing brace")) inexpr = Seq!(~inopeny, p"[^{}]+", ~inclosey) > (x -> esc(Meta.parse(x))) openy = Seq!(E"(", ~opt_ws) closey = Alt!(E")", Error("invalid expression")) sexpr = Seq!(~openy, Repeat(lisp + ~opt_ws; backtrack=false), ~closey) |> (x -> x) lisp.matcher = Alt!(floaty, doubley, inty, booly, stringy, keywordy, vary, symboly, opsymy, insymy, inexpr, sexpr) const top_level = Seq!(Repeat(~opt_ws + lisp; backtrack=false), ~opt_ws, Eos()) function parse_string(str::AbstractString) try return parse_one(str, top_level)[1] catch e error(e.msg) end end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
6597
module Parser export parse_domain, parse_problem, parse_pddl, @pddl, @pddl_str export load_domain, load_problem using ParserCombinator, Julog, ValSplit, DocStringExtensions using ..PDDL: Signature, GenericDomain, GenericProblem, GenericAction using ..PDDL: DEFAULT_REQUIREMENTS, IMPLIED_REQUIREMENTS "PDDL keyword." struct Keyword name::Symbol end Keyword(name::AbstractString) = Keyword(Symbol(name)) Base.show(io::IO, kw::Keyword) = print(io, "KW:", kw.name) """ $(SIGNATURES) Parse top level description to a PDDL.jl data structure. """ @valsplit parse_top_level(Val(name::Symbol), expr) = error("Unrecognized description: :$name") """ $(SIGNATURES) Returns whether `name` is associated with a top-level description. """ @valsplit is_top_level(Val(name::Symbol)) = false """ @add_top_level(name, f) Register `f` as a top-level parser for PDDL descriptions (e.g domains, problems). """ macro add_top_level(name, f) f = esc(f) _parse_top_level = GlobalRef(@__MODULE__, :parse_top_level) _is_top_level = GlobalRef(@__MODULE__, :is_top_level) quote $_parse_top_level(::Val{$name}, expr) = $f(expr) $_is_top_level(::Val{$name}) = true end end """ $(SIGNATURES) Parse header field for a PDDL description. """ @valsplit parse_header_field(Val(desc::Symbol), fieldname, expr) = error("Unrecognized description: :$desc") @valsplit parse_header_field(desc::Union{Val,Nothing}, Val(fieldname::Symbol), expr) = error("Unrecognized fieldname: :$fieldname") """ $(SIGNATURES) Returns whether `fieldname` is a header field for a PDDL description. """ @valsplit is_header_field(Val(desc::Symbol), fieldname::Symbol) = false @valsplit is_header_field(desc::Union{Val,Nothing}, Val(fieldname::Symbol)) = false """ @add_header_field(desc, fieldname, f) Register `f` as a parser for a header field in a PDDL description. """ macro add_header_field(desc, fieldname, f) f = esc(f) _parse_header_field = GlobalRef(@__MODULE__, :parse_header_field) _is_header_field = GlobalRef(@__MODULE__, :is_header_field) quote $_parse_header_field(::Val{$desc}, ::Val{$fieldname}, expr) = $f(expr) $_parse_header_field(::Nothing, ::Val{$fieldname}, expr) = $f(expr) $_is_header_field(::Val{$desc}, ::Val{$fieldname}) = true $_is_header_field(::Nothing, ::Val{$fieldname}) = true end end """ $(SIGNATURES) Parse body field for a PDDL description. """ @valsplit parse_body_field(Val(desc::Symbol), fieldname, expr) = error("Unrecognized description: :$desc") @valsplit parse_body_field(desc::Union{Val,Nothing}, Val(fieldname::Symbol), expr) = error("Unrecognized fieldname: :$fieldname") """ $(SIGNATURES) Returns whether `fieldname` is a body field for a PDDL description. """ @valsplit is_body_field(Val(desc::Symbol), fieldname::Symbol) = false @valsplit is_body_field(desc::Union{Val,Nothing}, Val(fieldname::Symbol)) = false """ @add_body_field(desc, fieldname, f) Register `f` as a parser for a body field in a PDDL description. """ macro add_body_field(desc, fieldname, f) f = esc(f) _parse_body_field = GlobalRef(@__MODULE__, :parse_body_field) _is_body_field = GlobalRef(@__MODULE__, :is_body_field) quote $_parse_body_field(::Val{$desc}, ::Val{$fieldname}, expr) = $f(expr) $_parse_body_field(::Nothing, ::Val{$fieldname}, expr) = $f(expr) $_is_body_field(::Val{$desc}, ::Val{$fieldname}) = true $_is_body_field(::Nothing, ::Val{$fieldname}) = true end end # Utility functions include("utils.jl") # Lisp-style grammar for PDDL include("grammar.jl") # Parsers for PDDL formulas include("formulas.jl") # Parser for top-level PDDL descriptions include("descriptions.jl") # Parsers for PDDL domains include("domain.jl") # Parsers for PDDL problems include("problem.jl") """ parse_pddl(str) Parse to PDDL structure based on initial keyword. """ function parse_pddl(expr::Vector; interpolate::Bool = false) if isa(expr[1], Keyword) kw = expr[1].name if is_header_field(nothing, kw) return parse_header_field(nothing, kw, expr) elseif is_body_field(nothing, kw) return parse_body_field(nothing, kw, expr) end error("Keyword $kw not recognized.") elseif expr[1] == :define kw = expr[2][1] return parse_top_level(kw, expr) else return parse_formula(expr; interpolate = interpolate) end end parse_pddl(sym::Union{Symbol,Number,Var}; interpolate::Bool = false) = parse_formula(sym; interpolate = interpolate) parse_pddl(str::AbstractString; interpolate::Bool = false) = parse_pddl(parse_string(str); interpolate = interpolate) parse_pddl(strs::AbstractString...; interpolate::Bool = false) = [parse_pddl(parse_string(s); interpolate = interpolate) for s in strs] """ @pddl(strs...) Parse string(s) to PDDL construct(s). When parsing PDDL formulae, the variable `x` can be interpolated into the string using the syntax `\\\$x`. For example, `@pddl("(on \\\$x \\\$y)")` will parse to `Compound(:on, Term[x, y])` if `x` and `y` are [`Term`](@ref)s. Julia expressions can be interpolated by surrounding the expression with curly braces, i.e. `\\\${...}`. """ macro pddl(str::AbstractString) return parse_pddl(str; interpolate = true) end macro pddl(strs::AbstractString...) results = parse_pddl.(strs; interpolate = true) if any(r isa Expr for r in results) return Expr(:vect, results...) else return collect(results) end end """ pddl"..." Parse string `"..."` to PDDL construct. When parsing PDDL formulae, the variable `x` can be interpolated into the string using the syntax `\$x`. For example, `pddl"(on \$x \$y)"` will parse to `Compound(:on, Term[x, y])` if `x` and `y` are [`Term`](@ref)s. Julia expressions can be interpolated by surrounding the expression with curly braces, i.e. `\${...}`. """ macro pddl_str(str::AbstractString) return parse_pddl(str; interpolate = true) end """ load_domain(path::AbstractString) load_domain(io::IO) Load PDDL domain from specified path or IO object. """ function load_domain(io::IO) str = read(io, String) return parse_domain(str) end load_domain(path::AbstractString) = open(io->load_domain(io), path) """ load_problem(path::AbstractString) load_problem(io::IO) Load PDDL problem from specified path or IO object. """ function load_problem(io::IO) str = read(io, String) return parse_problem(str) end load_problem(path::AbstractString) = open(io->load_problem(io), path) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2194
""" $(SIGNATURES) Parse PDDL problem description. """ parse_problem(expr::Vector) = GenericProblem(parse_description(:problem, expr)...) parse_problem(str::AbstractString) = parse_problem(parse_string(str)) @add_top_level(:problem, parse_problem) """ $(SIGNATURES) Parse domain for planning problem. """ parse_domain_name(expr::Vector) = expr[2] @add_header_field(:problem, :domain, parse_domain_name) """ $(SIGNATURES) Parse objects in planning problem. """ function parse_objects(expr::Vector) @assert (expr[1].name == :objects) ":objects keyword is missing." objs, types = parse_typed_consts(expr[2:end]) types = Dict{Const,Symbol}(o => t for (o, t) in zip(objs, types)) return (objects=objs, objtypes=types) end parse_objects(::Nothing) = (objects=Const[], objtypes=Dict{Const,Symbol}()) @add_header_field(:problem, :objects, parse_objects) """ $(SIGNATURES) Parse initial formula literals in planning problem. """ function parse_init(expr::Vector) @assert (expr[1].name == :init) ":init keyword is missing." return [parse_formula(e) for e in expr[2:end]] end parse_init(::Nothing) = Term[] @add_header_field(:problem, :init, parse_init) """ $(SIGNATURES) Parse goal formula in planning problem. """ function parse_goal(expr::Vector) @assert (expr[1].name == :goal) ":goal keyword is missing." return parse_formula(expr[2]) end parse_goal(::Nothing) = Const(true) @add_header_field(:problem, :goal, parse_goal) """ $(SIGNATURES) Parse metric expression in planning problem. """ function parse_metric(expr::Vector) @assert (expr[1].name == :metric) ":metric keyword is missing." @assert (expr[2] in (:minimize, :maximize)) "Unrecognized optimization." return Compound(expr[2], [parse_formula(expr[3])]) end parse_metric(expr::Nothing) = nothing @add_header_field(:problem, :metric, parse_metric) """ $(SIGNATURES) Parse constraints formula in planning problem. """ function parse_constraints(expr::Vector) @assert (expr[1].name == :constraints) ":constraints keyword is missing." return parse_formula(expr[2]) end parse_constraints(::Nothing) = nothing @add_header_field(:problem, :constraints, parse_constraints)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
235
## Convert expressions back to strings unparse(expr) = string(expr) unparse(expr::Vector) = "(" * join(unparse.(expr), " ") * ")" unparse(expr::Var) = "?" * lowercase(string(expr.name)) unparse(expr::Keyword) = ":" * string(expr.name)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
501
""" EndStateSimulator(max_steps::Union{Int,Nothing} = nothing) Simulator that returns the end state of simulation. """ @kwdef struct EndStateSimulator <: Simulator max_steps::Union{Int,Nothing} = nothing end function simulate(sim::EndStateSimulator, domain::Domain, state::State, actions) state = copy(state) for (t, act) in enumerate(actions) state = transition!(domain, state, act) sim.max_steps !== nothing && t >= sim.max_steps && break end return state end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
960
"Abstract type for PDDL simulators." abstract type Simulator end """ (sim::Simulator)(domain::Domain, state::State, actions) Simulates the evolution of a PDDL `domain` as a sequence of `actions` are executed from an initial `state`. """ (sim::Simulator)(domain::Domain, state::State, actions) = simulate(sim, domain, state, actions) """ simulate([sim=StateRecorder()], domain::Domain, state::State, actions) Simulates the evolution of a PDDL `domain` as a sequence of `actions` are executed from an initial `state`. The type of simulator, `sim`, specifies what information is collected and returned. By default, `sim` is a [`StateRecorder`](@ref), which records and returns the state trajectory. """ simulate(sim::Simulator, domain::Domain, state::State, actions) = error("Not implemented.") include("state_recorder.jl") include("end_state.jl") simulate(domain::Domain, state::State, actions) = simulate(StateRecorder(), domain, state, actions)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
532
""" StateRecorder(max_steps::Union{Int,Nothing} = nothing) Simulator that records the state trajectory, including the start state. """ @kwdef struct StateRecorder <: Simulator max_steps::Union{Int,Nothing} = nothing end function simulate(sim::StateRecorder, domain::Domain, state::State, actions) trajectory = [state] for (t, act) in enumerate(actions) state = transition(domain, state, act) push!(trajectory, state) sim.max_steps !== nothing && t >= sim.max_steps && break end return trajectory end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
15085
""" PDDL.Arrays Extends PDDL with array-valued fluents. Register by calling `PDDL.Arrays.@register()`. Attach to a specific `domain` by calling `PDDL.Arrays.attach!(domain)`. # Datatypes ## Generic Arrays - `array`: A multidimensional array with untyped elements. - `vector`: A 1D array with untyped elements. - `matrix`: A 2D array with untyped elements. ## Bit Arrays - `bit-array`: A multidimensional array with `boolean` elements. - `bit-vector`: A 1D array with `boolean` elements. - `bit-matrix`: A 2D array with `boolean` elements. ## Integer Arrays - `int-array`: A multidimensional array with `integer` elements. - `int-vector`: A 1D array with `integer` elements. - `int-matrix`: A 2D array with `integer` elements. ## Numeric Arrays - `num-array`: A multidimensional array with `number` elements. - `num-vector`: A 1D array with `number` elements. - `num-matrix`: A 2D array with `number` elements. ## Array Indices - `array-index`: A multidimensional array index, represented as a `Tuple`. - `vector-index`: A 1D array index, represented as an `Int`. - `matrix-index`: A 2D array index, represented as a 2-tuple. # Predicates - `(has-index ?a ?i)`: Checks if `?i` is a valid index for `?a`. - `(has-row ?m ?i)`: Checks if `?i` is a valid row index for matrix `?m`. - `(has-col ?m ?i)`: Checks if `?i` is a valid column index for matrix `?m`. # Functions ## Array Constructors - `(new-array ?v ?n1 ?n2 ...)`: Construct a new array filled with `?v`. - `(new-matrix ?v ?h ?w)`: Construct a new `?h` x `?w` matrix filled with `?v`. - `(new-vector ?v ?n)`: Construct a new vector of length `?n` filled with `?v`. - `(vec ?x1 ?x2 ... ?xn)`: Construct a vector from `?x1`, `?x2`, etc. - `(mat ?v1 ?v2 ... ?vn)`: Construct a matrix from column vectors `?v1`, `?v2`, etc. Similar constructors are available for bit arrays, integer arrays, and numeric arrays. ## Index Constructors - `(index ?i1 ?i2 ...)`: Construct an array index from `?i1`, `?i2`, etc. - `(vec-index ?i)`: Construct a 1D array index from `?i`. - `(mat-index ?i1 ?i2)`: Construct a 2D array index from `?i1`, `?i2`. ## Accessors - `(get-index ?a ?i ?j ...)`: Get element `(?i, ?j, ...)` of `?a`. - `(set-index ?a ?v ?i ?j ...)`: Set element `(?i, ?j, ...)` of `?a` to `?v`. ## Array Dimensions - `(length ?a)`: Get the number of elements in an array `?a`. - `(height ?a)`: Get the height of a matrix `?m`. - `(width ?a)`: Get the width of a matrix `?m`. - `(ndims ?a)`: Get the number of dimensions of an array `?a`. ## Array Manipulation - `(push ?v ?x)`: Push `?x` onto the end of `?v`. - `(pop ?v)`: Pop the last element of `?v`. - `(transpose ?m)`: Transpose a matrix `?m`. ## Index Manipulation - `(get-row ?idx)`: Get the row number of a `matrix-index`. - `(get-col ?idx)`: Get the column number of a `matrix-index`. - `(set-row ?idx ?row)`: Set the row number of a `matrix-index` to `?row`. - `(set-col ?idx ?col)`: Set the column number of a `matrix-index` to `?col`. - `(increase-row ?idx ?d)`: Increase the row number of a `matrix-index` by `?d`. - `(increase-col ?idx ?d)`: Increase the column number of a `matrix-index` by `?d`. - `(decrease-row ?idx ?d)`: Decrease the row number of a `matrix-index` by `?d`. - `(decrease-col ?idx ?d)`: Decrease the column number of a `matrix-index` by `?d`. """ @pddltheory module Arrays using ..PDDL using ..PDDL: BooleanAbs, IntervalAbs, SetAbs, lub, isboth, empty_interval # Generic array constructors new_array(val, dims...) = fill!(Array{Any}(undef, dims), val) new_matrix(val, h, w) = fill!(Matrix{Any}(undef, h, w), val) new_vector(val, n) = fill!(Vector{Any}(undef, n), val) vec(xs...) = collect(Any, xs) mat(vs::Vector{Any}...) = Matrix{Any}(hcat(vs...)) # Bit array constructors new_bit_array(val::Bool, dims...) = val ? trues(dims) : falses(dims) new_bit_matrix(val::Bool, h, w) = val ? trues(h, w) : falses(h, w) new_bit_vector(val::Bool, n) = val ? trues(n) : falses(n) bit_vec(xs...) = BitVector(collect(xs)) bit_mat(vs::BitVector...) = hcat(vs...)::BitMatrix # Integer array constructors new_int_array(val::Integer, dims...) = fill!(Array{Int}(undef, dims), val) new_int_matrix(val::Integer, h, w) = fill!(Matrix{Int}(undef, h, w), val) new_int_vector(val::Integer, n) = fill!(Vector{Int}(undef, n), val) int_vec(xs...) = collect(Int, xs) int_mat(vs::Vector{Int}...) = Matrix{Int}(hcat(vs...)) # Numeric array constructors new_num_array(val::Real, dims...) = fill!(Array{Float64}(undef, dims), val) new_num_matrix(val::Real, h, w) = fill!(Matrix{Float64}(undef, h, w), val) new_num_vector(val::Real, n) = fill!(Vector{Float64}(undef, n), val) num_vec(xs...) = collect(Float64, xs) num_mat(vs::Vector{Float64}...) = Matrix{Float64}(hcat(vs...)) # Index constructors index(idxs::Int...) = idxs vec_index(i::Int) = i mat_index(i::Int, j::Int) = (i, j) # Array accessors get_index(a::AbstractArray{T,N}, idxs::Vararg{Int,N}) where {T,N} = getindex(a, idxs...) get_index(a::AbstractArray{T,N}, idxs::NTuple{N,Int}) where {T,N} = getindex(a, idxs...) set_index(a::AbstractArray{T,N}, val, idxs::Vararg{Int,N}) where {T,N} = setindex!(copy(a), val, idxs...) set_index(a::AbstractArray{T,N}, val, idxs::NTuple{N,Int}) where {T,N} = setindex!(copy(a), val, idxs...) # Bounds checking has_index(a::AbstractArray{T,N}, idxs::Vararg{Int,N}) where {T,N} = checkbounds(Bool, a, idxs...) has_index(a::AbstractArray{T,N}, idxs::NTuple{N,Int}) where {T,N} = checkbounds(Bool, a, idxs...) has_row(m::AbstractMatrix, i::Int) = checkbounds(Bool, m, i, :) has_col(m::AbstractMatrix, j::Int) = checkbounds(Bool, m, :, j) # Index component accessors get_index(idx::NTuple{N, Int}, i::Int) where {N} = getindex(idx, i) get_row(idx::Tuple{Int, Int}) = idx[1] get_col(idx::Tuple{Int, Int}) = idx[2] set_index(idx::NTuple{N, Int}, val::Int, i::Int) where {N} = (idx[1:i-1]..., val, idx[i+1:end]...) set_row(idx::Tuple{Int, Int}, val::Int) = (val, idx[2]) set_col(idx::Tuple{Int, Int}, val::Int) = (idx[1], val) # Index component modifiers increase_index(idx::NTuple{N, Int}, i::Int, val::Int) where {N} = (idx[1:i-1]..., idx[i] + val, idx[i+1:end]...) increase_row(idx::Tuple{Int, Int}, val::Int) = (idx[1] + val, idx[2]) increase_col(idx::Tuple{Int, Int}, val::Int) = (idx[1], idx[2] + val) decrease_index(idx::NTuple{N, Int}, i::Int, val::Int) where {N} = (idx[1:i-1]..., idx[i] - val, idx[i+1:end]...) decrease_row(idx::Tuple{Int, Int}, val::Int) = (idx[1] - val, idx[2]) decrease_col(idx::Tuple{Int, Int}, val::Int) = (idx[1], idx[2] - val) # Array dimensions length(a::AbstractArray) = Base.length(a) height(m::AbstractMatrix) = size(m, 1) width(m::AbstractMatrix) = size(m, 2) ndims(a::AbstractArray) = Base.ndims(a) # Push and pop push(v::AbstractVector, x) = push!(copy(v), x) pop(v::AbstractVector) = (v = copy(v); pop!(v); v) # Transformations _transpose(v::AbstractVector) = permutedims(v) _transpose(m::AbstractMatrix) = permutedims(m) # Accessors with abstract indices function get_index( a::AbstractArray{T,N}, idxs::Vararg{SetAbs{Int},N} ) where {T,N} val = SetAbs{T}() for i in Iterators.product((i.set for i in idxs)...) has_index(a, i) && push!(val.set, get_index(a, i)) end return val end function get_index( a::AbstractArray{T,N}, idxs::SetAbs{NTuple{N, Int}} ) where {T,N} val = SetAbs{T}() for i in idxs.set has_index(a, i) && push!(val.set, get_index(a, i)) end return val end function get_index( a::AbstractArray{T,N}, idxs::SetAbs{NTuple{N, Int}} ) where {T <: BooleanAbs, N} val::BooleanAbs = missing for i in idxs.set has_index(a, i) || continue val = lub(val, get_index(a, i)) end return val end function get_index( a::AbstractArray{T,N}, idxs::Vararg{IntervalAbs{Int},N} ) where {T <: Real,N} val = empty_interval(IntervalAbs{T}) for i in Iterators.product((i.lo:i.hi for i in idxs)...) has_index(a, i) || continue val = lub(val, IntervalAbs{T}(get_index(a, i))) end return val end function get_index( a::AbstractArray{T,N}, idxs::Vararg{IntervalAbs{Int},N} ) where {T <: BooleanAbs,N} val::BooleanAbs = missing for i in Iterators.product((i.lo:i.hi for i in idxs)...) has_index(a, i) || continue val = lub(val, get_index(a, i)) end return val end # Bounds checking with abstract indices function has_index( a::AbstractArray{T,N}, idxs::Vararg{SetAbs{Int},N} ) where {T, N} iter = (has_index(a, i) for i in Iterators.product((i.set for i in idxs)...)) return lub(BooleanAbs, iter) end function has_index( a::AbstractArray{T,N}, idxs::SetAbs{NTuple{N, Int}} ) where {T,N} iter = (has_index(a, i) for i in idxs.set) return lub(BooleanAbs, iter) end function has_index( a::AbstractArray{T,N}, idxs::Vararg{IntervalAbs{Int},N} ) where {T, N} iter = (has_index(a, i) for i in Iterators.product(((i.lo, i.hi) for i in idxs)...)) return lub(BooleanAbs, iter) end has_row(m::AbstractMatrix, idxs::SetAbs{Int}) = lub(BooleanAbs, (has_row(m, i) for i in idxs.set)) has_row(m::AbstractMatrix, i::IntervalAbs{Int}) = lub(has_row(m, i.lo), has_row(m, i.hi)) has_col(m::AbstractMatrix, idxs::SetAbs{Int}) = lub(BooleanAbs, (has_col(m, j) for j in idxs.set)) has_col(m::AbstractMatrix, j::IntervalAbs{Int}) = lub(has_col(m, j.lo), has_col(m, j.hi)) # Abstract index component accessors get_index(idxs::SetAbs{T}, i::Int) where {T <: Tuple} = SetAbs{Int}(;iter=(idx[i] for idx in idxs.set)) get_row(idxs::SetAbs{T}) where {T <: Tuple} = SetAbs{Int}(;iter=(idx[1] for idx in idxs.set)) get_col(idxs::SetAbs{T}) where {T <: Tuple} = SetAbs{Int}(;iter=(idx[2] for idx in idxs.set)) set_index(idxs::SetAbs{T}, i::Int, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(set_index(idx, i, val) for idx in idxs.set)) set_row(idxs::SetAbs{T}, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(set_row(idx, val) for idx in idxs.set)) set_col(idxs::SetAbs{T}, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(set_col(idx, val) for idx in idxs.set)) # Abstract index component modifiers increase_index(idxs::SetAbs{T}, i::Int, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(increase_index(idx, i, val) for idx in idxs.set)) increase_row(idxs::SetAbs{T}, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(increase_row(idx, val) for idx in idxs.set)) increase_col(idxs::SetAbs{T}, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(increase_col(idx, val) for idx in idxs.set)) decrease_index(idxs::SetAbs{T}, i::Int, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(decrease_index(idx, i, val) for idx in idxs.set)) decrease_row(idxs::SetAbs{T}, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(decrease_row(idx, val) for idx in idxs.set)) decrease_col(idxs::SetAbs{T}, val::Int) where {T <: Tuple} = SetAbs{T}(;iter=(decrease_col(idx, val) for idx in idxs.set)) # Conversions to terms vec_to_term(v::AbstractVector) = Compound(:vec, PDDL.val_to_term.(v)) bitvec_to_term(v::BitVector) = Compound(Symbol("bit-vec"), Const.(Int.(v))) intvec_to_term(v::Vector{<:Integer}) = Compound(Symbol("int-vec"), Const.(Int.(v))) numvec_to_term(v::Vector{<:Real}) = Compound(Symbol("num-vec"), Const.(Float64.(v))) mat_to_term(m::AbstractMatrix) = Compound(:transpose, [Compound(:mat, vec_to_term.(eachrow(m)))]) bitmat_to_term(m::BitMatrix) = Compound(:transpose, [Compound(Symbol("bit-mat"), bitvec_to_term.(BitVector.(eachrow(m))))]) intmat_to_term(m::Matrix{<:Integer}) = Compound(:transpose, [Compound(Symbol("int-mat"), intvec_to_term.(eachrow(m)))]) nummat_to_term(m::Matrix{<:Real}) = Compound(:transpose, [Compound(Symbol("num-mat"), numvec_to_term.(eachrow(m)))]) index_to_term(idxs::NTuple{N,Int}) where {N} = Compound(:index, [Const(i) for i in idxs]) const DATATYPES = Dict( "array" => (type=Array{Any}, default=Array{Any}(undef, ())), "vector" => (type=Vector{Any}, default=Vector{Any}(undef, 0)), "matrix" => (type=Matrix{Any}, default=Matrix{Any}(undef, 0, 0)), "bit-array" => (type=BitArray, default=falses()), "bit-vector" => (type=BitVector, default=falses(0)), "bit-matrix" => (type=BitMatrix, default=falses(0, 0)), "int-array" => (type=Array{Int64}, default=zeros(Int64)), "int-vector" => (type=Vector{Int64}, default=zeros(Int64, 0)), "int-matrix" => (type=Matrix{Int64}, default=zeros(Int64, 0, 0)), "num-array" => (type=Array{Float64}, default=zeros(Float64)), "num-vector" => (type=Vector{Float64}, default=zeros(Float64, 0)), "num-matrix" => (type=Matrix{Float64}, default=zeros(Float64, 0, 0)), "array-index" => (type=NTuple{N, Int} where {N}, default=()), "vector-index" => (type=Int, default=1), "matrix-index" => (type=Tuple{Int, Int}, default=(1, 1)) ) const ABSTRACTIONS = Dict( "index" => SetAbs, "vector-index" => SetAbs{Int}, "matrix-index" => SetAbs{Tuple{Int, Int}} ) const CONVERTERS = Dict( "vector" => vec_to_term, "matrix" => mat_to_term, "bit-vector" => bitvec_to_term, "bit-matrix" => bitmat_to_term, "int-vector" => intvec_to_term, "int-matrix" => intmat_to_term, "num-vector" => numvec_to_term, "num-matrix" => nummat_to_term, "array-index" => index_to_term, "matrix-index" => index_to_term ) const PREDICATES = Dict( # Bounds checking "has-index" => has_index, "has-row" => has_row, "has-col" => has_col ) const FUNCTIONS = Dict( # Generic array constructors "new-array" => new_array, "new-vector" => new_vector, "new-matrix" => new_matrix, "vec" => vec, "mat" => mat, # Bit array constructors "new-bit-array" => new_bit_array, "new-bit-vector" => new_bit_vector, "new-bit-matrix" => new_bit_matrix, "bit-vec" => bit_vec, "bit-mat" => bit_mat, # Integer array constructors "new-int-array" => new_int_array, "new-int-vector" => new_int_vector, "new-int-matrix" => new_int_matrix, "int-vec" => int_vec, "int-mat" => int_mat, # Numeric array constructors "new-num-array" => new_num_array, "new-num-vector" => new_num_vector, "new-num-matrix" => new_num_matrix, "num-vec" => num_vec, "num-mat" => num_mat, # Array index constructors "index" => index, "vec-index" => vec_index, "mat-index" => mat_index, # Array accessors "get-index" => get_index, "set-index" => set_index, # Index accessors "get-row" => get_row, "get-col" => get_col, "set-row" => set_row, "set-col" => set_col, # Index modifiers "increase-index" => increase_index, "increase-row" => increase_row, "increase-col" => increase_col, "decrease-index" => decrease_index, "decrease-row" => decrease_row, "decrease-col" => decrease_col, # Array dimensions "length" => length, "height" => height, "width" => width, "ndims" => ndims, # Push and pop "push" => push, "pop" => pop, # Transformations "transpose" => _transpose ) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2051
""" PDDL.Sets Extends PDDL with set-valued fluents. Set members must be PDDL objects. Register by calling `PDDL.Sets.@register()`. Attach to a specific `domain` by calling `PDDL.Sets.attach!(domain)`. # Datatypes - `set`: A set of PDDL objects. # Predicates - `(member ?x - object ?s - set)`: Is `?x` a member of `?s`? - `(subset ?s1 ?s2 - set)`: Is `?s1` a subset of `?s2`? # Functions - `(construct-set ?x ?y ... - object)`: Constructs a set from `?x`, `?y`, etc. - `(empty-set)`: Constructs an empty set. - `(cardinality ?s - set)`: The number of elements in `?s`. - `(union ?s1 ?s2 - set)`: The union of `?s1` and `?s2`. - `(intersect ?s1 ?s2 - set)`: The intersection of `?s1` and `?s2`. - `(difference ?s1 ?s2 - set)`: The set difference of `?s1` and `?s2`. - `(add-element ?s - set? ?x - object)`: Add `?x` to `?s`. - `(rem-element ?s - set? ?x - object)`: Remove `?x` from `?s`. """ @pddltheory module Sets using ..PDDL using ..PDDL: SetAbs construct_set(xs::Symbol...) = Set{Symbol}(xs) empty_set() = Set{Symbol}() cardinality(s::Set) = length(s) member(s::Set, x) = in(x, s) subset(x::Set, y::Set) = issubset(x, y) union(x::Set, y::Set) = Base.union(x, y) intersect(x::Set, y::Set) = Base.intersect(x, y) difference(x::Set, y::Set) = setdiff(x, y) add_element(s::Set, x) = push!(copy(s), x) rem_element(s::Set, x) = pop!(copy(s), x) set_to_term(s::Set) = isempty(s) ? Const(Symbol("(empty-set)")) : Compound(Symbol("construct-set"), PDDL.val_to_term.(collect(s))) const DATATYPES = Dict( "set" => (type=Set{Symbol}, default=Set{Symbol}()) ) const ABSTRACTIONS = Dict( "set" => SetAbs{Set{Symbol}} ) const CONVERTERS = Dict( "set" => set_to_term ) const PREDICATES = Dict( "member" => member, "subset" => subset ) const FUNCTIONS = Dict( "construct-set" => construct_set, "empty-set" => empty_set, "cardinality" => cardinality, "union" => union, "intersect" => intersect, "difference" => difference, "add-element" => add_element, "rem-element" => rem_element ) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3461
# Theories for data types "Generate expression to register definitions in a theory module." function register_theory_expr(theory::Module) expr = Expr(:block) for (name, ty) in theory.DATATYPES push!(expr.args, register_expr(:datatype, name, QuoteNode(ty))) end for (name, ty) in theory.ABSTRACTIONS push!(expr.args, register_expr(:abstraction, name, QuoteNode(ty))) end for (name, ty) in theory.CONVERTERS push!(expr.args, register_expr(:converter, name, QuoteNode(ty))) end for (name, f) in theory.PREDICATES push!(expr.args, register_expr(:predicate, name, QuoteNode(f))) end for (name, f) in theory.FUNCTIONS push!(expr.args, register_expr(:function, name, QuoteNode(f))) end push!(expr.args, nothing) return expr end "Runtime registration of the definitions in a theory module." function register_theory!(theory::Module) for (name, ty) in theory.DATATYPES PDDL.register!(:datatype, name, ty) end for (name, ty) in theory.ABSTRACTIONS PDDL.register!(:abstraction, name, ty) end for (name, ty) in theory.CONVERTERS PDDL.register!(:converter, name, ty) end for (name, f) in theory.PREDICATES PDDL.register!(:predicate, name, f) end for (name, f) in theory.FUNCTIONS PDDL.register!(:function, name, f) end return nothing end "Runtime deregistration of the definitions in a theory module." function deregister_theory!(theory::Module) for (name, ty) in theory.DATATYPES PDDL.deregister!(:datatype, name) end for (name, ty) in theory.ABSTRACTIONS PDDL.deregister!(:abstraction, name) end for (name, ty) in theory.CONVERTERS PDDL.deregister!(:converter, name) end for (name, f) in theory.PREDICATES PDDL.deregister!(:predicate, name) end for (name, f) in theory.FUNCTIONS PDDL.deregister!(:function, name) end return nothing end "Attach a custom theory to a PDDL domain." function attach_theory!(domain::Domain, theory::Module) for (name, ty) in theory.DATATYPES PDDL.attach!(domain, :datatype, name, ty) end for (name, f) in theory.PREDICATES PDDL.attach!(domain, :function, name, f) end for (name, f) in theory.FUNCTIONS PDDL.attach!(domain, :function, name, f) end return nothing end """ @pddltheory module M ... end Declares a module `M` as a PDDL theory. This defines the `M.@register`, `M.register!`, `M.deregister!` and `M.attach!` functions automatically. """ macro pddltheory(module_expr) if !Meta.isexpr(module_expr, :module) error("Only `module` expressions can be declared as PDDL theories.") end autodefs = quote macro register() return $(GlobalRef(PDDL, :register_theory_expr))(@__MODULE__) end function register!() return $(GlobalRef(PDDL, :register_theory!))(@__MODULE__) end function deregister!() return $(GlobalRef(PDDL, :deregister_theory!))(@__MODULE__) end function attach!(domain::$(GlobalRef(PDDL, :Domain))) return $(GlobalRef(PDDL, :attach_theory!))(domain, @__MODULE__) end end module_block = module_expr.args[3] append!(module_block.args, autodefs.args) return esc(module_expr) end # Array-valued fluents include("arrays.jl") # Set-valued fluents include("sets.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
9703
module Writer export write_pddl, write_domain, write_problem export save_domain, save_problem using Julog, DocStringExtensions using ..PDDL: IMPLIED_REQUIREMENTS, Domain, Problem, Action, get_name, get_requirements, get_typetree, get_constants, get_constypes, get_predicates, get_functions, get_actions, get_axioms, get_domain_name, get_objects, get_objtypes, get_init_terms, get_goal, get_metric, get_constraints, get_argvars, get_argtypes, get_precond, get_effect """ $(SIGNATURES) Write list of typed formulae in PDDL syntax. """ function write_typed_list(formulae::Vector{<:Term}, types::Vector{Symbol}) if all(x -> x == :object, types) return join(write_subformula.(formulae), " ") end str = "" for (i, (f, t)) in enumerate(zip(formulae, types)) str *= "$(write_subformula(f)) " if i == length(formulae) || t != types[i+1] str *= "- $t " end end return str[1:end-1] end function write_typed_list(formulae::Vector{<:Term}) formulae, types = zip([(t.args[1], t.name) for t in formulae]...) return write_typed_list(collect(formulae), collect(types)) end function write_typed_list(formulae::Vector{<:Term}, types::Dict{<:Term,Symbol}) types = Symbol[types[f] for f in formulae] return write_typed_list(formulae, types) end """ $(SIGNATURES) Indent list of PDDL constants. """ function indent_const_list(str::String, indent::Int, maxchars::Int=80) if length(str) < maxchars - indent return str end lines = String[] while length(str) > 0 l_end = min(maxchars - indent, length(str)) if l_end != length(str) l_end = findlast(' ', str[1:l_end]) end if isnothing(l_end) l_end = findfirst(' ', str) end if isnothing(l_end) l_end = length(str) end push!(lines, str[1:l_end]) str = str[l_end+1:end] end return join(lines, "\n" * ' '^indent) end """ $(SIGNATURES) Indent list of typed PDDL constants. """ function indent_typed_list(str::String, indent::Int, maxchars::Int=80) if length(str) < maxchars - indent return str end if !occursin(" - ", str) return indent_const_list(str, indent, maxchars) end substrs = String[] while length(str) > 0 idxs = findnext(r" - (\S+)", str, 1) if isnothing(idxs) idxs = [length(str)] end push!(substrs, str[1:idxs[end]]) str = strip(str[idxs[end]+1:end]) end substrs = indent_const_list.(substrs, indent, maxchars) return join(substrs, "\n" * ' '^indent) end """ write_formula(f::Term) Write formula in PDDL syntax. """ function write_formula end function write_formula(name::Symbol, args) if name in [:exists, :forall] typecond, body = args var_str = write_typed_list(flatten_conjs(typecond)) body_str = write_formula(body) return "($name ($var_str) $body_str)" elseif name in [:and, :or, :not, :when, :imply, :(==), :>, :<, :!=, :>=, :<=, :+, :-, :*, :/, :assign, :increase, :decrease, Symbol("scale-up"), Symbol("scale-down")] name = name == :(==) ? :(=) : name args = join((write_formula(a) for a in args), " ") return "($name $args)" elseif isempty(args) return "($name)" else args = join((write_subformula(a) for a in args), " ") return "($name $args)" end end function write_formula(f::Const) if f.name isa Symbol return "(" * repr(f) * ")" elseif f.name isa AbstractString return "\"" * repr(f) * "\"" else return repr(f) end end write_formula(f::Compound) = write_formula(f.name, f.args) write_formula(f::Var) = "?" * lowercasefirst(repr(f)) write_formula(::Nothing) = "" write_subformula(f::Compound) = write_formula(f) write_subformula(f::Var) = "?" * lowercasefirst(repr(f)) write_subformula(f::Const) = f.name isa AbstractString ? "\"" * repr(f) * "\"" : repr(f) """ $(SIGNATURES) Write to string in PDDL syntax. """ write_pddl(f::Term) = write_formula(f) """ $(SIGNATURES) Write domain in PDDL syntax. """ function write_domain(domain::Domain, indent::Int=2) strs = Dict{Symbol,String}() fields = [:requirements, :types, :constants, :predicates, :functions] strs[:requirements] = write_requirements(get_requirements(domain)) strs[:types] = write_typetree(get_typetree(domain)) strs[:constants] = indent_typed_list( write_typed_list(get_constants(domain), get_constypes(domain)), 14) strs[:predicates] = write_signatures(get_predicates(domain)) strs[:functions] = write_signatures(get_functions(domain)) strs = ["($(repr(k)) $(strs[k]))" for k in fields if haskey(strs, k) && length(strs[k]) > 0] append!(strs, write_axiom.(values(get_axioms(domain)))) append!(strs, write_action.(values(get_actions(domain)), indent=3)) pushfirst!(strs, "(define (domain $(domain.name))") return join(strs, "\n" * ' '^indent) * "\n)" end write_pddl(domain::Domain) = write_domain(domain) """ $(SIGNATURES) Write domain requirements. """ function write_requirements(requirements::Dict{Symbol,Bool}) reqs = Set(k for (k, v) in requirements if v) for (k, implied) in IMPLIED_REQUIREMENTS if haskey(requirements, k) setdiff!(reqs, implied) end end return join([":$r" for r in reqs], " ") end """ $(SIGNATURES) Write domain typetree. """ function write_typetree(typetree) strs = Dict{Symbol,String}() for (type, subtypes) in pairs(typetree) if isempty(subtypes) || type == :object continue end subtype_str = join(subtypes, " ") strs[type] = "$subtype_str - $type" end maxtypes = collect(union(get(typetree, :object, Symbol[]), keys(strs))) strs[:object] = join(sort(maxtypes), " ") return strip(join(values(strs), " ")) end """ $(SIGNATURES) Write domain predicates or functions. """ function write_signatures(signatures) strs = String[] for (name, sig) in pairs(signatures) args = collect(Term, sig.args) types = collect(Symbol, sig.argtypes) args_str = write_typed_list(args, types) sig_str = isempty(args_str) ? "($name)" : "($name $args_str)" if sig.type != :boolean && sig.type != :numeric sig_str = "$sig_str - $(sig.type)" end push!(strs, sig_str) end return join(strs, " ") end """ $(SIGNATURES) Write PDDL axiom / derived predicate. """ function write_axiom(c::Clause; key=":derived") head_str = write_formula(c.head) body_str = length(c.body) == 1 ? write_formula(c.body[1]) : "(and " * join(write_formula.(c.body), " ") * ")" return "($key $head_str $body_str)" end """ $(SIGNATURES) Write action in PDDL syntax. """ function write_action(action::Action; indent::Int=1) strs = Dict{Symbol,String}() fields = [:action, :parameters, :precondition, :effect] strs[:action] = string(get_name(action)) strs[:parameters] = "(" * write_typed_list(get_argvars(action), get_argtypes(action)) * ")" strs[:precondition] = write_formula(get_precond(action)) strs[:effect] = write_formula(get_effect(action)) strs = ["$(repr(k)) $(strs[k])" for k in fields] return "(" * join(strs, "\n" * ' '^indent) * ")" end write_pddl(action::Action) = write_action(action) """ $(SIGNATURES) Write action signature in PDDL syntax. """ function write_action_sig(action::Action) name = get_name(action) vars = get_argvars(action) types = get_argtypes(action) if isempty(vars) return "($name)" else return "($name " * write_typed_list(vars, types) * ")" end end """ $(SIGNATURES) Write problem in PDDL syntax. """ function write_problem(problem::Problem, indent::Int=2) strs = Dict{Symbol,String}() fields = [:domain, :objects, :init, :goal, :metric, :constraints] strs[:domain] = string(problem.domain) strs[:objects] = indent_typed_list( write_typed_list(get_objects(problem), get_objtypes(problem)), 12) strs[:init] = write_init(get_init_terms(problem), 9) strs[:goal] = write_formula(get_goal(problem)) strs[:metric] = write_formula(get_metric(problem))[2:end-1] strs[:constraints] = write_formula(get_constraints(problem)) strs = ["($(repr(k)) $(strs[k]))" for k in fields if haskey(strs, k) && length(strs[k]) > 0] pushfirst!(strs, "(define (problem $(get_name(problem)))") return join(strs, "\n" * ' '^indent) * "\n)" end write_pddl(problem::Problem) = write_problem(problem) """ $(SIGNATURES) Write initial problem formulae in PDDL syntax. """ function write_init(init::Vector{<:Term}, indent::Int=2, maxchars::Int=80) strs = write_formula.(init) if sum(length.(strs)) + length("(:init )") < maxchars return join(strs, " ") end return join(strs, "\n" * ' '^indent) end """ save_domain(path::String, domain::Domain) Save PDDL domain to specified path. """ function save_domain(path::String, domain::Domain) open(f->write(f, write_domain(domain)), path, "w") return path end """ save_problem(path::String, problem::Problem) Save PDDL problem to specified path. """ function save_problem(path::String, problem::Problem) open(f->write(f, write_problem(problem)), path, "w") return path end Base.show(io::IO, ::MIME"text/pddl", domain::Domain) = print(io, write_pddl(domain)) Base.show(io::IO, ::MIME"text/pddl", problem::Problem) = print(io, write_pddl(problem)) Base.show(io::IO, ::MIME"text/pddl", action::Action) = print(io, write_pddl(action)) Base.show(io::IO, ::MIME"text/pddl", term::Term) = print(io, write_pddl(term)) end
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
453
using PDDL, PDDL.Parser, Test # Define equivalence shorthand for abstract interpreter testing function ≃(a, b) val = PDDL.equiv(a, b) return (val == true) || (val == PDDL.both) end include("parser/test.jl") include("strips/test.jl") include("typing/test.jl") include("axioms/test.jl") include("adl/test.jl") include("numeric/test.jl") include("constants/test.jl") include("arrays/test.jl") include("sets/test.jl") include("functions/test.jl")
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
3572
# Test ADL features in a grid flipping domain & assembly domain @testset "action description language (adl)" begin path = joinpath(dirname(pathof(PDDL)), "..", "test", "adl") domain = load_domain(joinpath(path, "flip-domain.pddl")) @test domain.name == Symbol("flip") problem = load_problem(joinpath(path, "flip-problem.pddl")) @test problem.name == Symbol("flip-problem") Base.show(IOBuffer(), "text/plain", problem) state = initstate(domain, problem) implementations = [ "concrete interpreter" => domain, "ground interpreter" => ground(domain, state), "cached interpreter" => CachedDomain(domain), "concrete compiler" => first(compiled(domain, state)), "cached compiler" => CachedDomain(first(compiled(domain, state))), ] @testset "flip ($name)" for (name, domain) in implementations state = initstate(domain, problem) state = execute(domain, state, pddl"(flip_column c1)", check=true) state = execute(domain, state, pddl"(flip_column c3)", check=true) state = execute(domain, state, pddl"(flip_row r2)", check=true) @test satisfy(domain, state, problem.goal) == true # Ensure that Base.show does not error buffer = IOBuffer() action = first(PDDL.get_actions(domain)) Base.show(buffer, "text/plain", domain) Base.show(buffer, "text/plain", state) Base.show(buffer, "text/plain", action) close(buffer) end # Test all ADL features in assembly domain path = joinpath(dirname(pathof(PDDL)), "..", "test", "adl") domain = load_domain(joinpath(path, "assembly-domain.pddl")) problem = load_problem(joinpath(path, "assembly-problem.pddl")) Base.show(IOBuffer(), "text/plain", problem) state = initstate(domain, problem) implementations = [ "concrete interpreter" => domain, "ground interpreter" => ground(domain, state), "cached interpreter" => CachedDomain(domain), "concrete compiler" => first(compiled(domain, state)), "cached compiler" => CachedDomain(first(compiled(domain, state))), ] @testset "assembly ($name)" for (name, domain) in implementations # Test for static fluents if name != "ground interpreter" static_fluents = infer_static_fluents(domain) @test :requires in static_fluents @test length(static_fluents) == 6 end # Execute plan to assemble a frob state = initstate(domain, problem) # Commit charger to assembly of frob state = execute(domain, state, pddl"(commit charger frob)", check=true) # Once commited, we can't commit again @test available(domain, state, pddl"(commit charger frob)") == false # We can't add a tube to the frob before adding the widget and fastener @test available(domain, state, pddl"(assemble tube frob)") == false state = execute(domain, state, pddl"(assemble widget frob)", check=true) @test available(domain, state, pddl"(assemble tube frob)") == false state = execute(domain, state, pddl"(assemble fastener frob)", check=true) # Having added both widget and fastener, now we can add the tube @test available(domain, state, pddl"(assemble tube frob)") == true state = execute(domain, state, pddl"(assemble tube frob)", check=true) # We've completely assembled a frob! @test satisfy(domain, state, problem.goal) == true # Ensure that Base.show does not error buffer = IOBuffer() action = first(PDDL.get_actions(domain)) Base.show(buffer, "text/plain", domain) Base.show(buffer, "text/plain", state) Base.show(buffer, "text/plain", action) close(buffer) end end # action description language (adl)
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
5136
@testset "array fluents" begin # Register array theory PDDL.Arrays.@register() # Load gridworld domain and problem path = joinpath(dirname(pathof(PDDL)), "..", "test", "arrays") domain = load_domain(joinpath(path, "gridworld-domain.pddl")) problem = load_problem(joinpath(path, "gridworld-problem.pddl")) # Ensure that Base.show does not error Base.show(IOBuffer(), "text/plain", problem) # Make sure function declarations have the right output type @test PDDL.get_function(domain, :walls).type == Symbol("bit-matrix") @test PDDL.get_function(domain, :pos).type == Symbol("matrix-index") state = initstate(domain, problem) implementations = [ "concrete interpreter" => domain, "ground interpreter" => ground(domain, state), "abstracted interpreter" => abstracted(domain), "cached interpreter" => CachedDomain(domain), "concrete compiler" => first(compiled(domain, state)), "abstract compiler" => first(compiled(abstracted(domain), state)), "cached compiler" => CachedDomain(first(compiled(domain, state))), ] @testset "gridworld ($name)" for (name, domain) in implementations # Initialize state, test array dimensios, access and goal state = initstate(domain, problem) @test domain[state => pddl"(width (walls))"] == 3 @test domain[state => pddl"(height (walls))"] == 3 @test domain[state => pddl"(get-index walls 2 2)"] == true @test domain[state => pddl"(get-index walls 1 2)"] == true @test domain[state => pddl"(get-index walls (index 2 2))"] == true @test domain[state => pddl"(get-index walls (index 1 2))"] == true @test satisfy(domain, state, problem.goal) == false # Check that we can only move down because of wall actions = available(domain, state) |> collect @test length(actions) == 1 && actions[1].name == :down # Execute plan to reach goal state = execute(domain, state, pddl"(down)", check=true) state = execute(domain, state, pddl"(down)", check=true) state = execute(domain, state, pddl"(right)", check=true) state = execute(domain, state, pddl"(right)", check=true) state = execute(domain, state, pddl"(up)", check=true) state = execute(domain, state, pddl"(up)", check=true) # Check that goal is achieved @test satisfy(domain, state, problem.goal) == true # Ensure that Base.show does not error buffer = IOBuffer() action = first(PDDL.get_actions(domain)) Base.show(buffer, "text/plain", domain) Base.show(buffer, "text/plain", action) close(buffer) end # Test writing of array-valued fluents original_state = initstate(domain, problem) problem_str = write_problem(GenericProblem(original_state)) reparsed_state = initstate(domain, parse_problem(problem_str)) @test reparsed_state == original_state # Load stairs domain and problem path = joinpath(dirname(pathof(PDDL)), "..", "test", "arrays") domain = load_domain(joinpath(path, "stairs-domain.pddl")) problem = load_problem(joinpath(path, "stairs-problem.pddl")) # Make sure function declarations have the right output type @test PDDL.get_function(domain, :stairs).type == Symbol("num-vector") state = initstate(domain, problem) implementations = [ "concrete interpreter" => domain, "ground interpreter" => ground(domain, state), "abstracted interpreter" => abstracted(domain), "cached interpreter" => CachedDomain(domain), "concrete compiler" => first(compiled(domain, state)), "abstract compiler" => first(compiled(abstracted(domain), state)), "cached compiler" => CachedDomain(first(compiled(domain, state))), ] @testset "stairs ($name)" for (name, domain) in implementations # Initialize state, test array dimensios, access and goal state = initstate(domain, problem) @test domain[state => pddl"(length (stairs))"] == 5 @test domain[state => pddl"(get-index stairs 1)"] == 1.0 @test domain[state => pddl"(get-index stairs 2)"] == 3.0 @test satisfy(domain, state, problem.goal) == false # Check that we can only jump because first stair is too high actions = available(domain, state) |> collect @test length(actions) == 1 && actions[1].name == Symbol("jump-up") # Execute plan to reach goal state = execute(domain, state, pddl"(jump-up)", check=true) state = execute(domain, state, pddl"(climb-up)", check=true) state = execute(domain, state, pddl"(jump-down)", check=true) state = execute(domain, state, pddl"(jump-up)", check=true) state = execute(domain, state, pddl"(jump-up)", check=true) state = execute(domain, state, pddl"(jump-down)", check=true) state = execute(domain, state, pddl"(climb-up)", check=true) state = execute(domain, state, pddl"(jump-up)", check=true) # Check that goal is achieved @test satisfy(domain, state, problem.goal) == true # Ensure that Base.show does not error buffer = IOBuffer() action = first(PDDL.get_actions(domain)) Base.show(buffer, "text/plain", domain) Base.show(buffer, "text/plain", state) Base.show(buffer, "text/plain", action) close(buffer) end # Deregister array theory PDDL.Arrays.deregister!() end # array fluents
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
2205
# Test functionality of PDDL axioms / derived predicates @testset "axioms" begin path = joinpath(dirname(pathof(PDDL)), "..", "test", "axioms") domain = load_domain(joinpath(path, "domain.pddl")) @test domain.name == Symbol("blocksworld-axioms") @test convert(Term, domain.predicates[:above]) == pddl"(above ?x ?y)" @test Clause(pddl"(handempty)", [pddl"(forall (?x) (not (holding ?x)))"]) in values(domain.axioms) problem = load_problem(joinpath(path, "problem.pddl")) @test problem.name == Symbol("blocksworld-problem") @test problem.objects == @pddl("a", "b", "c") Base.show(IOBuffer(), "text/plain", problem) state = initstate(domain, problem) implementations = [ "concrete interpreter" => domain, "ground interpreter" => ground(domain, state), "abstracted interpreter" => abstracted(domain), "cached interpreter" => CachedDomain(domain), "concrete compiler" => first(compiled(domain, state)), "abstract compiler" => first(compiled(abstracted(domain), state)), "cached compiler" => CachedDomain(first(compiled(domain, state))), ] @testset "axioms ($name)" for (name, domain) in implementations # Test forward execution of plans state = initstate(domain, problem) state = execute(domain, state, pddl"(pickup b)", check=true) @test domain[state => pddl"(holding b)"] ≃ true state = execute(domain, state, pddl"(stack b c)", check=true) @test domain[state => pddl"(on b c)"] ≃ true state = execute(domain, state, pddl"(pickup a)", check=true) @test domain[state => pddl"(holding a)"] ≃ true state = execute(domain, state, pddl"(stack a b)", check=true) @test domain[state => pddl"(above a c)"] ≃ true @test satisfy(domain, state, problem.goal) ≃ true # Test action availability state = initstate(domain, problem) @test Set{Term}(available(domain, state)) == Set{Term}(@pddl("(pickup a)", "(pickup b)", "(pickup c)")) # Ensure that Base.show does not error buffer = IOBuffer() action = first(PDDL.get_actions(domain)) Base.show(buffer, "text/plain", domain) Base.show(buffer, "text/plain", state) Base.show(buffer, "text/plain", action) close(buffer) end end # axioms
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git
[ "Apache-2.0" ]
0.2.18
df1e12fb86d1f081833a74249335aa02657be774
code
1446
# Test functionality of domain constants @testset "domain constants" begin path = joinpath(dirname(pathof(PDDL)), "..", "test", "constants") domain = load_domain(joinpath(path, "domain.pddl")) @test domain.name == Symbol("taxi") problem = load_problem(joinpath(path, "problem.pddl")) @test problem.name == Symbol("taxi-problem") Base.show(IOBuffer(), "text/plain", problem) # Check that constants are loaded correctly @test domain.constants == @pddl("red", "green", "yellow", "blue", "intaxi") # Check that types of constants resolve state = initstate(domain, problem) @test domain[state => pddl"(pasloc red)"] == true # Execute plan and check that it succeeds plan = @pddl( "(move loc6 loc5 west)", "(move loc5 loc0 north)", "(pickup loc0 red)", "(move loc0 loc1 east)", "(move loc1 loc6 south)", "(move loc6 loc11 south)", "(move loc11 loc12 east)", "(move loc12 loc13 east)", "(move loc13 loc14 east)", "(move loc14 loc9 north)", "(move loc9 loc4 north)", "(dropoff loc4 green)" ) sim = EndStateSimulator() state = sim(domain, state, plan) @test satisfy(domain, state, problem.goal) == true # Ensure that Base.show does not error buffer = IOBuffer() action = first(PDDL.get_actions(domain)) Base.show(buffer, "text/plain", domain) Base.show(buffer, "text/plain", problem) Base.show(buffer, "text/plain", state) Base.show(buffer, "text/plain", action) close(buffer) end # domain constants
PDDL
https://github.com/JuliaPlanners/PDDL.jl.git